feat(scripts): a server metrics run catches CPU, memory and first-request regressions #41159
Mergedjuliusmarmingemerged 10 commits into
main fromrefs/pull/41159/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -0,0 +1,17 @@1+import { describe, expect, it } from "vite-plus/test";2+3+import { compareMetrics, type ServerMetrics } from "./server-metrics.ts";4+5+const metrics = (quiet: { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }) =>6+ ({7+ meta: { commit: "abc", platform: "linux-x64", macPath: true },8+ quiet: { ...quiet, heapAfterGcMB: 200 },9+ }) satisfies ServerMetrics;10+11+describe("compareMetrics", () => {12+ it.each([13+ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"]],14+ ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, []],15+ ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, []],16+ ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"]],17+ ["an improvement", { cpuPct: 0.1, wakeupsPerSec: 7 }, []],@@ -0,0 +326,21 @@326+ await fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(1_000) });327+ readyMs = Math.round(performance.now() - started);328+ } catch {329+ await sleep(100);330+ }331+ }332+ if (readyMs === undefined || !inspector) throw new Error(`server never answered:\n${stderr}`);333+ const devtools = await inspect(inspector);334+ const cli = (args: ReadonlyArray<string>) =>335+ new Promise<{ code: number | null; stdout: string }>((resolve) => {336+ const command = NodeChildProcess.spawn(337+ process.execPath,338+ ["src/bin.ts", ...args, "--base-dir", baseDir],339+ { cwd: serverDir, env, stdio: ["ignore", "pipe", "pipe"] },340+ );341+ let stdout = "";342+ command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));343+ command.on("exit", (code) => resolve({ code, stdout }));344+ });345+ const added = await cli(["project", "add", project]);346+ if (added.code !== 0) throw new Error(`project add failed: ${added.stdout}`);@@ -0,0 +323,21 @@323+ for (let attempt = 0; attempt < 600 && readyMs === undefined; attempt++) {324+ if (child.exitCode !== null) throw new Error(`server exited early:\n${stderr}`);325+ try {326+ await fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(1_000) });327+ readyMs = Math.round(performance.now() - started);328+ } catch {329+ await sleep(100);330+ }331+ }332+ if (readyMs === undefined || !inspector) throw new Error(`server never answered:\n${stderr}`);333+ const devtools = await inspect(inspector);334+ const cli = (args: ReadonlyArray<string>) =>335+ new Promise<{ code: number | null; stdout: string }>((resolve) => {336+ const command = NodeChildProcess.spawn(337+ process.execPath,338+ ["src/bin.ts", ...args, "--base-dir", baseDir],339+ { cwd: serverDir, env, stdio: ["ignore", "pipe", "pipe"] },340+ );341+ let stdout = "";342+ command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));343+ command.on("exit", (code) => resolve({ code, stdout }));@@ -0,0 +593,21 @@593+ ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%`594+ : "new";595+ lines.push(`| ${metric} | ${x} | ${y} | ${shown} | ${verdict} |`);596+ }597+ return { table: lines.join("\n"), regressed };598+}599+600+function option(args: ReadonlyArray<string>, name: string): string | undefined {601+ const index = args.indexOf(name);602+ return index === -1 ? undefined : args[index + 1];603+}604+605+if (import.meta.main) {606+ const [command, ...args] = process.argv.slice(2);607+ if (command === "run") {608+ const only = (option(args, "--only") ?? "").split(",").filter(Boolean);609+ const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray<string>).includes(name));610+ if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`);611+ const metrics = await runOnce({612+ macPath: args.includes("--mac-path"),613+ runs: Number(option(args, "--runs") ?? 5),
Pushedac5bd58
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +8,21 @@8+ meta: { commit: "abc", platform: "linux-x64", noAgentScope: true },9+ runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })),10+ }) satisfies ServerMetrics;11+const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 };12+13+describe("compareMetrics", () => {14+ it.each([15+ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"]],16+ ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, []],17+ ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, []],18+ ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"]],19+ ["an improvement", { cpuPct: 0.1, wakeupsPerSec: 7 }, []],20+ ])("one run each: %s", (_name, change, regressed) => {21+ expect(compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })).regressed).toEqual(22+ regressed,23+ );24+ });25+26+ it("does not treat a metric missing on one side as a regression", () => {27+ const before = quietRuns({ ...base, wakeupsPerSec: null });28+ expect(compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 9 })).regressed).toEqual([]);@@ -0,0 +30,21 @@30+31+ it("flags repeated runs only when the whole interval clears the limit", () => {32+ const steady = quietRuns(33+ { ...base, cpuPct: 26.1 },34+ { ...base, cpuPct: 27.4 },35+ { ...base, cpuPct: 25.8 },36+ );37+ const fixed = quietRuns(38+ { ...base, cpuPct: 2.2 },39+ { ...base, cpuPct: 2.5 },40+ { ...base, cpuPct: 2.1 },41+ );42+ expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct");43+ expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct");44+ // One noisy run on each side overlaps the other side's values.45+ const noisy = quietRuns(46+ { ...base, cpuPct: 2.2 },47+ { ...base, cpuPct: 9 },48+ { ...base, cpuPct: 2.4 },49+ );50+ expect(compareMetrics(fixed, noisy).regressed).toEqual([]);@@ -0,0 +1,17 @@1+// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalFetch:off globalDate:off globalRandom:off - a standalone benchmark driver around one server process.2+import * as NodeChildProcess from "node:child_process";3+import * as NodeFS from "node:fs";4+import * as NodeHttp from "node:http";5+import * as NodeNet from "node:net";6+import * as NodeOS from "node:os";7+import * as NodePath from "node:path";8+9+const HELP = `Usage:10+ node scripts/server-metrics.ts run [--out <file>] [--checkout <dir>] [--repeat <k>] [run options]11+ node scripts/server-metrics.ts ab <checkoutA> <checkoutB> [--rounds <k>] [--out-dir <dir>] [run options]12+ node scripts/server-metrics.ts compare <before.json> <after.json> [--threshold <percent>]13+14+run Starts a checkout's server (default: this one) against a temp base dir, a temp HOME, a15+ temp git project and a fake Anthropic Messages API, drives the real \`claude\` CLI16+ through it, and writes one JSON object of measurements. Each scenario gets a fresh17+ server. A full run takes about 8 minutes. --repeat runs it k times into one file.@@ -0,0 +248,21 @@248+};249+const powershell = (script: string) =>250+ commandOutput("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);251+252+/** CPU seconds and RSS bytes of one process. */253+function sample(pid: number): { cpuSeconds: number; rss: number } {254+ if (platform === "linux") {255+ const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]!.split(" ");256+ const status = NodeFS.readFileSync(`/proc/${pid}/status`, "utf8");257+ return {258+ cpuSeconds: (Number(stat[11]) + Number(stat[12])) / 100,259+ rss: Number(/VmRSS:\s+(\d+)/.exec(status)?.[1] ?? 0) * 1024,260+ };261+ }262+ if (platform === "win32") {263+ const [cpu = "0", rss = "0"] = (264+ powershell(265+ `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`,266+ ) ?? ""267+ ).split(/\s+/);268+ return { cpuSeconds: Number(cpu), rss: Number(rss) };@@ -0,0 +273,21 @@273+ .split(/\s+/)274+ .filter(Boolean);275+ const cpuSeconds = time276+ .split(":")277+ .map(Number)278+ .reduce((total, part) => total * 60 + part, 0);279+ return { cpuSeconds, rss: Number(rss) * 1024 };280+}281+282+/** Context switches of one process since it started, or null when this platform cannot tell. */283+function contextSwitches(pid: number): number | null {284+ if (platform === "linux") {285+ let switches = 0;286+ for (const task of NodeFS.readdirSync(`/proc/${pid}/task`)) {287+ try {288+ const status = NodeFS.readFileSync(`/proc/${pid}/task/${task}/status`, "utf8");289+ for (const match of status.matchAll(/ctxt_switches:\s+(\d+)/g))290+ switches += Number(match[1]);291+ } catch {}292+ }293+ return switches;@@ -0,0 +348,21 @@348+ socket.addEventListener("error", reject, { once: true });349+ });350+ let nextId = 0;351+ const pending = new Map<number, (result: unknown) => void>();352+ let chunks: string[] = [];353+ socket.addEventListener("message", (event) => {354+ const message = JSON.parse(String(event.data)) as {355+ id?: number;356+ result?: unknown;357+ method?: string;358+ params?: { chunk?: string };359+ };360+ if (message.id !== undefined) pending.get(message.id)?.(message.result);361+ else if (message.method === "HeapProfiler.addHeapSnapshotChunk")362+ chunks.push(message.params?.chunk ?? "");363+ });364+ const send = (method: string, params: object = {}) =>365+ new Promise<unknown>((resolve) => {366+ const id = ++nextId;367+ pending.set(id, resolve);368+ socket.send(JSON.stringify({ id, method, params }));@@ -0,0 +492,21 @@492+ const project = NodePath.join(directory, "project");493+ NodeFS.mkdirSync(project);494+ NodeFS.writeFileSync(NodePath.join(project, "README.md"), "# bench\n");495+ for (const args of [496+ ["init", "-q", "-b", "main"],497+ ["add", "."],498+ ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"],499+ ]) {500+ NodeChildProcess.execFileSync("git", args, { cwd: project });501+ }502+ const baseDir = NodePath.join(directory, "base");503+ // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API.504+ NodeFS.mkdirSync(NodePath.join(baseDir, "userdata"), { recursive: true });505+ NodeFS.writeFileSync(506+ NodePath.join(baseDir, "userdata/settings.json"),507+ JSON.stringify({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }),508+ );509+ const env: NodeJS.ProcessEnv = {510+ ...process.env,511+ HOME: environment.home,512+ USERPROFILE: environment.home,@@ -0,0 +565,21 @@565+ );566+ let stdout = "";567+ command.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));568+ command.on("exit", (code) => resolve({ code, stdout }));569+ });570+ const added = await cli(["project", "add", project]);571+ if (added.code !== 0) throw new Error(`project add failed: ${added.stdout}`);572+573+ // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU.574+ const sampleEveryMs = platform === "win32" ? 5_000 : 1_000;575+ const measure = async (seconds: number): Promise<Window> => {576+ const firstSwitches = contextSwitches(pid);577+ const first = sample(pid);578+ let rssPeak = first.rss;579+ const start = performance.now();580+ while (performance.now() - start < seconds * 1_000) {581+ await sleep(sampleEveryMs);582+ rssPeak = Math.max(rssPeak, sample(pid).rss);583+ }584+ const last = sample(pid);585+ const lastSwitches = contextSwitches(pid);@@ -0,0 +667,21 @@667+ if (result.code !== 0) throw new Error(`thread start failed: ${result.stdout}`);668+ const request = environment.api.requests.find(669+ (entry) => entry.agent && entry.marker === marker && entry.at >= started,670+ );671+ if (!request) throw new Error(`the agent request for ${marker} never reached the fake API`);672+ toRequest.push(request.at - started);673+ toDone.push(done);674+ }675+ return { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) };676+}677+678+/** Starts threads that each answer once, and returns their ids. */679+async function openThreads(server: Server, from: number, count: number) {680+ const answers = await Promise.all(681+ Array.from({ length: count }, (_, index) =>682+ server.threadStart(`Say hello ${from + index}.`, ["--wait"]),683+ ),684+ );685+ const failed = answers.filter((answer) => answer.code !== 0).length;686+ if (failed) throw new Error(`${failed} of ${count} threads failed`);687+ return answers.map((answer) => /Thread (\S+)/.exec(answer.stdout)?.[1] ?? "");@@ -0,0 +743,21 @@743+ if (wanted("rest")) {744+ await sleep(15_000);745+ measured.rest = await server.measure(30);746+ }747+ if (wanted("firstWord")) {748+ measured.firstWord = {749+ inPlace: await firstWord(environment, server, options.runs, false),750+ worktree: await firstWord(environment, server, options.runs, true),751+ };752+ }753+ });754+ }755+ if (wanted("quiet")) {756+ await withServer("quiet", async (server) => {757+ const points: Array<{ threads: number; window: Window }> = [];758+ let open = 0;759+ for (const threads of options.threads) {760+ if (threads > open) await openThreads(server, open, threads - open);761+ open = Math.max(open, threads);762+ await sleep(15_000);763+ points.push({ threads, window: await server.measure(30) });@@ -0,0 +770,21 @@770+ round(slope(fitted.map(({ threads, window }) => [threads, pick(window)])), 3);771+ measured.scaling = {772+ heapMBPerThread: fit((window) => window.heapAfterGcMB),773+ rssMBPerThread: fit((window) => window.rssMB),774+ cpuPctPerThread: fit((window) => window.cpuPct),775+ wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null)776+ ? fit((window) => window.wakeupsPerSec!)777+ : null,778+ points: points.map(({ threads, window }) => [779+ threads,780+ window.cpuPct,781+ window.wakeupsPerSec,782+ window.rssMB,783+ window.heapAfterGcMB,784+ ]),785+ };786+ await profile(server, "quiet");787+ });788+ }789+ if (wanted("streaming")) {790+ await withServer("streaming", async (server) => {@@ -0,0 +802,21 @@802+ measured.streaming = await server.measure(60);803+ await profile(server, "streaming");804+ });805+ }806+ if (options.soakMinutes > 0) {807+ await withServer("soak", async (server) => {808+ const threads = await openThreads(server, 0, 10);809+ await sleep(60_000);810+ // The snapshot inflates RSS once, so the slopes start after it.811+ const before = heapByConstructor(await server.snapshot());812+ const samples: Array<{ hours: number; window: Window }> = [];813+ const start = performance.now();814+ let nextSample = 0;815+ for (let turn = 0; performance.now() - start < options.soakMinutes * 60_000; turn++) {816+ const elapsed = performance.now() - start;817+ if (elapsed >= nextSample) {818+ samples.push({ hours: elapsed / 3_600_000, window: await server.measure(5) });819+ nextSample += 120_000;820+ }821+ const threadId = threads[Math.floor(Math.random() * threads.length)]!;822+ await server.threadSend(threadId, `Short reply ${turn}.`);@@ -0,0 +846,21 @@846+ }847+ } finally {848+ api.close();849+ NodeFS.rmSync(home, { recursive: true, force: true });850+ }851+ return { measured: measured as Measured, profiles, soakHeapGrowth };852+}853+854+function machineLoad() {855+ if (platform === "win32")856+ return powershell(857+ "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average",858+ );859+ return NodeOS.loadavg()860+ .map((value) => value.toFixed(2))861+ .join(" ");862+}863+864+function metaFor(options: RunOptions) {865+ const claude = commandOutput("claude", ["--version"]);866+ if (claude === null) throw new Error("The real `claude` CLI must be on PATH.");@@ -0,0 +1001,21 @@1001+}1002+1003+function option(args: ReadonlyArray<string>, name: string): string | undefined {1004+ const index = args.indexOf(name);1005+ return index === -1 ? undefined : args[index + 1];1006+}1007+1008+function runOptions(args: ReadonlyArray<string>, checkout: string): RunOptions {1009+ const only = (option(args, "--only") ?? "").split(",").filter(Boolean);1010+ const unknown = only.filter((name) => !(SCENARIOS as ReadonlyArray<string>).includes(name));1011+ if (unknown.length) throw new Error(`unknown scenario: ${unknown.join(", ")}`);1012+ const threads = (option(args, "--threads") ?? "0,5,10,20").split(",").map(Number);1013+ if (threads.some((count) => !Number.isInteger(count) || count < 0))1014+ throw new Error("--threads takes counts such as 0,5,10,20");1015+ return {1016+ checkout: NodePath.resolve(checkout),1017+ noAgentScope: args.includes("--no-agent-scope") || args.includes("--mac-path"),1018+ runs: Number(option(args, "--runs") ?? 5),1019+ threads,1020+ only: option(args, "--soak") && !option(args, "--only") ? ["none"] : only,1021+ soakMinutes: Number(option(args, "--soak") ?? 0),@@ -0,0 +1031,21 @@1031+1032+const printComparison = (before: ServerMetrics, after: ServerMetrics, threshold: number) => {1033+ const { table, regressed, improved } = compareMetrics(before, after, threshold);1034+ console.log(table);1035+ if (improved.length) console.error(`Better: ${improved.join(", ")}`);1036+ if (regressed.length) {1037+ console.error(`Worse: ${regressed.join(", ")}`);1038+ process.exitCode = 1;1039+ }1040+};1041+1042+if (import.meta.main) {1043+ const [command, ...args] = process.argv.slice(2);1044+ const threshold = Number(option(args, "--threshold") ?? 10);1045+ if (command === "run") {1046+ const out = option(args, "--out");1047+ const options = {1048+ ...runOptions(args, option(args, "--checkout") ?? harnessRoot),1049+ profileDir: out ? out.replace(/\.json$/, "") + "-profiles" : undefined,1050+ };1051+ write(out, await runMany(options, Number(option(args, "--repeat") ?? 1)));
Pushed7a0569d
- @@ -0,0 +142,21 @@142+ return values;143+ };144+ const a = collect(before);145+ const b = collect(after);146+ const lines = [147+ "### Server metrics (lower is better)",148+ "",149+ `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" : ""}`,150+ "",151+ "| metric | before | after | change | 95% interval | |",152+ "| :-- | --: | --: | --: | --: | :-- |",153+ ];154+ const regressed: string[] = [];155+ const improved: string[] = [];156+ for (const metric of new Set([...a.keys(), ...b.keys()])) {157+ if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue;158+ const x = a.get(metric);159+ const y = b.get(metric);160+ if (!x || !y) {161+ lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`);162+ continue;@@ -0,0 +275,21 @@275+ : `(${type.replace(/^(concatenated|sliced) /, "")})`;276+ const entry = totals.get(name) ?? { count: 0, bytes: 0 };277+ entry.count++;278+ entry.bytes += snapshot.nodes[index + sizeAt]!;279+ totals.set(name, entry);280+ }281+ return totals;282+}283+284+/** The constructors whose heap grew most from one snapshot to the next. */285+export function heapGrowth(286+ before: ReturnType<typeof heapByConstructor>,287+ after: ReturnType<typeof heapByConstructor>,288+) {289+ return [...after]290+ .map(([name, { count, bytes }]) => ({291+ constructor: name,292+ count: count - (before.get(name)?.count ?? 0),293+ MB: round((bytes - (before.get(name)?.bytes ?? 0)) / 1e6, 2),294+ }))295+ .toSorted((a, b) => b.MB - a.MB)@@ -0,0 +197,21 @@197+ const pending = new Map<number, Deferred.Deferred<unknown>>();198+ const chunks: string[] = [];199+ let nextId = 0;200+ const decodeMessage = decodeJson(201+ Schema.Struct({202+ id: Schema.optional(Schema.Number),203+ result: Schema.optional(Schema.Unknown),204+ method: Schema.optional(Schema.String),205+ params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })),206+ }),207+ );208+ const text = new TextDecoder();209+ yield* reader.pull.pipe(210+ Effect.flatMap((frames) =>211+ Effect.forEach(frames, (frame) =>212+ decodeMessage(typeof frame === "string" ? frame : text.decode(frame)).pipe(213+ Effect.flatMap((message) => {214+ if (message.id !== undefined) {215+ const waiting = pending.get(message.id);216+ pending.delete(message.id);217+ return waiting ? Deferred.succeed(waiting, message.result) : Effect.void;@@ -0,0 +465,21 @@465+ cwd: environment.serverDir,466+ env,467+ extendEnv: false,468+ stdin: "ignore",469+ stdout: "ignore",470+ stderr: "pipe",471+ },472+ ),473+ );474+ const pid = Number(child.pid);475+ const stderr = yield* Ref.make("");476+ yield* child.stderr.pipe(477+ Stream.decodeText(),478+ Stream.runForEach((chunk) => Ref.update(stderr, (text) => (text + chunk).slice(-8_000))),479+ Effect.ignore,480+ Effect.forkScoped,481+ );482+483+ yield* Effect.addFinalizer(() =>484+ Effect.gen(function* () {485+ const spawned = yield* descendantsOf(pid);@@ -0,0 +515,21 @@515+ cwd: environment.serverDir,516+ env,517+ allowExit: [0, 1, 2],518+ });519+ const added = yield* cli(["project", "add", project]);520+ if (added.exitCode !== 0) {521+ return yield* new MetricsError({ message: `project add failed: ${added.stderr}` });522+ }523+524+ // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU.525+ const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000);526+ const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) {527+ const firstSwitches = yield* contextSwitches(pid);528+ const first = yield* sample(pid);529+ let rssPeak = first.rss;530+ const start = yield* Clock.currentTimeMillis;531+ while ((yield* Clock.currentTimeMillis) - start < seconds * 1_000) {532+ yield* Effect.sleep(sampleEvery);533+ rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss);534+ }535+ const last = yield* sample(pid);@@ -0,0 +566,21 @@566+ project,567+ message,568+ ]),569+ threadSend: (threadId: string, message: string) =>570+ cli(["thread", "send", "--wait", threadId, message]),571+ };572+});573+574+type Server = Effect.Success<ReturnType<typeof startServer>>;575+576+const firstWord = Effect.fn("serverMetrics.firstWord")(function* (577+ environment: Environment,578+ server: Server,579+ runs: number,580+ worktree: boolean,581+) {582+ const toRequest: number[] = [];583+ const toDone: number[] = [];584+ for (let index = 0; index < runs; index++) {585+ const marker = `bench-run-${worktree ? 1000 + index : index}`;586+ const started = yield* Clock.currentTimeMillis;@@ -0,0 +745,21 @@745+ }746+ if (options.soakMinutes > 0) {747+ yield* withServer("soak", (server) =>748+ Effect.gen(function* () {749+ const threads = yield* openThreads(server, 0, 10);750+ yield* Effect.sleep(Duration.seconds(60));751+ // The snapshot inflates RSS once, so the slopes start after it.752+ const before = yield* server.snapshot;753+ const samples: Array<{ hours: number; window: Window }> = [];754+ const start = yield* Clock.currentTimeMillis;755+ const elapsed = Effect.map(Clock.currentTimeMillis, (now) => now - start);756+ const takeSample = Effect.gen(function* () {757+ samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) });758+ });759+ let nextSample = 0;760+ for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) {761+ if ((yield* elapsed) >= nextSample) {762+ yield* takeSample;763+ nextSample += 120_000;764+ }765+ const threadId = threads[yield* Random.nextIntBetween(0, threads.length)] ?? "";
Pushed6c14cf3
- @@ -0,0 +345,21 @@345+});346+347+const numberOrNull = (text: Option.Option<string>) => {348+ const value = Number(Option.getOrElse(text, () => "").replace(/\+$/, ""));349+ return Option.isSome(text) && text.value !== "" && Number.isFinite(value) ? value : null;350+};351+352+/**353+ * Context switches so far, by Linux task (one total elsewhere), or null when this platform354+ * cannot tell. Per task, so a thread that exits between two samples drops out of both.355+ */356+const contextSwitches = Effect.fn("serverMetrics.contextSwitches")(function* (pid: number) {357+ const platform = yield* HostProcess.Platform;358+ if (platform === "linux") {359+ const fs = yield* FileSystem.FileSystem;360+ const switches = new Map<string, number>();361+ for (const task of yield* fs.readDirectory(`/proc/${pid}/task`)) {362+ const status = yield* fs363+ .readFileString(`/proc/${pid}/task/${task}/status`)364+ .pipe(Effect.option);365+ if (Option.isNone(status)) continue;
Pushed16c957d
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Other scenarios#
All 64 scenario measurements match
main.All 64 scenario measurements
short turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsshort turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsBaseline:
f29c824· PR result:16c957d· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.