From 56de5c4313b28b2474e66cd94a4b8ec87e2faadc Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:58:02 -0800 Subject: [PATCH 01/10] feat(scripts): measure server CPU, wakeups, memory and first-request time against a fake Claude API Adds scripts/server-metrics.ts (report:server). run starts this checkout's server with throwaway state, the real claude CLI and an in-process fake Anthropic API, and records startup, rest, 20 quiet threads, 5 streaming threads and time to the agent's first request. --mac-path takes the no-agent-scope path macOS always takes. compare exits 1 on a regression. Co-Authored-By: Claude Opus 5.5 --- docs/internals/performance-regressions.md | 12 + package.json | 1 + scripts/server-metrics.test.ts | 29 + scripts/server-metrics.ts | 636 ++++++++++++++++++++++ 4 files changed, 678 insertions(+) create mode 100644 scripts/server-metrics.test.ts create mode 100644 scripts/server-metrics.ts diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 25ecabd80c5a4..dbf54ce6dc47a 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -97,6 +97,18 @@ catalog digests and status deltas gets the provider list of its first config in provider with 250 slash commands and 200 skills. The lists load with the first cwd snapshot, and a machine refresh sends back an empty provider list. +## Server process metrics + +`node scripts/server-metrics.ts run --out ` starts this checkout's server against throwaway state, a +fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and heap at +rest, with 20 quiet Claude threads and with 5 streaming, plus how long a new thread takes to reach +the API. `compare` exits 1 on a regression, so it can gate a release or a scheduled +run. Only the server process is measured. + +Run it with `--mac-path` on Linux too. macOS has no agent scope, so its servers take per-process +paths Linux servers with a systemd user manager never run. A one-second `ps -A` poll per Claude +session cost 0.1.11 about 18% of a core with 20 open threads on macOS and went unnoticed on Linux. + ## Event store and startup Sequence cursors must seek an index rather than scan retained history. The application sequence diff --git a/package.json b/package.json index 9f1d2bee11b58..190d7e25cc3ec 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "tc": "vp run -r --cache --concurrency-limit 4 typecheck", "check:changed": "node scripts/check-changed.ts", "report:renders": "node scripts/render-metrics.ts", + "report:server": "node scripts/server-metrics.ts", "lint": "vp lint --report-unused-disable-directives", "i18n:untranslated": "node scripts/i18n-untranslated.ts", "knip": "knip --preprocessor ./scripts/knip-schemas.ts", diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts new file mode 100644 index 0000000000000..515141f71de72 --- /dev/null +++ b/scripts/server-metrics.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { compareMetrics, type ServerMetrics } from "./server-metrics.ts"; + +const metrics = (quiet: { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }) => + ({ + meta: { commit: "abc", platform: "linux-x64", macPath: true }, + quiet: { ...quiet, heapAfterGcMB: 200 }, + }) satisfies ServerMetrics; + +describe("compareMetrics", () => { + it.each([ + ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"]], + ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, []], + ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, []], + ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"]], + ["an improvement", { cpuPct: 0.1, wakeupsPerSec: 7 }, []], + ])("%s", (_name, change, regressed) => { + const before = metrics({ cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }); + const after = metrics({ cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500, ...change }); + expect(compareMetrics(before, after).regressed).toEqual(regressed); + }); + + it("does not treat a metric missing on one side as a regression", () => { + const before = metrics({ cpuPct: 0.3, wakeupsPerSec: null, rssPeakMB: 500 }); + const after = metrics({ cpuPct: 0.3, wakeupsPerSec: 9, rssPeakMB: 500 }); + expect(compareMetrics(before, after).regressed).toEqual([]); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts new file mode 100644 index 0000000000000..4ab85e1c4259b --- /dev/null +++ b/scripts/server-metrics.ts @@ -0,0 +1,636 @@ +// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalFetch:off globalDate:off - a standalone benchmark driver around one server process. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeHttp from "node:http"; +import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +const HELP = `Usage: + node scripts/server-metrics.ts run [--out ] [--mac-path] [--runs ] [--only ] + node scripts/server-metrics.ts compare [--threshold ] + +run Starts this checkout's server (apps/server/src/bin.ts) against a temp base dir, a temp + HOME, a temp git project and a fake Anthropic Messages API, drives the real \`claude\` + CLI through it, and writes one JSON object of measurements. Each scenario gets a fresh + server. Takes about 6 minutes. + + startup spawn to the first HTTP answer, in ms. + rest 30 s idle: server CPU %, wakeups/s, RSS peak, heap after a forced GC. + firstWord --runs (default 5) sequential \`thread start\` runs in the project folder and in a + new worktree: ms until the fake API receives the agent's request, and until the + reply finished. Median and p90. + quiet 20 Claude threads that answered and stay open, idle 20 s, then a 60 s window. + streaming 5 threads streaming a 2,000-word reply at 50 ms a word, 60 s window. + +--mac-path Linux only: starts the server without XDG_RUNTIME_DIR, so it has no agent scope and + takes the per-process path macOS always takes (apps/server/src/process/agentScope.ts). +Wakeups are voluntary plus involuntary context switches of the server's threads (Linux /proc); +they are null on macOS. Only the server process is measured, not the agent CLIs. + +compare Prints a markdown table of every metric (lower is better) and exits 1 when one got + worse by more than --threshold percent (default 10) and by more than its noise floor: + 1 point of CPU, 20 wakeups/s, 15 MB, 300 ms. With 5 runs a p90 is the + slowest run, so read a lone p90 change as noise unless the median moved too. + +Comparing two refs needs both checkouts, since the server runs each tree's code: + node scripts/server-metrics.ts run --out ../main-server.json # on main + node scripts/server-metrics.ts run --out ../branch-server.json # on the branch + node scripts/server-metrics.ts compare ../main-server.json ../branch-server.json`; + +const root = NodePath.resolve(import.meta.dirname, ".."); +// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. +const platform = NodeOS.platform(); +// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. +const architecture = NodeOS.arch(); +const serverDir = NodePath.join(root, "apps/server"); +const MODEL = "claude-haiku-4-5"; +const SLOW_MARKER = "[[stream-slowly]]"; + +interface Window { + readonly cpuPct: number; + readonly wakeupsPerSec: number | null; + readonly rssPeakMB: number; + readonly heapAfterGcMB: number; +} +interface Spread { + readonly median: number; + readonly p90: number; +} +interface FirstWord { + readonly toRequestMs: Spread; + readonly toDoneMs: Spread; +} +export interface ServerMetrics { + readonly meta: Readonly>; + readonly startup?: { readonly readyMs: number }; + readonly rest?: Window; + readonly firstWord?: { readonly inPlace: FirstWord; readonly worktree: FirstWord }; + readonly quiet?: Window; + readonly streaming?: Window; +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const round = (value: number) => Math.round(value * 10) / 10; + +function spread(values: ReadonlyArray): Spread { + const sorted = values.toSorted((a, b) => a - b); + const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; + return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; +} + +interface ApiRequest { + readonly at: number; + readonly stream: boolean; + readonly agent: boolean; + readonly marker: string | undefined; +} + +/** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ +function startFakeAnthropic() { + const requests: ApiRequest[] = []; + const server = NodeHttp.createServer((request, response) => { + let raw = ""; + request.on("data", (chunk: Buffer) => (raw += chunk)); + request.on("end", async () => { + const url = request.url ?? ""; + if (url.includes("count_tokens")) { + response.writeHead(200, { "content-type": "application/json" }); + return response.end(JSON.stringify({ input_tokens: 100 })); + } + if (!url.startsWith("/v1/messages")) { + response.writeHead(404, { "content-type": "application/json" }); + return response.end(JSON.stringify({ type: "error", error: { type: "not_found_error" } })); + } + let body: { stream?: boolean; model?: string; tools?: unknown[] } = {}; + try { + body = JSON.parse(raw); + } catch {} + const slow = raw.includes(SLOW_MARKER); + requests.push({ + at: performance.now(), + stream: body.stream === true, + // Title and branch-name jobs carry only their structured-output tool; the agent carries many. + agent: body.stream === true && (body.tools?.length ?? 0) > 1, + marker: /bench-run-(\d+)/.exec(raw)?.[0], + }); + const model = body.model ?? MODEL; + const id = `msg_bench_${requests.length}`; + if (!body.stream) { + response.writeHead(200, { "content-type": "application/json" }); + return response.end( + JSON.stringify({ + id, + type: "message", + role: "assistant", + model, + content: [{ type: "text", text: "Bench reply" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 2 }, + }), + ); + } + const event = (name: string, data: object) => + response.write(`event: ${name}\ndata: ${JSON.stringify({ type: name, ...data })}\n\n`); + response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + event("message_start", { + message: { + id, + type: "message", + role: "assistant", + model, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 100, output_tokens: 1 }, + }, + }); + event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }); + const words = slow ? 2_000 : 40; + for (let word = 0; word < words && !response.destroyed; word++) { + event("content_block_delta", { + index: 0, + delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` }, + }); + await sleep(slow ? 50 : 5); + } + event("content_block_stop", { index: 0 }); + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }); + event("message_stop", {}); + response.end(); + }); + }); + return new Promise<{ port: number; requests: ApiRequest[]; close: () => void }>((resolve) => + server.listen(0, "127.0.0.1", () => { + const address = server.address() as NodeNet.AddressInfo; + resolve({ + port: address.port, + requests, + close: () => { + server.closeAllConnections(); + server.close(); + }, + }); + }), + ); +} + +function freePort() { + return new Promise((resolve, reject) => { + const probe = NodeNet.createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const { port } = probe.address() as NodeNet.AddressInfo; + probe.close(() => resolve(port)); + }); + }); +} + +const commandOutput = (command: string, args: ReadonlyArray, cwd = root) => { + const result = NodeChildProcess.spawnSync(command, args, { cwd, encoding: "utf8" }); + return result.status === 0 ? result.stdout.trim() : null; +}; + +/** CPU seconds, context switches and RSS bytes of one process. */ +function sample(pid: number): { cpuSeconds: number; switches: number | null; rss: number } { + if (platform === "linux") { + const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]!.split(" "); + const ticks = Number(stat[11]) + Number(stat[12]); + let switches = 0; + for (const task of NodeFS.readdirSync(`/proc/${pid}/task`)) { + try { + const status = NodeFS.readFileSync(`/proc/${pid}/task/${task}/status`, "utf8"); + for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) + switches += Number(match[1]); + } catch {} + } + const status = NodeFS.readFileSync(`/proc/${pid}/status`, "utf8"); + return { + cpuSeconds: ticks / 100, + switches, + rss: Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0) * 1024, + }; + } + const [rss = "0", time = "0:0"] = ( + commandOutput("ps", ["-o", "rss=,time=", "-p", `${pid}`]) ?? "" + ) + .split(/\s+/) + .filter(Boolean); + const cpuSeconds = time + .split(":") + .map(Number) + .reduce((total, part) => total * 60 + part, 0); + return { cpuSeconds, switches: null, rss: Number(rss) * 1024 }; +} + +/** One Chrome DevTools Protocol session on the server's inspector. */ +async function inspect(webSocketUrl: string) { + const socket = new WebSocket(webSocketUrl); + await new Promise((resolve, reject) => { + socket.addEventListener("open", resolve, { once: true }); + socket.addEventListener("error", reject, { once: true }); + }); + let nextId = 0; + const pending = new Map void>(); + socket.addEventListener("message", (event) => { + const message = JSON.parse(String(event.data)) as { id?: number; result?: unknown }; + if (message.id !== undefined) pending.get(message.id)?.(message.result); + }); + const send = (method: string) => + new Promise((resolve) => { + const id = ++nextId; + pending.set(id, resolve); + socket.send(JSON.stringify({ id, method })); + }); + return { + heapAfterGc: async () => { + await send("HeapProfiler.collectGarbage"); + await send("HeapProfiler.collectGarbage"); + const { usedSize } = (await send("Runtime.getHeapUsage")) as { usedSize: number }; + return usedSize; + }, + close: () => socket.close(), + }; +} + +interface Environment { + readonly home: string; + readonly api: Awaited>; + readonly macPath: boolean; +} + +async function startServer(environment: Environment, name: string) { + const directory = NodeFS.mkdtempSync(NodePath.join(environment.home, `${name}-`)); + const project = NodePath.join(directory, "project"); + NodeFS.mkdirSync(project); + NodeFS.writeFileSync(NodePath.join(project, "README.md"), "# bench\n"); + for (const args of [ + ["init", "-q", "-b", "main"], + ["add", "."], + ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], + ]) { + NodeChildProcess.execFileSync("git", args, { cwd: project }); + } + const baseDir = NodePath.join(directory, "base"); + // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. + NodeFS.mkdirSync(NodePath.join(baseDir, "userdata"), { recursive: true }); + NodeFS.writeFileSync( + NodePath.join(baseDir, "userdata/settings.json"), + JSON.stringify({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), + ); + const env: NodeJS.ProcessEnv = { + ...process.env, + HOME: environment.home, + ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.api.port}`, + ANTHROPIC_API_KEY: "sk-bench", + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", + OTEL_SDK_DISABLED: "true", + T3CODE_DEV_SEED: "0", + }; + delete env.ANTHROPIC_AUTH_TOKEN; + delete env.T3CODE_HOME; + if (environment.macPath) delete env.XDG_RUNTIME_DIR; + const port = await freePort(); + const started = performance.now(); + const child = NodeChildProcess.spawn( + process.execPath, + [ + "--inspect=127.0.0.1:0", + "src/bin.ts", + "serve", + "--base-dir", + baseDir, + "--port", + `${port}`, + "--host", + "127.0.0.1", + project, + ], + { cwd: serverDir, env, stdio: ["ignore", "ignore", "pipe"] }, + ); + const pid = child.pid!; + let inspector = ""; + let stderr = ""; + child.stderr.setEncoding("utf8").on("data", (chunk: string) => { + stderr = (stderr + chunk).slice(-8_000); + inspector ||= /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(stderr)?.[0] ?? ""; + }); + let readyMs: number | undefined; + for (let attempt = 0; attempt < 600 && readyMs === undefined; attempt++) { + if (child.exitCode !== null) throw new Error(`server exited early:\n${stderr}`); + try { + await fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(1_000) }); + readyMs = Math.round(performance.now() - started); + } catch { + await sleep(100); + } + } + if (readyMs === undefined || !inspector) throw new Error(`server never answered:\n${stderr}`); + const devtools = await inspect(inspector); + const cli = (args: ReadonlyArray) => + new Promise<{ code: number | null; stdout: string }>((resolve) => { + const command = NodeChildProcess.spawn( + process.execPath, + ["src/bin.ts", ...args, "--base-dir", baseDir], + { cwd: serverDir, env, stdio: ["ignore", "pipe", "pipe"] }, + ); + let stdout = ""; + command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk)); + command.on("exit", (code) => resolve({ code, stdout })); + }); + const added = await cli(["project", "add", project]); + if (added.code !== 0) throw new Error(`project add failed: ${added.stdout}`); + + const measure = async (seconds: number): Promise => { + const first = sample(pid); + let rssPeak = first.rss; + const start = performance.now(); + while (performance.now() - start < seconds * 1_000) { + await sleep(1_000); + rssPeak = Math.max(rssPeak, sample(pid).rss); + } + const last = sample(pid); + const elapsed = (performance.now() - start) / 1_000; + return { + cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / elapsed) * 100), + wakeupsPerSec: + first.switches === null || last.switches === null + ? null + : round((last.switches - first.switches) / elapsed), + rssPeakMB: Math.round(rssPeak / 1e6), + heapAfterGcMB: round((await devtools.heapAfterGc()) / 1e6), + }; + }; + + const threadStart = (message: string, extra: ReadonlyArray = []) => + cli([ + "thread", + "start", + "--provider", + "claudeAgent", + "--model", + MODEL, + ...extra, + project, + message, + ]); + + const descendants = () => { + if (platform !== "linux") return []; + const children = new Map(); + for (const entry of NodeFS.readdirSync("/proc")) { + if (!/^\d+$/.test(entry)) continue; + try { + const ppid = Number( + NodeFS.readFileSync(`/proc/${entry}/stat`, "utf8").split(") ")[1]!.split(" ")[1], + ); + children.set(ppid, [...(children.get(ppid) ?? []), Number(entry)]); + } catch {} + } + const found: number[] = []; + const pending = [pid]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + for (const child of children.get(next) ?? []) { + found.push(child); + pending.push(child); + } + } + return found; + }; + + const stop = async () => { + devtools.close(); + const spawned = descendants(); + child.kill("SIGTERM"); + for (let attempt = 0; attempt < 100 && child.exitCode === null; attempt++) await sleep(100); + if (child.exitCode === null) child.kill("SIGKILL"); + for (const leftover of spawned) { + try { + process.kill(leftover, "SIGKILL"); + } catch {} + } + NodeFS.rmSync(directory, { recursive: true, force: true }); + }; + + return { readyMs, measure, threadStart, stop }; +} + +async function firstWord( + environment: Environment, + server: Awaited>, + runs: number, + worktree: boolean, +): Promise { + const toRequest: number[] = []; + const toDone: number[] = []; + for (let run = 0; run < runs; run++) { + const marker = `bench-run-${worktree ? 1000 + run : run}`; + const started = performance.now(); + const result = await server.threadStart(`Say hello. ${marker}`, [ + "--wait", + ...(worktree ? ["--worktree", "main"] : []), + ]); + const done = performance.now() - started; + if (result.code !== 0) throw new Error(`thread start failed: ${result.stdout}`); + const request = environment.api.requests.find( + (entry) => entry.agent && entry.marker === marker && entry.at >= started, + ); + if (!request) throw new Error(`the agent request for ${marker} never reached the fake API`); + toRequest.push(request.at - started); + toDone.push(done); + } + return { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; +} + +const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; + +export async function runOnce(options: { + macPath: boolean; + runs: number; + only: ReadonlyArray; +}): Promise { + const claude = commandOutput("claude", ["--version"]); + if (claude === null) throw new Error("The real `claude` CLI must be on PATH."); + if (options.macPath && platform !== "linux") throw new Error("--mac-path is Linux only."); + const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-server-metrics-")); + const api = await startFakeAnthropic(); + const environment: Environment = { home, api, macPath: options.macPath }; + const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); + const agentScope = + platform === "linux" && + !options.macPath && + !!process.env.XDG_RUNTIME_DIR && + commandOutput("sh", ["-c", "command -v systemd-run"]) !== null; + const result: { + -readonly [K in keyof ServerMetrics]: ServerMetrics[K]; + } = { + meta: { + platform: `${platform}-${architecture}`, + node: process.version, + claude, + commit: commandOutput("git", ["rev-parse", "--short=12", "HEAD"]), + macPath: options.macPath, + agentScope, + measuredAt: new Date().toISOString(), + }, + }; + try { + if (wanted("startup") || wanted("rest") || wanted("firstWord")) { + const server = await startServer(environment, "rest"); + try { + result.startup = { readyMs: server.readyMs }; + if (wanted("rest")) { + await sleep(15_000); + result.rest = await server.measure(30); + } + if (wanted("firstWord")) { + result.firstWord = { + inPlace: await firstWord(environment, server, options.runs, false), + worktree: await firstWord(environment, server, options.runs, true), + }; + } + } finally { + await server.stop(); + } + } + if (wanted("quiet")) { + const server = await startServer(environment, "quiet"); + try { + const answers = await Promise.all( + Array.from({ length: 20 }, (_, index) => + server.threadStart(`Say hello ${index}.`, ["--wait"]), + ), + ); + const failed = answers.filter((answer) => answer.code !== 0).length; + if (failed) throw new Error(`${failed} of 20 quiet threads failed`); + await sleep(20_000); + result.quiet = await server.measure(60); + } finally { + await server.stop(); + } + } + if (wanted("streaming")) { + const server = await startServer(environment, "streaming"); + try { + const started = await Promise.all( + Array.from({ length: 5 }, (_, index) => + server.threadStart(`Write a long answer ${index}. ${SLOW_MARKER}`), + ), + ); + if (started.some((answer) => answer.code !== 0)) throw new Error("streaming start failed"); + for (let attempt = 0; attempt < 300; attempt++) { + if (api.requests.filter((request) => request.agent && request.stream).length >= 5) break; + await sleep(100); + } + await sleep(5_000); + result.streaming = await server.measure(60); + } finally { + await server.stop(); + } + } + } finally { + api.close(); + NodeFS.rmSync(home, { recursive: true, force: true }); + } + return result; +} + +/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ +export function flatten(metrics: ServerMetrics): Map { + const values = new Map(); + const visit = (value: unknown, path: string) => { + if (typeof value === "number") values.set(path, value); + else if (value && typeof value === "object") { + for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); + } + }; + const { meta: _meta, ...measured } = metrics; + visit(measured, ""); + return values; +} + +function noiseFloor(metric: string) { + if (metric.endsWith("cpuPct")) return 1; + if (metric.endsWith("wakeupsPerSec")) return 20; + if (metric.endsWith("MB")) return 15; + return 300; +} + +export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { + const a = flatten(before); + const b = flatten(after); + const lines = [ + "### Server metrics (lower is better)", + "", + `before \`${before.meta.commit}\`, after \`${after.meta.commit}\`, ${after.meta.platform}${after.meta.macPath ? ", mac path" : ""}`, + "", + "| metric | before | after | change | |", + "| :-- | --: | --: | --: | :-- |", + ]; + const regressed: string[] = []; + for (const metric of new Set([...a.keys(), ...b.keys()])) { + const x = a.get(metric); + const y = b.get(metric); + if (x === undefined || y === undefined) { + lines.push(`| ${metric} | ${x ?? "–"} | ${y ?? "–"} | n/a | |`); + continue; + } + const delta = y - x; + const percent = x === 0 ? (y === 0 ? 0 : Infinity) : (delta / x) * 100; + const beyondFloor = Math.abs(delta) > noiseFloor(metric); + const verdict = + beyondFloor && percent > threshold + ? "worse" + : beyondFloor && percent < -threshold + ? "better" + : ""; + if (verdict === "worse") regressed.push(metric); + const shown = Number.isFinite(percent) + ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` + : "new"; + lines.push(`| ${metric} | ${x} | ${y} | ${shown} | ${verdict} |`); + } + return { table: lines.join("\n"), regressed }; +} + +function option(args: ReadonlyArray, name: string): string | undefined { + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; +} + +if (import.meta.main) { + const [command, ...args] = process.argv.slice(2); + if (command === "run") { + const only = (option(args, "--only") ?? "").split(",").filter(Boolean); + const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray).includes(name)); + if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`); + const metrics = await runOnce({ + macPath: args.includes("--mac-path"), + runs: Number(option(args, "--runs") ?? 5), + only, + }); + const json = JSON.stringify(metrics, null, 2); + const out = option(args, "--out"); + if (out) NodeFS.writeFileSync(out, json + "\n"); + else console.log(json); + } else if (command === "compare" && args[0] && args[1]) { + const read = (path: string) => JSON.parse(NodeFS.readFileSync(path, "utf8")) as ServerMetrics; + const { table, regressed } = compareMetrics( + read(args[0]), + read(args[1]), + Number(option(args, "--threshold") ?? 10), + ); + console.log(table); + if (regressed.length) { + console.error(`Worse: ${regressed.join(", ")}`); + process.exitCode = 1; + } + } else { + console.log(HELP); + if (command !== "--help" && command !== "-h" && command !== undefined) process.exitCode = 1; + } +} From ac5bd585c665d9643a682f673f778a2f08d73a60 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:55:08 -0800 Subject: [PATCH 02/10] feat(scripts): server metrics run on macOS and Windows, compare by interval, fit per-thread cost - Sampling works natively on Linux (/proc), macOS (ps, top's context switches) and Windows (Get-Process, thread context-switch counters); --no-agent-scope replaces --mac-path on Linux, which stays as an alias. - ab runs two checkouts alternately on one machine; --repeat repeats a run. compare flags a metric only when the 95% bootstrap interval of the median difference clears the threshold and the noise floor. - quiet measures 0, 5, 10 and 20 open threads and fits the cost per thread. - --soak reports heap and RSS slopes per hour and the constructors that grew. - The quiet and streaming windows save CPU and allocation profiles and list the top functions. Co-Authored-By: Claude Opus 5.5 --- docs/internals/performance-regressions.md | 29 +- scripts/server-metrics.test.ts | 66 +- scripts/server-metrics.ts | 796 +++++++++++++++++----- 3 files changed, 695 insertions(+), 196 deletions(-) diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index dbf54ce6dc47a..e67ff30a85e6a 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -99,15 +99,26 @@ machine refresh sends back an empty provider list. ## Server process metrics -`node scripts/server-metrics.ts run --out ` starts this checkout's server against throwaway state, a -fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and heap at -rest, with 20 quiet Claude threads and with 5 streaming, plus how long a new thread takes to reach -the API. `compare` exits 1 on a regression, so it can gate a release or a scheduled -run. Only the server process is measured. - -Run it with `--mac-path` on Linux too. macOS has no agent scope, so its servers take per-process -paths Linux servers with a systemd user manager never run. A one-second `ps -A` poll per Claude -session cost 0.1.11 about 18% of a core with 20 open threads on macOS and went unnoticed on Linux. +`node scripts/server-metrics.ts run --out ` starts a checkout's server against throwaway +state, a fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and +heap at rest, with quiet Claude threads and with 5 streaming, plus how long a new thread takes to +reach the API. Only the server process is measured. + +- Compare refs with `ab `, not with two files from different times. It + alternates the two on one machine, and `compare` flags a metric only when the bootstrap interval + of the median difference clears both the threshold and the noise floor. Single runs on a busy + machine differ by more than most regressions. +- Read per-thread cost from `scaling`, a fit over 5 to 20 open threads. It separates what each + open thread costs from the fixed cost of the server, which the absolute numbers mix. +- `--soak ` reports heap and RSS slopes in MB per hour and the constructors that grew. + A rising heap floor is a leak; a high but flat one is not. +- The quiet and streaming windows save a CPU and an allocation profile, so a regression comes with + the functions that cost it. + +Run it on macOS and Windows too, and on Linux with `--no-agent-scope`. Only Linux has agent +scopes, so other platforms take per-process paths a Linux server with a systemd user manager never +runs. A one-second `ps -A` poll per Claude session cost 0.1.11 about 18% of a core with 20 open +threads on macOS and went unnoticed on Linux. ## Event store and startup diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 515141f71de72..cd78cb9311bbe 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,12 +1,14 @@ import { describe, expect, it } from "vite-plus/test"; -import { compareMetrics, type ServerMetrics } from "./server-metrics.ts"; +import { compareMetrics, slope, type ServerMetrics } from "./server-metrics.ts"; -const metrics = (quiet: { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }) => +type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; +const quietRuns = (...runs: Quiet[]) => ({ - meta: { commit: "abc", platform: "linux-x64", macPath: true }, - quiet: { ...quiet, heapAfterGcMB: 200 }, + meta: { commit: "abc", platform: "linux-x64", noAgentScope: true }, + runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })), }) satisfies ServerMetrics; +const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; describe("compareMetrics", () => { it.each([ @@ -15,15 +17,57 @@ describe("compareMetrics", () => { ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, []], ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"]], ["an improvement", { cpuPct: 0.1, wakeupsPerSec: 7 }, []], - ])("%s", (_name, change, regressed) => { - const before = metrics({ cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }); - const after = metrics({ cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500, ...change }); - expect(compareMetrics(before, after).regressed).toEqual(regressed); + ])("one run each: %s", (_name, change, regressed) => { + expect(compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })).regressed).toEqual( + regressed, + ); }); it("does not treat a metric missing on one side as a regression", () => { - const before = metrics({ cpuPct: 0.3, wakeupsPerSec: null, rssPeakMB: 500 }); - const after = metrics({ cpuPct: 0.3, wakeupsPerSec: 9, rssPeakMB: 500 }); - expect(compareMetrics(before, after).regressed).toEqual([]); + const before = quietRuns({ ...base, wakeupsPerSec: null }); + expect(compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 9 })).regressed).toEqual([]); + }); + + it("flags repeated runs only when the whole interval clears the limit", () => { + const steady = quietRuns( + { ...base, cpuPct: 26.1 }, + { ...base, cpuPct: 27.4 }, + { ...base, cpuPct: 25.8 }, + ); + const fixed = quietRuns( + { ...base, cpuPct: 2.2 }, + { ...base, cpuPct: 2.5 }, + { ...base, cpuPct: 2.1 }, + ); + expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + // One noisy run on each side overlaps the other side's values. + const noisy = quietRuns( + { ...base, cpuPct: 2.2 }, + { ...base, cpuPct: 9 }, + { ...base, cpuPct: 2.4 }, + ); + expect(compareMetrics(fixed, noisy).regressed).toEqual([]); + }); + + it("reads a single-run file from before runs existed", () => { + const legacy = { meta: { commit: "old" }, quiet: { ...base, rssMB: 500, heapAfterGcMB: 200 } }; + const after = quietRuns({ ...base, cpuPct: 18.6 }); + expect(compareMetrics(legacy as unknown as ServerMetrics, after).regressed).toEqual([ + "quiet.cpuPct", + ]); + }); +}); + +describe("slope", () => { + it("fits the cost per thread", () => { + expect( + slope([ + [0, 175], + [5, 180], + [10, 185], + [20, 195], + ]), + ).toBeCloseTo(1); }); }); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 4ab85e1c4259b..9b1f145ef16d5 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalFetch:off globalDate:off - a standalone benchmark driver around one server process. +// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalFetch:off globalDate:off globalRandom:off - a standalone benchmark driver around one server process. import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeHttp from "node:http"; @@ -7,43 +7,53 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; const HELP = `Usage: - node scripts/server-metrics.ts run [--out ] [--mac-path] [--runs ] [--only ] + node scripts/server-metrics.ts run [--out ] [--checkout ] [--repeat ] [run options] + node scripts/server-metrics.ts ab [--rounds ] [--out-dir ] [run options] node scripts/server-metrics.ts compare [--threshold ] -run Starts this checkout's server (apps/server/src/bin.ts) against a temp base dir, a temp - HOME, a temp git project and a fake Anthropic Messages API, drives the real \`claude\` - CLI through it, and writes one JSON object of measurements. Each scenario gets a fresh - server. Takes about 6 minutes. +run Starts a checkout's server (default: this one) against a temp base dir, a temp HOME, a + temp git project and a fake Anthropic Messages API, drives the real \`claude\` CLI + through it, and writes one JSON object of measurements. Each scenario gets a fresh + server. A full run takes about 8 minutes. --repeat runs it k times into one file. +ab Runs two checkouts alternately (A B, then B A, ... for --rounds, default 3) on this + machine, writes a.json and b.json, prints the comparison and exits 1 on a regression. + Each checkout needs its dependencies installed; the server code comes from it, the + harness from this script, so an old release works too. +Scenarios (--only startup,rest,firstWord,quiet,streaming; soak runs only with --soak): startup spawn to the first HTTP answer, in ms. - rest 30 s idle: server CPU %, wakeups/s, RSS peak, heap after a forced GC. + rest 30 s idle: server CPU %, wakeups/s, RSS peak and after GC, heap after a forced GC. firstWord --runs (default 5) sequential \`thread start\` runs in the project folder and in a new worktree: ms until the fake API receives the agent's request, and until the reply finished. Median and p90. - quiet 20 Claude threads that answered and stay open, idle 20 s, then a 60 s window. + quiet Claude threads that answered and stay open, measured at --threads (default + 0,5,10,20) for 30 s each. \`quiet\` is the last point; \`scaling\` is the + least-squares cost per open thread (fitted from 1 thread up, since the first loads + the provider once): MB of heap and RSS, CPU points, wakeups/s. streaming 5 threads streaming a 2,000-word reply at 50 ms a word, 60 s window. + soak --soak (alone unless --only names more): 10 threads, a short turn to one of them every 30 s, heap after GC + and RSS every 2 minutes; reports MB/hour slopes and writes the constructors whose + heap grew most between a snapshot after warmup and one at the end. +After the quiet and streaming windows a separate 20 s window records a CPU profile and a +sampling allocation profile; the top functions go in the JSON, the full profiles next to --out. ---mac-path Linux only: starts the server without XDG_RUNTIME_DIR, so it has no agent scope and - takes the per-process path macOS always takes (apps/server/src/process/agentScope.ts). -Wakeups are voluntary plus involuntary context switches of the server's threads (Linux /proc); -they are null on macOS. Only the server process is measured, not the agent CLIs. +--no-agent-scope (alias --mac-path), Linux only: starts the server without XDG_RUNTIME_DIR, so +it has no agent scope and takes the per-process path macOS and Windows always take. +Wakeups: Linux sums the server's voluntary and involuntary context switches (/proc); macOS +uses \`top\`'s context-switch count; Windows sums its threads' context switches (CIM). +Only the server process is measured, not the agent CLIs. -compare Prints a markdown table of every metric (lower is better) and exits 1 when one got - worse by more than --threshold percent (default 10) and by more than its noise floor: - 1 point of CPU, 20 wakeups/s, 15 MB, 300 ms. With 5 runs a p90 is the - slowest run, so read a lone p90 change as noise unless the median moved too. +compare Prints a markdown table of every metric (lower is better). With two or more runs on each + side a metric is worse only when the 95% bootstrap interval of the median difference + lies above both --threshold percent (default 10) and its noise floor: 1 point of CPU, + 20 wakeups/s, 15 MB, 300 ms, 2 MB per thread, 0.2 CPU points per thread. With one run + on a side it compares the two values against the same limits. Exits 1 on a regression.`; -Comparing two refs needs both checkouts, since the server runs each tree's code: - node scripts/server-metrics.ts run --out ../main-server.json # on main - node scripts/server-metrics.ts run --out ../branch-server.json # on the branch - node scripts/server-metrics.ts compare ../main-server.json ../branch-server.json`; - -const root = NodePath.resolve(import.meta.dirname, ".."); +const harnessRoot = NodePath.resolve(import.meta.dirname, ".."); // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. const platform = NodeOS.platform(); // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. const architecture = NodeOS.arch(); -const serverDir = NodePath.join(root, "apps/server"); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; @@ -51,6 +61,7 @@ interface Window { readonly cpuPct: number; readonly wakeupsPerSec: number | null; readonly rssPeakMB: number; + readonly rssMB: number; readonly heapAfterGcMB: number; } interface Spread { @@ -61,17 +72,43 @@ interface FirstWord { readonly toRequestMs: Spread; readonly toDoneMs: Spread; } -export interface ServerMetrics { - readonly meta: Readonly>; +interface Scaling { + readonly heapMBPerThread: number; + readonly rssMBPerThread: number; + readonly cpuPctPerThread: number; + readonly wakeupsPerThread: number | null; + /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ + readonly points: ReadonlyArray>; +} +interface Soak { + readonly minutes: number; + readonly heapMBPerHour: number; + readonly rssMBPerHour: number; +} +/** One pass over the scenarios. */ +export interface Measured { readonly startup?: { readonly readyMs: number }; readonly rest?: Window; readonly firstWord?: { readonly inPlace: FirstWord; readonly worktree: FirstWord }; readonly quiet?: Window; + readonly scaling?: Scaling; readonly streaming?: Window; + readonly soak?: Soak; +} +interface Hotspot { + readonly frame: string; + readonly value: number; +} +export interface ServerMetrics { + readonly meta: Readonly>; + readonly runs: ReadonlyArray; + /** Top CPU self time (ms) and allocated bytes (MB) by function, from the last run. */ + readonly profiles?: Readonly>; + readonly soakHeapGrowth?: ReadonlyArray<{ constructor: string; count: number; MB: number }>; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -const round = (value: number) => Math.round(value * 10) / 10; +const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; function spread(values: ReadonlyArray): Spread { const sorted = values.toSorted((a, b) => a - b); @@ -79,6 +116,21 @@ function spread(values: ReadonlyArray): Spread { return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; } +/** Least-squares slope of y over x. */ +export function slope(points: ReadonlyArray) { + const n = points.length; + if (n < 2) return 0; + const mx = points.reduce((sum, [x]) => sum + x, 0) / n; + const my = points.reduce((sum, [, y]) => sum + y, 0) / n; + let numerator = 0; + let denominator = 0; + for (const [x, y] of points) { + numerator += (x - mx) * (y - my); + denominator += (x - mx) ** 2; + } + return denominator === 0 ? 0 : numerator / denominator; +} + interface ApiRequest { readonly at: number; readonly stream: boolean; @@ -190,31 +242,31 @@ function freePort() { }); } -const commandOutput = (command: string, args: ReadonlyArray, cwd = root) => { +const commandOutput = (command: string, args: ReadonlyArray, cwd = harnessRoot) => { const result = NodeChildProcess.spawnSync(command, args, { cwd, encoding: "utf8" }); return result.status === 0 ? result.stdout.trim() : null; }; +const powershell = (script: string) => + commandOutput("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); -/** CPU seconds, context switches and RSS bytes of one process. */ -function sample(pid: number): { cpuSeconds: number; switches: number | null; rss: number } { +/** CPU seconds and RSS bytes of one process. */ +function sample(pid: number): { cpuSeconds: number; rss: number } { if (platform === "linux") { const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]!.split(" "); - const ticks = Number(stat[11]) + Number(stat[12]); - let switches = 0; - for (const task of NodeFS.readdirSync(`/proc/${pid}/task`)) { - try { - const status = NodeFS.readFileSync(`/proc/${pid}/task/${task}/status`, "utf8"); - for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) - switches += Number(match[1]); - } catch {} - } const status = NodeFS.readFileSync(`/proc/${pid}/status`, "utf8"); return { - cpuSeconds: ticks / 100, - switches, + cpuSeconds: (Number(stat[11]) + Number(stat[12])) / 100, rss: Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0) * 1024, }; } + if (platform === "win32") { + const [cpu = "0", rss = "0"] = ( + powershell( + `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, + ) ?? "" + ).split(/\s+/); + return { cpuSeconds: Number(cpu), rss: Number(rss) }; + } const [rss = "0", time = "0:0"] = ( commandOutput("ps", ["-o", "rss=,time=", "-p", `${pid}`]) ?? "" ) @@ -224,7 +276,68 @@ function sample(pid: number): { cpuSeconds: number; switches: number | null; rss .split(":") .map(Number) .reduce((total, part) => total * 60 + part, 0); - return { cpuSeconds, switches: null, rss: Number(rss) * 1024 }; + return { cpuSeconds, rss: Number(rss) * 1024 }; +} + +/** Context switches of one process since it started, or null when this platform cannot tell. */ +function contextSwitches(pid: number): number | null { + if (platform === "linux") { + let switches = 0; + for (const task of NodeFS.readdirSync(`/proc/${pid}/task`)) { + try { + const status = NodeFS.readFileSync(`/proc/${pid}/task/${task}/status`, "utf8"); + for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) + switches += Number(match[1]); + } catch {} + } + return switches; + } + if (platform === "win32") { + const total = powershell( + `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, + ); + return total === null || total === "" ? null : Number(total); + } + if (platform === "darwin") { + const table = commandOutput("top", ["-l", "1", "-pid", `${pid}`, "-stats", "pid,csw"]); + const row = table + ?.split("\n") + .map((line) => line.trim().split(/\s+/)) + .find(([first]) => first === `${pid}`); + const value = Number(row?.[1]?.replace(/\+$/, "")); + return Number.isFinite(value) ? value : null; + } + return null; +} + +/** Every process below `pid`, read once. */ +function descendantsOf(pid: number): number[] { + const children = new Map(); + const add = (child: number, parent: number) => + children.set(parent, [...(children.get(parent) ?? []), child]); + if (platform === "linux") { + for (const entry of NodeFS.readdirSync("/proc")) { + if (!/^\d+$/.test(entry)) continue; + try { + const stat = NodeFS.readFileSync(`/proc/${entry}/stat`, "utf8").split(") ")[1]!.split(" "); + add(Number(entry), Number(stat[1])); + } catch {} + } + } else if (platform === "darwin") { + for (const line of (commandOutput("ps", ["-A", "-o", "pid=,ppid="]) ?? "").split("\n")) { + const [child, parent] = line.trim().split(/\s+/).map(Number); + if (child && parent) add(child, parent); + } + } else return []; + const found: number[] = []; + const pending = [pid]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + for (const child of children.get(next) ?? []) { + found.push(child); + pending.push(child); + } + } + return found; } /** One Chrome DevTools Protocol session on the server's inspector. */ @@ -236,15 +349,23 @@ async function inspect(webSocketUrl: string) { }); let nextId = 0; const pending = new Map void>(); + let chunks: string[] = []; socket.addEventListener("message", (event) => { - const message = JSON.parse(String(event.data)) as { id?: number; result?: unknown }; + const message = JSON.parse(String(event.data)) as { + id?: number; + result?: unknown; + method?: string; + params?: { chunk?: string }; + }; if (message.id !== undefined) pending.get(message.id)?.(message.result); + else if (message.method === "HeapProfiler.addHeapSnapshotChunk") + chunks.push(message.params?.chunk ?? ""); }); - const send = (method: string) => + const send = (method: string, params: object = {}) => new Promise((resolve) => { const id = ++nextId; pending.set(id, resolve); - socket.send(JSON.stringify({ id, method })); + socket.send(JSON.stringify({ id, method, params })); }); return { heapAfterGc: async () => { @@ -253,14 +374,117 @@ async function inspect(webSocketUrl: string) { const { usedSize } = (await send("Runtime.getHeapUsage")) as { usedSize: number }; return usedSize; }, + profile: async (seconds: number) => { + await send("Profiler.enable"); + await send("Profiler.setSamplingInterval", { interval: 1_000 }); + await send("Profiler.start"); + await send("HeapProfiler.startSampling", { + samplingInterval: 32_768, + includeObjectsCollectedByMajorGC: true, + includeObjectsCollectedByMinorGC: true, + }); + await sleep(seconds * 1_000); + const { profile: heap } = (await send("HeapProfiler.stopSampling")) as { profile: object }; + const { profile: cpu } = (await send("Profiler.stop")) as { profile: object }; + await send("Profiler.disable"); + return { cpu, heap }; + }, + snapshot: async () => { + chunks = []; + await send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); + const json = chunks.join(""); + chunks = []; + return json; + }, close: () => socket.close(), }; } +const shortUrl = (url: string) => + url + .replace(/^file:\/\//, "") + .split(/[\\/]/) + .slice(-3) + .join("/"); + +interface CpuProfile { + readonly nodes: ReadonlyArray<{ + id: number; + hitCount?: number; + callFrame: { functionName: string; url: string; lineNumber: number }; + }>; + readonly samples?: ReadonlyArray; + readonly startTime: number; + readonly endTime: number; +} +interface HeapProfileNode { + readonly callFrame: { functionName: string; url: string; lineNumber: number }; + readonly selfSize: number; + readonly children: ReadonlyArray; +} + +const frameName = (frame: { functionName: string; url: string; lineNumber: number }) => + `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); + +const top = (totals: Map, digits: number): Hotspot[] => + [...totals] + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([frame, value]) => ({ frame, value: round(value, digits) })); + +/** Top CPU self time in ms and allocated MB, by function. */ +export function summarizeProfiles(cpu: CpuProfile, heap: { head: HeapProfileNode }) { + const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); + const cpuTotals = new Map(); + for (const node of cpu.nodes) { + if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; + const name = frameName(node.callFrame); + cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); + } + const allocations = new Map(); + const visit = (node: HeapProfileNode) => { + const name = frameName(node.callFrame); + allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); + for (const child of node.children) visit(child); + }; + visit(heap.head); + return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; +} + +/** Self size by constructor from a V8 heap snapshot. */ +export function heapByConstructor(json: string) { + const snapshot = JSON.parse(json) as { + snapshot: { meta: { node_fields: string[]; node_types: [string[]] } }; + nodes: number[]; + strings: string[]; + }; + const fields = snapshot.snapshot.meta.node_fields; + const types = snapshot.snapshot.meta.node_types[0]; + const typeAt = fields.indexOf("type"); + const nameAt = fields.indexOf("name"); + const sizeAt = fields.indexOf("self_size"); + const totals = new Map(); + for (let index = 0; index < snapshot.nodes.length; index += fields.length) { + const type = types[snapshot.nodes[index + typeAt]!]!; + const name = + type === "object" + ? snapshot.strings[snapshot.nodes[index + nameAt]!]!.slice(0, 80) + : type === "closure" + ? `(closure) ${snapshot.strings[snapshot.nodes[index + nameAt]!]!.slice(0, 60)}` + : `(${type.replace(/^(concatenated|sliced) /, "")})`; + const entry = totals.get(name) ?? { count: 0, bytes: 0 }; + entry.count++; + entry.bytes += snapshot.nodes[index + sizeAt]!; + totals.set(name, entry); + } + return totals; +} + interface Environment { readonly home: string; readonly api: Awaited>; - readonly macPath: boolean; + readonly noAgentScope: boolean; + readonly serverDir: string; } async function startServer(environment: Environment, name: string) { @@ -285,6 +509,7 @@ async function startServer(environment: Environment, name: string) { const env: NodeJS.ProcessEnv = { ...process.env, HOME: environment.home, + USERPROFILE: environment.home, ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.api.port}`, ANTHROPIC_API_KEY: "sk-bench", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", @@ -293,7 +518,7 @@ async function startServer(environment: Environment, name: string) { }; delete env.ANTHROPIC_AUTH_TOKEN; delete env.T3CODE_HOME; - if (environment.macPath) delete env.XDG_RUNTIME_DIR; + if (environment.noAgentScope) delete env.XDG_RUNTIME_DIR; const port = await freePort(); const started = performance.now(); const child = NodeChildProcess.spawn( @@ -310,7 +535,7 @@ async function startServer(environment: Environment, name: string) { "127.0.0.1", project, ], - { cwd: serverDir, env, stdio: ["ignore", "ignore", "pipe"] }, + { cwd: environment.serverDir, env, stdio: ["ignore", "ignore", "pipe"] }, ); const pid = child.pid!; let inspector = ""; @@ -336,7 +561,7 @@ async function startServer(environment: Environment, name: string) { const command = NodeChildProcess.spawn( process.execPath, ["src/bin.ts", ...args, "--base-dir", baseDir], - { cwd: serverDir, env, stdio: ["ignore", "pipe", "pipe"] }, + { cwd: environment.serverDir, env, stdio: ["ignore", "pipe", "pipe"] }, ); let stdout = ""; command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk)); @@ -345,24 +570,30 @@ async function startServer(environment: Environment, name: string) { const added = await cli(["project", "add", project]); if (added.code !== 0) throw new Error(`project add failed: ${added.stdout}`); + // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. + const sampleEveryMs = platform === "win32" ? 5_000 : 1_000; const measure = async (seconds: number): Promise => { + const firstSwitches = contextSwitches(pid); const first = sample(pid); let rssPeak = first.rss; const start = performance.now(); while (performance.now() - start < seconds * 1_000) { - await sleep(1_000); + await sleep(sampleEveryMs); rssPeak = Math.max(rssPeak, sample(pid).rss); } const last = sample(pid); + const lastSwitches = contextSwitches(pid); const elapsed = (performance.now() - start) / 1_000; + const heap = await devtools.heapAfterGc(); return { cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / elapsed) * 100), wakeupsPerSec: - first.switches === null || last.switches === null + firstSwitches === null || lastSwitches === null ? null - : round((last.switches - first.switches) / elapsed), + : round((lastSwitches - firstSwitches) / elapsed), rssPeakMB: Math.round(rssPeak / 1e6), - heapAfterGcMB: round((await devtools.heapAfterGc()) / 1e6), + rssMB: Math.round(sample(pid).rss / 1e6), + heapAfterGcMB: round(heap / 1e6), }; }; @@ -378,34 +609,14 @@ async function startServer(environment: Environment, name: string) { project, message, ]); - - const descendants = () => { - if (platform !== "linux") return []; - const children = new Map(); - for (const entry of NodeFS.readdirSync("/proc")) { - if (!/^\d+$/.test(entry)) continue; - try { - const ppid = Number( - NodeFS.readFileSync(`/proc/${entry}/stat`, "utf8").split(") ")[1]!.split(" ")[1], - ); - children.set(ppid, [...(children.get(ppid) ?? []), Number(entry)]); - } catch {} - } - const found: number[] = []; - const pending = [pid]; - for (let next = pending.pop(); next !== undefined; next = pending.pop()) { - for (const child of children.get(next) ?? []) { - found.push(child); - pending.push(child); - } - } - return found; - }; + const threadSend = (threadId: string, message: string) => + cli(["thread", "send", "--wait", threadId, message]); const stop = async () => { devtools.close(); - const spawned = descendants(); - child.kill("SIGTERM"); + const spawned = descendantsOf(pid); + if (platform === "win32") commandOutput("taskkill", ["/PID", `${pid}`, "/T", "/F"]); + else child.kill("SIGTERM"); for (let attempt = 0; attempt < 100 && child.exitCode === null; attempt++) await sleep(100); if (child.exitCode === null) child.kill("SIGKILL"); for (const leftover of spawned) { @@ -413,15 +624,33 @@ async function startServer(environment: Environment, name: string) { process.kill(leftover, "SIGKILL"); } catch {} } - NodeFS.rmSync(directory, { recursive: true, force: true }); + for (let attempt = 0; attempt < 20; attempt++) { + try { + NodeFS.rmSync(directory, { recursive: true, force: true }); + break; + } catch { + // Windows keeps a file locked for a moment after its process exits. + await sleep(500); + } + } }; - return { readyMs, measure, threadStart, stop }; + return { + readyMs, + measure, + threadStart, + threadSend, + profile: devtools.profile, + snapshot: devtools.snapshot, + stop, + }; } +type Server = Awaited>; + async function firstWord( environment: Environment, - server: Awaited>, + server: Server, runs: number, worktree: boolean, ): Promise { @@ -446,76 +675,119 @@ async function firstWord( return { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; } +/** Starts threads that each answer once, and returns their ids. */ +async function openThreads(server: Server, from: number, count: number) { + const answers = await Promise.all( + Array.from({ length: count }, (_, index) => + server.threadStart(`Say hello ${from + index}.`, ["--wait"]), + ), + ); + const failed = answers.filter((answer) => answer.code !== 0).length; + if (failed) throw new Error(`${failed} of ${count} threads failed`); + return answers.map((answer) => /Thread (\S+)/.exec(answer.stdout)?.[1] ?? ""); +} + const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; -export async function runOnce(options: { - macPath: boolean; - runs: number; - only: ReadonlyArray; -}): Promise { - const claude = commandOutput("claude", ["--version"]); - if (claude === null) throw new Error("The real `claude` CLI must be on PATH."); - if (options.macPath && platform !== "linux") throw new Error("--mac-path is Linux only."); +interface RunOptions { + readonly checkout: string; + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: ReadonlyArray; + readonly only: ReadonlyArray; + readonly soakMinutes: number; + /** Where full CPU and allocation profiles go; none are written without it. */ + readonly profileDir: string | undefined; +} + +export async function runOnce(options: RunOptions) { const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-server-metrics-")); const api = await startFakeAnthropic(); - const environment: Environment = { home, api, macPath: options.macPath }; + const environment: Environment = { + home, + api, + noAgentScope: options.noAgentScope, + serverDir: NodePath.join(options.checkout, "apps/server"), + }; const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); - const agentScope = - platform === "linux" && - !options.macPath && - !!process.env.XDG_RUNTIME_DIR && - commandOutput("sh", ["-c", "command -v systemd-run"]) !== null; - const result: { - -readonly [K in keyof ServerMetrics]: ServerMetrics[K]; - } = { - meta: { - platform: `${platform}-${architecture}`, - node: process.version, - claude, - commit: commandOutput("git", ["rev-parse", "--short=12", "HEAD"]), - macPath: options.macPath, - agentScope, - measuredAt: new Date().toISOString(), - }, + const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; + const profiles: Record> = {}; + let soakHeapGrowth: ServerMetrics["soakHeapGrowth"]; + const profile = async (server: Server, name: string) => { + const { cpu, heap } = await server.profile(20); + profiles[name] = summarizeProfiles(cpu as CpuProfile, heap as { head: HeapProfileNode }); + if (options.profileDir) { + NodeFS.mkdirSync(options.profileDir, { recursive: true }); + NodeFS.writeFileSync( + NodePath.join(options.profileDir, `${name}.cpuprofile`), + JSON.stringify(cpu), + ); + NodeFS.writeFileSync( + NodePath.join(options.profileDir, `${name}.heapprofile`), + JSON.stringify(heap), + ); + } + }; + const withServer = async (name: string, body: (server: Server) => Promise) => { + const server = await startServer(environment, name); + try { + await body(server); + } finally { + await server.stop(); + } }; try { if (wanted("startup") || wanted("rest") || wanted("firstWord")) { - const server = await startServer(environment, "rest"); - try { - result.startup = { readyMs: server.readyMs }; + await withServer("rest", async (server) => { + measured.startup = { readyMs: server.readyMs }; if (wanted("rest")) { await sleep(15_000); - result.rest = await server.measure(30); + measured.rest = await server.measure(30); } if (wanted("firstWord")) { - result.firstWord = { + measured.firstWord = { inPlace: await firstWord(environment, server, options.runs, false), worktree: await firstWord(environment, server, options.runs, true), }; } - } finally { - await server.stop(); - } + }); } if (wanted("quiet")) { - const server = await startServer(environment, "quiet"); - try { - const answers = await Promise.all( - Array.from({ length: 20 }, (_, index) => - server.threadStart(`Say hello ${index}.`, ["--wait"]), - ), - ); - const failed = answers.filter((answer) => answer.code !== 0).length; - if (failed) throw new Error(`${failed} of 20 quiet threads failed`); - await sleep(20_000); - result.quiet = await server.measure(60); - } finally { - await server.stop(); - } + await withServer("quiet", async (server) => { + const points: Array<{ threads: number; window: Window }> = []; + let open = 0; + for (const threads of options.threads) { + if (threads > open) await openThreads(server, open, threads - open); + open = Math.max(open, threads); + await sleep(15_000); + points.push({ threads, window: await server.measure(30) }); + } + measured.quiet = points.at(-1)!.window; + // The first thread also loads the provider's modules once, so the fit leaves out 0 threads. + const withThreads = points.filter(({ threads }) => threads > 0); + const fitted = withThreads.length >= 2 ? withThreads : points; + const fit = (pick: (window: Window) => number) => + round(slope(fitted.map(({ threads, window }) => [threads, pick(window)])), 3); + measured.scaling = { + heapMBPerThread: fit((window) => window.heapAfterGcMB), + rssMBPerThread: fit((window) => window.rssMB), + cpuPctPerThread: fit((window) => window.cpuPct), + wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null) + ? fit((window) => window.wakeupsPerSec!) + : null, + points: points.map(({ threads, window }) => [ + threads, + window.cpuPct, + window.wakeupsPerSec, + window.rssMB, + window.heapAfterGcMB, + ]), + }; + await profile(server, "quiet"); + }); } if (wanted("streaming")) { - const server = await startServer(environment, "streaming"); - try { + await withServer("streaming", async (server) => { const started = await Promise.all( Array.from({ length: 5 }, (_, index) => server.threadStart(`Write a long answer ${index}. ${SLOW_MARKER}`), @@ -527,20 +799,108 @@ export async function runOnce(options: { await sleep(100); } await sleep(5_000); - result.streaming = await server.measure(60); - } finally { - await server.stop(); - } + measured.streaming = await server.measure(60); + await profile(server, "streaming"); + }); + } + if (options.soakMinutes > 0) { + await withServer("soak", async (server) => { + const threads = await openThreads(server, 0, 10); + await sleep(60_000); + // The snapshot inflates RSS once, so the slopes start after it. + const before = heapByConstructor(await server.snapshot()); + const samples: Array<{ hours: number; window: Window }> = []; + const start = performance.now(); + let nextSample = 0; + for (let turn = 0; performance.now() - start < options.soakMinutes * 60_000; turn++) { + const elapsed = performance.now() - start; + if (elapsed >= nextSample) { + samples.push({ hours: elapsed / 3_600_000, window: await server.measure(5) }); + nextSample += 120_000; + } + const threadId = threads[Math.floor(Math.random() * threads.length)]!; + await server.threadSend(threadId, `Short reply ${turn}.`); + await sleep(Math.max(0, start + (turn + 1) * 30_000 - performance.now())); + } + samples.push({ + hours: (performance.now() - start) / 3_600_000, + window: await server.measure(5), + }); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: round( + slope(samples.map(({ hours, window }) => [hours, window.heapAfterGcMB])), + ), + rssMBPerHour: round(slope(samples.map(({ hours, window }) => [hours, window.rssMB]))), + }; + const after = heapByConstructor(await server.snapshot()); + soakHeapGrowth = [...after] + .map(([name, { count, bytes }]) => ({ + constructor: name, + count: count - (before.get(name)?.count ?? 0), + MB: round((bytes - (before.get(name)?.bytes ?? 0)) / 1e6, 2), + })) + .toSorted((a, b) => b.MB - a.MB) + .slice(0, 25); + }); } } finally { api.close(); NodeFS.rmSync(home, { recursive: true, force: true }); } - return result; + return { measured: measured as Measured, profiles, soakHeapGrowth }; +} + +function machineLoad() { + if (platform === "win32") + return powershell( + "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average", + ); + return NodeOS.loadavg() + .map((value) => value.toFixed(2)) + .join(" "); +} + +function metaFor(options: RunOptions) { + const claude = commandOutput("claude", ["--version"]); + if (claude === null) throw new Error("The real `claude` CLI must be on PATH."); + if (options.noAgentScope && platform !== "linux") + throw new Error("--no-agent-scope is Linux only; other platforms never have an agent scope."); + return { + platform: `${platform}-${architecture}`, + cpus: NodeOS.cpus().length, + node: process.version, + claude, + commit: commandOutput("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), + noAgentScope: options.noAgentScope, + agentScope: + platform === "linux" && + !options.noAgentScope && + !!process.env.XDG_RUNTIME_DIR && + commandOutput("sh", ["-c", "command -v systemd-run"]) !== null, + loadBefore: machineLoad(), + measuredAt: new Date().toISOString(), + }; +} + +async function runMany(options: RunOptions, repeat: number): Promise { + const meta = metaFor(options); + const runs: Measured[] = []; + let last: Awaited> | undefined; + for (let index = 0; index < repeat; index++) { + last = await runOnce(options); + runs.push(last.measured); + } + return { + meta: { ...meta, loadAfter: machineLoad() }, + runs, + ...(last ? { profiles: last.profiles } : {}), + ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + }; } /** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ -export function flatten(metrics: ServerMetrics): Map { +export function flatten(measured: Measured): Map { const values = new Map(); const visit = (value: unknown, path: string) => { if (typeof value === "number") values.set(path, value); @@ -548,53 +908,96 @@ export function flatten(metrics: ServerMetrics): Map { for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); } }; - const { meta: _meta, ...measured } = metrics; visit(measured, ""); return values; } function noiseFloor(metric: string) { + if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; + if (metric.startsWith("soak.")) return 20; if (metric.endsWith("cpuPct")) return 1; if (metric.endsWith("wakeupsPerSec")) return 20; if (metric.endsWith("MB")) return 15; return 300; } +const median = (values: ReadonlyArray) => { + const sorted = values.toSorted((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +}; + +/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ +export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyArray) { + let seed = 0x5eed; + const random = () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; + const resample = (values: ReadonlyArray) => + median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); + const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( + (x, y) => x - y, + ); + return [differences[49]!, differences[1_949]!] as const; +} + +/** Old single-run files hold the scenarios at the top level. */ +const runsOf = (metrics: ServerMetrics | (Measured & { meta: ServerMetrics["meta"] })) => + "runs" in metrics && Array.isArray(metrics.runs) + ? metrics.runs + : [Object.fromEntries(Object.entries(metrics).filter(([key]) => key !== "meta")) as Measured]; + export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const a = flatten(before); - const b = flatten(after); + const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of runsOf(metrics)) { + for (const [metric, value] of flatten(run)) + values.set(metric, [...(values.get(metric) ?? []), value]); + } + return values; + }; + const a = collect(before); + const b = collect(after); const lines = [ "### Server metrics (lower is better)", "", - `before \`${before.meta.commit}\`, after \`${after.meta.commit}\`, ${after.meta.platform}${after.meta.macPath ? ", mac path" : ""}`, + `before \`${before.meta.commit}\` (${runsOf(before).length} runs), after \`${after.meta.commit}\` (${runsOf(after).length} runs), ${after.meta.platform}${after.meta.noAgentScope || after.meta.macPath ? ", no agent scope" : ""}`, "", - "| metric | before | after | change | |", - "| :-- | --: | --: | --: | :-- |", + "| metric | before | after | change | 95% interval | |", + "| :-- | --: | --: | --: | --: | :-- |", ]; const regressed: string[] = []; + const improved: string[] = []; for (const metric of new Set([...a.keys(), ...b.keys()])) { + if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; const x = a.get(metric); const y = b.get(metric); - if (x === undefined || y === undefined) { - lines.push(`| ${metric} | ${x ?? "–"} | ${y ?? "–"} | n/a | |`); + if (!x || !y) { + lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); continue; } - const delta = y - x; - const percent = x === 0 ? (y === 0 ? 0 : Infinity) : (delta / x) * 100; - const beyondFloor = Math.abs(delta) > noiseFloor(metric); - const verdict = - beyondFloor && percent > threshold - ? "worse" - : beyondFloor && percent < -threshold - ? "better" - : ""; + const mx = median(x); + const my = median(y); + // A change counts only past both the relative threshold and the absolute noise floor. + const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const [low, high] = + x.length > 1 && y.length > 1 ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; + const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; if (verdict === "worse") regressed.push(metric); + if (verdict === "better") improved.push(metric); + const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; const shown = Number.isFinite(percent) ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` : "new"; - lines.push(`| ${metric} | ${x} | ${y} | ${shown} | ${verdict} |`); + const interval = x.length > 1 && y.length > 1 ? `${round(low, 2)} to ${round(high, 2)}` : ""; + lines.push( + `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, + ); } - return { table: lines.join("\n"), regressed }; + return { table: lines.join("\n"), regressed, improved }; } function option(args: ReadonlyArray, name: string): string | undefined { @@ -602,33 +1005,74 @@ function option(args: ReadonlyArray, name: string): string | undefined { return index === -1 ? undefined : args[index + 1]; } +function runOptions(args: ReadonlyArray, checkout: string): RunOptions { + const only = (option(args, "--only") ?? "").split(",").filter(Boolean); + const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray).includes(name)); + if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`); + const threads = (option(args, "--threads") ?? "0,5,10,20").split(",").map(Number); + if (threads.some((count) => !Number.isInteger(count) || count < 0)) + throw new Error("--threads takes counts such as 0,5,10,20"); + return { + checkout: NodePath.resolve(checkout), + noAgentScope: args.includes("--no-agent-scope") || args.includes("--mac-path"), + runs: Number(option(args, "--runs") ?? 5), + threads, + only: option(args, "--soak") && !option(args, "--only") ? ["none"] : only, + soakMinutes: Number(option(args, "--soak") ?? 0), + profileDir: undefined, + }; +} + +const write = (path: string | undefined, metrics: ServerMetrics) => { + const json = JSON.stringify(metrics, null, 2); + if (path) NodeFS.writeFileSync(path, json + "\n"); + else console.log(json); +}; + +const printComparison = (before: ServerMetrics, after: ServerMetrics, threshold: number) => { + const { table, regressed, improved } = compareMetrics(before, after, threshold); + console.log(table); + if (improved.length) console.error(`Better: ${improved.join(", ")}`); + if (regressed.length) { + console.error(`Worse: ${regressed.join(", ")}`); + process.exitCode = 1; + } +}; + if (import.meta.main) { const [command, ...args] = process.argv.slice(2); + const threshold = Number(option(args, "--threshold") ?? 10); if (command === "run") { - const only = (option(args, "--only") ?? "").split(",").filter(Boolean); - const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray).includes(name)); - if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`); - const metrics = await runOnce({ - macPath: args.includes("--mac-path"), - runs: Number(option(args, "--runs") ?? 5), - only, - }); - const json = JSON.stringify(metrics, null, 2); const out = option(args, "--out"); - if (out) NodeFS.writeFileSync(out, json + "\n"); - else console.log(json); + const options = { + ...runOptions(args, option(args, "--checkout") ?? harnessRoot), + profileDir: out ? out.replace(/\.json$/, "") + "-profiles" : undefined, + }; + write(out, await runMany(options, Number(option(args, "--repeat") ?? 1))); + } else if (command === "ab" && args[0] && args[1] && !args[0].startsWith("--")) { + const outDir = NodePath.resolve(option(args, "--out-dir") ?? "server-metrics-ab"); + NodeFS.mkdirSync(outDir, { recursive: true }); + const sides = [args[0], args[1]].map((checkout) => runOptions(args, checkout)); + const metas = sides.map((side) => metaFor(side)); + const runs: [Measured[], Measured[]] = [[], []]; + const rounds = Number(option(args, "--rounds") ?? 3); + for (let round = 0; round < rounds; round++) { + // A B, then B A, so a drift in machine load lands on both sides. + for (const side of round % 2 === 0 ? [0, 1] : [1, 0]) { + console.error(`round ${round + 1}/${rounds}: ${side === 0 ? "A" : "B"}`); + runs[side]!.push((await runOnce(sides[side]!)).measured); + } + } + const [before, after] = [0, 1].map((side) => ({ + meta: { ...metas[side]!, loadAfter: machineLoad() }, + runs: runs[side]!, + })); + write(NodePath.join(outDir, "a.json"), before!); + write(NodePath.join(outDir, "b.json"), after!); + printComparison(before!, after!, threshold); } else if (command === "compare" && args[0] && args[1]) { const read = (path: string) => JSON.parse(NodeFS.readFileSync(path, "utf8")) as ServerMetrics; - const { table, regressed } = compareMetrics( - read(args[0]), - read(args[1]), - Number(option(args, "--threshold") ?? 10), - ); - console.log(table); - if (regressed.length) { - console.error(`Worse: ${regressed.join(", ")}`); - process.exitCode = 1; - } + printComparison(read(args[0]), read(args[1]), threshold); } else { console.log(HELP); if (command !== "--help" && command !== "-h" && command !== undefined) process.exitCode = 1; From 7a0569df49c64e3fc60f405491a2e8a23efacba3 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:39:15 -0800 Subject: [PATCH 03/10] refactor(scripts): server metrics runs on Effect The script now follows the repo's other scripts (prove-scenario.ts): effect/cli commands (run, ab, compare) under NodeRuntime.runMain, with FileSystem, Path, ChildProcessSpawner, HttpServer for the fake API, HttpClient, Socket for the inspector, Schema for the result files and profiles, and Clock for timing. The result schema, comparison and statistics live in server-metrics-report.ts, which the tests import. Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 297 ++++++ scripts/server-metrics.test.ts | 10 +- scripts/server-metrics.ts | 1661 +++++++++++++++--------------- 3 files changed, 1119 insertions(+), 849 deletions(-) create mode 100644 scripts/server-metrics-report.ts diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts new file mode 100644 index 0000000000000..97092191ecbf2 --- /dev/null +++ b/scripts/server-metrics-report.ts @@ -0,0 +1,297 @@ +// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare. +import * as Schema from "effect/Schema"; + +const Window = Schema.Struct({ + cpuPct: Schema.Number, + wakeupsPerSec: Schema.NullOr(Schema.Number), + rssPeakMB: Schema.Number, + rssMB: Schema.Number, + heapAfterGcMB: Schema.Number, +}); +export type Window = typeof Window.Type; +const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number }); +const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread }); +export type FirstWord = typeof FirstWord.Type; +const Scaling = Schema.Struct({ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + wakeupsPerThread: Schema.NullOr(Schema.Number), + /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ + points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))), +}); +const Soak = Schema.Struct({ + minutes: Schema.Number, + heapMBPerHour: Schema.Number, + rssMBPerHour: Schema.Number, +}); + +/** One pass over the scenarios. */ +export const Measured = Schema.Struct({ + startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), + rest: Schema.optional(Window), + firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), + quiet: Schema.optional(Window), + scaling: Schema.optional(Scaling), + streaming: Schema.optional(Window), + soak: Schema.optional(Soak), +}); +export type Measured = typeof Measured.Type; + +const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number }); +export type Hotspot = typeof Hotspot.Type; +const ProfileSummary = Schema.Struct({ + cpuMs: Schema.Array(Hotspot), + allocatedMB: Schema.Array(Hotspot), +}); +export type ProfileSummary = typeof ProfileSummary.Type; +export const HeapGrowth = Schema.Struct({ + constructor: Schema.String, + count: Schema.Number, + MB: Schema.Number, +}); + +export const ServerMetrics = Schema.Struct({ + meta: Schema.Record( + Schema.String, + Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), + ), + runs: Schema.Array(Measured), + /** Top CPU self time (ms) and allocated MB by function, from the last run. */ + profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), + soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), +}); +export type ServerMetrics = typeof ServerMetrics.Type; + +export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; + +export function spread(values: ReadonlyArray) { + const sorted = values.toSorted((a, b) => a - b); + const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; + return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; +} + +/** Least-squares slope of y over x. */ +export function slope(points: ReadonlyArray) { + const n = points.length; + if (n < 2) return 0; + const mx = points.reduce((sum, [x]) => sum + x, 0) / n; + const my = points.reduce((sum, [, y]) => sum + y, 0) / n; + let numerator = 0; + let denominator = 0; + for (const [x, y] of points) { + numerator += (x - mx) * (y - my); + denominator += (x - mx) ** 2; + } + return denominator === 0 ? 0 : numerator / denominator; +} + +/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ +export function flatten(measured: Measured): Map { + const values = new Map(); + const visit = (value: unknown, path: string) => { + if (typeof value === "number") values.set(path, value); + else if (value && typeof value === "object") { + for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); + } + }; + visit(measured, ""); + return values; +} + +function noiseFloor(metric: string) { + if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; + if (metric.startsWith("soak.")) return 20; + if (metric.endsWith("cpuPct")) return 1; + if (metric.endsWith("wakeupsPerSec")) return 20; + if (metric.endsWith("MB")) return 15; + return 300; +} + +const median = (values: ReadonlyArray) => { + const sorted = values.toSorted((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +}; + +/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ +export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyArray) { + let seed = 0x5eed; + const random = () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; + const resample = (values: ReadonlyArray) => + median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); + const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( + (x, y) => x - y, + ); + return [differences[49]!, differences[1_949]!] as const; +} + +export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { + const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); + } + } + return values; + }; + const a = collect(before); + const b = collect(after); + const lines = [ + "### Server metrics (lower is better)", + "", + `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, + "", + "| metric | before | after | change | 95% interval | |", + "| :-- | --: | --: | --: | --: | :-- |", + ]; + const regressed: string[] = []; + const improved: string[] = []; + for (const metric of new Set([...a.keys(), ...b.keys()])) { + if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; + const x = a.get(metric); + const y = b.get(metric); + if (!x || !y) { + lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); + continue; + } + const mx = median(x); + const my = median(y); + // A change counts only past both the relative threshold and the absolute noise floor. + const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const repeated = x.length > 1 && y.length > 1; + const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; + const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; + if (verdict === "worse") regressed.push(metric); + if (verdict === "better") improved.push(metric); + const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; + const shown = Number.isFinite(percent) + ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` + : "new"; + const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : ""; + lines.push( + `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, + ); + } + return { table: lines.join("\n"), regressed, improved }; +} + +const CallFrame = Schema.Struct({ + functionName: Schema.String, + url: Schema.String, + lineNumber: Schema.Number, +}); +type CallFrame = typeof CallFrame.Type; +export const CpuProfile = Schema.Struct({ + nodes: Schema.Array( + Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }), + ), + samples: Schema.optional(Schema.Array(Schema.Number)), + startTime: Schema.Number, + endTime: Schema.Number, +}); +interface HeapProfileNode { + readonly callFrame: CallFrame; + readonly selfSize: number; + readonly children: ReadonlyArray; +} +const HeapProfileNode: Schema.Codec = Schema.Struct({ + callFrame: CallFrame, + selfSize: Schema.Number, + children: Schema.Array(Schema.suspend(() => HeapProfileNode)), +}); +export const HeapProfile = Schema.Struct({ head: HeapProfileNode }); + +const shortUrl = (url: string) => + url + .replace(/^file:\/\//, "") + .split(/[\\/]/) + .slice(-3) + .join("/"); +const frameName = (frame: CallFrame) => + `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); +const top = (totals: Map, digits: number): Hotspot[] => + [...totals] + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([frame, value]) => ({ frame, value: round(value, digits) })); + +/** Top CPU self time in ms and allocated MB, by function. */ +export function summarizeProfiles( + cpu: typeof CpuProfile.Type, + heap: typeof HeapProfile.Type, +): ProfileSummary { + const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); + const cpuTotals = new Map(); + for (const node of cpu.nodes) { + if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; + const name = frameName(node.callFrame); + cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); + } + const allocations = new Map(); + const visit = (node: HeapProfileNode) => { + const name = frameName(node.callFrame); + allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); + for (const child of node.children) visit(child); + }; + visit(heap.head); + return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; +} + +export const HeapSnapshot = Schema.Struct({ + snapshot: Schema.Struct({ + meta: Schema.Struct({ + node_fields: Schema.Array(Schema.String), + node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + }), + }), + nodes: Schema.Array(Schema.Number), + strings: Schema.Array(Schema.String), +}); + +/** Self size by constructor from a V8 heap snapshot. */ +export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { + const fields = snapshot.snapshot.meta.node_fields; + const typeNames = snapshot.snapshot.meta.node_types[0]; + const types = Array.isArray(typeNames) ? typeNames : []; + const typeAt = fields.indexOf("type"); + const nameAt = fields.indexOf("name"); + const sizeAt = fields.indexOf("self_size"); + const totals = new Map(); + for (let index = 0; index < snapshot.nodes.length; index += fields.length) { + const type = types[snapshot.nodes[index + typeAt]!] ?? "?"; + const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? ""; + const name = + type === "object" + ? label.slice(0, 80) + : type === "closure" + ? `(closure) ${label.slice(0, 60)}` + : `(${type.replace(/^(concatenated|sliced) /, "")})`; + const entry = totals.get(name) ?? { count: 0, bytes: 0 }; + entry.count++; + entry.bytes += snapshot.nodes[index + sizeAt]!; + totals.set(name, entry); + } + return totals; +} + +/** The constructors whose heap grew most from one snapshot to the next. */ +export function heapGrowth( + before: ReturnType, + after: ReturnType, +) { + return [...after] + .map(([name, { count, bytes }]) => ({ + constructor: name, + count: count - (before.get(name)?.count ?? 0), + MB: round((bytes - (before.get(name)?.bytes ?? 0)) / 1e6, 2), + })) + .toSorted((a, b) => b.MB - a.MB) + .slice(0, 25); +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index cd78cb9311bbe..dd704c5eb269d 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { compareMetrics, slope, type ServerMetrics } from "./server-metrics.ts"; +import { compareMetrics, slope, type ServerMetrics } from "./server-metrics-report.ts"; type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; const quietRuns = (...runs: Quiet[]) => @@ -49,14 +49,6 @@ describe("compareMetrics", () => { ); expect(compareMetrics(fixed, noisy).regressed).toEqual([]); }); - - it("reads a single-run file from before runs existed", () => { - const legacy = { meta: { commit: "old" }, quiet: { ...base, rssMB: 500, heapAfterGcMB: 200 } }; - const after = quietRuns({ ...base, cpuPct: 18.6 }); - expect(compareMetrics(legacy as unknown as ServerMetrics, after).regressed).toEqual([ - "quiet.cpuPct", - ]); - }); }); describe("slope", () => { diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 9b1f145ef16d5..2c3c6f48e3ef3 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1,191 +1,150 @@ -// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalFetch:off globalDate:off globalRandom:off - a standalone benchmark driver around one server process. -import * as NodeChildProcess from "node:child_process"; -import * as NodeFS from "node:fs"; +#!/usr/bin/env node +// Measures a checkout's server process (CPU, wakeups, memory, time to the API) against a fake +// Anthropic API and the real `claude` CLI. See docs/internals/performance-regressions.md. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http server. import * as NodeHttp from "node:http"; -import * as NodeNet from "node:net"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -const HELP = `Usage: - node scripts/server-metrics.ts run [--out ] [--checkout ] [--repeat ] [run options] - node scripts/server-metrics.ts ab [--rounds ] [--out-dir ] [run options] - node scripts/server-metrics.ts compare [--threshold ] +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Random from "effect/Random"; +import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Argument, Command, Flag } from "effect/cli"; +import { HttpClient, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as Socket from "effect/socket/Socket"; -run Starts a checkout's server (default: this one) against a temp base dir, a temp HOME, a - temp git project and a fake Anthropic Messages API, drives the real \`claude\` CLI - through it, and writes one JSON object of measurements. Each scenario gets a fresh - server. A full run takes about 8 minutes. --repeat runs it k times into one file. -ab Runs two checkouts alternately (A B, then B A, ... for --rounds, default 3) on this - machine, writes a.json and b.json, prints the comparison and exits 1 on a regression. - Each checkout needs its dependencies installed; the server code comes from it, the - harness from this script, so an old release works too. +import { run } from "./scenarios/shell.ts"; +import { + compareMetrics, + CpuProfile, + HeapProfile, + HeapSnapshot, + heapByConstructor, + heapGrowth, + round, + ServerMetrics, + slope, + spread, + summarizeProfiles, + type FirstWord, + type Measured, + type ProfileSummary, + type Window, +} from "./server-metrics-report.ts"; -Scenarios (--only startup,rest,firstWord,quiet,streaming; soak runs only with --soak): - startup spawn to the first HTTP answer, in ms. - rest 30 s idle: server CPU %, wakeups/s, RSS peak and after GC, heap after a forced GC. - firstWord --runs (default 5) sequential \`thread start\` runs in the project folder and in a - new worktree: ms until the fake API receives the agent's request, and until the - reply finished. Median and p90. - quiet Claude threads that answered and stay open, measured at --threads (default - 0,5,10,20) for 30 s each. \`quiet\` is the last point; \`scaling\` is the - least-squares cost per open thread (fitted from 1 thread up, since the first loads - the provider once): MB of heap and RSS, CPU points, wakeups/s. - streaming 5 threads streaming a 2,000-word reply at 50 ms a word, 60 s window. - soak --soak (alone unless --only names more): 10 threads, a short turn to one of them every 30 s, heap after GC - and RSS every 2 minutes; reports MB/hour slopes and writes the constructors whose - heap grew most between a snapshot after warmup and one at the end. -After the quiet and streaming windows a separate 20 s window records a CPU profile and a -sampling allocation profile; the top functions go in the JSON, the full profiles next to --out. - ---no-agent-scope (alias --mac-path), Linux only: starts the server without XDG_RUNTIME_DIR, so -it has no agent scope and takes the per-process path macOS and Windows always take. -Wakeups: Linux sums the server's voluntary and involuntary context switches (/proc); macOS -uses \`top\`'s context-switch count; Windows sums its threads' context switches (CIM). -Only the server process is measured, not the agent CLIs. - -compare Prints a markdown table of every metric (lower is better). With two or more runs on each - side a metric is worse only when the 95% bootstrap interval of the median difference - lies above both --threshold percent (default 10) and its noise floor: 1 point of CPU, - 20 wakeups/s, 15 MB, 300 ms, 2 MB per thread, 0.2 CPU points per thread. With one run - on a side it compares the two values against the same limits. Exits 1 on a regression.`; - -const harnessRoot = NodePath.resolve(import.meta.dirname, ".."); -// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. -const platform = NodeOS.platform(); -// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone Node tooling has no Effect runtime. -const architecture = NodeOS.arch(); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; -interface Window { - readonly cpuPct: number; - readonly wakeupsPerSec: number | null; - readonly rssPeakMB: number; - readonly rssMB: number; - readonly heapAfterGcMB: number; -} -interface Spread { - readonly median: number; - readonly p90: number; -} -interface FirstWord { - readonly toRequestMs: Spread; - readonly toDoneMs: Spread; -} -interface Scaling { - readonly heapMBPerThread: number; - readonly rssMBPerThread: number; - readonly cpuPctPerThread: number; - readonly wakeupsPerThread: number | null; - /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ - readonly points: ReadonlyArray>; -} -interface Soak { - readonly minutes: number; - readonly heapMBPerHour: number; - readonly rssMBPerHour: number; -} -/** One pass over the scenarios. */ -export interface Measured { - readonly startup?: { readonly readyMs: number }; - readonly rest?: Window; - readonly firstWord?: { readonly inPlace: FirstWord; readonly worktree: FirstWord }; - readonly quiet?: Window; - readonly scaling?: Scaling; - readonly streaming?: Window; - readonly soak?: Soak; -} -interface Hotspot { - readonly frame: string; - readonly value: number; -} -export interface ServerMetrics { - readonly meta: Readonly>; - readonly runs: ReadonlyArray; - /** Top CPU self time (ms) and allocated bytes (MB) by function, from the last run. */ - readonly profiles?: Readonly>; - readonly soakHeapGrowth?: ReadonlyArray<{ constructor: string; count: number; MB: number }>; -} +export class MetricsError extends Schema.TaggedError()("MetricsError", { + message: Schema.String, +}) {} -const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); -const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeJson = (schema: S) => + Schema.decodeUnknownEffect(Schema.fromJsonString(schema)); +const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(ServerMetrics)); -function spread(values: ReadonlyArray): Spread { - const sorted = values.toSorted((a, b) => a - b); - const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; - return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; -} +/** What a command printed, or none when it is missing or failed. */ +const output = (program: string, args: ReadonlyArray, cwd?: string) => + run(program, args, cwd === undefined ? {} : { cwd }).pipe( + Effect.map(({ stdout }) => stdout.trim()), + Effect.option, + ); +const powershell = (script: string) => + output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); -/** Least-squares slope of y over x. */ -export function slope(points: ReadonlyArray) { - const n = points.length; - if (n < 2) return 0; - const mx = points.reduce((sum, [x]) => sum + x, 0) / n; - const my = points.reduce((sum, [, y]) => sum + y, 0) / n; - let numerator = 0; - let denominator = 0; - for (const [x, y] of points) { - numerator += (x - mx) * (y - my); - denominator += (x - mx) ** 2; - } - return denominator === 0 ? 0 : numerator / denominator; -} +const httpServerOn = (port: number) => + NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" }); interface ApiRequest { readonly at: number; - readonly stream: boolean; readonly agent: boolean; + readonly stream: boolean; readonly marker: string | undefined; } +const MessagesRequest = Schema.Struct({ + stream: Schema.optional(Schema.Boolean), + model: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Array(Schema.Unknown)), +}); + /** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ -function startFakeAnthropic() { +const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { const requests: ApiRequest[] = []; - const server = NodeHttp.createServer((request, response) => { - let raw = ""; - request.on("data", (chunk: Buffer) => (raw += chunk)); - request.on("end", async () => { - const url = request.url ?? ""; - if (url.includes("count_tokens")) { - response.writeHead(200, { "content-type": "application/json" }); - return response.end(JSON.stringify({ input_tokens: 100 })); - } - if (!url.startsWith("/v1/messages")) { - response.writeHead(404, { "content-type": "application/json" }); - return response.end(JSON.stringify({ type: "error", error: { type: "not_found_error" } })); - } - let body: { stream?: boolean; model?: string; tools?: unknown[] } = {}; - try { - body = JSON.parse(raw); - } catch {} - const slow = raw.includes(SLOW_MARKER); - requests.push({ - at: performance.now(), - stream: body.stream === true, - // Title and branch-name jobs carry only their structured-output tool; the agent carries many. - agent: body.stream === true && (body.tools?.length ?? 0) > 1, - marker: /bench-run-(\d+)/.exec(raw)?.[0], + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.url.includes("count_tokens")) { + return HttpServerResponse.jsonUnsafe({ input_tokens: 100 }); + } + if (!request.url.startsWith("/v1/messages")) { + return HttpServerResponse.jsonUnsafe( + { type: "error", error: { type: "not_found_error" } }, + { status: 404 }, + ); + } + const raw = yield* request.text.pipe(Effect.orElseSucceed(() => "")); + const body = yield* decodeJson(MessagesRequest)(raw).pipe( + Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), + ); + const streamed = body.stream === true; + requests.push({ + at: yield* Clock.currentTimeMillis, + stream: streamed, + // Title and branch-name jobs carry only their structured-output tool; the agent carries many. + agent: streamed && (body.tools?.length ?? 0) > 1, + marker: /bench-run-(\d+)/.exec(raw)?.[0], + }); + const model = body.model ?? MODEL; + const id = `msg_bench_${requests.length}`; + if (!streamed) { + return HttpServerResponse.jsonUnsafe({ + id, + type: "message", + role: "assistant", + model, + content: [{ type: "text", text: "Bench reply" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 2 }, }); - const model = body.model ?? MODEL; - const id = `msg_bench_${requests.length}`; - if (!body.stream) { - response.writeHead(200, { "content-type": "application/json" }); - return response.end( - JSON.stringify({ - id, - type: "message", - role: "assistant", - model, - content: [{ type: "text", text: "Bench reply" }], - stop_reason: "end_turn", - stop_sequence: null, - usage: { input_tokens: 10, output_tokens: 2 }, - }), - ); - } - const event = (name: string, data: object) => - response.write(`event: ${name}\ndata: ${JSON.stringify({ type: name, ...data })}\n\n`); - response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + } + const event = (name: string, data: object) => + `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; + const slow = raw.includes(SLOW_MARKER); + const words = slow ? 2_000 : 40; + const deltas = Stream.range(0, words - 1).pipe( + Stream.mapEffect((word) => + Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.as( + event("content_block_delta", { + index: 0, + delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` }, + }), + ), + ), + ), + ); + const events = Stream.make( event("message_start", { message: { id, @@ -197,79 +156,147 @@ function startFakeAnthropic() { stop_sequence: null, usage: { input_tokens: 100, output_tokens: 1 }, }, - }); - event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }); - const words = slow ? 2_000 : 40; - for (let word = 0; word < words && !response.destroyed; word++) { - event("content_block_delta", { - index: 0, - delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` }, - }); - await sleep(slow ? 50 : 5); - } - event("content_block_stop", { index: 0 }); - event("message_delta", { - delta: { stop_reason: "end_turn", stop_sequence: null }, - usage: { output_tokens: words }, - }); - event("message_stop", {}); - response.end(); + }), + event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), + ).pipe( + Stream.concat(deltas), + Stream.concat( + Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + event("message_stop", {}), + ), + ), + Stream.encodeText, + ); + return HttpServerResponse.stream(events, { + contentType: "text/event-stream", + headers: { "cache-control": "no-cache" }, }); }); - return new Promise<{ port: number; requests: ApiRequest[]; close: () => void }>((resolve) => - server.listen(0, "127.0.0.1", () => { - const address = server.address() as NodeNet.AddressInfo; - resolve({ - port: address.port, - requests, - close: () => { - server.closeAllConnections(); - server.close(); - }, - }); + // Each run gets its own listener, closed with the run's scope. + const context = yield* Layer.build(httpServerOn(0)); + return yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + if (address._tag === "UnixPathAddress") { + return yield* new MetricsError({ message: "the fake API has no TCP address" }); + } + return { port: address.port, requests }; + }).pipe(Effect.provide(context)); +}); + +/** A Chrome DevTools Protocol session on the server's inspector. */ +const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { + const socket = yield* Socket.makeWebSocket(url); + const reader = yield* socket.reader; + const writer = yield* socket.writer; + const pending = new Map>(); + const chunks: string[] = []; + let nextId = 0; + const decodeMessage = decodeJson( + Schema.Struct({ + id: Schema.optional(Schema.Number), + result: Schema.optional(Schema.Unknown), + method: Schema.optional(Schema.String), + params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })), }), ); -} - -function freePort() { - return new Promise((resolve, reject) => { - const probe = NodeNet.createServer(); - probe.once("error", reject); - probe.listen(0, "127.0.0.1", () => { - const { port } = probe.address() as NodeNet.AddressInfo; - probe.close(() => resolve(port)); - }); + const text = new TextDecoder(); + yield* reader.pull.pipe( + Effect.flatMap((frames) => + Effect.forEach(frames, (frame) => + decodeMessage(typeof frame === "string" ? frame : text.decode(frame)).pipe( + Effect.flatMap((message) => { + if (message.id !== undefined) { + const waiting = pending.get(message.id); + pending.delete(message.id); + return waiting ? Deferred.succeed(waiting, message.result) : Effect.void; + } + if (message.method === "HeapProfiler.addHeapSnapshotChunk") { + chunks.push(message.params?.chunk ?? ""); + } + return Effect.void; + }), + Effect.ignore, + ), + ), + ), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ); + const send = Effect.fn("serverMetrics.cdp")(function* (method: string, params: object = {}) { + const id = ++nextId; + const answer = yield* Deferred.make(); + pending.set(id, answer); + yield* writer.write(encodeJson({ id, method, params })); + return yield* Deferred.await(answer); }); -} - -const commandOutput = (command: string, args: ReadonlyArray, cwd = harnessRoot) => { - const result = NodeChildProcess.spawnSync(command, args, { cwd, encoding: "utf8" }); - return result.status === 0 ? result.stdout.trim() : null; -}; -const powershell = (script: string) => - commandOutput("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); + const decodeHeapUsage = Schema.decodeUnknownEffect(Schema.Struct({ usedSize: Schema.Number })); + const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile })); + const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile })); + return { + heapAfterGc: Effect.gen(function* () { + yield* send("HeapProfiler.collectGarbage"); + yield* send("HeapProfiler.collectGarbage"); + return (yield* decodeHeapUsage(yield* send("Runtime.getHeapUsage"))).usedSize; + }), + profile: Effect.fn("serverMetrics.profile")(function* (seconds: number) { + yield* send("Profiler.enable"); + yield* send("Profiler.setSamplingInterval", { interval: 1_000 }); + yield* send("Profiler.start"); + yield* send("HeapProfiler.startSampling", { + samplingInterval: 32_768, + includeObjectsCollectedByMajorGC: true, + includeObjectsCollectedByMinorGC: true, + }); + yield* Effect.sleep(Duration.seconds(seconds)); + const heap = yield* send("HeapProfiler.stopSampling"); + const cpu = yield* send("Profiler.stop"); + yield* send("Profiler.disable"); + return { + summary: summarizeProfiles( + (yield* decodeCpuProfile(cpu)).profile, + (yield* decodeHeapProfile(heap)).profile, + ), + raw: { cpu, heap }, + }; + }), + snapshot: Effect.gen(function* () { + chunks.length = 0; + yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); + const json = chunks.join(""); + chunks.length = 0; + return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + }), + }; +}); /** CPU seconds and RSS bytes of one process. */ -function sample(pid: number): { cpuSeconds: number; rss: number } { +const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { + const platform = yield* HostProcess.Platform; if (platform === "linux") { - const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]!.split(" "); - const status = NodeFS.readFileSync(`/proc/${pid}/status`, "utf8"); + const fs = yield* FileSystem.FileSystem; + const stat = (yield* fs.readFileString(`/proc/${pid}/stat`)).split(") ")[1]?.split(" ") ?? []; + const status = yield* fs.readFileString(`/proc/${pid}/status`); return { cpuSeconds: (Number(stat[11]) + Number(stat[12])) / 100, rss: Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0) * 1024, }; } if (platform === "win32") { - const [cpu = "0", rss = "0"] = ( - powershell( - `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, - ) ?? "" - ).split(/\s+/); + const line = yield* powershell( + `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, + ); + const [cpu = "0", rss = "0"] = Option.getOrElse(line, () => "").split(/\s+/); return { cpuSeconds: Number(cpu), rss: Number(rss) }; } - const [rss = "0", time = "0:0"] = ( - commandOutput("ps", ["-o", "rss=,time=", "-p", `${pid}`]) ?? "" - ) + const line = yield* output("ps", ["-o", "rss=,time=", "-p", `${pid}`]); + const [rss = "0", time = "0:0"] = Option.getOrElse(line, () => "") .split(/\s+/) .filter(Boolean); const cpuSeconds = time @@ -277,54 +304,62 @@ function sample(pid: number): { cpuSeconds: number; rss: number } { .map(Number) .reduce((total, part) => total * 60 + part, 0); return { cpuSeconds, rss: Number(rss) * 1024 }; -} +}); + +const numberOrNull = (text: Option.Option) => { + const value = Number(Option.getOrElse(text, () => "").replace(/\+$/, "")); + return Option.isSome(text) && text.value !== "" && Number.isFinite(value) ? value : null; +}; /** Context switches of one process since it started, or null when this platform cannot tell. */ -function contextSwitches(pid: number): number | null { +const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pid: number) { + const platform = yield* HostProcess.Platform; if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; let switches = 0; - for (const task of NodeFS.readdirSync(`/proc/${pid}/task`)) { - try { - const status = NodeFS.readFileSync(`/proc/${pid}/task/${task}/status`, "utf8"); - for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) - switches += Number(match[1]); - } catch {} + for (const task of yield* fs.readDirectory(`/proc/${pid}/task`)) { + const status = yield* fs + .readFileString(`/proc/${pid}/task/${task}/status`) + .pipe(Effect.orElseSucceed(() => "")); + for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) switches += Number(match[1]); } return switches; } if (platform === "win32") { - const total = powershell( - `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, + return numberOrNull( + yield* powershell( + `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, + ), ); - return total === null || total === "" ? null : Number(total); - } - if (platform === "darwin") { - const table = commandOutput("top", ["-l", "1", "-pid", `${pid}`, "-stats", "pid,csw"]); - const row = table - ?.split("\n") - .map((line) => line.trim().split(/\s+/)) - .find(([first]) => first === `${pid}`); - const value = Number(row?.[1]?.replace(/\+$/, "")); - return Number.isFinite(value) ? value : null; } - return null; -} + if (platform !== "darwin") return null; + const table = yield* output("top", ["-l", "1", "-pid", `${pid}`, "-stats", "pid,csw"]); + const row = Option.getOrElse(table, () => "") + .split("\n") + .map((line) => line.trim().split(/\s+/)) + .find(([first]) => first === `${pid}`); + return numberOrNull(Option.fromNullishOr(row?.[1])); +}); -/** Every process below `pid`, read once. */ -function descendantsOf(pid: number): number[] { +/** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ +const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { + const platform = yield* HostProcess.Platform; const children = new Map(); const add = (child: number, parent: number) => children.set(parent, [...(children.get(parent) ?? []), child]); if (platform === "linux") { - for (const entry of NodeFS.readdirSync("/proc")) { + const fs = yield* FileSystem.FileSystem; + for (const entry of yield* fs.readDirectory("/proc")) { if (!/^\d+$/.test(entry)) continue; - try { - const stat = NodeFS.readFileSync(`/proc/${entry}/stat`, "utf8").split(") ")[1]!.split(" "); - add(Number(entry), Number(stat[1])); - } catch {} + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const parent = Number(stat.split(") ")[1]?.split(" ")[1]); + if (parent) add(Number(entry), parent); } } else if (platform === "darwin") { - for (const line of (commandOutput("ps", ["-A", "-o", "pid=,ppid="]) ?? "").split("\n")) { + const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); + for (const line of Option.getOrElse(table, () => "").split("\n")) { const [child, parent] = line.trim().split(/\s+/).map(Number); if (child && parent) add(child, parent); } @@ -338,354 +373,253 @@ function descendantsOf(pid: number): number[] { } } return found; -} - -/** One Chrome DevTools Protocol session on the server's inspector. */ -async function inspect(webSocketUrl: string) { - const socket = new WebSocket(webSocketUrl); - await new Promise((resolve, reject) => { - socket.addEventListener("open", resolve, { once: true }); - socket.addEventListener("error", reject, { once: true }); - }); - let nextId = 0; - const pending = new Map void>(); - let chunks: string[] = []; - socket.addEventListener("message", (event) => { - const message = JSON.parse(String(event.data)) as { - id?: number; - result?: unknown; - method?: string; - params?: { chunk?: string }; - }; - if (message.id !== undefined) pending.get(message.id)?.(message.result); - else if (message.method === "HeapProfiler.addHeapSnapshotChunk") - chunks.push(message.params?.chunk ?? ""); - }); - const send = (method: string, params: object = {}) => - new Promise((resolve) => { - const id = ++nextId; - pending.set(id, resolve); - socket.send(JSON.stringify({ id, method, params })); - }); - return { - heapAfterGc: async () => { - await send("HeapProfiler.collectGarbage"); - await send("HeapProfiler.collectGarbage"); - const { usedSize } = (await send("Runtime.getHeapUsage")) as { usedSize: number }; - return usedSize; - }, - profile: async (seconds: number) => { - await send("Profiler.enable"); - await send("Profiler.setSamplingInterval", { interval: 1_000 }); - await send("Profiler.start"); - await send("HeapProfiler.startSampling", { - samplingInterval: 32_768, - includeObjectsCollectedByMajorGC: true, - includeObjectsCollectedByMinorGC: true, - }); - await sleep(seconds * 1_000); - const { profile: heap } = (await send("HeapProfiler.stopSampling")) as { profile: object }; - const { profile: cpu } = (await send("Profiler.stop")) as { profile: object }; - await send("Profiler.disable"); - return { cpu, heap }; - }, - snapshot: async () => { - chunks = []; - await send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); - const json = chunks.join(""); - chunks = []; - return json; - }, - close: () => socket.close(), - }; -} - -const shortUrl = (url: string) => - url - .replace(/^file:\/\//, "") - .split(/[\\/]/) - .slice(-3) - .join("/"); - -interface CpuProfile { - readonly nodes: ReadonlyArray<{ - id: number; - hitCount?: number; - callFrame: { functionName: string; url: string; lineNumber: number }; - }>; - readonly samples?: ReadonlyArray; - readonly startTime: number; - readonly endTime: number; -} -interface HeapProfileNode { - readonly callFrame: { functionName: string; url: string; lineNumber: number }; - readonly selfSize: number; - readonly children: ReadonlyArray; -} - -const frameName = (frame: { functionName: string; url: string; lineNumber: number }) => - `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); - -const top = (totals: Map, digits: number): Hotspot[] => - [...totals] - .toSorted((a, b) => b[1] - a[1]) - .slice(0, 10) - .map(([frame, value]) => ({ frame, value: round(value, digits) })); - -/** Top CPU self time in ms and allocated MB, by function. */ -export function summarizeProfiles(cpu: CpuProfile, heap: { head: HeapProfileNode }) { - const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); - const cpuTotals = new Map(); - for (const node of cpu.nodes) { - if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; - const name = frameName(node.callFrame); - cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); - } - const allocations = new Map(); - const visit = (node: HeapProfileNode) => { - const name = frameName(node.callFrame); - allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); - for (const child of node.children) visit(child); - }; - visit(heap.head); - return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; -} - -/** Self size by constructor from a V8 heap snapshot. */ -export function heapByConstructor(json: string) { - const snapshot = JSON.parse(json) as { - snapshot: { meta: { node_fields: string[]; node_types: [string[]] } }; - nodes: number[]; - strings: string[]; - }; - const fields = snapshot.snapshot.meta.node_fields; - const types = snapshot.snapshot.meta.node_types[0]; - const typeAt = fields.indexOf("type"); - const nameAt = fields.indexOf("name"); - const sizeAt = fields.indexOf("self_size"); - const totals = new Map(); - for (let index = 0; index < snapshot.nodes.length; index += fields.length) { - const type = types[snapshot.nodes[index + typeAt]!]!; - const name = - type === "object" - ? snapshot.strings[snapshot.nodes[index + nameAt]!]!.slice(0, 80) - : type === "closure" - ? `(closure) ${snapshot.strings[snapshot.nodes[index + nameAt]!]!.slice(0, 60)}` - : `(${type.replace(/^(concatenated|sliced) /, "")})`; - const entry = totals.get(name) ?? { count: 0, bytes: 0 }; - entry.count++; - entry.bytes += snapshot.nodes[index + sizeAt]!; - totals.set(name, entry); - } - return totals; -} +}); interface Environment { readonly home: string; - readonly api: Awaited>; + readonly apiPort: number; + readonly requests: ReadonlyArray; readonly noAgentScope: boolean; readonly serverDir: string; } -async function startServer(environment: Environment, name: string) { - const directory = NodeFS.mkdtempSync(NodePath.join(environment.home, `${name}-`)); - const project = NodePath.join(directory, "project"); - NodeFS.mkdirSync(project); - NodeFS.writeFileSync(NodePath.join(project, "README.md"), "# bench\n"); +/** A free loopback port: bind 0, read it, let it go. */ +const freePort = Effect.scoped( + Effect.gen(function* () { + const context = yield* Layer.build(httpServerOn(0)); + const { address } = Context.get(context, HttpServer.HttpServer); + return address._tag === "UnixPathAddress" ? 0 : address.port; + }), +); + +/** A fresh server with its own base dir and git project, stopped when the scope closes. */ +const startServer = Effect.fn("serverMetrics.startServer")(function* ( + environment: Environment, + name: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const http = yield* HttpClient.HttpClient; + const platform = yield* HostProcess.Platform; + const node = yield* HostProcess.ExecutablePath; + const hostEnvironment = yield* HostProcess.Environment; + const directory = yield* fs.makeTempDirectory({ + directory: environment.home, + prefix: `${name}-`, + }); + const project = path.join(directory, "project"); + yield* fs.makeDirectory(project); + yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); for (const args of [ ["init", "-q", "-b", "main"], ["add", "."], ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], ]) { - NodeChildProcess.execFileSync("git", args, { cwd: project }); + yield* run("git", args, { cwd: project }); } - const baseDir = NodePath.join(directory, "base"); + const baseDir = path.join(directory, "base"); // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. - NodeFS.mkdirSync(NodePath.join(baseDir, "userdata"), { recursive: true }); - NodeFS.writeFileSync( - NodePath.join(baseDir, "userdata/settings.json"), - JSON.stringify({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), + yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); + yield* fs.writeFileString( + path.join(baseDir, "userdata/settings.json"), + encodeJson({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), ); - const env: NodeJS.ProcessEnv = { - ...process.env, + const dropped = new Set([ + "ANTHROPIC_AUTH_TOKEN", + "T3CODE_HOME", + ...(environment.noAgentScope ? ["XDG_RUNTIME_DIR"] : []), + ]); + const env: Record = { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined && !dropped.has(entry[0]), + ), + ), HOME: environment.home, USERPROFILE: environment.home, - ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.api.port}`, + ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.apiPort}`, ANTHROPIC_API_KEY: "sk-bench", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", OTEL_SDK_DISABLED: "true", T3CODE_DEV_SEED: "0", }; - delete env.ANTHROPIC_AUTH_TOKEN; - delete env.T3CODE_HOME; - if (environment.noAgentScope) delete env.XDG_RUNTIME_DIR; - const port = await freePort(); - const started = performance.now(); - const child = NodeChildProcess.spawn( - process.execPath, - [ - "--inspect=127.0.0.1:0", - "src/bin.ts", - "serve", - "--base-dir", - baseDir, - "--port", - `${port}`, - "--host", - "127.0.0.1", - project, - ], - { cwd: environment.serverDir, env, stdio: ["ignore", "ignore", "pipe"] }, + const port = yield* freePort; + const started = yield* Clock.currentTimeMillis; + const child = yield* spawner.spawn( + ChildProcess.make( + node, + [ + "--inspect=127.0.0.1:0", + "src/bin.ts", + "serve", + "--base-dir", + baseDir, + "--port", + `${port}`, + "--host", + "127.0.0.1", + project, + ], + { + cwd: environment.serverDir, + env, + extendEnv: false, + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + }, + ), ); - const pid = child.pid!; - let inspector = ""; - let stderr = ""; - child.stderr.setEncoding("utf8").on("data", (chunk: string) => { - stderr = (stderr + chunk).slice(-8_000); - inspector ||= /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(stderr)?.[0] ?? ""; - }); - let readyMs: number | undefined; - for (let attempt = 0; attempt < 600 && readyMs === undefined; attempt++) { - if (child.exitCode !== null) throw new Error(`server exited early:\n${stderr}`); - try { - await fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(1_000) }); - readyMs = Math.round(performance.now() - started); - } catch { - await sleep(100); - } - } - if (readyMs === undefined || !inspector) throw new Error(`server never answered:\n${stderr}`); - const devtools = await inspect(inspector); + const pid = Number(child.pid); + const stderr = yield* Ref.make(""); + yield* child.stderr.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => Ref.update(stderr, (text) => (text + chunk).slice(-8_000))), + Effect.ignore, + Effect.forkScoped, + ); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const spawned = yield* descendantsOf(pid); + if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]); + else yield* child.kill({ killSignal: "SIGTERM" }).pipe(Effect.ignore); + yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore); + if (spawned.length > 0) yield* output("kill", ["-9", ...spawned.map(String)]); + // Windows keeps a file locked for a moment after its process exits. + yield* fs + .remove(directory, { recursive: true }) + .pipe(Effect.retry({ schedule: Schedule.spaced(Duration.millis(500)), times: 20 })); + }).pipe(Effect.ignore), + ); + + const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe( + Effect.timeout(Duration.seconds(1)), + Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }), + Effect.flatMap(() => Clock.currentTimeMillis), + Effect.map((now) => Math.round(now - started)), + Effect.catch(() => + Effect.flatMap( + Ref.get(stderr), + (text) => new MetricsError({ message: `server never answered:\n${text}` }), + ), + ), + ); + const inspectorUrl = /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(yield* Ref.get(stderr))?.[0]; + if (!inspectorUrl) return yield* new MetricsError({ message: "no inspector URL on stderr" }); + const devtools = yield* inspect(inspectorUrl); + const cli = (args: ReadonlyArray) => - new Promise<{ code: number | null; stdout: string }>((resolve) => { - const command = NodeChildProcess.spawn( - process.execPath, - ["src/bin.ts", ...args, "--base-dir", baseDir], - { cwd: environment.serverDir, env, stdio: ["ignore", "pipe", "pipe"] }, - ); - let stdout = ""; - command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk)); - command.on("exit", (code) => resolve({ code, stdout })); + run(node, ["src/bin.ts", ...args, "--base-dir", baseDir], { + cwd: environment.serverDir, + env, + allowExit: [0, 1, 2], }); - const added = await cli(["project", "add", project]); - if (added.code !== 0) throw new Error(`project add failed: ${added.stdout}`); + const added = yield* cli(["project", "add", project]); + if (added.exitCode !== 0) { + return yield* new MetricsError({ message: `project add failed: ${added.stderr}` }); + } // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. - const sampleEveryMs = platform === "win32" ? 5_000 : 1_000; - const measure = async (seconds: number): Promise => { - const firstSwitches = contextSwitches(pid); - const first = sample(pid); + const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000); + const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) { + const firstSwitches = yield* contextSwitches(pid); + const first = yield* sample(pid); let rssPeak = first.rss; - const start = performance.now(); - while (performance.now() - start < seconds * 1_000) { - await sleep(sampleEveryMs); - rssPeak = Math.max(rssPeak, sample(pid).rss); + const start = yield* Clock.currentTimeMillis; + while ((yield* Clock.currentTimeMillis) - start < seconds * 1_000) { + yield* Effect.sleep(sampleEvery); + rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss); } - const last = sample(pid); - const lastSwitches = contextSwitches(pid); - const elapsed = (performance.now() - start) / 1_000; - const heap = await devtools.heapAfterGc(); - return { + const last = yield* sample(pid); + const lastSwitches = yield* contextSwitches(pid); + const elapsed = ((yield* Clock.currentTimeMillis) - start) / 1_000; + const heap = yield* devtools.heapAfterGc; + const window: Window = { cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / elapsed) * 100), wakeupsPerSec: firstSwitches === null || lastSwitches === null ? null : round((lastSwitches - firstSwitches) / elapsed), rssPeakMB: Math.round(rssPeak / 1e6), - rssMB: Math.round(sample(pid).rss / 1e6), + rssMB: Math.round((yield* sample(pid)).rss / 1e6), heapAfterGcMB: round(heap / 1e6), }; - }; - - const threadStart = (message: string, extra: ReadonlyArray = []) => - cli([ - "thread", - "start", - "--provider", - "claudeAgent", - "--model", - MODEL, - ...extra, - project, - message, - ]); - const threadSend = (threadId: string, message: string) => - cli(["thread", "send", "--wait", threadId, message]); - - const stop = async () => { - devtools.close(); - const spawned = descendantsOf(pid); - if (platform === "win32") commandOutput("taskkill", ["/PID", `${pid}`, "/T", "/F"]); - else child.kill("SIGTERM"); - for (let attempt = 0; attempt < 100 && child.exitCode === null; attempt++) await sleep(100); - if (child.exitCode === null) child.kill("SIGKILL"); - for (const leftover of spawned) { - try { - process.kill(leftover, "SIGKILL"); - } catch {} - } - for (let attempt = 0; attempt < 20; attempt++) { - try { - NodeFS.rmSync(directory, { recursive: true, force: true }); - break; - } catch { - // Windows keeps a file locked for a moment after its process exits. - await sleep(500); - } - } - }; + return window; + }); return { readyMs, measure, - threadStart, - threadSend, profile: devtools.profile, snapshot: devtools.snapshot, - stop, + threadStart: (message: string, extra: ReadonlyArray = []) => + cli([ + "thread", + "start", + "--provider", + "claudeAgent", + "--model", + MODEL, + ...extra, + project, + message, + ]), + threadSend: (threadId: string, message: string) => + cli(["thread", "send", "--wait", threadId, message]), }; -} +}); -type Server = Awaited>; +type Server = Effect.Success>; -async function firstWord( +const firstWord = Effect.fn("serverMetrics.firstWord")(function* ( environment: Environment, server: Server, runs: number, worktree: boolean, -): Promise { +) { const toRequest: number[] = []; const toDone: number[] = []; - for (let run = 0; run < runs; run++) { - const marker = `bench-run-${worktree ? 1000 + run : run}`; - const started = performance.now(); - const result = await server.threadStart(`Say hello. ${marker}`, [ + for (let index = 0; index < runs; index++) { + const marker = `bench-run-${worktree ? 1000 + index : index}`; + const started = yield* Clock.currentTimeMillis; + const result = yield* server.threadStart(`Say hello. ${marker}`, [ "--wait", ...(worktree ? ["--worktree", "main"] : []), ]); - const done = performance.now() - started; - if (result.code !== 0) throw new Error(`thread start failed: ${result.stdout}`); - const request = environment.api.requests.find( + const done = (yield* Clock.currentTimeMillis) - started; + if (result.exitCode !== 0) { + return yield* new MetricsError({ message: `thread start failed: ${result.stdout}` }); + } + const request = environment.requests.find( (entry) => entry.agent && entry.marker === marker && entry.at >= started, ); - if (!request) throw new Error(`the agent request for ${marker} never reached the fake API`); + if (!request) { + return yield* new MetricsError({ message: `the agent request for ${marker} never arrived` }); + } toRequest.push(request.at - started); toDone.push(done); } - return { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; -} + const result: FirstWord = { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; + return result; +}); /** Starts threads that each answer once, and returns their ids. */ -async function openThreads(server: Server, from: number, count: number) { - const answers = await Promise.all( - Array.from({ length: count }, (_, index) => - server.threadStart(`Say hello ${from + index}.`, ["--wait"]), - ), +const openThreads = Effect.fn("serverMetrics.openThreads")(function* ( + server: Server, + from: number, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => from + index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait"]), + { concurrency: "unbounded" }, ); - const failed = answers.filter((answer) => answer.code !== 0).length; - if (failed) throw new Error(`${failed} of ${count} threads failed`); + const failed = answers.filter((answer) => answer.exitCode !== 0).length; + if (failed) return yield* new MetricsError({ message: `${failed} of ${count} threads failed` }); return answers.map((answer) => /Thread (\S+)/.exec(answer.stdout)?.[1] ?? ""); -} +}); const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; @@ -700,69 +634,70 @@ interface RunOptions { readonly profileDir: string | undefined; } -export async function runOnce(options: RunOptions) { - const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-server-metrics-")); - const api = await startFakeAnthropic(); +/** One pass over the scenarios, each on a fresh server. */ +const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); + const api = yield* serveFakeAnthropic(); const environment: Environment = { home, - api, + apiPort: api.port, + requests: api.requests, noAgentScope: options.noAgentScope, - serverDir: NodePath.join(options.checkout, "apps/server"), + serverDir: path.join(options.checkout, "apps/server"), }; const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; - const profiles: Record> = {}; - let soakHeapGrowth: ServerMetrics["soakHeapGrowth"]; - const profile = async (server: Server, name: string) => { - const { cpu, heap } = await server.profile(20); - profiles[name] = summarizeProfiles(cpu as CpuProfile, heap as { head: HeapProfileNode }); - if (options.profileDir) { - NodeFS.mkdirSync(options.profileDir, { recursive: true }); - NodeFS.writeFileSync( - NodePath.join(options.profileDir, `${name}.cpuprofile`), - JSON.stringify(cpu), - ); - NodeFS.writeFileSync( - NodePath.join(options.profileDir, `${name}.heapprofile`), - JSON.stringify(heap), - ); - } - }; - const withServer = async (name: string, body: (server: Server) => Promise) => { - const server = await startServer(environment, name); - try { - await body(server); - } finally { - await server.stop(); - } - }; - try { - if (wanted("startup") || wanted("rest") || wanted("firstWord")) { - await withServer("rest", async (server) => { + const profiles: Record = {}; + let soakHeapGrowth: ReturnType | undefined; + const withServer = (name: string, body: (server: Server) => Effect.Effect) => + Effect.scoped(Effect.flatMap(startServer(environment, name), body)); + const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { + const { summary, raw } = yield* server.profile(20); + profiles[name] = summary; + if (options.profileDir === undefined) return; + yield* fs.makeDirectory(options.profileDir, { recursive: true }); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.cpuprofile`), + encodeJson(raw.cpu), + ); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.heapprofile`), + encodeJson(raw.heap), + ); + }); + + if (wanted("startup") || wanted("rest") || wanted("firstWord")) { + yield* withServer("rest", (server) => + Effect.gen(function* () { measured.startup = { readyMs: server.readyMs }; if (wanted("rest")) { - await sleep(15_000); - measured.rest = await server.measure(30); + yield* Effect.sleep(Duration.seconds(15)); + measured.rest = yield* server.measure(30); } if (wanted("firstWord")) { measured.firstWord = { - inPlace: await firstWord(environment, server, options.runs, false), - worktree: await firstWord(environment, server, options.runs, true), + inPlace: yield* firstWord(environment, server, options.runs, false), + worktree: yield* firstWord(environment, server, options.runs, true), }; } - }); - } - if (wanted("quiet")) { - await withServer("quiet", async (server) => { + }), + ); + } + if (wanted("quiet")) { + yield* withServer("quiet", (server) => + Effect.gen(function* () { const points: Array<{ threads: number; window: Window }> = []; let open = 0; for (const threads of options.threads) { - if (threads > open) await openThreads(server, open, threads - open); + if (threads > open) yield* openThreads(server, open, threads - open); open = Math.max(open, threads); - await sleep(15_000); - points.push({ threads, window: await server.measure(30) }); + yield* Effect.sleep(Duration.seconds(15)); + points.push({ threads, window: yield* server.measure(30) }); } - measured.quiet = points.at(-1)!.window; + const last = points.at(-1); + if (last) measured.quiet = last.window; // The first thread also loads the provider's modules once, so the fit leaves out 0 threads. const withThreads = points.filter(({ threads }) => threads > 0); const fitted = withThreads.length >= 2 ? withThreads : points; @@ -773,7 +708,7 @@ export async function runOnce(options: RunOptions) { rssMBPerThread: fit((window) => window.rssMB), cpuPctPerThread: fit((window) => window.cpuPct), wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null) - ? fit((window) => window.wakeupsPerSec!) + ? fit((window) => window.wakeupsPerSec ?? 0) : null, points: points.map(({ threads, window }) => [ threads, @@ -783,298 +718,344 @@ export async function runOnce(options: RunOptions) { window.heapAfterGcMB, ]), }; - await profile(server, "quiet"); - }); - } - if (wanted("streaming")) { - await withServer("streaming", async (server) => { - const started = await Promise.all( - Array.from({ length: 5 }, (_, index) => - server.threadStart(`Write a long answer ${index}. ${SLOW_MARKER}`), - ), + yield* profile(server, "quiet"); + }), + ); + } + if (wanted("streaming")) { + yield* withServer("streaming", (server) => + Effect.gen(function* () { + const started = yield* Effect.forEach( + [0, 1, 2, 3, 4], + (index) => server.threadStart(`Write a long answer ${index}. ${SLOW_MARKER}`), + { concurrency: "unbounded" }, ); - if (started.some((answer) => answer.code !== 0)) throw new Error("streaming start failed"); - for (let attempt = 0; attempt < 300; attempt++) { - if (api.requests.filter((request) => request.agent && request.stream).length >= 5) break; - await sleep(100); + if (started.some((answer) => answer.exitCode !== 0)) { + return yield* new MetricsError({ message: "streaming start failed" }); } - await sleep(5_000); - measured.streaming = await server.measure(60); - await profile(server, "streaming"); - }); - } - if (options.soakMinutes > 0) { - await withServer("soak", async (server) => { - const threads = await openThreads(server, 0, 10); - await sleep(60_000); + const streaming = () => api.requests.filter((request) => request.agent && request.stream); + for (let attempt = 0; attempt < 300 && streaming().length < 5; attempt++) { + yield* Effect.sleep(Duration.millis(100)); + } + yield* Effect.sleep(Duration.seconds(5)); + measured.streaming = yield* server.measure(60); + yield* profile(server, "streaming"); + }), + ); + } + if (options.soakMinutes > 0) { + yield* withServer("soak", (server) => + Effect.gen(function* () { + const threads = yield* openThreads(server, 0, 10); + yield* Effect.sleep(Duration.seconds(60)); // The snapshot inflates RSS once, so the slopes start after it. - const before = heapByConstructor(await server.snapshot()); + const before = yield* server.snapshot; const samples: Array<{ hours: number; window: Window }> = []; - const start = performance.now(); + const start = yield* Clock.currentTimeMillis; + const elapsed = Effect.map(Clock.currentTimeMillis, (now) => now - start); + const takeSample = Effect.gen(function* () { + samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); + }); let nextSample = 0; - for (let turn = 0; performance.now() - start < options.soakMinutes * 60_000; turn++) { - const elapsed = performance.now() - start; - if (elapsed >= nextSample) { - samples.push({ hours: elapsed / 3_600_000, window: await server.measure(5) }); + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if ((yield* elapsed) >= nextSample) { + yield* takeSample; nextSample += 120_000; } - const threadId = threads[Math.floor(Math.random() * threads.length)]!; - await server.threadSend(threadId, `Short reply ${turn}.`); - await sleep(Math.max(0, start + (turn + 1) * 30_000 - performance.now())); + const threadId = threads[yield* Random.nextIntBetween(0, threads.length)] ?? ""; + yield* server.threadSend(threadId, `Short reply ${turn}.`); + yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); } - samples.push({ - hours: (performance.now() - start) / 3_600_000, - window: await server.measure(5), - }); + yield* takeSample; + const perHour = (pick: (window: Window) => number) => + round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); measured.soak = { minutes: options.soakMinutes, - heapMBPerHour: round( - slope(samples.map(({ hours, window }) => [hours, window.heapAfterGcMB])), - ), - rssMBPerHour: round(slope(samples.map(({ hours, window }) => [hours, window.rssMB]))), + heapMBPerHour: perHour((window) => window.heapAfterGcMB), + rssMBPerHour: perHour((window) => window.rssMB), }; - const after = heapByConstructor(await server.snapshot()); - soakHeapGrowth = [...after] - .map(([name, { count, bytes }]) => ({ - constructor: name, - count: count - (before.get(name)?.count ?? 0), - MB: round((bytes - (before.get(name)?.bytes ?? 0)) / 1e6, 2), - })) - .toSorted((a, b) => b.MB - a.MB) - .slice(0, 25); - }); - } - } finally { - api.close(); - NodeFS.rmSync(home, { recursive: true, force: true }); + soakHeapGrowth = heapGrowth(before, yield* server.snapshot); + }), + ); } return { measured: measured as Measured, profiles, soakHeapGrowth }; -} +}, Effect.scoped); -function machineLoad() { - if (platform === "win32") - return powershell( +const machineLoad = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") { + return yield* powershell( "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average", ); - return NodeOS.loadavg() - .map((value) => value.toFixed(2)) - .join(" "); -} + } + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const load = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(load, (text) => text.split(" ").slice(0, 3).join(" ")); + } + return yield* output("sysctl", ["-n", "vm.loadavg"]); +}).pipe( + Effect.map((load) => + Option.getOrNull(Option.map(load, (text) => text.replace(/[{}]/g, "").trim())), + ), +); -function metaFor(options: RunOptions) { - const claude = commandOutput("claude", ["--version"]); - if (claude === null) throw new Error("The real `claude` CLI must be on PATH."); - if (options.noAgentScope && platform !== "linux") - throw new Error("--no-agent-scope is Linux only; other platforms never have an agent scope."); +const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { + const platform = yield* HostProcess.Platform; + const architecture = yield* HostProcess.Architecture; + const environment = yield* HostProcess.Environment; + const node = yield* HostProcess.ExecutablePath; + const claude = yield* output("claude", ["--version"]); + if (Option.isNone(claude)) { + return yield* new MetricsError({ message: "The real `claude` CLI must be on PATH." }); + } + if (options.noAgentScope && platform !== "linux") { + return yield* new MetricsError({ + message: "--no-agent-scope is Linux only; other platforms never have an agent scope.", + }); + } + const cpus = + platform === "win32" + ? Option.fromNullishOr(environment.NUMBER_OF_PROCESSORS) + : yield* output("getconf", ["_NPROCESSORS_ONLN"]); return { platform: `${platform}-${architecture}`, - cpus: NodeOS.cpus().length, - node: process.version, - claude, - commit: commandOutput("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), + cpus: Option.getOrNull(Option.map(cpus, Number)), + node: Option.getOrNull(yield* output(node, ["--version"])), + claude: claude.value, + commit: Option.getOrNull( + yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), + ), noAgentScope: options.noAgentScope, agentScope: platform === "linux" && !options.noAgentScope && - !!process.env.XDG_RUNTIME_DIR && - commandOutput("sh", ["-c", "command -v systemd-run"]) !== null, - loadBefore: machineLoad(), - measuredAt: new Date().toISOString(), + !!environment.XDG_RUNTIME_DIR && + Option.isSome(yield* output("sh", ["-c", "command -v systemd-run"])), + loadBefore: yield* machineLoad, + measuredAt: DateTime.formatIso(yield* DateTime.now), }; -} +}); -async function runMany(options: RunOptions, repeat: number): Promise { - const meta = metaFor(options); - const runs: Measured[] = []; - let last: Awaited> | undefined; - for (let index = 0; index < repeat; index++) { - last = await runOnce(options); - runs.push(last.measured); - } - return { - meta: { ...meta, loadAfter: machineLoad() }, - runs, - ...(last ? { profiles: last.profiles } : {}), - ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), - }; -} - -/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ -export function flatten(measured: Measured): Map { - const values = new Map(); - const visit = (value: unknown, path: string) => { - if (typeof value === "number") values.set(path, value); - else if (value && typeof value === "object") { - for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); - } - }; - visit(measured, ""); - return values; -} +const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* ( + out: Option.Option, + metrics: ServerMetrics, +) { + const fs = yield* FileSystem.FileSystem; + const json = yield* encodeMetrics(metrics); + if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`); + else yield* Console.log(json); +}); -function noiseFloor(metric: string) { - if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; - if (metric.startsWith("soak.")) return 20; - if (metric.endsWith("cpuPct")) return 1; - if (metric.endsWith("wakeupsPerSec")) return 20; - if (metric.endsWith("MB")) return 15; - return 300; -} +/** Prints the comparison and sets exit code 1 when a metric got worse. */ +const report = Effect.fn("serverMetrics.report")(function* ( + before: ServerMetrics, + after: ServerMetrics, + threshold: number, +) { + const { table, regressed, improved } = compareMetrics(before, after, threshold); + yield* Console.log(table); + if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); + if (regressed.length === 0) return; + yield* Console.error(`Worse: ${regressed.join(", ")}`); + yield* Effect.sync(() => { + process.exitCode = 1; + }); +}); -const median = (values: ReadonlyArray) => { - const sorted = values.toSorted((a, b) => a - b); - const middle = Math.floor(sorted.length / 2); - return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +const thresholdFlag = Flag.Int("threshold").pipe( + Flag.withDescription("Percent a metric must move, past its noise floor, to count."), + Flag.withDefault(10), +); +const runFlags = { + noAgentScope: Flag.Boolean("no-agent-scope").pipe( + Flag.withAlias("mac-path"), + Flag.withDefault(false), + Flag.withDescription( + "Linux only: start the server without XDG_RUNTIME_DIR, so it takes the no-agent-scope path macOS and Windows always take.", + ), + ), + runs: Flag.Int("runs").pipe( + Flag.withDescription("firstWord runs in each variant."), + Flag.withDefault(5), + ), + threads: Flag.String("threads").pipe( + Flag.withDescription("Open thread counts the quiet scenario measures."), + Flag.withDefault("0,5,10,20"), + ), + only: Flag.String("only").pipe( + Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), + Flag.optional, + ), + soak: Flag.Int("soak").pipe( + Flag.withDescription( + "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + ), + Flag.withDefault(0), + ), }; - -/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ -export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyArray) { - let seed = 0x5eed; - const random = () => { - seed = (seed + 0x6d2b79f5) | 0; - let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; - const resample = (values: ReadonlyArray) => - median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); - const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( - (x, y) => x - y, - ); - return [differences[49]!, differences[1_949]!] as const; -} - -/** Old single-run files hold the scenarios at the top level. */ -const runsOf = (metrics: ServerMetrics | (Measured & { meta: ServerMetrics["meta"] })) => - "runs" in metrics && Array.isArray(metrics.runs) - ? metrics.runs - : [Object.fromEntries(Object.entries(metrics).filter(([key]) => key !== "meta")) as Measured]; - -export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const collect = (metrics: ServerMetrics) => { - const values = new Map(); - for (const run of runsOf(metrics)) { - for (const [metric, value] of flatten(run)) - values.set(metric, [...(values.get(metric) ?? []), value]); - } - return values; - }; - const a = collect(before); - const b = collect(after); - const lines = [ - "### Server metrics (lower is better)", - "", - `before \`${before.meta.commit}\` (${runsOf(before).length} runs), after \`${after.meta.commit}\` (${runsOf(after).length} runs), ${after.meta.platform}${after.meta.noAgentScope || after.meta.macPath ? ", no agent scope" : ""}`, - "", - "| metric | before | after | change | 95% interval | |", - "| :-- | --: | --: | --: | --: | :-- |", - ]; - const regressed: string[] = []; - const improved: string[] = []; - for (const metric of new Set([...a.keys(), ...b.keys()])) { - if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; - const x = a.get(metric); - const y = b.get(metric); - if (!x || !y) { - lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); - continue; - } - const mx = median(x); - const my = median(y); - // A change counts only past both the relative threshold and the absolute noise floor. - const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); - const [low, high] = - x.length > 1 && y.length > 1 ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; - if (verdict === "worse") regressed.push(metric); - if (verdict === "better") improved.push(metric); - const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; - const shown = Number.isFinite(percent) - ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` - : "new"; - const interval = x.length > 1 && y.length > 1 ? `${round(low, 2)} to ${round(high, 2)}` : ""; - lines.push( - `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, - ); - } - return { table: lines.join("\n"), regressed, improved }; -} - -function option(args: ReadonlyArray, name: string): string | undefined { - const index = args.indexOf(name); - return index === -1 ? undefined : args[index + 1]; +interface RunFlags { + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: string; + readonly only: Option.Option; + readonly soak: number; } -function runOptions(args: ReadonlyArray, checkout: string): RunOptions { - const only = (option(args, "--only") ?? "").split(",").filter(Boolean); +const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( + flags: RunFlags, + checkout: string, + profileDir: string | undefined, +) { + const path = yield* Path.Path; + const only = Option.getOrElse(flags.only, () => "") + .split(",") + .filter(Boolean); const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray).includes(name)); - if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`); - const threads = (option(args, "--threads") ?? "0,5,10,20").split(",").map(Number); - if (threads.some((count) => !Number.isInteger(count) || count < 0)) - throw new Error("--threads takes counts such as 0,5,10,20"); - return { - checkout: NodePath.resolve(checkout), - noAgentScope: args.includes("--no-agent-scope") || args.includes("--mac-path"), - runs: Number(option(args, "--runs") ?? 5), + if (unknown.length) { + return yield* new MetricsError({ message: `unknown scenario: ${unknown.join(", ")}` }); + } + const threads = flags.threads.split(",").map(Number); + if (threads.some((count) => !Number.isInteger(count) || count < 0)) { + return yield* new MetricsError({ message: "--threads takes counts such as 0,5,10,20" }); + } + const options: RunOptions = { + checkout: path.resolve(checkout), + noAgentScope: flags.noAgentScope, + runs: flags.runs, threads, - only: option(args, "--soak") && !option(args, "--only") ? ["none"] : only, - soakMinutes: Number(option(args, "--soak") ?? 0), - profileDir: undefined, + only: flags.soak > 0 && only.length === 0 ? ["none"] : only, + soakMinutes: flags.soak, + profileDir, }; -} - -const write = (path: string | undefined, metrics: ServerMetrics) => { - const json = JSON.stringify(metrics, null, 2); - if (path) NodeFS.writeFileSync(path, json + "\n"); - else console.log(json); -}; + return options; +}); -const printComparison = (before: ServerMetrics, after: ServerMetrics, threshold: number) => { - const { table, regressed, improved } = compareMetrics(before, after, threshold); - console.log(table); - if (improved.length) console.error(`Better: ${improved.join(", ")}`); - if (regressed.length) { - console.error(`Worse: ${regressed.join(", ")}`); - process.exitCode = 1; - } -}; +const runCommand = Command.make( + "run", + { + ...runFlags, + out: Flag.String("out").pipe(Flag.withDescription("JSON file to write."), Flag.optional), + checkout: Flag.String("checkout").pipe( + Flag.withDescription("Checkout whose server to measure, with dependencies installed."), + Flag.optional, + ), + repeat: Flag.Int("repeat").pipe( + Flag.withDescription("Runs to record in one file."), + Flag.withDefault(1), + ), + }, + Effect.fn("serverMetrics.run")(function* (input) { + const path = yield* Path.Path; + const checkout = Option.getOrElse(input.checkout, () => + path.resolve(import.meta.dirname, ".."), + ); + const profileDir = Option.getOrUndefined( + Option.map(input.out, (out) => `${out.replace(/\.json$/, "")}-profiles`), + ); + const options = yield* toRunOptions(input, checkout, profileDir); + const meta = yield* metaFor(options); + const runs: Measured[] = []; + let last: Effect.Success> | undefined; + for (let index = 0; index < input.repeat; index++) { + last = yield* runOnce(options); + runs.push(last.measured); + } + yield* writeMetrics(input.out, { + meta: { ...meta, loadAfter: yield* machineLoad }, + runs, + ...(last ? { profiles: last.profiles } : {}), + ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + }); + }), +).pipe( + Command.withDescription( + "Measure a checkout's server: startup, rest, first word, quiet threads with their cost per thread, streaming, and an optional soak.", + ), +); -if (import.meta.main) { - const [command, ...args] = process.argv.slice(2); - const threshold = Number(option(args, "--threshold") ?? 10); - if (command === "run") { - const out = option(args, "--out"); - const options = { - ...runOptions(args, option(args, "--checkout") ?? harnessRoot), - profileDir: out ? out.replace(/\.json$/, "") + "-profiles" : undefined, - }; - write(out, await runMany(options, Number(option(args, "--repeat") ?? 1))); - } else if (command === "ab" && args[0] && args[1] && !args[0].startsWith("--")) { - const outDir = NodePath.resolve(option(args, "--out-dir") ?? "server-metrics-ab"); - NodeFS.mkdirSync(outDir, { recursive: true }); - const sides = [args[0], args[1]].map((checkout) => runOptions(args, checkout)); - const metas = sides.map((side) => metaFor(side)); +const abCommand = Command.make( + "ab", + { + ...runFlags, + checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")), + checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")), + rounds: Flag.Int("rounds").pipe( + Flag.withDescription("Rounds; each runs A and B once, alternating which goes first."), + Flag.withDefault(3), + ), + outDir: Flag.String("out-dir").pipe( + Flag.withDescription("Directory for a.json and b.json."), + Flag.withDefault("server-metrics-ab"), + ), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.ab")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const outDir = path.resolve(input.outDir); + yield* fs.makeDirectory(outDir, { recursive: true }); + const sides = [ + yield* toRunOptions(input, input.checkoutA, undefined), + yield* toRunOptions(input, input.checkoutB, undefined), + ] as const; + const metas = [yield* metaFor(sides[0]), yield* metaFor(sides[1])] as const; const runs: [Measured[], Measured[]] = [[], []]; - const rounds = Number(option(args, "--rounds") ?? 3); - for (let round = 0; round < rounds; round++) { + for (let round = 0; round < input.rounds; round++) { // A B, then B A, so a drift in machine load lands on both sides. - for (const side of round % 2 === 0 ? [0, 1] : [1, 0]) { - console.error(`round ${round + 1}/${rounds}: ${side === 0 ? "A" : "B"}`); - runs[side]!.push((await runOnce(sides[side]!)).measured); + for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { + yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`); + runs[side].push((yield* runOnce(sides[side])).measured); } } - const [before, after] = [0, 1].map((side) => ({ - meta: { ...metas[side]!, loadAfter: machineLoad() }, - runs: runs[side]!, - })); - write(NodePath.join(outDir, "a.json"), before!); - write(NodePath.join(outDir, "b.json"), after!); - printComparison(before!, after!, threshold); - } else if (command === "compare" && args[0] && args[1]) { - const read = (path: string) => JSON.parse(NodeFS.readFileSync(path, "utf8")) as ServerMetrics; - printComparison(read(args[0]), read(args[1]), threshold); - } else { - console.log(HELP); - if (command !== "--help" && command !== "-h" && command !== undefined) process.exitCode = 1; - } + const loadAfter = yield* machineLoad; + const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] }; + const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] }; + yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); + yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); + yield* report(before, after, input.threshold); + }), +).pipe( + Command.withDescription( + "Run two checkouts alternately on this machine and compare them. Each needs its dependencies installed; the harness comes from this script, so an old release works too.", + ), +); + +const compareCommand = Command.make( + "compare", + { + before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")), + after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.compare")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + yield* report(yield* read(input.before), yield* read(input.after), input.threshold); + }), +).pipe( + Command.withDescription( + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + ), +); + +const serverMetricsCommand = Command.make("server-metrics").pipe( + Command.withDescription( + "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + ), + Command.withSubcommands([runCommand, abCommand, compareCommand]), +); + +if (import.meta.main) { + Command.run(serverMetricsCommand, { version: "0.0.0" }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeHttpClient.layerUndici, + NodeSocket.layerWebSocketConstructor, + ), + ), + NodeRuntime.runMain, + ); } From 6c14cf3828d20854ce5784edb0bb9452584eb4c4 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:11:14 -0800 Subject: [PATCH 04/10] fix(scripts): server metrics fails loudly instead of reporting bad numbers From review: - A failed or unreadable process probe fails the window instead of reading as 0. - Linux context switches are summed per task, so a thread that exits between two samples cannot make the rate negative; each counter uses its own interval and a monotonic clock. - Inspector error replies and a closed inspector fail the waiting call. - Soak turns go to real thread ids (stderr's `Thread `, with a half-open index) and a failed turn fails the soak; streaming waits for its own five replies and fails without them. - compare fails when the two files share no metric; soak growth lists only constructors that grew. - --threads must ascend; --runs, --repeat and --rounds must be at least 1. - CLAUDE_CONFIG_DIR is dropped from the server's environment; cleanup runs even when descendant discovery fails; the last sample counts toward the RSS peak. Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 12 +- scripts/server-metrics.test.ts | 98 ++++++++------ scripts/server-metrics.ts | 222 +++++++++++++++++++++++-------- 3 files changed, 234 insertions(+), 98 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 97092191ecbf2..a32f0224a70eb 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -153,6 +153,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre ]; const regressed: string[] = []; const improved: string[] = []; + let compared = 0; for (const metric of new Set([...a.keys(), ...b.keys()])) { if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; const x = a.get(metric); @@ -161,6 +162,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); continue; } + compared++; const mx = median(x); const my = median(y); // A change counts only past both the relative threshold and the absolute noise floor. @@ -179,7 +181,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, ); } - return { table: lines.join("\n"), regressed, improved }; + return { table: lines.join("\n"), regressed, improved, compared }; } const CallFrame = Schema.Struct({ @@ -290,8 +292,10 @@ export function heapGrowth( .map(([name, { count, bytes }]) => ({ constructor: name, count: count - (before.get(name)?.count ?? 0), - MB: round((bytes - (before.get(name)?.bytes ?? 0)) / 1e6, 2), + bytes: bytes - (before.get(name)?.bytes ?? 0), })) - .toSorted((a, b) => b.MB - a.MB) - .slice(0, 25); + .filter((entry) => entry.bytes > 0) + .toSorted((a, b) => b.bytes - a.bytes) + .slice(0, 25) + .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); } diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index dd704c5eb269d..8d348c86609ac 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,65 +1,87 @@ import { describe, expect, it } from "vite-plus/test"; -import { compareMetrics, slope, type ServerMetrics } from "./server-metrics-report.ts"; +import { compareMetrics, heapGrowth, slope, type ServerMetrics } from "./server-metrics-report.ts"; type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; +const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; const quietRuns = (...runs: Quiet[]) => ({ - meta: { commit: "abc", platform: "linux-x64", noAgentScope: true }, + meta, runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })), }) satisfies ServerMetrics; const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; +const cpuRuns = (...values: number[]) => + quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); describe("compareMetrics", () => { it.each([ - ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"]], - ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, []], - ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, []], - ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"]], - ["an improvement", { cpuPct: 0.1, wakeupsPerSec: 7 }, []], - ])("one run each: %s", (_name, change, regressed) => { - expect(compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })).regressed).toEqual( - regressed, - ); + ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], + ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, [], []], + ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, [], []], + ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"], []], + [ + "an improvement past the floors", + { cpuPct: 0.1, wakeupsPerSec: 7, rssPeakMB: 400 }, + [], + ["quiet.rssPeakMB"], + ], + ])("one run each: %s", (_name, change, regressed, improved) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); }); - it("does not treat a metric missing on one side as a regression", () => { + it("shows a metric missing on one side as n/a, not as a change", () => { const before = quietRuns({ ...base, wakeupsPerSec: null }); - expect(compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 9 })).regressed).toEqual([]); + const result = compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 50 })); + expect(result.regressed).toEqual([]); + expect(result.table).toContain("| quiet.wakeupsPerSec | – | 50 | n/a | | |"); }); it("flags repeated runs only when the whole interval clears the limit", () => { - const steady = quietRuns( - { ...base, cpuPct: 26.1 }, - { ...base, cpuPct: 27.4 }, - { ...base, cpuPct: 25.8 }, - ); - const fixed = quietRuns( - { ...base, cpuPct: 2.2 }, - { ...base, cpuPct: 2.5 }, - { ...base, cpuPct: 2.1 }, - ); + const steady = cpuRuns(26.1, 27.4, 25.8); + const fixed = cpuRuns(2.2, 2.5, 2.1); expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); - // One noisy run on each side overlaps the other side's values. - const noisy = quietRuns( - { ...base, cpuPct: 2.2 }, - { ...base, cpuPct: 9 }, - { ...base, cpuPct: 2.4 }, - ); - expect(compareMetrics(fixed, noisy).regressed).toEqual([]); + // The medians differ by 2.8 points, past the floor, but a resampled median can match. + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + }); + + it("counts how many metrics both sides share", () => { + const startupOnly: ServerMetrics = { meta, runs: [{ startup: { readyMs: 9_000 } }] }; + expect(compareMetrics(startupOnly, quietRuns(base)).compared).toBe(0); + expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(5); + }); +}); + +describe("heapGrowth", () => { + it("lists only constructors that grew, small growth included", () => { + const before = new Map([ + ["Shrank", { count: 10, bytes: 5_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 1, bytes: 1_000 }], + ]); + const after = new Map([ + ["Shrank", { count: 5, bytes: 1_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 2, bytes: 1_500 }], + ["New", { count: 4, bytes: 3_000_000 }], + ]); + expect(heapGrowth(before, after)).toEqual([ + { constructor: "New", count: 4, MB: 3 }, + { constructor: "Grew", count: 1, MB: 0 }, + ]); }); }); describe("slope", () => { it("fits the cost per thread", () => { - expect( - slope([ - [0, 175], - [5, 180], - [10, 185], - [20, 195], - ]), - ).toBeCloseTo(1); + const points: Array = [ + [0, 175], + [5, 180], + [10, 185], + [20, 195], + ]; + expect(slope(points)).toBeCloseTo(1); }); }); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 2c3c6f48e3ef3..00a6838e6de9c 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -72,6 +72,9 @@ const output = (program: string, args: ReadonlyArray, cwd?: string) => const powershell = (script: string) => output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); +/** Milliseconds on a monotonic clock, for intervals only. */ +const nowMs = Effect.map(Clock.monotonicTimeNanos, (nanos) => Number(nanos) / 1e6); + const httpServerOn = (port: number) => NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" }); @@ -108,7 +111,7 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio ); const streamed = body.stream === true; requests.push({ - at: yield* Clock.currentTimeMillis, + at: yield* nowMs, stream: streamed, // Title and branch-name jobs carry only their structured-output tool; the agent carries many. agent: streamed && (body.tools?.length ?? 0) > 1, @@ -194,13 +197,18 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { const socket = yield* Socket.makeWebSocket(url); const reader = yield* socket.reader; const writer = yield* socket.writer; - const pending = new Map>(); + const pending = new Map< + number, + { method: string; answer: Deferred.Deferred } + >(); const chunks: string[] = []; let nextId = 0; + let closed = false; const decodeMessage = decodeJson( Schema.Struct({ id: Schema.optional(Schema.Number), result: Schema.optional(Schema.Unknown), + error: Schema.optional(Schema.Struct({ message: Schema.String })), method: Schema.optional(Schema.String), params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })), }), @@ -214,7 +222,13 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { if (message.id !== undefined) { const waiting = pending.get(message.id); pending.delete(message.id); - return waiting ? Deferred.succeed(waiting, message.result) : Effect.void; + if (!waiting) return Effect.void; + return message.error + ? Deferred.fail( + waiting.answer, + new MetricsError({ message: `${waiting.method}: ${message.error.message}` }), + ) + : Deferred.succeed(waiting.answer, message.result); } if (message.method === "HeapProfiler.addHeapSnapshotChunk") { chunks.push(message.params?.chunk ?? ""); @@ -227,12 +241,24 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { ), Effect.forever, Effect.ignore, + // A closed connection answers nothing, so every waiting call fails instead of hanging. + Effect.ensuring( + Effect.suspend(() => { + closed = true; + const waiting = [...pending.values()]; + pending.clear(); + return Effect.forEach(waiting, ({ method, answer }) => + Deferred.fail(answer, new MetricsError({ message: `${method}: the inspector closed` })), + ); + }), + ), Effect.forkScoped, ); const send = Effect.fn("serverMetrics.cdp")(function* (method: string, params: object = {}) { + if (closed) return yield* new MetricsError({ message: `${method}: the inspector closed` }); const id = ++nextId; - const answer = yield* Deferred.make(); - pending.set(id, answer); + const answer = yield* Deferred.make(); + pending.set(id, { method, answer }); yield* writer.write(encodeJson({ id, method, params })); return yield* Deferred.await(answer); }); @@ -276,34 +302,46 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { }; }); -/** CPU seconds and RSS bytes of one process. */ +/** CPU seconds and RSS bytes of one process; a failed or unreadable probe fails the window. */ const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { const platform = yield* HostProcess.Platform; + const checked = (cpuSeconds: number, rss: number, probe: string) => + Number.isFinite(cpuSeconds) && Number.isFinite(rss) + ? Effect.succeed({ cpuSeconds, rss }) + : Effect.fail(new MetricsError({ message: `could not read process ${pid}: ${probe}` })); if (platform === "linux") { const fs = yield* FileSystem.FileSystem; const stat = (yield* fs.readFileString(`/proc/${pid}/stat`)).split(") ")[1]?.split(" ") ?? []; const status = yield* fs.readFileString(`/proc/${pid}/status`); - return { - cpuSeconds: (Number(stat[11]) + Number(stat[12])) / 100, - rss: Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0) * 1024, - }; + const rss = /VmRSS:\s+(\d+)/.exec(status)?.[1]; + return yield* checked( + (Number(stat[11]) + Number(stat[12])) / 100, + rss === undefined ? Number.NaN : Number(rss) * 1024, + "/proc", + ); } if (platform === "win32") { const line = yield* powershell( `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, ); - const [cpu = "0", rss = "0"] = Option.getOrElse(line, () => "").split(/\s+/); - return { cpuSeconds: Number(cpu), rss: Number(rss) }; + const [cpu = "", rss = ""] = Option.getOrElse(line, () => "").split(/\s+/); + return yield* checked( + cpu ? Number(cpu) : Number.NaN, + rss ? Number(rss) : Number.NaN, + "Get-Process", + ); } const line = yield* output("ps", ["-o", "rss=,time=", "-p", `${pid}`]); - const [rss = "0", time = "0:0"] = Option.getOrElse(line, () => "") + const [rss = "", time = ""] = Option.getOrElse(line, () => "") .split(/\s+/) .filter(Boolean); const cpuSeconds = time - .split(":") - .map(Number) - .reduce((total, part) => total * 60 + part, 0); - return { cpuSeconds, rss: Number(rss) * 1024 }; + ? time + .split(":") + .map(Number) + .reduce((total, part) => total * 60 + part, 0) + : Number.NaN; + return yield* checked(cpuSeconds, rss ? Number(rss) * 1024 : Number.NaN, "ps"); }); const numberOrNull = (text: Option.Option) => { @@ -311,24 +349,34 @@ const numberOrNull = (text: Option.Option) => { return Option.isSome(text) && text.value !== "" && Number.isFinite(value) ? value : null; }; -/** Context switches of one process since it started, or null when this platform cannot tell. */ +/** + * Context switches so far, by Linux task (one total elsewhere), or null when this platform + * cannot tell. Per task, so a thread that exits between two samples drops out of both. + */ const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pid: number) { const platform = yield* HostProcess.Platform; if (platform === "linux") { const fs = yield* FileSystem.FileSystem; - let switches = 0; + const switches = new Map(); for (const task of yield* fs.readDirectory(`/proc/${pid}/task`)) { const status = yield* fs .readFileString(`/proc/${pid}/task/${task}/status`) - .pipe(Effect.orElseSucceed(() => "")); - for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g)) switches += Number(match[1]); + .pipe(Effect.option); + if (Option.isNone(status)) continue; + let total = 0; + for (const match of status.value.matchAll(/ctxt_switches:\s+(\d+)/g)) + total += Number(match[1]); + switches.set(task, total); } return switches; } + const total = (value: number | null) => (value === null ? null : new Map([["process", value]])); if (platform === "win32") { - return numberOrNull( - yield* powershell( - `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, + return total( + numberOrNull( + yield* powershell( + `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, + ), ), ); } @@ -338,9 +386,20 @@ const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pi .split("\n") .map((line) => line.trim().split(/\s+/)) .find(([first]) => first === `${pid}`); - return numberOrNull(Option.fromNullishOr(row?.[1])); + return total(numberOrNull(Option.fromNullishOr(row?.[1]))); }); +/** Switches between two samples: tasks new in the second count whole; a negative total is unknown. */ +const switchesBetween = ( + first: ReadonlyMap | null, + last: ReadonlyMap | null, +) => { + if (first === null || last === null) return null; + let delta = 0; + for (const [task, count] of last) delta += count - (first.get(task) ?? 0); + return delta < 0 ? null : delta; +}; + /** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { const platform = yield* HostProcess.Platform; @@ -428,6 +487,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const dropped = new Set([ "ANTHROPIC_AUTH_TOKEN", "T3CODE_HOME", + "CLAUDE_CONFIG_DIR", ...(environment.noAgentScope ? ["XDG_RUNTIME_DIR"] : []), ]); const env: Record = { @@ -445,7 +505,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( T3CODE_DEV_SEED: "0", }; const port = yield* freePort; - const started = yield* Clock.currentTimeMillis; + const started = yield* nowMs; const child = yield* spawner.spawn( ChildProcess.make( node, @@ -482,7 +542,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( yield* Effect.addFinalizer(() => Effect.gen(function* () { - const spawned = yield* descendantsOf(pid); + const spawned = yield* descendantsOf(pid).pipe(Effect.orElseSucceed(() => [])); if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]); else yield* child.kill({ killSignal: "SIGTERM" }).pipe(Effect.ignore); yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore); @@ -497,7 +557,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe( Effect.timeout(Duration.seconds(1)), Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }), - Effect.flatMap(() => Clock.currentTimeMillis), + Effect.andThen(nowMs), Effect.map((now) => Math.round(now - started)), Effect.catch(() => Effect.flatMap( @@ -524,25 +584,26 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000); const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) { + // Each counter is divided by the time between its own two reads; a CIM probe can take seconds. + const switchesStart = yield* nowMs; const firstSwitches = yield* contextSwitches(pid); + const start = yield* nowMs; const first = yield* sample(pid); let rssPeak = first.rss; - const start = yield* Clock.currentTimeMillis; - while ((yield* Clock.currentTimeMillis) - start < seconds * 1_000) { + while ((yield* nowMs) - start < seconds * 1_000) { yield* Effect.sleep(sampleEvery); rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss); } const last = yield* sample(pid); + const cpuElapsed = ((yield* nowMs) - start) / 1_000; const lastSwitches = yield* contextSwitches(pid); - const elapsed = ((yield* Clock.currentTimeMillis) - start) / 1_000; + const switchesElapsed = ((yield* nowMs) - switchesStart) / 1_000; + const switches = switchesBetween(firstSwitches, lastSwitches); const heap = yield* devtools.heapAfterGc; const window: Window = { - cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / elapsed) * 100), - wakeupsPerSec: - firstSwitches === null || lastSwitches === null - ? null - : round((lastSwitches - firstSwitches) / elapsed), - rssPeakMB: Math.round(rssPeak / 1e6), + cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), + wakeupsPerSec: switches === null ? null : round(switches / switchesElapsed), + rssPeakMB: Math.round(Math.max(rssPeak, last.rss) / 1e6), rssMB: Math.round((yield* sample(pid)).rss / 1e6), heapAfterGcMB: round(heap / 1e6), }; @@ -583,14 +644,16 @@ const firstWord = Effect.fn("serverMetrics.firstWord")(function* ( const toDone: number[] = []; for (let index = 0; index < runs; index++) { const marker = `bench-run-${worktree ? 1000 + index : index}`; - const started = yield* Clock.currentTimeMillis; + const started = yield* nowMs; const result = yield* server.threadStart(`Say hello. ${marker}`, [ "--wait", ...(worktree ? ["--worktree", "main"] : []), ]); - const done = (yield* Clock.currentTimeMillis) - started; + const done = (yield* nowMs) - started; if (result.exitCode !== 0) { - return yield* new MetricsError({ message: `thread start failed: ${result.stdout}` }); + return yield* new MetricsError({ + message: `thread start failed: ${result.stderr.trim() || result.stdout.trim()}`, + }); } const request = environment.requests.find( (entry) => entry.agent && entry.marker === marker && entry.at >= started, @@ -616,9 +679,18 @@ const openThreads = Effect.fn("serverMetrics.openThreads")(function* ( (index) => server.threadStart(`Say hello ${index}.`, ["--wait"]), { concurrency: "unbounded" }, ); - const failed = answers.filter((answer) => answer.exitCode !== 0).length; - if (failed) return yield* new MetricsError({ message: `${failed} of ${count} threads failed` }); - return answers.map((answer) => /Thread (\S+)/.exec(answer.stdout)?.[1] ?? ""); + const failed = answers.find((answer) => answer.exitCode !== 0); + if (failed) { + return yield* new MetricsError({ + message: `a thread failed to answer: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + // Without --json, `thread start` prints the new thread's id to stderr, older releases too. + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + if (ids.some((id) => id === undefined)) { + return yield* new MetricsError({ message: "thread start printed no thread id" }); + } + return ids.filter((id) => id !== undefined); }); const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; @@ -634,7 +706,7 @@ interface RunOptions { readonly profileDir: string | undefined; } -/** One pass over the scenarios, each on a fresh server. */ +/** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -725,18 +797,29 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption if (wanted("streaming")) { yield* withServer("streaming", (server) => Effect.gen(function* () { + // Earlier scenarios share the fake API, so only this launch's markers count. + const markers = [0, 1, 2, 3, 4].map((index) => `bench-run-${9_000 + index}`); const started = yield* Effect.forEach( - [0, 1, 2, 3, 4], - (index) => server.threadStart(`Write a long answer ${index}. ${SLOW_MARKER}`), + markers, + (marker) => server.threadStart(`Write a long answer. ${SLOW_MARKER} ${marker}`), { concurrency: "unbounded" }, ); if (started.some((answer) => answer.exitCode !== 0)) { return yield* new MetricsError({ message: "streaming start failed" }); } - const streaming = () => api.requests.filter((request) => request.agent && request.stream); - for (let attempt = 0; attempt < 300 && streaming().length < 5; attempt++) { + const streaming = () => + new Set( + api.requests + .filter((request) => request.agent && request.stream) + .map((request) => request.marker), + ); + for (let attempt = 0; attempt < 300; attempt++) { + if (markers.every((marker) => streaming().has(marker))) break; yield* Effect.sleep(Duration.millis(100)); } + if (!markers.every((marker) => streaming().has(marker))) { + return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); + } yield* Effect.sleep(Duration.seconds(5)); measured.streaming = yield* server.measure(60); yield* profile(server, "streaming"); @@ -751,8 +834,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption // The snapshot inflates RSS once, so the slopes start after it. const before = yield* server.snapshot; const samples: Array<{ hours: number; window: Window }> = []; - const start = yield* Clock.currentTimeMillis; - const elapsed = Effect.map(Clock.currentTimeMillis, (now) => now - start); + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); const takeSample = Effect.gen(function* () { samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); }); @@ -762,8 +845,16 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* takeSample; nextSample += 120_000; } - const threadId = threads[yield* Random.nextIntBetween(0, threads.length)] ?? ""; - yield* server.threadSend(threadId, `Short reply ${turn}.`); + const threadId = + threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); } yield* takeSample; @@ -853,8 +944,13 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { - const { table, regressed, improved } = compareMetrics(before, after, threshold); + const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); yield* Console.log(table); + if (compared === 0) { + return yield* new MetricsError({ + message: "the two files share no metric, so nothing was compared", + }); + } if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); if (regressed.length === 0) return; yield* Console.error(`Worse: ${regressed.join(", ")}`); @@ -916,9 +1012,19 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( return yield* new MetricsError({ message: `unknown scenario: ${unknown.join(", ")}` }); } const threads = flags.threads.split(",").map(Number); - if (threads.some((count) => !Number.isInteger(count) || count < 0)) { - return yield* new MetricsError({ message: "--threads takes counts such as 0,5,10,20" }); + // Threads stay open, so a lower count after a higher one would mislabel its window. + if ( + threads.some( + (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), + ) + ) { + return yield* new MetricsError({ + message: "--threads takes ascending counts such as 0,5,10,20", + }); } + if (flags.runs < 1) return yield* new MetricsError({ message: "--runs must be at least 1" }); + if (flags.soak < 0) + return yield* new MetricsError({ message: "--soak takes minutes, 0 for none" }); const options: RunOptions = { checkout: path.resolve(checkout), noAgentScope: flags.noAgentScope, @@ -953,6 +1059,8 @@ const runCommand = Command.make( const profileDir = Option.getOrUndefined( Option.map(input.out, (out) => `${out.replace(/\.json$/, "")}-profiles`), ); + if (input.repeat < 1) + return yield* new MetricsError({ message: "--repeat must be at least 1" }); const options = yield* toRunOptions(input, checkout, profileDir); const meta = yield* metaFor(options); const runs: Measured[] = []; @@ -970,7 +1078,7 @@ const runCommand = Command.make( }), ).pipe( Command.withDescription( - "Measure a checkout's server: startup, rest, first word, quiet threads with their cost per thread, streaming, and an optional soak.", + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", ), ); @@ -991,6 +1099,8 @@ const abCommand = Command.make( threshold: thresholdFlag, }, Effect.fn("serverMetrics.ab")(function* (input) { + if (input.rounds < 1) + return yield* new MetricsError({ message: "--rounds must be at least 1" }); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const outDir = path.resolve(input.outDir); From 5310068356e84066d3f3b5fdf5e2e8467d9db132 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:32:10 -0800 Subject: [PATCH 05/10] fix(scripts): server metrics leaves a task it could not read out of the wakeup count Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 17 +++++++++++++++++ scripts/server-metrics.test.ts | 28 +++++++++++++++++++++++++++- scripts/server-metrics.ts | 18 ++++++------------ 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index a32f0224a70eb..8b8070d43a5da 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -65,6 +65,23 @@ export type ServerMetrics = typeof ServerMetrics.Type; export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; +/** + * Switches between two samples: tasks new in the second count whole, tasks unreadable in either are + * left out, and a negative total is unknown. + */ +export const switchesBetween = ( + first: ReadonlyMap | null, + last: ReadonlyMap | null, +) => { + if (first === null || last === null) return null; + let delta = 0; + for (const [task, count] of last) { + const start = first.get(task) ?? 0; + if (!Number.isNaN(count) && !Number.isNaN(start)) delta += count - start; + } + return delta < 0 ? null : delta; +}; + export function spread(values: ReadonlyArray) { const sorted = values.toSorted((a, b) => a - b); const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 8d348c86609ac..c542946044b49 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; -import { compareMetrics, heapGrowth, slope, type ServerMetrics } from "./server-metrics-report.ts"; +import { + compareMetrics, + heapGrowth, + slope, + switchesBetween, + type ServerMetrics, +} from "./server-metrics-report.ts"; type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; @@ -85,3 +91,23 @@ describe("slope", () => { expect(slope(points)).toBeCloseTo(1); }); }); + +describe("switchesBetween", () => { + it.each([ + ["a task in both samples counts its growth", [["1", 100]], [["1", 160]], 60], + [ + "a task new in the second sample counts whole", + [["1", 100]], + [ + ["1", 100], + ["2", 40], + ], + 40, + ], + ["a task unreadable at first is left out", [["1", Number.NaN]], [["1", 100_060]], 0], + ["a task unreadable at the end is left out", [["1", 100]], [["1", Number.NaN]], 0], + ["a negative total is unknown", [["1", 100]], [["1", 40]], null], + ] as const)("%s", (_name, first, last, expected) => { + expect(switchesBetween(new Map(first), new Map(last))).toBe(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 00a6838e6de9c..bc6a27c992ab0 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -45,6 +45,7 @@ import { slope, spread, summarizeProfiles, + switchesBetween, type FirstWord, type Measured, type ProfileSummary, @@ -362,7 +363,11 @@ const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pi const status = yield* fs .readFileString(`/proc/${pid}/task/${task}/status`) .pipe(Effect.option); - if (Option.isNone(status)) continue; + // A task listed but unreadable has no known count; NaN keeps it out of the delta. + if (Option.isNone(status)) { + switches.set(task, Number.NaN); + continue; + } let total = 0; for (const match of status.value.matchAll(/ctxt_switches:\s+(\d+)/g)) total += Number(match[1]); @@ -389,17 +394,6 @@ const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pi return total(numberOrNull(Option.fromNullishOr(row?.[1]))); }); -/** Switches between two samples: tasks new in the second count whole; a negative total is unknown. */ -const switchesBetween = ( - first: ReadonlyMap | null, - last: ReadonlyMap | null, -) => { - if (first === null || last === null) return null; - let delta = 0; - for (const [task, count] of last) delta += count - (first.get(task) ?? 0); - return delta < 0 ? null : delta; -}; - /** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { const platform = yield* HostProcess.Platform; From bda5eb591f1aa843520d97c017240377d1c3b3c5 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:37:06 -0800 Subject: [PATCH 06/10] fix(scripts): server metrics counts wakeups with the process's lifetime counter Per-thread counters lose the switches of threads that exit during the window, and miss threads that start and exit between samples. getrusage through the inspector keeps them. Windows reports none that way, so its wakeups are null. Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 17 -------- scripts/server-metrics.test.ts | 28 +------------ scripts/server-metrics.ts | 71 ++++++++------------------------ 3 files changed, 19 insertions(+), 97 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 8b8070d43a5da..a32f0224a70eb 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -65,23 +65,6 @@ export type ServerMetrics = typeof ServerMetrics.Type; export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; -/** - * Switches between two samples: tasks new in the second count whole, tasks unreadable in either are - * left out, and a negative total is unknown. - */ -export const switchesBetween = ( - first: ReadonlyMap | null, - last: ReadonlyMap | null, -) => { - if (first === null || last === null) return null; - let delta = 0; - for (const [task, count] of last) { - const start = first.get(task) ?? 0; - if (!Number.isNaN(count) && !Number.isNaN(start)) delta += count - start; - } - return delta < 0 ? null : delta; -}; - export function spread(values: ReadonlyArray) { const sorted = values.toSorted((a, b) => a - b); const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index c542946044b49..8d348c86609ac 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,12 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { - compareMetrics, - heapGrowth, - slope, - switchesBetween, - type ServerMetrics, -} from "./server-metrics-report.ts"; +import { compareMetrics, heapGrowth, slope, type ServerMetrics } from "./server-metrics-report.ts"; type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; @@ -91,23 +85,3 @@ describe("slope", () => { expect(slope(points)).toBeCloseTo(1); }); }); - -describe("switchesBetween", () => { - it.each([ - ["a task in both samples counts its growth", [["1", 100]], [["1", 160]], 60], - [ - "a task new in the second sample counts whole", - [["1", 100]], - [ - ["1", 100], - ["2", 40], - ], - 40, - ], - ["a task unreadable at first is left out", [["1", Number.NaN]], [["1", 100_060]], 0], - ["a task unreadable at the end is left out", [["1", 100]], [["1", Number.NaN]], 0], - ["a negative total is unknown", [["1", 100]], [["1", 40]], null], - ] as const)("%s", (_name, first, last, expected) => { - expect(switchesBetween(new Map(first), new Map(last))).toBe(expected); - }); -}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index bc6a27c992ab0..c827defde49e1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -45,7 +45,6 @@ import { slope, spread, summarizeProfiles, - switchesBetween, type FirstWord, type Measured, type ProfileSummary, @@ -264,9 +263,21 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { return yield* Deferred.await(answer); }); const decodeHeapUsage = Schema.decodeUnknownEffect(Schema.Struct({ usedSize: Schema.Number })); + const decodeEvaluated = Schema.decodeUnknownEffect( + Schema.Struct({ result: Schema.Struct({ value: Schema.Number }) }), + ); const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile })); const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile })); return { + // getrusage keeps the switches of threads that already exited, unlike per-thread counters. + contextSwitches: send("Runtime.evaluate", { + expression: + "(() => { const u = process.resourceUsage(); return u.voluntaryContextSwitches + u.involuntaryContextSwitches; })()", + returnByValue: true, + }).pipe( + Effect.flatMap(decodeEvaluated), + Effect.map(({ result }) => result.value), + ), heapAfterGc: Effect.gen(function* () { yield* send("HeapProfiler.collectGarbage"); yield* send("HeapProfiler.collectGarbage"); @@ -345,55 +356,6 @@ const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { return yield* checked(cpuSeconds, rss ? Number(rss) * 1024 : Number.NaN, "ps"); }); -const numberOrNull = (text: Option.Option) => { - const value = Number(Option.getOrElse(text, () => "").replace(/\+$/, "")); - return Option.isSome(text) && text.value !== "" && Number.isFinite(value) ? value : null; -}; - -/** - * Context switches so far, by Linux task (one total elsewhere), or null when this platform - * cannot tell. Per task, so a thread that exits between two samples drops out of both. - */ -const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pid: number) { - const platform = yield* HostProcess.Platform; - if (platform === "linux") { - const fs = yield* FileSystem.FileSystem; - const switches = new Map(); - for (const task of yield* fs.readDirectory(`/proc/${pid}/task`)) { - const status = yield* fs - .readFileString(`/proc/${pid}/task/${task}/status`) - .pipe(Effect.option); - // A task listed but unreadable has no known count; NaN keeps it out of the delta. - if (Option.isNone(status)) { - switches.set(task, Number.NaN); - continue; - } - let total = 0; - for (const match of status.value.matchAll(/ctxt_switches:\s+(\d+)/g)) - total += Number(match[1]); - switches.set(task, total); - } - return switches; - } - const total = (value: number | null) => (value === null ? null : new Map([["process", value]])); - if (platform === "win32") { - return total( - numberOrNull( - yield* powershell( - `(Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=${pid}" | Measure-Object ContextSwitchesPersec -Sum).Sum`, - ), - ), - ); - } - if (platform !== "darwin") return null; - const table = yield* output("top", ["-l", "1", "-pid", `${pid}`, "-stats", "pid,csw"]); - const row = Option.getOrElse(table, () => "") - .split("\n") - .map((line) => line.trim().split(/\s+/)) - .find(([first]) => first === `${pid}`); - return total(numberOrNull(Option.fromNullishOr(row?.[1]))); -}); - /** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { const platform = yield* HostProcess.Platform; @@ -579,8 +541,10 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000); const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) { // Each counter is divided by the time between its own two reads; a CIM probe can take seconds. + // Windows reports no context switches through getrusage, so wakeups are unknown there. + const countSwitches = platform === "win32" ? Effect.succeed(null) : devtools.contextSwitches; const switchesStart = yield* nowMs; - const firstSwitches = yield* contextSwitches(pid); + const firstSwitches = yield* countSwitches; const start = yield* nowMs; const first = yield* sample(pid); let rssPeak = first.rss; @@ -590,9 +554,10 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( } const last = yield* sample(pid); const cpuElapsed = ((yield* nowMs) - start) / 1_000; - const lastSwitches = yield* contextSwitches(pid); + const lastSwitches = yield* countSwitches; const switchesElapsed = ((yield* nowMs) - switchesStart) / 1_000; - const switches = switchesBetween(firstSwitches, lastSwitches); + const switches = + firstSwitches === null || lastSwitches === null ? null : lastSwitches - firstSwitches; const heap = yield* devtools.heapAfterGc; const window: Window = { cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), From e2fd6bec676ed9e1eadd0b4771e5b7b402dc4ee0 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:41:18 -0800 Subject: [PATCH 07/10] fix(scripts): server metrics rejects zero counts and malformed ps CPU times Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 8 ++++++++ scripts/server-metrics.test.ts | 22 +++++++++++++++++++++- scripts/server-metrics.ts | 13 ++++++------- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index a32f0224a70eb..24f2d2bbf6704 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -65,6 +65,14 @@ export type ServerMetrics = typeof ServerMetrics.Type; export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; +/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */ +export function parsePsCpuTime(text: string) { + const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); + if (match === null) return Number.NaN; + const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match; + return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds); +} + export function spread(values: ReadonlyArray) { const sorted = values.toSorted((a, b) => a - b); const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 8d348c86609ac..50ae690060951 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from "vite-plus/test"; -import { compareMetrics, heapGrowth, slope, type ServerMetrics } from "./server-metrics-report.ts"; +import { + compareMetrics, + heapGrowth, + parsePsCpuTime, + slope, + type ServerMetrics, +} from "./server-metrics-report.ts"; type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; @@ -85,3 +91,17 @@ describe("slope", () => { expect(slope(points)).toBeCloseTo(1); }); }); + +describe("parsePsCpuTime", () => { + it.each([ + ["0:00.00", 0], + ["1:02.50", 62.5], + ["1:00:00.00", 3600], + ["2-01:00:00", 2 * 86_400 + 3600], + ["::", Number.NaN], + ["", Number.NaN], + ["1:2:3:4", Number.NaN], + ])("%s", (text, seconds) => { + expect(parsePsCpuTime(text)).toBe(seconds); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index c827defde49e1..0e0570c75743e 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -44,6 +44,7 @@ import { ServerMetrics, slope, spread, + parsePsCpuTime, summarizeProfiles, type FirstWord, type Measured, @@ -51,6 +52,7 @@ import { type Window, } from "./server-metrics-report.ts"; +const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; @@ -347,13 +349,7 @@ const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { const [rss = "", time = ""] = Option.getOrElse(line, () => "") .split(/\s+/) .filter(Boolean); - const cpuSeconds = time - ? time - .split(":") - .map(Number) - .reduce((total, part) => total * 60 + part, 0) - : Number.NaN; - return yield* checked(cpuSeconds, rss ? Number(rss) * 1024 : Number.NaN, "ps"); + return yield* checked(parsePsCpuTime(time), rss ? Number(rss) * 1024 : Number.NaN, "ps"); }); /** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ @@ -931,6 +927,7 @@ const runFlags = { ), ), runs: Flag.Int("runs").pipe( + Flag.withSchema(PositiveInt), Flag.withDescription("firstWord runs in each variant."), Flag.withDefault(5), ), @@ -1006,6 +1003,7 @@ const runCommand = Command.make( Flag.optional, ), repeat: Flag.Int("repeat").pipe( + Flag.withSchema(PositiveInt), Flag.withDescription("Runs to record in one file."), Flag.withDefault(1), ), @@ -1048,6 +1046,7 @@ const abCommand = Command.make( checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")), checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")), rounds: Flag.Int("rounds").pipe( + Flag.withSchema(PositiveInt), Flag.withDescription("Rounds; each runs A and B once, alternating which goes first."), Flag.withDefault(3), ), From 109be74c8556ebbb583e142616ced2850d1fae6a Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:44:11 -0800 Subject: [PATCH 08/10] fix(scripts): server metrics waits only for streams this launch started Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 0e0570c75743e..b56a0307d8c6f 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -752,8 +752,9 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption if (wanted("streaming")) { yield* withServer("streaming", (server) => Effect.gen(function* () { - // Earlier scenarios share the fake API, so only this launch's markers count. + // Earlier scenarios share the fake API, so only this launch's requests count. const markers = [0, 1, 2, 3, 4].map((index) => `bench-run-${9_000 + index}`); + const launchedAt = yield* nowMs; const started = yield* Effect.forEach( markers, (marker) => server.threadStart(`Write a long answer. ${SLOW_MARKER} ${marker}`), @@ -765,7 +766,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const streaming = () => new Set( api.requests - .filter((request) => request.agent && request.stream) + .filter((request) => request.agent && request.stream && request.at >= launchedAt) .map((request) => request.marker), ); for (let attempt = 0; attempt < 300; attempt++) { From 8f34f0ea7658d31e6eef46359900f4230373a2f9 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:46:55 -0800 Subject: [PATCH 09/10] fix(scripts): server metrics force-kills a server that ignores SIGTERM Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index b56a0307d8c6f..bd549ed2a349b 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -477,6 +477,8 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( cwd: environment.serverDir, env, extendEnv: false, + // A server that ignores SIGTERM still stops, so cleanup always reaches the temp dir. + forceKillAfter: Duration.seconds(10), stdin: "ignore", stdout: "ignore", stderr: "pipe", @@ -496,7 +498,10 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( Effect.gen(function* () { const spawned = yield* descendantsOf(pid).pipe(Effect.orElseSucceed(() => [])); if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]); - else yield* child.kill({ killSignal: "SIGTERM" }).pipe(Effect.ignore); + else + yield* child + .kill({ killSignal: "SIGTERM", forceKillAfter: Duration.seconds(10) }) + .pipe(Effect.timeout(Duration.seconds(15)), Effect.ignore); yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore); if (spawned.length > 0) yield* output("kill", ["-9", ...spawned.map(String)]); // Windows keeps a file locked for a moment after its process exits. From 16c957d41245a7e160138eba2a20b6290abc0a6c Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:53:02 -0800 Subject: [PATCH 10/10] fix(scripts): server metrics times each probe at its midpoint and tests run selection Co-Authored-By: Claude Opus 5.5 --- scripts/scenarios/shell.ts | 2 +- scripts/server-metrics-report.ts | 32 +++++++++++++++- scripts/server-metrics.test.ts | 51 ++++++++++++++++++++++++ scripts/server-metrics.ts | 66 ++++++++++++++++---------------- 4 files changed, 117 insertions(+), 34 deletions(-) diff --git a/scripts/scenarios/shell.ts b/scripts/scenarios/shell.ts index 40e3b224fa694..32adbe1920a8c 100644 --- a/scripts/scenarios/shell.ts +++ b/scripts/scenarios/shell.ts @@ -52,7 +52,7 @@ export const run = Effect.fn("scenario.run")( ); if (!(options.allowExit ?? [0]).includes(exitCode)) { return yield* new ScenarioError({ - message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${stderr.trim().slice(-600)}`, + message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${(stderr.trim() || stdout.trim()).slice(-600)}`, }); } return { stdout, stderr, exitCode: Number(exitCode) }; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 24f2d2bbf6704..c024e9737ef46 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -67,12 +67,42 @@ export const round = (value: number, digits = 1) => Math.round(value * 10 ** dig /** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */ export function parsePsCpuTime(text: string) { - const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); + const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); if (match === null) return Number.NaN; const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match; return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds); } +/** + * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay + * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else. + */ +export function parseRunSelection(input: { + readonly only: string; + readonly threads: string; + readonly soak: number; + readonly scenarios: ReadonlyArray; +}): + | { readonly only: ReadonlyArray; readonly threads: ReadonlyArray } + | { readonly error: string } { + const only = input.only.split(",").filter(Boolean); + const unknown = only.filter((name) => !input.scenarios.includes(name)); + if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` }; + const threads = input.threads + .split(",") + .map((count) => (count.trim() === "" ? Number.NaN : Number(count))); + if ( + threads.some( + (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), + ) + ) { + return { error: "--threads takes ascending counts such as 0,5,10,20" }; + } + if (!Number.isInteger(input.soak) || input.soak < 0) + return { error: "--soak takes minutes, 0 for none" }; + return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads }; +} + export function spread(values: ReadonlyArray) { const sorted = values.toSorted((a, b) => a - b); const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 50ae690060951..fe87cbbd39c68 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -4,6 +4,7 @@ import { compareMetrics, heapGrowth, parsePsCpuTime, + parseRunSelection, slope, type ServerMetrics, } from "./server-metrics-report.ts"; @@ -98,6 +99,7 @@ describe("parsePsCpuTime", () => { ["1:02.50", 62.5], ["1:00:00.00", 3600], ["2-01:00:00", 2 * 86_400 + 3600], + ["1-02:03", Number.NaN], ["::", Number.NaN], ["", Number.NaN], ["1:2:3:4", Number.NaN], @@ -105,3 +107,52 @@ describe("parsePsCpuTime", () => { expect(parsePsCpuTime(text)).toBe(seconds); }); }); + +describe("parseRunSelection", () => { + const scenarios = ["rest", "quiet", "streaming"]; + it.each([ + [ + "the default thread counts", + { only: "", threads: "0,5,10,20", soak: 0 }, + { only: [], threads: [0, 5, 10, 20] }, + ], + [ + "descending thread counts", + { only: "", threads: "5,20,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "an empty thread count", + { only: "", threads: "0,,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "named scenarios", + { only: "rest,quiet", threads: "0", soak: 0 }, + { only: ["rest", "quiet"], threads: [0] }, + ], + [ + "an unknown scenario", + { only: "rest,idle", threads: "0", soak: 0 }, + { error: "unknown scenario: idle" }, + ], + ["a soak alone", { only: "", threads: "0", soak: 10 }, { only: ["none"], threads: [0] }], + [ + "a soak with scenarios", + { only: "rest", threads: "0", soak: 10 }, + { only: ["rest"], threads: [0] }, + ], + [ + "a negative soak", + { only: "", threads: "0", soak: -1 }, + { error: "--soak takes minutes, 0 for none" }, + ], + [ + "an infinite soak", + { only: "", threads: "0", soak: Number.POSITIVE_INFINITY }, + { error: "--soak takes minutes, 0 for none" }, + ], + ])("%s", (_name, input, expected) => { + expect(parseRunSelection({ ...input, scenarios })).toEqual(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index bd549ed2a349b..3a9887f40f5fb 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -45,6 +45,7 @@ import { slope, spread, parsePsCpuTime, + parseRunSelection, summarizeProfiles, type FirstWord, type Measured, @@ -535,7 +536,9 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( }); const added = yield* cli(["project", "add", project]); if (added.exitCode !== 0) { - return yield* new MetricsError({ message: `project add failed: ${added.stderr}` }); + return yield* new MetricsError({ + message: `project add failed: ${added.stderr.trim() || added.stdout.trim()}`, + }); } // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. @@ -544,21 +547,32 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( // Each counter is divided by the time between its own two reads; a CIM probe can take seconds. // Windows reports no context switches through getrusage, so wakeups are unknown there. const countSwitches = platform === "win32" ? Effect.succeed(null) : devtools.contextSwitches; - const switchesStart = yield* nowMs; - const firstSwitches = yield* countSwitches; - const start = yield* nowMs; - const first = yield* sample(pid); + // A probe can take seconds (CIM on Windows), so each read is timed at its midpoint. + const timed = Effect.fn("serverMetrics.timedRead")(function* ( + read: Effect.Effect, + ) { + const before = yield* nowMs; + const value = yield* read; + return { value, at: (before + (yield* nowMs)) / 2 }; + }); + const firstSwitches = yield* timed(countSwitches); + const firstSample = yield* timed(sample(pid)); + const first = firstSample.value; + const start = firstSample.at; let rssPeak = first.rss; while ((yield* nowMs) - start < seconds * 1_000) { yield* Effect.sleep(sampleEvery); rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss); } - const last = yield* sample(pid); - const cpuElapsed = ((yield* nowMs) - start) / 1_000; - const lastSwitches = yield* countSwitches; - const switchesElapsed = ((yield* nowMs) - switchesStart) / 1_000; + const lastSample = yield* timed(sample(pid)); + const last = lastSample.value; + const cpuElapsed = (lastSample.at - start) / 1_000; + const lastSwitches = yield* timed(countSwitches); + const switchesElapsed = (lastSwitches.at - firstSwitches.at) / 1_000; const switches = - firstSwitches === null || lastSwitches === null ? null : lastSwitches - firstSwitches; + firstSwitches.value === null || lastSwitches.value === null + ? null + : lastSwitches.value - firstSwitches.value; const heap = yield* devtools.heapAfterGc; const window: Window = { cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), @@ -946,6 +960,7 @@ const runFlags = { Flag.optional, ), soak: Flag.Int("soak").pipe( + Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", ), @@ -966,33 +981,20 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir: string | undefined, ) { const path = yield* Path.Path; - const only = Option.getOrElse(flags.only, () => "") - .split(",") - .filter(Boolean); - const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray).includes(name)); - if (unknown.length) { - return yield* new MetricsError({ message: `unknown scenario: ${unknown.join(", ")}` }); - } - const threads = flags.threads.split(",").map(Number); - // Threads stay open, so a lower count after a higher one would mislabel its window. - if ( - threads.some( - (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), - ) - ) { - return yield* new MetricsError({ - message: "--threads takes ascending counts such as 0,5,10,20", - }); - } - if (flags.runs < 1) return yield* new MetricsError({ message: "--runs must be at least 1" }); - if (flags.soak < 0) - return yield* new MetricsError({ message: "--soak takes minutes, 0 for none" }); + const selection = parseRunSelection({ + only: Option.getOrElse(flags.only, () => ""), + threads: flags.threads, + soak: flags.soak, + scenarios: SCENARIOS, + }); + if ("error" in selection) return yield* new MetricsError({ message: selection.error }); + const { only, threads } = selection; const options: RunOptions = { checkout: path.resolve(checkout), noAgentScope: flags.noAgentScope, runs: flags.runs, threads, - only: flags.soak > 0 && only.length === 0 ? ["none"] : only, + only, soakMinutes: flags.soak, profileDir, };