Open History to see the last commit
1#!/usr/bin/env node
2// Measures a checkout's server process (CPU, wakeups, memory, time to the API) against a fake
3// Anthropic API and the real `claude` CLI. See docs/internals/performance-regressions.md.
4// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http server.
5import * as NodeHttp from "node:http";
6
7import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
8import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import * as NodeSocket from "@effect/platform-node/NodeSocket";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
14import * as Clock from "effect/Clock";
15import * as Console from "effect/Console";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import * as Random from "effect/Random";
26import * as Ref from "effect/Ref";
27import * as Schedule from "effect/Schedule";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30import { Argument, Command, Flag } from "effect/cli";
31import { HttpClient, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";
32import { ChildProcess, ChildProcessSpawner } from "effect/process";
33import * as Socket from "effect/socket/Socket";
34
35import { run } from "./scenarios/shell.ts";
36import {
37 compareMetrics,
38 CpuProfile,
39 HeapProfile,
40 HeapSnapshot,
41 heapByConstructor,
42 heapGrowth,
43 round,
44 ServerMetrics,
45 slope,
46 spread,
47 parsePsCpuTime,
48 parseRunSelection,
49 summarizeProfiles,
50 type FirstWord,
51 type Measured,
52 type ProfileSummary,
53 type Window,
54} from "./server-metrics-report.ts";
55
56const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
57const MODEL = "claude-haiku-4-5";
58const SLOW_MARKER = "[[stream-slowly]]";
59
60export class MetricsError extends Schema.TaggedError<MetricsError>()("MetricsError", {
61 message: Schema.String,
62}) {}
63
64const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
65const decodeJson = <S extends Schema.Top>(schema: S) =>
66 Schema.decodeUnknownEffect(Schema.fromJsonString(schema));
67const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(ServerMetrics));
68
69/** What a command printed, or none when it is missing or failed. */
70const output = (program: string, args: ReadonlyArray<string>, cwd?: string) =>
71 run(program, args, cwd === undefined ? {} : { cwd }).pipe(
72 Effect.map(({ stdout }) => stdout.trim()),
73 Effect.option,
74 );
75const powershell = (script: string) =>
76 output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
77
78/** Milliseconds on a monotonic clock, for intervals only. */
79const nowMs = Effect.map(Clock.monotonicTimeNanos, (nanos) => Number(nanos) / 1e6);
80
81const httpServerOn = (port: number) =>
82 NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" });
83
84interface ApiRequest {
85 readonly at: number;
86 readonly agent: boolean;
87 readonly stream: boolean;
88 readonly marker: string | undefined;
89}
90
91const MessagesRequest = Schema.Struct({
92 stream: Schema.optional(Schema.Boolean),
93 model: Schema.optional(Schema.String),
94 tools: Schema.optional(Schema.Array(Schema.Unknown)),
95});
96
97/** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */
98const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () {
99 const requests: ApiRequest[] = [];
100 const app = Effect.gen(function* () {
101 const request = yield* HttpServerRequest.HttpServerRequest;
102 if (request.url.includes("count_tokens")) {
103 return HttpServerResponse.jsonUnsafe({ input_tokens: 100 });
104 }
105 if (!request.url.startsWith("/v1/messages")) {
106 return HttpServerResponse.jsonUnsafe(
107 { type: "error", error: { type: "not_found_error" } },
108 { status: 404 },
109 );
110 }
111 const raw = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
112 const body = yield* decodeJson(MessagesRequest)(raw).pipe(
113 Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})),
114 );
115 const streamed = body.stream === true;
116 requests.push({
117 at: yield* nowMs,
118 stream: streamed,
119 // Title and branch-name jobs carry only their structured-output tool; the agent carries many.
120 agent: streamed && (body.tools?.length ?? 0) > 1,
121 marker: /bench-run-(\d+)/.exec(raw)?.[0],
122 });
123 const model = body.model ?? MODEL;
124 const id = `msg_bench_${requests.length}`;
125 if (!streamed) {
126 return HttpServerResponse.jsonUnsafe({
127 id,
128 type: "message",
129 role: "assistant",
130 model,
131 content: [{ type: "text", text: "Bench reply" }],
132 stop_reason: "end_turn",
133 stop_sequence: null,
134 usage: { input_tokens: 10, output_tokens: 2 },
135 });
136 }
137 const event = (name: string, data: object) =>
138 `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`;
139 const slow = raw.includes(SLOW_MARKER);
140 const words = slow ? 2_000 : 40;
141 const deltas = Stream.range(0, words - 1).pipe(
142 Stream.mapEffect((word) =>
143 Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe(
144 Effect.as(
145 event("content_block_delta", {
146 index: 0,
147 delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` },
148 }),
149 ),
150 ),
151 ),
152 );
153 const events = Stream.make(
154 event("message_start", {
155 message: {
156 id,
157 type: "message",
158 role: "assistant",
159 model,
160 content: [],
161 stop_reason: null,
162 stop_sequence: null,
163 usage: { input_tokens: 100, output_tokens: 1 },
164 },
165 }),
166 event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }),
167 ).pipe(
168 Stream.concat(deltas),
169 Stream.concat(
170 Stream.make(
171 event("content_block_stop", { index: 0 }),
172 event("message_delta", {
173 delta: { stop_reason: "end_turn", stop_sequence: null },
174 usage: { output_tokens: words },
175 }),
176 event("message_stop", {}),
177 ),
178 ),
179 Stream.encodeText,
180 );
181 return HttpServerResponse.stream(events, {
182 contentType: "text/event-stream",
183 headers: { "cache-control": "no-cache" },
184 });
185 });
186 // Each run gets its own listener, closed with the run's scope.
187 const context = yield* Layer.build(httpServerOn(0));
188 return yield* Effect.gen(function* () {
189 yield* HttpServer.serveEffect(Effect.interruptible(app));
190 const { address } = yield* HttpServer.HttpServer;
191 if (address._tag === "UnixPathAddress") {
192 return yield* new MetricsError({ message: "the fake API has no TCP address" });
193 }
194 return { port: address.port, requests };
195 }).pipe(Effect.provide(context));
196});
197
198/** A Chrome DevTools Protocol session on the server's inspector. */
199const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) {
200 const socket = yield* Socket.makeWebSocket(url);
201 const reader = yield* socket.reader;
202 const writer = yield* socket.writer;
203 const pending = new Map<
204 number,
205 { method: string; answer: Deferred.Deferred<unknown, MetricsError> }
206 >();
207 const chunks: string[] = [];
208 let nextId = 0;
209 let closed = false;
210 const decodeMessage = decodeJson(
211 Schema.Struct({
212 id: Schema.optional(Schema.Number),
213 result: Schema.optional(Schema.Unknown),
214 error: Schema.optional(Schema.Struct({ message: Schema.String })),
215 method: Schema.optional(Schema.String),
216 params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })),
217 }),
218 );
219 const text = new TextDecoder();
220 yield* reader.pull.pipe(
221 Effect.flatMap((frames) =>
222 Effect.forEach(frames, (frame) =>
223 decodeMessage(typeof frame === "string" ? frame : text.decode(frame)).pipe(
224 Effect.flatMap((message) => {
225 if (message.id !== undefined) {
226 const waiting = pending.get(message.id);
227 pending.delete(message.id);
228 if (!waiting) return Effect.void;
229 return message.error
230 ? Deferred.fail(
231 waiting.answer,
232 new MetricsError({ message: `${waiting.method}: ${message.error.message}` }),
233 )
234 : Deferred.succeed(waiting.answer, message.result);
235 }
236 if (message.method === "HeapProfiler.addHeapSnapshotChunk") {
237 chunks.push(message.params?.chunk ?? "");
238 }
239 return Effect.void;
240 }),
241 Effect.ignore,
242 ),
243 ),
244 ),
245 Effect.forever,
246 Effect.ignore,
247 // A closed connection answers nothing, so every waiting call fails instead of hanging.
248 Effect.ensuring(
249 Effect.suspend(() => {
250 closed = true;
251 const waiting = [...pending.values()];
252 pending.clear();
253 return Effect.forEach(waiting, ({ method, answer }) =>
254 Deferred.fail(answer, new MetricsError({ message: `${method}: the inspector closed` })),
255 );
256 }),
257 ),
258 Effect.forkScoped,
259 );
260 const send = Effect.fn("serverMetrics.cdp")(function* (method: string, params: object = {}) {
261 if (closed) return yield* new MetricsError({ message: `${method}: the inspector closed` });
262 const id = ++nextId;
263 const answer = yield* Deferred.make<unknown, MetricsError>();
264 pending.set(id, { method, answer });
265 yield* writer.write(encodeJson({ id, method, params }));
266 return yield* Deferred.await(answer);
267 });
268 const decodeHeapUsage = Schema.decodeUnknownEffect(Schema.Struct({ usedSize: Schema.Number }));
269 const decodeEvaluated = Schema.decodeUnknownEffect(
270 Schema.Struct({ result: Schema.Struct({ value: Schema.Number }) }),
271 );
272 const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile }));
273 const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile }));
274 return {
275 // getrusage keeps the switches of threads that already exited, unlike per-thread counters.
276 contextSwitches: send("Runtime.evaluate", {
277 expression:
278 "(() => { const u = process.resourceUsage(); return u.voluntaryContextSwitches + u.involuntaryContextSwitches; })()",
279 returnByValue: true,
280 }).pipe(
281 Effect.flatMap(decodeEvaluated),
282 Effect.map(({ result }) => result.value),
283 ),
284 heapAfterGc: Effect.gen(function* () {
285 yield* send("HeapProfiler.collectGarbage");
286 yield* send("HeapProfiler.collectGarbage");
287 return (yield* decodeHeapUsage(yield* send("Runtime.getHeapUsage"))).usedSize;
288 }),
289 profile: Effect.fn("serverMetrics.profile")(function* (seconds: number) {
290 yield* send("Profiler.enable");
291 yield* send("Profiler.setSamplingInterval", { interval: 1_000 });
292 yield* send("Profiler.start");
293 yield* send("HeapProfiler.startSampling", {
294 samplingInterval: 32_768,
295 includeObjectsCollectedByMajorGC: true,
296 includeObjectsCollectedByMinorGC: true,
297 });
298 yield* Effect.sleep(Duration.seconds(seconds));
299 const heap = yield* send("HeapProfiler.stopSampling");
300 const cpu = yield* send("Profiler.stop");
301 yield* send("Profiler.disable");
302 return {
303 summary: summarizeProfiles(
304 (yield* decodeCpuProfile(cpu)).profile,
305 (yield* decodeHeapProfile(heap)).profile,
306 ),
307 raw: { cpu, heap },
308 };
309 }),
310 snapshot: Effect.gen(function* () {
311 chunks.length = 0;
312 yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false });
313 const json = chunks.join("");
314 chunks.length = 0;
315 return heapByConstructor(yield* decodeJson(HeapSnapshot)(json));
316 }),
317 };
318});
319
320/** CPU seconds and RSS bytes of one process; a failed or unreadable probe fails the window. */
321const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) {
322 const platform = yield* HostProcess.Platform;
323 const checked = (cpuSeconds: number, rss: number, probe: string) =>
324 Number.isFinite(cpuSeconds) && Number.isFinite(rss)
325 ? Effect.succeed({ cpuSeconds, rss })
326 : Effect.fail(new MetricsError({ message: `could not read process ${pid}: ${probe}` }));
327 if (platform === "linux") {
328 const fs = yield* FileSystem.FileSystem;
329 const stat = (yield* fs.readFileString(`/proc/${pid}/stat`)).split(") ")[1]?.split(" ") ?? [];
330 const status = yield* fs.readFileString(`/proc/${pid}/status`);
331 const rss = /VmRSS:\s+(\d+)/.exec(status)?.[1];
332 return yield* checked(
333 (Number(stat[11]) + Number(stat[12])) / 100,
334 rss === undefined ? Number.NaN : Number(rss) * 1024,
335 "/proc",
336 );
337 }
338 if (platform === "win32") {
339 const line = yield* powershell(
340 `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`,
341 );
342 const [cpu = "", rss = ""] = Option.getOrElse(line, () => "").split(/\s+/);
343 return yield* checked(
344 cpu ? Number(cpu) : Number.NaN,
345 rss ? Number(rss) : Number.NaN,
346 "Get-Process",
347 );
348 }
349 const line = yield* output("ps", ["-o", "rss=,time=", "-p", `${pid}`]);
350 const [rss = "", time = ""] = Option.getOrElse(line, () => "")
351 .split(/\s+/)
352 .filter(Boolean);
353 return yield* checked(parsePsCpuTime(time), rss ? Number(rss) * 1024 : Number.NaN, "ps");
354});
355
356/** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */
357const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) {
358 const platform = yield* HostProcess.Platform;
359 const children = new Map<number, number[]>();
360 const add = (child: number, parent: number) =>
361 children.set(parent, [...(children.get(parent) ?? []), child]);
362 if (platform === "linux") {
363 const fs = yield* FileSystem.FileSystem;
364 for (const entry of yield* fs.readDirectory("/proc")) {
365 if (!/^\d+$/.test(entry)) continue;
366 const stat = yield* fs
367 .readFileString(`/proc/${entry}/stat`)
368 .pipe(Effect.orElseSucceed(() => ""));
369 const parent = Number(stat.split(") ")[1]?.split(" ")[1]);
370 if (parent) add(Number(entry), parent);
371 }
372 } else if (platform === "darwin") {
373 const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]);
374 for (const line of Option.getOrElse(table, () => "").split("\n")) {
375 const [child, parent] = line.trim().split(/\s+/).map(Number);
376 if (child && parent) add(child, parent);
377 }
378 } else return [];
379 const found: number[] = [];
380 const pending = [pid];
381 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
382 for (const child of children.get(next) ?? []) {
383 found.push(child);
384 pending.push(child);
385 }
386 }
387 return found;
388});
389
390interface Environment {
391 readonly home: string;
392 readonly apiPort: number;
393 readonly requests: ReadonlyArray<ApiRequest>;
394 readonly noAgentScope: boolean;
395 readonly serverDir: string;
396}
397
398/** A free loopback port: bind 0, read it, let it go. */
399const freePort = Effect.scoped(
400 Effect.gen(function* () {
401 const context = yield* Layer.build(httpServerOn(0));
402 const { address } = Context.get(context, HttpServer.HttpServer);
403 return address._tag === "UnixPathAddress" ? 0 : address.port;
404 }),
405);
406
407/** A fresh server with its own base dir and git project, stopped when the scope closes. */
408const startServer = Effect.fn("serverMetrics.startServer")(function* (
409 environment: Environment,
410 name: string,
411) {
412 const fs = yield* FileSystem.FileSystem;
413 const path = yield* Path.Path;
414 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
415 const http = yield* HttpClient.HttpClient;
416 const platform = yield* HostProcess.Platform;
417 const node = yield* HostProcess.ExecutablePath;
418 const hostEnvironment = yield* HostProcess.Environment;
419 const directory = yield* fs.makeTempDirectory({
420 directory: environment.home,
421 prefix: `${name}-`,
422 });
423 const project = path.join(directory, "project");
424 yield* fs.makeDirectory(project);
425 yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n");
426 for (const args of [
427 ["init", "-q", "-b", "main"],
428 ["add", "."],
429 ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"],
430 ]) {
431 yield* run("git", args, { cwd: project });
432 }
433 const baseDir = path.join(directory, "base");
434 // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API.
435 yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true });
436 yield* fs.writeFileString(
437 path.join(baseDir, "userdata/settings.json"),
438 encodeJson({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }),
439 );
440 const dropped = new Set([
441 "ANTHROPIC_AUTH_TOKEN",
442 "T3CODE_HOME",
443 "CLAUDE_CONFIG_DIR",
444 ...(environment.noAgentScope ? ["XDG_RUNTIME_DIR"] : []),
445 ]);
446 const env: Record<string, string> = {
447 ...Object.fromEntries(
448 Object.entries(hostEnvironment).filter(
449 (entry): entry is [string, string] => entry[1] !== undefined && !dropped.has(entry[0]),
450 ),
451 ),
452 HOME: environment.home,
453 USERPROFILE: environment.home,
454 ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.apiPort}`,
455 ANTHROPIC_API_KEY: "sk-bench",
456 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
457 OTEL_SDK_DISABLED: "true",
458 T3CODE_DEV_SEED: "0",
459 };
460 const port = yield* freePort;
461 const started = yield* nowMs;
462 const child = yield* spawner.spawn(
463 ChildProcess.make(
464 node,
465 [
466 "--inspect=127.0.0.1:0",
467 "src/bin.ts",
468 "serve",
469 "--base-dir",
470 baseDir,
471 "--port",
472 `${port}`,
473 "--host",
474 "127.0.0.1",
475 project,
476 ],
477 {
478 cwd: environment.serverDir,
479 env,
480 extendEnv: false,
481 // A server that ignores SIGTERM still stops, so cleanup always reaches the temp dir.
482 forceKillAfter: Duration.seconds(10),
483 stdin: "ignore",
484 stdout: "ignore",
485 stderr: "pipe",
486 },
487 ),
488 );
489 const pid = Number(child.pid);
490 const stderr = yield* Ref.make("");
491 yield* child.stderr.pipe(
492 Stream.decodeText(),
493 Stream.runForEach((chunk) => Ref.update(stderr, (text) => (text + chunk).slice(-8_000))),
494 Effect.ignore,
495 Effect.forkScoped,
496 );
497
498 yield* Effect.addFinalizer(() =>
499 Effect.gen(function* () {
500 const spawned = yield* descendantsOf(pid).pipe(Effect.orElseSucceed(() => []));
501 if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]);
502 else
503 yield* child
504 .kill({ killSignal: "SIGTERM", forceKillAfter: Duration.seconds(10) })
505 .pipe(Effect.timeout(Duration.seconds(15)), Effect.ignore);
506 yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore);
507 if (spawned.length > 0) yield* output("kill", ["-9", ...spawned.map(String)]);
508 // Windows keeps a file locked for a moment after its process exits.
509 yield* fs
510 .remove(directory, { recursive: true })
511 .pipe(Effect.retry({ schedule: Schedule.spaced(Duration.millis(500)), times: 20 }));
512 }).pipe(Effect.ignore),
513 );
514
515 const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe(
516 Effect.timeout(Duration.seconds(1)),
517 Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }),
518 Effect.andThen(nowMs),
519 Effect.map((now) => Math.round(now - started)),
520 Effect.catch(() =>
521 Effect.flatMap(
522 Ref.get(stderr),
523 (text) => new MetricsError({ message: `server never answered:\n${text}` }),
524 ),
525 ),
526 );
527 const inspectorUrl = /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(yield* Ref.get(stderr))?.[0];
528 if (!inspectorUrl) return yield* new MetricsError({ message: "no inspector URL on stderr" });
529 const devtools = yield* inspect(inspectorUrl);
530
531 const cli = (args: ReadonlyArray<string>) =>
532 run(node, ["src/bin.ts", ...args, "--base-dir", baseDir], {
533 cwd: environment.serverDir,
534 env,
535 allowExit: [0, 1, 2],
536 });
537 const added = yield* cli(["project", "add", project]);
538 if (added.exitCode !== 0) {
539 return yield* new MetricsError({
540 message: `project add failed: ${added.stderr.trim() || added.stdout.trim()}`,
541 });
542 }
543
544 // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU.
545 const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000);
546 const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) {
547 // Each counter is divided by the time between its own two reads; a CIM probe can take seconds.
548 // Windows reports no context switches through getrusage, so wakeups are unknown there.
549 const countSwitches = platform === "win32" ? Effect.succeed(null) : devtools.contextSwitches;
550 // A probe can take seconds (CIM on Windows), so each read is timed at its midpoint.
551 const timed = Effect.fn("serverMetrics.timedRead")(function* <A, E, R>(
552 read: Effect.Effect<A, E, R>,
553 ) {
554 const before = yield* nowMs;
555 const value = yield* read;
556 return { value, at: (before + (yield* nowMs)) / 2 };
557 });
558 const firstSwitches = yield* timed(countSwitches);
559 const firstSample = yield* timed(sample(pid));
560 const first = firstSample.value;
561 const start = firstSample.at;
562 let rssPeak = first.rss;
563 while ((yield* nowMs) - start < seconds * 1_000) {
564 yield* Effect.sleep(sampleEvery);
565 rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss);
566 }
567 const lastSample = yield* timed(sample(pid));
568 const last = lastSample.value;
569 const cpuElapsed = (lastSample.at - start) / 1_000;
570 const lastSwitches = yield* timed(countSwitches);
571 const switchesElapsed = (lastSwitches.at - firstSwitches.at) / 1_000;
572 const switches =
573 firstSwitches.value === null || lastSwitches.value === null
574 ? null
575 : lastSwitches.value - firstSwitches.value;
576 const heap = yield* devtools.heapAfterGc;
577 const window: Window = {
578 cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100),
579 wakeupsPerSec: switches === null ? null : round(switches / switchesElapsed),
580 rssPeakMB: Math.round(Math.max(rssPeak, last.rss) / 1e6),
581 rssMB: Math.round((yield* sample(pid)).rss / 1e6),
582 heapAfterGcMB: round(heap / 1e6),
583 };
584 return window;
585 });
586
587 return {
588 readyMs,
589 measure,
590 profile: devtools.profile,
591 snapshot: devtools.snapshot,
592 threadStart: (message: string, extra: ReadonlyArray<string> = []) =>
593 cli([
594 "thread",
595 "start",
596 "--provider",
597 "claudeAgent",
598 "--model",
599 MODEL,
600 ...extra,
601 project,
602 message,
603 ]),
604 threadSend: (threadId: string, message: string) =>
605 cli(["thread", "send", "--wait", threadId, message]),
606 };
607});
608
609type Server = Effect.Success<ReturnType<typeof startServer>>;
610
611const firstWord = Effect.fn("serverMetrics.firstWord")(function* (
612 environment: Environment,
613 server: Server,
614 runs: number,
615 worktree: boolean,
616) {
617 const toRequest: number[] = [];
618 const toDone: number[] = [];
619 for (let index = 0; index < runs; index++) {
620 const marker = `bench-run-${worktree ? 1000 + index : index}`;
621 const started = yield* nowMs;
622 const result = yield* server.threadStart(`Say hello. ${marker}`, [
623 "--wait",
624 ...(worktree ? ["--worktree", "main"] : []),
625 ]);
626 const done = (yield* nowMs) - started;
627 if (result.exitCode !== 0) {
628 return yield* new MetricsError({
629 message: `thread start failed: ${result.stderr.trim() || result.stdout.trim()}`,
630 });
631 }
632 const request = environment.requests.find(
633 (entry) => entry.agent && entry.marker === marker && entry.at >= started,
634 );
635 if (!request) {
636 return yield* new MetricsError({ message: `the agent request for ${marker} never arrived` });
637 }
638 toRequest.push(request.at - started);
639 toDone.push(done);
640 }
641 const result: FirstWord = { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) };
642 return result;
643});
644
645/** Starts threads that each answer once, and returns their ids. */
646const openThreads = Effect.fn("serverMetrics.openThreads")(function* (
647 server: Server,
648 from: number,
649 count: number,
650) {
651 const answers = yield* Effect.forEach(
652 Array.from({ length: count }, (_, index) => from + index),
653 (index) => server.threadStart(`Say hello ${index}.`, ["--wait"]),
654 { concurrency: "unbounded" },
655 );
656 const failed = answers.find((answer) => answer.exitCode !== 0);
657 if (failed) {
658 return yield* new MetricsError({
659 message: `a thread failed to answer: ${failed.stderr.trim() || failed.stdout.trim()}`,
660 });
661 }
662 // Without --json, `thread start` prints the new thread's id to stderr, older releases too.
663 const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]);
664 if (ids.some((id) => id === undefined)) {
665 return yield* new MetricsError({ message: "thread start printed no thread id" });
666 }
667 return ids.filter((id) => id !== undefined);
668});
669
670const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const;
671
672interface RunOptions {
673 readonly checkout: string;
674 readonly noAgentScope: boolean;
675 readonly runs: number;
676 readonly threads: ReadonlyArray<number>;
677 readonly only: ReadonlyArray<string>;
678 readonly soakMinutes: number;
679 /** Where full CPU and allocation profiles go; none are written without it. */
680 readonly profileDir: string | undefined;
681}
682
683/** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */
684const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) {
685 const fs = yield* FileSystem.FileSystem;
686 const path = yield* Path.Path;
687 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" });
688 const api = yield* serveFakeAnthropic();
689 const environment: Environment = {
690 home,
691 apiPort: api.port,
692 requests: api.requests,
693 noAgentScope: options.noAgentScope,
694 serverDir: path.join(options.checkout, "apps/server"),
695 };
696 const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario);
697 const measured: { -readonly [K in keyof Measured]: Measured[K] } = {};
698 const profiles: Record<string, ProfileSummary> = {};
699 let soakHeapGrowth: ReturnType<typeof heapGrowth> | undefined;
700 const withServer = <A, E, R>(name: string, body: (server: Server) => Effect.Effect<A, E, R>) =>
701 Effect.scoped(Effect.flatMap(startServer(environment, name), body));
702 const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) {
703 const { summary, raw } = yield* server.profile(20);
704 profiles[name] = summary;
705 if (options.profileDir === undefined) return;
706 yield* fs.makeDirectory(options.profileDir, { recursive: true });
707 yield* fs.writeFileString(
708 path.join(options.profileDir, `${name}.cpuprofile`),
709 encodeJson(raw.cpu),
710 );
711 yield* fs.writeFileString(
712 path.join(options.profileDir, `${name}.heapprofile`),
713 encodeJson(raw.heap),
714 );
715 });
716
717 if (wanted("startup") || wanted("rest") || wanted("firstWord")) {
718 yield* withServer("rest", (server) =>
719 Effect.gen(function* () {
720 measured.startup = { readyMs: server.readyMs };
721 if (wanted("rest")) {
722 yield* Effect.sleep(Duration.seconds(15));
723 measured.rest = yield* server.measure(30);
724 }
725 if (wanted("firstWord")) {
726 measured.firstWord = {
727 inPlace: yield* firstWord(environment, server, options.runs, false),
728 worktree: yield* firstWord(environment, server, options.runs, true),
729 };
730 }
731 }),
732 );
733 }
734 if (wanted("quiet")) {
735 yield* withServer("quiet", (server) =>
736 Effect.gen(function* () {
737 const points: Array<{ threads: number; window: Window }> = [];
738 let open = 0;
739 for (const threads of options.threads) {
740 if (threads > open) yield* openThreads(server, open, threads - open);
741 open = Math.max(open, threads);
742 yield* Effect.sleep(Duration.seconds(15));
743 points.push({ threads, window: yield* server.measure(30) });
744 }
745 const last = points.at(-1);
746 if (last) measured.quiet = last.window;
747 // The first thread also loads the provider's modules once, so the fit leaves out 0 threads.
748 const withThreads = points.filter(({ threads }) => threads > 0);
749 const fitted = withThreads.length >= 2 ? withThreads : points;
750 const fit = (pick: (window: Window) => number) =>
751 round(slope(fitted.map(({ threads, window }) => [threads, pick(window)])), 3);
752 measured.scaling = {
753 heapMBPerThread: fit((window) => window.heapAfterGcMB),
754 rssMBPerThread: fit((window) => window.rssMB),
755 cpuPctPerThread: fit((window) => window.cpuPct),
756 wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null)
757 ? fit((window) => window.wakeupsPerSec ?? 0)
758 : null,
759 points: points.map(({ threads, window }) => [
760 threads,
761 window.cpuPct,
762 window.wakeupsPerSec,
763 window.rssMB,
764 window.heapAfterGcMB,
765 ]),
766 };
767 yield* profile(server, "quiet");
768 }),
769 );
770 }
771 if (wanted("streaming")) {
772 yield* withServer("streaming", (server) =>
773 Effect.gen(function* () {
774 // Earlier scenarios share the fake API, so only this launch's requests count.
775 const markers = [0, 1, 2, 3, 4].map((index) => `bench-run-${9_000 + index}`);
776 const launchedAt = yield* nowMs;
777 const started = yield* Effect.forEach(
778 markers,
779 (marker) => server.threadStart(`Write a long answer. ${SLOW_MARKER} ${marker}`),
780 { concurrency: "unbounded" },
781 );
782 if (started.some((answer) => answer.exitCode !== 0)) {
783 return yield* new MetricsError({ message: "streaming start failed" });
784 }
785 const streaming = () =>
786 new Set(
787 api.requests
788 .filter((request) => request.agent && request.stream && request.at >= launchedAt)
789 .map((request) => request.marker),
790 );
791 for (let attempt = 0; attempt < 300; attempt++) {
792 if (markers.every((marker) => streaming().has(marker))) break;
793 yield* Effect.sleep(Duration.millis(100));
794 }
795 if (!markers.every((marker) => streaming().has(marker))) {
796 return yield* new MetricsError({ message: "fewer than 5 replies started streaming" });
797 }
798 yield* Effect.sleep(Duration.seconds(5));
799 measured.streaming = yield* server.measure(60);
800 yield* profile(server, "streaming");
801 }),
802 );
803 }
804 if (options.soakMinutes > 0) {
805 yield* withServer("soak", (server) =>
806 Effect.gen(function* () {
807 const threads = yield* openThreads(server, 0, 10);
808 yield* Effect.sleep(Duration.seconds(60));
809 // The snapshot inflates RSS once, so the slopes start after it.
810 const before = yield* server.snapshot;
811 const samples: Array<{ hours: number; window: Window }> = [];
812 const start = yield* nowMs;
813 const elapsed = Effect.map(nowMs, (now) => now - start);
814 const takeSample = Effect.gen(function* () {
815 samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) });
816 });
817 let nextSample = 0;
818 for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) {
819 if ((yield* elapsed) >= nextSample) {
820 yield* takeSample;
821 nextSample += 120_000;
822 }
823 const threadId =
824 threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })];
825 if (threadId === undefined)
826 return yield* new MetricsError({ message: "no soak threads" });
827 const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`);
828 if (sent.exitCode !== 0) {
829 return yield* new MetricsError({
830 message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`,
831 });
832 }
833 yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed))));
834 }
835 yield* takeSample;
836 const perHour = (pick: (window: Window) => number) =>
837 round(slope(samples.map(({ hours, window }) => [hours, pick(window)])));
838 measured.soak = {
839 minutes: options.soakMinutes,
840 heapMBPerHour: perHour((window) => window.heapAfterGcMB),
841 rssMBPerHour: perHour((window) => window.rssMB),
842 };
843 soakHeapGrowth = heapGrowth(before, yield* server.snapshot);
844 }),
845 );
846 }
847 return { measured: measured as Measured, profiles, soakHeapGrowth };
848}, Effect.scoped);
849
850const machineLoad = Effect.gen(function* () {
851 const platform = yield* HostProcess.Platform;
852 if (platform === "win32") {
853 return yield* powershell(
854 "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average",
855 );
856 }
857 if (platform === "linux") {
858 const fs = yield* FileSystem.FileSystem;
859 const load = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option);
860 return Option.map(load, (text) => text.split(" ").slice(0, 3).join(" "));
861 }
862 return yield* output("sysctl", ["-n", "vm.loadavg"]);
863}).pipe(
864 Effect.map((load) =>
865 Option.getOrNull(Option.map(load, (text) => text.replace(/[{}]/g, "").trim())),
866 ),
867);
868
869const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) {
870 const platform = yield* HostProcess.Platform;
871 const architecture = yield* HostProcess.Architecture;
872 const environment = yield* HostProcess.Environment;
873 const node = yield* HostProcess.ExecutablePath;
874 const claude = yield* output("claude", ["--version"]);
875 if (Option.isNone(claude)) {
876 return yield* new MetricsError({ message: "The real `claude` CLI must be on PATH." });
877 }
878 if (options.noAgentScope && platform !== "linux") {
879 return yield* new MetricsError({
880 message: "--no-agent-scope is Linux only; other platforms never have an agent scope.",
881 });
882 }
883 const cpus =
884 platform === "win32"
885 ? Option.fromNullishOr(environment.NUMBER_OF_PROCESSORS)
886 : yield* output("getconf", ["_NPROCESSORS_ONLN"]);
887 return {
888 platform: `${platform}-${architecture}`,
889 cpus: Option.getOrNull(Option.map(cpus, Number)),
890 node: Option.getOrNull(yield* output(node, ["--version"])),
891 claude: claude.value,
892 commit: Option.getOrNull(
893 yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout),
894 ),
895 noAgentScope: options.noAgentScope,
896 agentScope:
897 platform === "linux" &&
898 !options.noAgentScope &&
899 !!environment.XDG_RUNTIME_DIR &&
900 Option.isSome(yield* output("sh", ["-c", "command -v systemd-run"])),
901 loadBefore: yield* machineLoad,
902 measuredAt: DateTime.formatIso(yield* DateTime.now),
903 };
904});
905
906const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* (
907 out: Option.Option<string>,
908 metrics: ServerMetrics,
909) {
910 const fs = yield* FileSystem.FileSystem;
911 const json = yield* encodeMetrics(metrics);
912 if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`);
913 else yield* Console.log(json);
914});
915
916/** Prints the comparison and sets exit code 1 when a metric got worse. */
917const report = Effect.fn("serverMetrics.report")(function* (
918 before: ServerMetrics,
919 after: ServerMetrics,
920 threshold: number,
921) {
922 const { table, regressed, improved, compared } = compareMetrics(before, after, threshold);
923 yield* Console.log(table);
924 if (compared === 0) {
925 return yield* new MetricsError({
926 message: "the two files share no metric, so nothing was compared",
927 });
928 }
929 if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`);
930 if (regressed.length === 0) return;
931 yield* Console.error(`Worse: ${regressed.join(", ")}`);
932 yield* Effect.sync(() => {
933 process.exitCode = 1;
934 });
935});
936
937const thresholdFlag = Flag.Int("threshold").pipe(
938 Flag.withDescription("Percent a metric must move, past its noise floor, to count."),
939 Flag.withDefault(10),
940);
941const runFlags = {
942 noAgentScope: Flag.Boolean("no-agent-scope").pipe(
943 Flag.withAlias("mac-path"),
944 Flag.withDefault(false),
945 Flag.withDescription(
946 "Linux only: start the server without XDG_RUNTIME_DIR, so it takes the no-agent-scope path macOS and Windows always take.",
947 ),
948 ),
949 runs: Flag.Int("runs").pipe(
950 Flag.withSchema(PositiveInt),
951 Flag.withDescription("firstWord runs in each variant."),
952 Flag.withDefault(5),
953 ),
954 threads: Flag.String("threads").pipe(
955 Flag.withDescription("Open thread counts the quiet scenario measures."),
956 Flag.withDefault("0,5,10,20"),
957 ),
958 only: Flag.String("only").pipe(
959 Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`),
960 Flag.optional,
961 ),
962 soak: Flag.Int("soak").pipe(
963 Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
964 Flag.withDescription(
965 "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 ),
967 Flag.withDefault(0),
968 ),
969};
970interface RunFlags {
971 readonly noAgentScope: boolean;
972 readonly runs: number;
973 readonly threads: string;
974 readonly only: Option.Option<string>;
975 readonly soak: number;
976}
977
978const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* (
979 flags: RunFlags,
980 checkout: string,
981 profileDir: string | undefined,
982) {
983 const path = yield* Path.Path;
984 const selection = parseRunSelection({
985 only: Option.getOrElse(flags.only, () => ""),
986 threads: flags.threads,
987 soak: flags.soak,
988 scenarios: SCENARIOS,
989 });
990 if ("error" in selection) return yield* new MetricsError({ message: selection.error });
991 const { only, threads } = selection;
992 const options: RunOptions = {
993 checkout: path.resolve(checkout),
994 noAgentScope: flags.noAgentScope,
995 runs: flags.runs,
996 threads,
997 only,
998 soakMinutes: flags.soak,
999 profileDir,
1000 };
1001 return options;
1002});
1003
1004const runCommand = Command.make(
1005 "run",
1006 {
1007 ...runFlags,
1008 out: Flag.String("out").pipe(Flag.withDescription("JSON file to write."), Flag.optional),
1009 checkout: Flag.String("checkout").pipe(
1010 Flag.withDescription("Checkout whose server to measure, with dependencies installed."),
1011 Flag.optional,
1012 ),
1013 repeat: Flag.Int("repeat").pipe(
1014 Flag.withSchema(PositiveInt),
1015 Flag.withDescription("Runs to record in one file."),
1016 Flag.withDefault(1),
1017 ),
1018 },
1019 Effect.fn("serverMetrics.run")(function* (input) {
1020 const path = yield* Path.Path;
1021 const checkout = Option.getOrElse(input.checkout, () =>
1022 path.resolve(import.meta.dirname, ".."),
1023 );
1024 const profileDir = Option.getOrUndefined(
1025 Option.map(input.out, (out) => `${out.replace(/\.json$/, "")}-profiles`),
1026 );
1027 if (input.repeat < 1)
1028 return yield* new MetricsError({ message: "--repeat must be at least 1" });
1029 const options = yield* toRunOptions(input, checkout, profileDir);
1030 const meta = yield* metaFor(options);
1031 const runs: Measured[] = [];
1032 let last: Effect.Success<ReturnType<typeof runOnce>> | undefined;
1033 for (let index = 0; index < input.repeat; index++) {
1034 last = yield* runOnce(options);
1035 runs.push(last.measured);
1036 }
1037 yield* writeMetrics(input.out, {
1038 meta: { ...meta, loadAfter: yield* machineLoad },
1039 runs,
1040 ...(last ? { profiles: last.profiles } : {}),
1041 ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}),
1042 });
1043 }),
1044).pipe(
1045 Command.withDescription(
1046 "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.",
1047 ),
1048);
1049
1050const abCommand = Command.make(
1051 "ab",
1052 {
1053 ...runFlags,
1054 checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")),
1055 checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")),
1056 rounds: Flag.Int("rounds").pipe(
1057 Flag.withSchema(PositiveInt),
1058 Flag.withDescription("Rounds; each runs A and B once, alternating which goes first."),
1059 Flag.withDefault(3),
1060 ),
1061 outDir: Flag.String("out-dir").pipe(
1062 Flag.withDescription("Directory for a.json and b.json."),
1063 Flag.withDefault("server-metrics-ab"),
1064 ),
1065 threshold: thresholdFlag,
1066 },
1067 Effect.fn("serverMetrics.ab")(function* (input) {
1068 if (input.rounds < 1)
1069 return yield* new MetricsError({ message: "--rounds must be at least 1" });
1070 const fs = yield* FileSystem.FileSystem;
1071 const path = yield* Path.Path;
1072 const outDir = path.resolve(input.outDir);
1073 yield* fs.makeDirectory(outDir, { recursive: true });
1074 const sides = [
1075 yield* toRunOptions(input, input.checkoutA, undefined),
1076 yield* toRunOptions(input, input.checkoutB, undefined),
1077 ] as const;
1078 const metas = [yield* metaFor(sides[0]), yield* metaFor(sides[1])] as const;
1079 const runs: [Measured[], Measured[]] = [[], []];
1080 for (let round = 0; round < input.rounds; round++) {
1081 // A B, then B A, so a drift in machine load lands on both sides.
1082 for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) {
1083 yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`);
1084 runs[side].push((yield* runOnce(sides[side])).measured);
1085 }
1086 }
1087 const loadAfter = yield* machineLoad;
1088 const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] };
1089 const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] };
1090 yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before);
1091 yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after);
1092 yield* report(before, after, input.threshold);
1093 }),
1094).pipe(
1095 Command.withDescription(
1096 "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.",
1097 ),
1098);
1099
1100const compareCommand = Command.make(
1101 "compare",
1102 {
1103 before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")),
1104 after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")),
1105 threshold: thresholdFlag,
1106 },
1107 Effect.fn("serverMetrics.compare")(function* (input) {
1108 const fs = yield* FileSystem.FileSystem;
1109 const read = (file: string) =>
1110 fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics)));
1111 yield* report(yield* read(input.before), yield* read(input.after), input.threshold);
1112 }),
1113).pipe(
1114 Command.withDescription(
1115 "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.",
1116 ),
1117);
1118
1119const serverMetricsCommand = Command.make("server-metrics").pipe(
1120 Command.withDescription(
1121 "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.",
1122 ),
1123 Command.withSubcommands([runCommand, abCommand, compareCommand]),
1124);
1125
1126if (import.meta.main) {
1127 Command.run(serverMetricsCommand, { version: "0.0.0" }).pipe(
1128 Effect.provide(
1129 Layer.mergeAll(
1130 NodeServices.layer,
1131 NodeHttpClient.layerUndici,
1132 NodeSocket.layerWebSocketConstructor,
1133 ),
1134 ),
1135 NodeRuntime.runMain,
1136 );
1137}