Files
PaperClipAI/scripts/scale-ramp/main.ts
T
DottaandClaude Opus 5.5 b5ba548112 feat(server): add an instance-admin server metrics endpoint for the scale ramp (#21708)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The scaling plan
(`doc/plans/2026-11-13-thousand-concurrent-agents.md`) has a finish line
that a real-agent ramp harness checks (#21695)
> - Four finish-line criteria need numbers from inside each server
process: main-thread CPU, run event lateness, agent API time before the
handler, and missed lease renewals
> - The server had no way to give them, so every harness run was at best
"incomplete"
> - This pull request adds one instance-admin endpoint that returns
those numbers per process over a short sliding window, off by default,
and connects the harness to it
> - The benefit is that a ramp run can measure every server criterion it
can see, with near-zero cost when on and no cost when off

## Linked Issues or Issue Description

Refs #21695

**Subsystem affected**

Server (instance routes, run event append, native lease renewal),
database client (statement counter), and the scale-ramp harness in
`scripts/scale-ramp/`.

**Problem or motivation**

The scale-ramp harness reads `PAPERCLIP_SCALE_METRICS_URL`, but the
server has no endpoint for it. The criteria `main_thread_cpu`,
`run_event_lateness_p99`, `agent_api_pre_handler_p99` and
`lease_renewals_missed_zero` are therefore always "not measured", and no
run can pass.

**Proposed solution**

Add `GET /api/instance/server-metrics`. It returns a JSON snapshot of
one server process over the last 50 to 60 s. Only an instance admin can
read it. The env flag `PAPERCLIP_SERVER_METRICS` (read once at start,
default off) turns on collection and the route. Off, the path answers
404 and no collector starts.

**Alternatives considered**

- The postgres.js `debug` option for the statement counter: rejected,
because it captures a stack (`new Error()`) for every query.
- Process CPU from `process.cpuUsage()` as `mainThreadCpu`: rejected,
because it includes GC and libuv threads. It is returned as `processCpu`
instead, and `mainThreadCpu` reads the main thread from `/proc` (Linux
only, null elsewhere).
- Default on: the measured cost is negligible (numbers below), but the
event-loop monitor wakes the process every 20 ms when idle, and this is
a new instance-wide surface. It stays off; the runbook says how to turn
it on for a ramp run.

## What Changed

- `server/src/services/server-metrics.ts`: a per-process collector. It
uses `performance.eventLoopUtilization()`, `monitorEventLoopDelay` (20
ms), `process.cpuUsage()`, the main thread's
`/proc/self/task/<pid>/stat` on Linux, and six 10 s buckets of native
`perf_hooks` histograms. One unref'd timer rotates the buckets. Nothing
on the hot path awaits, allocates per call or does I/O.
- `server/src/routes/instance-server-metrics.ts`: `GET
/api/instance/server-metrics`, guarded by the existing
`assertInstanceAdmin` (the check that `/instance/database-backups` and
other instance routes use). It returns numbers, a random per-process
`processId`, `uptimeSec`, `buildRevision` and `windowMs`. It returns no
SQL, names, IDs or hostnames.
- `server/src/app.ts`: when the flag is on, two middlewares time agent
API requests from arrival to the API router, the route is mounted, and
shutdown stops the collector. When the flag is off, nothing is mounted.
- The snapshot also carries `dedicatedConnections` from
`dedicatedDbConnectionStats()` (#21693): `limit`, `inUse`, `waiting` at
request time and `peakInUse`, `queued`, `overLimit`, `nestedOverLimit`
since start. The harness ignores it today; it shows dedicated-connection
queueing in a restart burst.
- `packages/db/src/statement-count.ts` and
`lazy-transaction-queries.ts`: a Drizzle logger that increments one
counter per statement replaces Drizzle's no-op logger. No edit to
`client.ts`.
- `paperclip-control-plane-port.ts`: one call records runner `emittedAt`
to committed row for each committed (not duplicate) runner event.
- `native-execution-lease.ts`: one call counts a lease whose renewal
deadline passed.
- Harness: missed lease renewals are summed per `processId` (several
processes, or a restart, no longer cancel out). A metrics URL on the
target origin gets the board token in the `Authorization` header;
`PAPERCLIP_SCALE_METRICS_TOKEN` still overrides it, and another origin
gets no token.
- Contract: `scripts/scale-ramp/server-metrics.fixture.json` is the
serializer's own output. A server test asserts the serializer produces
exactly this file, and a harness test parses it and checks every field.
- `rules/company-scope-exceptions.mdc`: adds the snapshot as an
instance-wide exception with its reason. The runbook in the plan doc
documents the path, the flag, the credential and each field.

| Field | Provided | Source |
| --- | --- | --- |
| `mainThreadCpu` | yes (Linux; null elsewhere) |
`/proc/self/task/<pid>/stat` utime+stime |
| `eventLoopUtilization` | yes | `performance.eventLoopUtilization()` |
| `eventLoopDelayP99Ms` | yes | `monitorEventLoopDelay`, highest 10 s
p99 in the window |
| `statementsPerSecond` | yes | Drizzle logger counter (not BEGIN/COMMIT
or raw driver calls) |
| `poolWaitP99Ms` | absent | postgres.js has no cheap hook for queue
time |
| `runEventLatenessP99Ms` | yes (null with no events) | runner event
append |
| `agentApiPreHandlerP99Ms` | yes (null with no agent requests) |
arrival and router-entry middlewares |
| `leaseRenewalsMissed` | yes, counter since process start | native
lease deadline timer |

## Verification

- `cd server && npx vitest run
src/__tests__/instance-server-metrics-routes.test.ts
src/__tests__/server-metrics.test.ts`: through `createApp` on the
embedded test database. 200 with the exact field set for an instance
admin; 403 for a company owner who is not an instance admin, for an
agent key, and unauthenticated; 404 and no collector when the flag is
off; values move after agent requests, statements, a late run event and
a missed renewal; the body has no IDs, keys or SQL.
- `cd server && npx vitest run
src/services/native-runtime/native-execution-lease.test.ts
src/services/native-runtime/paperclip-control-plane-port.test.ts
src/__tests__/api-server-timing.test.ts`: the lease and run-event hooks
(red/green checked for the lease hook by removing the call).
- `cd packages/db && npx vitest run src/lazy-transaction-queries.test.ts
src/client-options.test.ts`: the counter counts statements inside
transactions and savepoints.
- `node --test scripts/scale-ramp/scale-ramp.test.ts` and `tsc -p
scripts/scale-ramp/tsconfig.json`: 38 pass, including the fixture
contract and the board-token header.
- `node server/scripts/typecheck-layers.mjs` and `tsc --noEmit` in
`packages/db`: pass.

Overhead, measured on a shared, loaded laptop (load average 8 to 20),
median with min and max:

| Measure | Off | On |
| --- | --- | --- |
| Logger call per statement (5M calls x 7) | 0.28 ns (0.24 to 0.97) |
3.36 ns (3.32 to 6.16) |
| CPU per `select 1` statement, embedded Postgres (3,000 x 10) | 28.7 us
(20.3 to 42.4) | 32.3 us (20.7 to 45.5) |
| CPU per HTTP request, client and server in one process (2,000 x 6) |
67.0 us (40.4 to 107.4) | 64.2 us (40.9 to 83.3) |
| Idle process CPU, 5 s x 3 | 0.01% of a core (0.00 to 2.21) | 0.08%
(0.05 to 0.09) |
| Record one run event (Date.parse + histogram) | - | 148 ns (135 to
188) |
| One snapshot | - | 55 us |

The statement and request differences are inside the run-to-run spread.
The direct cost is about 3 ns per statement, against about 30 us of CPU
per statement.

## Risks

- Low risk. Off by default; off, only the statement counter runs, and it
costs one increment more than Drizzle's no-op logger.
- `mainThreadCpu` assumes Linux USER_HZ of 100 and is null on other
platforms. The harness then uses `eventLoopUtilization`.
- Run event lateness compares the runner's clock with the server's
clock, so clock skew adds to it. Negative values count as zero.
- With several processes, each request reaches one process. The harness
keeps the highest gauge and sums counter growth per process, but a
process it never samples is not seen.
- The statement counter does not count BEGIN/COMMIT or raw postgres.js
calls.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edits, local test runs).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:13:45 -06:00

181 lines
8.7 KiB
TypeScript

import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { createInterface } from "node:readline/promises";
import { cleanupRun, discoverState, type CleanupReport } from "./cleanup.ts";
import { PaperclipClient, Redactor, realClock, type Clock, type Fetcher } from "./client.ts";
import { FALLBACK_TOKEN_ENV, metricsCredential, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts";
import { criteriaTable } from "./criteria.ts";
import { checkSpend, estimateSpend, type SpendEstimate } from "./estimate.ts";
import { Ramp, type RampOutcome } from "./ramp.ts";
import { buildResult, summaryLines, verdictOf } from "./report.ts";
import { prepareCompany } from "./setup.ts";
import { emptyState, fileStateStore, type RunState } from "./state.ts";
export interface MainDeps {
env: NodeJS.ProcessEnv;
fetcher: Fetcher;
clock: Clock;
out: (line: string) => void;
err: (line: string) => void;
confirm: (question: string) => Promise<string>;
onInterrupt: (handler: () => void) => () => void;
random?: () => number;
}
export const EXIT = { pass: 0, fail: 1, usage: 2, incomplete: 3, error: 4 } as const;
export function planLines(options: Options, estimate: SpendEstimate): string[] {
const steps = options.steps.map(step => `${step.concurrency}`).join(" -> ");
const credential = options.profile.credentialKey === null ? "none"
: options.profile.providerSecretId ? `existing secret for ${options.profile.credentialKey}`
: `${options.profile.credentialKey} from the environment, stored as a company secret and deleted at cleanup`;
return [
`Target: ${options.target.baseUrl} (${options.target.kind})`,
`Run id: ${options.label}`,
`Company: ${options.companyId ?? "a new company named for the run id"}`,
`Ramp: ${steps} agents, ${options.steps[0]!.holdMs / 60_000} min per step, drain ${options.drainMs / 60_000} min, stop on the first failed criterion`,
`Agents: up to ${estimate.agents}, ${options.profile.provider} ${options.profile.model}; credential: ${credential}`,
`Tasks: about ${estimate.tasks}, hard cap ${estimate.maxTasks}`,
`Estimated spend: $${estimate.totalUsd} (model $${estimate.modelUsd}, sandboxes $${estimate.sandboxUsd} for ${estimate.sandboxHours} sandbox-hours), about ${estimate.wallMinutes} min`,
...estimate.assumptions.map(line => ` assumption: ${line}`),
"Criteria:",
...criteriaTable(options.thresholds).map(criterion => ` ${criterion.id} [${criterion.source}] ${criterion.description}: ${criterion.threshold}`),
];
}
async function writeOutputs(dir: string, name: string, body: unknown, summary: string[] | null, redactor: Redactor): Promise<void> {
await mkdir(dir, { recursive: true, mode: 0o700 });
await writeFile(path.join(dir, name), `${redactor.text(JSON.stringify(body, null, 2))}\n`, { mode: 0o600 });
if (summary) await writeFile(path.join(dir, "SUMMARY.md"), `${redactor.text(summary.join("\n"))}\n`, { mode: 0o600 });
}
export async function main(argv: readonly string[], deps: MainDeps): Promise<number> {
let options: Options;
try {
options = parseOptions(argv, deps.env, deps.clock.now(), deps.random);
} catch (error) {
deps.err(`scale ramp: ${error instanceof Error ? error.message : String(error)}`);
return EXIT.usage;
}
const secrets = readSecrets(deps.env, options.profile.providerSecretId ? null : options.profile.credentialKey);
const redactor = new Redactor([secrets.token, secrets.credential, secrets.metricsToken]);
const out = (line: string) => deps.out(redactor.text(line));
const err = (line: string) => deps.err(redactor.text(line));
const estimate = estimateSpend(options);
if (options.mode !== "cleanup") for (const line of planLines(options, estimate)) out(line);
if (options.mode === "dry-run") {
out("Dry run: nothing was created or contacted.");
return EXIT.pass;
}
if (options.mode === "run") {
const spend = checkSpend(estimate, options.spendThresholdUsd, options.confirmSpendUsd);
if (!spend.ok) {
err(spend.reason);
return EXIT.usage;
}
}
if (!secrets.token) {
err(`Set ${TOKEN_ENV} (or ${FALLBACK_TOKEN_ENV}) to a board token for ${options.target.host}`);
return EXIT.usage;
}
if (!options.yes) {
const action = options.mode === "cleanup" ? `clean up ${options.label} on` : "start creating agents and tasks on";
const answer = await deps.confirm(`Type ${options.target.host} to ${action} it: `);
if (answer.trim().toLowerCase() !== options.target.host) {
err("Confirmation did not match the target host; nothing was done.");
return EXIT.usage;
}
}
const api = new PaperclipClient(options.target, secrets.token, deps.fetcher, deps.clock, redactor);
const store = fileStateStore(options.outDir);
if (options.mode === "cleanup") {
let report: CleanupReport | null = null;
let error: string | null = null;
try {
const state = await store.load() ?? await discoverState(api, options.label, options.companyId, options.target.baseUrl, deps.clock.now());
report = await cleanupRun({ api, clock: deps.clock, label: options.label, state, log: out });
} catch (caught) {
error = caught instanceof Error ? caught.message : String(caught);
}
await writeOutputs(options.outDir, `cleanup-${deps.clock.now()}.json`, { runId: options.label, report, error }, null, redactor);
if (error) err(`Cleanup failed: ${error}`);
if (report) out(`Cleanup ${options.label}: ${report.runsCancelled} runs cancelled, ${report.tasksArchived} tasks archived, ${report.agentsDeleted} agents deleted, ${report.errors.length} errors`);
return error || (report?.errors.length ?? 0) > 0 ? EXIT.fail : EXIT.pass;
}
let interrupted = false;
const release = deps.onInterrupt(() => {
interrupted = true;
err("Interrupt received: stopping the ramp and cleaning up");
});
const startedAt = deps.clock.now();
const state: RunState = emptyState(options.label, options.target.baseUrl, startedAt);
let outcome: RampOutcome | null = null;
let cleanup: CleanupReport | null = null;
let error: string | null = null;
try {
await store.save(state);
await prepareCompany({ api, options, state, store, credential: secrets.credential, log: out });
const ramp = new Ramp({
api, clock: deps.clock, fetcher: deps.fetcher, options, state, store, maxTasks: estimate.maxTasks,
spendCapUsd: options.confirmSpendUsd ?? Math.max(options.spendThresholdUsd, estimate.totalUsd), metricsToken: metricsCredential(options, secrets),
log: out, shouldStop: () => interrupted,
});
outcome = await ramp.run();
} catch (caught) {
error = caught instanceof Error ? caught.message : String(caught);
err(`Ramp stopped by an error: ${error}`);
} finally {
out(`Cleaning up ${options.label}`);
try {
cleanup = await cleanupRun({ api, clock: deps.clock, label: options.label, state, log: out });
} catch (caught) {
err(`Cleanup failed; finish it with --cleanup-only ${options.label}: ${caught instanceof Error ? caught.message : String(caught)}`);
}
release();
}
const failedRequests = api.records.filter(record => !record.ok).length;
const result = buildResult({
options, estimate, startedAt, finishedAt: deps.clock.now(), outcome, cleanup, error,
requests: { total: api.records.length, failed: failedRequests },
credentialSource: options.profile.credentialKey === null ? "none" : options.profile.providerSecretId ? "existing secret" : "stored for the run and deleted at cleanup",
});
const summary = summaryLines(result);
await writeOutputs(options.outDir, "result.json", result, summary, redactor);
for (const line of summary) out(line);
out(`Result: ${path.join(options.outDir, "result.json")}`);
if (cleanup && cleanup.errors.length) err(`Cleanup left ${cleanup.errors.length} errors; finish it with --cleanup-only ${options.label}`);
const verdict = verdictOf(outcome, error);
return verdict === "pass" ? EXIT.pass : verdict === "fail" ? EXIT.fail : verdict === "incomplete" ? EXIT.incomplete : EXIT.error;
}
export function processDeps(): MainDeps {
return {
env: process.env,
fetcher: (url, init) => fetch(url, init),
clock: realClock,
out: line => process.stdout.write(`${line}\n`),
err: line => process.stderr.write(`${line}\n`),
confirm: async question => {
const rl = createInterface({ input: process.stdin, output: process.stderr });
try {
return await rl.question(question);
} finally {
rl.close();
}
},
onInterrupt: handler => {
const listener = () => handler();
process.once("SIGINT", listener);
process.once("SIGTERM", listener);
return () => {
process.off("SIGINT", listener);
process.off("SIGTERM", listener);
};
},
};
}