Open History to see the last commit
1// The pure half of server-metrics.ts: the JSON it writes, and how two of them compare.
2import * as Schema from "effect/Schema";
3
4import { bootstrapMedianDifference, loadWarnings, MachineState, round } from "../core/report.ts";
5
6const Window = Schema.Struct({
7 cpuPct: Schema.Number,
8 wakeupsPerSec: Schema.NullOr(Schema.Number),
9 rssPeakMB: Schema.Number,
10 rssMB: Schema.Number,
11 heapAfterGcMB: Schema.Number,
12 // Files written before these were recorded still decode, and compare shows them as n/a.
13 /** Event-loop delay past the 10 ms sampling interval, from a histogram inside the server. */
14 loopDelayP50Ms: Schema.optional(Schema.Number),
15 loopDelayP99Ms: Schema.optional(Schema.Number),
16 loopDelayMaxMs: Schema.optional(Schema.Number),
17 /**
18 * Delay samples taken. Each can wake an idle loop, so they sit inside `wakeupsPerSec` (up to
19 * 100/s at rest, near none under load, when the loop is already awake); not compared.
20 */
21 loopSamples: Schema.optional(Schema.Number),
22 /** GC events and their summed pause in the window, from a `gc` PerformanceObserver. */
23 gcCount: Schema.optional(Schema.Number),
24 gcPauseMs: Schema.optional(Schema.Number),
25});
26export type Window = typeof Window.Type;
27const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number });
28const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread });
29export type FirstWord = typeof FirstWord.Type;
30const Scaling = Schema.Struct({
31 heapMBPerThread: Schema.Number,
32 rssMBPerThread: Schema.Number,
33 cpuPctPerThread: Schema.Number,
34 wakeupsPerThread: Schema.NullOr(Schema.Number),
35 /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */
36 points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))),
37});
38const Soak = Schema.Struct({
39 minutes: Schema.Number,
40 heapMBPerHour: Schema.Number,
41 rssMBPerHour: Schema.Number,
42 /** Processes below the server, so agent or git children that outlive their thread show. */
43 childProcessesPerHour: Schema.optional(Schema.Number),
44});
45
46const WorkingPoint = Schema.Struct({
47 ...Window.fields,
48 /** Turns finished inside the window, per minute; higher is better. */
49 turnsPerMin: Schema.Number,
50 /** Send to the agent's first API request. */
51 toRequestMs: Spread,
52 /** The turn's last reply byte to the client seeing the run end. */
53 turnEndMs: Spread,
54 /** Send to the client seeing the run end. */
55 turnMs: Spread,
56});
57export type WorkingPoint = typeof WorkingPoint.Type;
58
59const Reconnect = Schema.Struct({
60 clients: Schema.Number,
61 threadsPerClient: Schema.optional(Schema.Number),
62 /** Drop to every subscription delivering its snapshot again. */
63 resubscribedMs: Schema.Number,
64 loopDelayP99Ms: Schema.Number,
65 loopDelayMaxMs: Schema.Number,
66});
67
68/** One pass over the scenarios. */
69export const Measured = Schema.Struct({
70 /** What else the machine was doing during the pass; never compared, only warned about. */
71 machine: Schema.optional(MachineState),
72 startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })),
73 rest: Schema.optional(Window),
74 firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })),
75 quiet: Schema.optional(Window),
76 scaling: Schema.optional(Scaling),
77 streaming: Schema.optional(Window),
78 soak: Schema.optional(Soak),
79 /** One web-like client attached over the WebSocket RPC, with N threads subscribed. */
80 clients: Schema.optional(
81 Schema.Struct({
82 /** The quiet window by subscribed thread count. */
83 attached: Schema.Record(Schema.String, Window),
84 /** A user's few devices, each holding the shell, VCS status and threads, drop and reconnect. */
85 reconnect: Schema.optional(Reconnect),
86 /** With --stress: 20 clients holding one thread each drop and reconnect at once. */
87 storm: Schema.optional(Reconnect),
88 }),
89 ),
90 /**
91 * N threads in worktrees of their own run editing turns back to back, all at once, with one
92 * web-like client subscribed to all of them. The scenario to steer server performance by.
93 */
94 working: Schema.optional(
95 Schema.Struct({
96 /** Each window by the number of threads working in it. */
97 active: Schema.Record(Schema.String, WorkingPoint),
98 /** Fits over the windows: what each additional working thread costs. */
99 heapMBPerThread: Schema.Number,
100 rssMBPerThread: Schema.Number,
101 cpuPctPerThread: Schema.Number,
102 loopDelayP99MsPerThread: Schema.Number,
103 }),
104 ),
105 /** 50 short turns back to back on one thread. */
106 pipeline: Schema.optional(
107 Schema.Struct({
108 /** Send to the agent's API request. */
109 toRequestMs: Spread,
110 /** The reply's last byte to the CLI seeing a finished run: turn end and checkpoint. */
111 turnEndMs: Spread,
112 /** Wall time per turn, the CLI's own start included. */
113 msPerTurn: Schema.Number,
114 loopDelayP99Ms: Schema.Number,
115 loopDelayMaxMs: Schema.Number,
116 gcPauseMs: Schema.Number,
117 }),
118 ),
119 /** A server on a copy of the developer's real database, its projects backed by clones. */
120 busy: Schema.optional(
121 Schema.Struct({
122 readyMs: Schema.Number,
123 projects: Schema.Number,
124 /** Off-heap MB the server held so its RSS is a long-lived server's; not compared. */
125 ballastMB: Schema.Number,
126 rest: Window,
127 shellMs: Spread,
128 shellKB: Schema.Number,
129 /** The seeded thread with the most messages, opened through its bounded HTTP snapshot. */
130 largeThread: Schema.optional(
131 Schema.Struct({
132 messages: Schema.Number,
133 openMs: Spread,
134 KB: Schema.Number,
135 /** Heap after GC once it was opened, less before. */
136 heapMB: Schema.Number,
137 }),
138 ),
139 /** Back-to-back turns in a clone, each ending in a checkpoint. */
140 git: Window,
141 }),
142 ),
143});
144export type Measured = typeof Measured.Type;
145
146const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number });
147export type Hotspot = typeof Hotspot.Type;
148const ProfileSummary = Schema.Struct({
149 cpuMs: Schema.Array(Hotspot),
150 allocatedMB: Schema.Array(Hotspot),
151});
152export type ProfileSummary = typeof ProfileSummary.Type;
153export const HeapGrowth = Schema.Struct({
154 constructor: Schema.String,
155 count: Schema.Number,
156 MB: Schema.Number,
157});
158
159/** An object whose retained size grew at every soak snapshot, and how it is reached. */
160export const RetainerGrowth = Schema.Struct({
161 path: Schema.String,
162 MB: Schema.Number,
163 retainedMB: Schema.Number,
164});
165export type RetainerGrowth = typeof RetainerGrowth.Type;
166
167export const ServerMetrics = Schema.Struct({
168 meta: Schema.Record(
169 Schema.String,
170 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
171 ),
172 runs: Schema.Array(Measured),
173 /** Top CPU self time (ms) and allocated MB by function, from the last run. */
174 profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)),
175 soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)),
176 soakRetainerGrowth: Schema.optional(Schema.Array(RetainerGrowth)),
177});
178export type ServerMetrics = typeof ServerMetrics.Type;
179
180/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */
181export function parsePsCpuTime(text: string) {
182 const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim());
183 if (match === null) return Number.NaN;
184 const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match;
185 return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
186}
187
188/**
189 * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay
190 * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else.
191 */
192export function parseRunSelection(input: {
193 readonly only: string;
194 readonly threads: string;
195 readonly soak: number;
196 readonly scenarios: ReadonlyArray<string>;
197}):
198 | { readonly only: ReadonlyArray<string>; readonly threads: ReadonlyArray<number> }
199 | { readonly error: string } {
200 const only = input.only.split(",").filter(Boolean);
201 const unknown = only.filter((name) => !input.scenarios.includes(name));
202 if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` };
203 const threads = input.threads
204 .split(",")
205 .map((count) => (count.trim() === "" ? Number.NaN : Number(count)));
206 if (
207 threads.some(
208 (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0),
209 )
210 ) {
211 return { error: "--threads takes ascending counts such as 0,5,10,20" };
212 }
213 if (!Number.isInteger(input.soak) || input.soak < 0)
214 return { error: "--soak takes minutes, 0 for none" };
215 return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads };
216}
217
218export function spread(values: ReadonlyArray<number>) {
219 const sorted = values.toSorted((a, b) => a - b);
220 const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)];
221 return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) };
222}
223
224/** Least-squares slope of y over x. */
225export function slope(points: ReadonlyArray<readonly [number, number]>) {
226 const n = points.length;
227 if (n < 2) return 0;
228 const mx = points.reduce((sum, [x]) => sum + x, 0) / n;
229 const my = points.reduce((sum, [, y]) => sum + y, 0) / n;
230 let numerator = 0;
231 let denominator = 0;
232 for (const [x, y] of points) {
233 numerator += (x - mx) * (y - my);
234 denominator += (x - mx) ** 2;
235 }
236 return denominator === 0 ? 0 : numerator / denominator;
237}
238
239/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */
240export function flatten(measured: Measured): Map<string, number> {
241 const values = new Map<string, number>();
242 const visit = (value: unknown, path: string) => {
243 if (typeof value === "number") values.set(path, value);
244 else if (value && typeof value === "object") {
245 for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key);
246 }
247 };
248 visit(measured, "");
249 return values;
250}
251
252/**
253 * How far a metric moves between runs of the same commit, and whether it moves little enough to
254 * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see
255 * docs/internals/performance-regressions.md for the runs these came from.
256 */
257export interface NoiseRule {
258 readonly pattern: RegExp;
259 /** Absolute change a metric must clear on top of the relative threshold. */
260 readonly floor: number;
261 /** False for metrics an A/A run moves too far to gate on: shown, never counted. */
262 readonly gate: boolean;
263}
264
265/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */
266const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false });
267
268// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the
269// agent scope, rounded up and taking the larger of the two.
270// busy and soak had no A/A run and keep the earlier floors.
271export const NOISE_RULES: ReadonlyArray<NoiseRule> = [
272 informational(/loopDelayP50Ms$/),
273 informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/),
274 informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/),
275 informational(/^(streaming|pipeline)\.gcPauseMs$/),
276 informational(
277 /^(pipeline\.loopDelayMaxMs|clients\.(storm|reconnect)\.loopDelayP99Ms|quiet\.cpuPct)$/,
278 ),
279 informational(/^scaling\.(cpuPct|wakeups)PerThread$/),
280 informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/),
281 informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/),
282 { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true },
283 { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true },
284 { pattern: /^soak\./, floor: 20, gate: true },
285 informational(/^working\.(cpuPct|loopDelayP99Ms)PerThread$/),
286 informational(/^working\.active\.\d+\.(wakeupsPerSec|loopDelayMaxMs|gcPauseMs)$/),
287 { pattern: /^working\.heapMBPerThread$/, floor: 0.06, gate: true },
288 { pattern: /^working\.rssMBPerThread$/, floor: 0.2, gate: true },
289 { pattern: /^working\.active\.\d+\.turnsPerMin$/, floor: 4, gate: true },
290 { pattern: /^working\.active\.\d+\.toRequestMs\.median$/, floor: 1_100, gate: true },
291 { pattern: /^working\.active\.\d+\.turnEndMs\.median$/, floor: 1_700, gate: true },
292 {
293 pattern: /^working\.active\.\d+\.(toRequestMs\.p90|turnMs\.median)$/,
294 floor: 1_900,
295 gate: true,
296 },
297 { pattern: /^working\.active\.\d+\.turnEndMs\.p90$/, floor: 2_200, gate: true },
298 { pattern: /^working\.active\.\d+\.turnMs\.p90$/, floor: 2_800, gate: true },
299 // Peak RSS while 20 agents run swings by a checkpoint's git children; the settled RSS does not.
300 { pattern: /^working\.active\.\d+\.rssPeakMB$/, floor: 170, gate: true },
301 { pattern: /^working\.active\.\d+\.(cpuPct|loopDelayP99Ms)$/, floor: 5, gate: true },
302 { pattern: /^working\.active\.\d+\.gcCount$/, floor: 8, gate: true },
303 { pattern: /^startup\.readyMs$/, floor: 600, gate: true },
304 { pattern: /^firstWord\./, floor: 600, gate: true },
305 { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true },
306 { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true },
307 // The reconnect had no A/A run yet and takes the storm's floors.
308 { pattern: /^clients\.(storm|reconnect)\.resubscribedMs$/, floor: 200, gate: true },
309 { pattern: /^rest\.cpuPct$/, floor: 1, gate: true },
310 { pattern: /cpuPct$/, floor: 3.5, gate: true },
311 { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true },
312 { pattern: /wakeupsPerSec$/, floor: 110, gate: true },
313 { pattern: /rssPeakMB$/, floor: 16, gate: true },
314 { pattern: /rssMB$/, floor: 4, gate: true },
315 { pattern: /heapAfterGcMB$/, floor: 1, gate: true },
316 { pattern: /MB$/, floor: 15, gate: true },
317 { pattern: /KB$/, floor: 20, gate: true },
318 { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true },
319 { pattern: /loopDelayP99Ms$/, floor: 3, gate: true },
320 { pattern: /loopDelayMaxMs$/, floor: 22, gate: true },
321 { pattern: /gcPauseMs$/, floor: 55, gate: true },
322 { pattern: /gcCount$/, floor: 6, gate: true },
323 { pattern: /./, floor: 300, gate: true },
324];
325
326// Estimated from one quick A/A run (3 rounds) on a 4-vCPU Azure Windows Server 2025 VM on
327// 2026-11-23, rounded up. Consulted before NOISE_RULES on that OS. macOS has no A/A run yet and
328// takes the defaults.
329const NOISE_RULE_OVERRIDES: Partial<Record<string, ReadonlyArray<NoiseRule>>> = {
330 win32: [
331 informational(/^working\.active\.20\.toRequestMs\.p90$/),
332 { pattern: /^working\.rssMBPerThread$/, floor: 0.6, gate: true },
333 { pattern: /^scaling\.rssMBPerThread$/, floor: 0.5, gate: true },
334 { pattern: /^working\.active\.\d+\.rssMB$/, floor: 10, gate: true },
335 { pattern: /^working\.active\.\d+\.loopDelayP99Ms$/, floor: 6, gate: true },
336 { pattern: /^pipeline\.loopDelayP99Ms$/, floor: 8, gate: true },
337 { pattern: /^streaming\.heapAfterGcMB$/, floor: 1.5, gate: true },
338 ],
339};
340
341/**
342 * The rules for the platform (`meta.platform`, e.g. `win32-x64`) every file recorded. Files from
343 * different platforms get the defaults and a warning.
344 */
345export function noiseRulesFor(files: ReadonlyArray<ServerMetrics>) {
346 const platforms = [...new Set(files.map(({ meta }) => String(meta.platform ?? "")))];
347 if (platforms.length !== 1) {
348 return {
349 rules: NOISE_RULES,
350 warning: `the files come from ${platforms.join(" and ")}, so the default noise floors apply`,
351 };
352 }
353 const overrides = NOISE_RULE_OVERRIDES[platforms[0]!.split("-")[0]!] ?? [];
354 return { rules: [...overrides, ...NOISE_RULES], warning: undefined };
355}
356
357export function noiseRule(metric: string, rules: ReadonlyArray<NoiseRule> = NOISE_RULES) {
358 return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true };
359}
360
361/** Why two files cannot be compared at all: a quick run measures shorter windows than a full one. */
362export function profileMismatch(before: ServerMetrics, after: ServerMetrics) {
363 const profile = (metrics: ServerMetrics) => metrics.meta.profile ?? "full";
364 return profile(before) === profile(after)
365 ? undefined
366 : `before is a ${profile(before)} run and after a ${profile(after)} one; compare quick runs only with quick runs`;
367}
368
369/** Throughput, where a drop is the regression. */
370export const higherIsBetter = (metric: string) => metric.endsWith("PerMin");
371
372/** Fields that describe a run rather than measure it. */
373const isMetric = (metric: string) =>
374 !(
375 metric === "soak.minutes" ||
376 metric.startsWith("machine.") ||
377 metric.endsWith("loopSamples") ||
378 metric === "busy.projects" ||
379 metric === "busy.ballastMB" ||
380 metric.endsWith(".clients") ||
381 metric.endsWith(".threadsPerClient") ||
382 metric.endsWith(".threads") ||
383 metric === "busy.largeThread.messages" ||
384 metric.startsWith("scaling.points")
385 );
386
387const median = (values: ReadonlyArray<number>) => {
388 const sorted = values.toSorted((a, b) => a - b);
389 const middle = Math.floor(sorted.length / 2);
390 return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
391};
392
393/**
394 * False for a wakeup count where only one side had the delay sampler: wakeups include the
395 * sampler's only when `loopSamples` sits beside them, so the two measured different things. The
396 * per-thread fit comes from the quiet windows, so it follows their method.
397 */
398function sameWakeupMethod(
399 metric: string,
400 a: ReadonlyMap<string, unknown>,
401 b: ReadonlyMap<string, unknown>,
402) {
403 const window =
404 metric === "scaling.wakeupsPerThread"
405 ? "quiet."
406 : metric.endsWith("wakeupsPerSec")
407 ? metric.slice(0, -"wakeupsPerSec".length)
408 : "";
409 return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`);
410}
411
412/** Why a directory is not an A/A pair: its files must record one and the same commit. */
413export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) {
414 const commits = [a.meta.commit, b.meta.commit];
415 if (commits.some((commit) => typeof commit !== "string" || commit === "")) {
416 return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`;
417 }
418 return commits[0] === commits[1]
419 ? undefined
420 : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`;
421}
422
423/** Every metric's values across a file's runs. */
424const collect = (metrics: ServerMetrics) => {
425 const values = new Map<string, number[]>();
426 for (const run of metrics.runs) {
427 for (const [metric, value] of flatten(run)) {
428 values.set(metric, [...(values.get(metric) ?? []), value]);
429 }
430 }
431 return values;
432};
433
434/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */
435const ceilSignificant = (value: number) => {
436 if (value <= 0) return 0;
437 const step = 10 ** (Math.floor(Math.log10(value)) - 1);
438 return round(Math.ceil(value / step) * step, 6);
439};
440
441/** An A/A interval wider than this share of a metric's median makes it informational. */
442export const NOISY_SHARE = 0.5;
443
444export interface NoiseRow {
445 readonly metric: string;
446 readonly median: number;
447 /** The widest half-width of an A/A pair's 95% interval of the median difference. */
448 readonly halfWidth: number;
449 /** The largest |median(A) - median(B)| over the A/A pairs. */
450 readonly aaDifference: number;
451 readonly floor: number;
452 readonly suggestedFloor: number;
453 readonly gate: boolean;
454 readonly suggestedGate: boolean;
455}
456
457/**
458 * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The
459 * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far
460 * an A/A interval must miss zero to flag. It is an estimate, not a bound.
461 */
462export function noiseReport(
463 pairs: ReadonlyArray<readonly [ServerMetrics, ServerMetrics]>,
464 rules: ReadonlyArray<NoiseRule> = noiseRulesFor(pairs.flat()).rules,
465) {
466 const found = new Map<string, { medians: number[]; halfWidth: number; aaDifference: number }>();
467 for (const [before, after] of pairs) {
468 const a = collect(before);
469 const b = collect(after);
470 for (const [metric, x] of a) {
471 const y = b.get(metric);
472 if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue;
473 const [low, high] = bootstrapMedianDifference(x, y);
474 const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 };
475 entry.medians.push(median([...x, ...y]));
476 entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2);
477 entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x)));
478 found.set(metric, entry);
479 }
480 }
481 const rows: NoiseRow[] = [...found].map(([metric, entry]) => {
482 const middle = median(entry.medians);
483 const rule = noiseRule(metric, rules);
484 return {
485 metric,
486 median: round(middle, 2),
487 halfWidth: round(entry.halfWidth, 2),
488 aaDifference: round(entry.aaDifference, 2),
489 floor: rule.floor,
490 suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)),
491 gate: rule.gate,
492 suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE,
493 };
494 });
495 const lines = [
496 "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |",
497 "| :-- | --: | --: | --: | --: | --: | :-: | :-: |",
498 ...rows.map(
499 (row) =>
500 `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`,
501 ),
502 ];
503 return { rows, table: lines.join("\n") };
504}
505
506export function compareMetrics(
507 before: ServerMetrics,
508 after: ServerMetrics,
509 threshold = 10,
510 rules?: ReadonlyArray<NoiseRule>,
511) {
512 const forPlatform = noiseRulesFor([before, after]);
513 const gating = rules ?? forPlatform.rules;
514 const a = collect(before);
515 const b = collect(after);
516 const lines = [
517 "### Server metrics (lower is better, except throughput per minute)",
518 "",
519 `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" : ""}`,
520 "",
521 "| metric | before | after | change | 95% interval | |",
522 "| :-- | --: | --: | --: | --: | :-- |",
523 ];
524 const regressed: string[] = [];
525 const improved: string[] = [];
526 let compared = 0;
527 const informational: string[] = [];
528 for (const metric of new Set([...a.keys(), ...b.keys()])) {
529 if (!isMetric(metric)) continue;
530 const x = a.get(metric);
531 const y = b.get(metric);
532 if (!x || !y) {
533 lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`);
534 continue;
535 }
536 // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file
537 // from before the sampler and one from after measured different things. The per-thread fit
538 // comes from the quiet windows.
539 if (!sameWakeupMethod(metric, a, b)) {
540 lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`);
541 continue;
542 }
543 compared++;
544 const mx = median(x);
545 const my = median(y);
546 // A change counts only past both the relative threshold and the absolute noise floor.
547 const rule = noiseRule(metric, gating);
548 const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100);
549 const repeated = x.length > 1 && y.length > 1;
550 const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx];
551 const up = low > limit ? "worse" : high < -limit ? "better" : "";
552 const moved = higherIsBetter(metric) ? { worse: "better", better: "worse", "": "" }[up] : up;
553 if (moved && !rule.gate) informational.push(metric);
554 else if (moved === "worse") regressed.push(metric);
555 else if (moved === "better") improved.push(metric);
556 const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy";
557 const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100;
558 const shown = Number.isFinite(percent)
559 ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%`
560 : "new";
561 const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : "";
562 lines.push(
563 `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`,
564 );
565 }
566 const warnings = [
567 ...(rules || !forPlatform.warning ? [] : [forPlatform.warning]),
568 ...loadWarnings("before", before),
569 ...loadWarnings("after", after),
570 ];
571 return { table: lines.join("\n"), regressed, improved, informational, compared, warnings };
572}
573
574const CallFrame = Schema.Struct({
575 functionName: Schema.String,
576 url: Schema.String,
577 lineNumber: Schema.Number,
578});
579type CallFrame = typeof CallFrame.Type;
580export const CpuProfile = Schema.Struct({
581 nodes: Schema.Array(
582 Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }),
583 ),
584 samples: Schema.optional(Schema.Array(Schema.Number)),
585 startTime: Schema.Number,
586 endTime: Schema.Number,
587});
588interface HeapProfileNode {
589 readonly callFrame: CallFrame;
590 readonly selfSize: number;
591 readonly children: ReadonlyArray<HeapProfileNode>;
592}
593const HeapProfileNode: Schema.Codec<HeapProfileNode> = Schema.Struct({
594 callFrame: CallFrame,
595 selfSize: Schema.Number,
596 children: Schema.Array(Schema.suspend(() => HeapProfileNode)),
597});
598export const HeapProfile = Schema.Struct({ head: HeapProfileNode });
599
600const shortUrl = (url: string) =>
601 url
602 .replace(/^file:\/\//, "")
603 .split(/[\\/]/)
604 .slice(-3)
605 .join("/");
606const frameName = (frame: CallFrame) =>
607 `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim();
608const top = (totals: Map<string, number>, digits: number): Hotspot[] =>
609 [...totals]
610 .toSorted((a, b) => b[1] - a[1])
611 .slice(0, 10)
612 .map(([frame, value]) => ({ frame, value: round(value, digits) }));
613
614/** Top CPU self time in ms and allocated MB, by function. */
615export function summarizeProfiles(
616 cpu: typeof CpuProfile.Type,
617 heap: typeof HeapProfile.Type,
618): ProfileSummary {
619 const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1);
620 const cpuTotals = new Map<string, number>();
621 for (const node of cpu.nodes) {
622 if (!node.hitCount || node.callFrame.functionName === "(idle)") continue;
623 const name = frameName(node.callFrame);
624 cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs);
625 }
626 const allocations = new Map<string, number>();
627 const visit = (node: HeapProfileNode) => {
628 const name = frameName(node.callFrame);
629 allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6);
630 for (const child of node.children) visit(child);
631 };
632 visit(heap.head);
633 return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) };
634}
635
636const TypeNames = Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String]));
637export const HeapSnapshot = Schema.Struct({
638 snapshot: Schema.Struct({
639 meta: Schema.Struct({
640 node_fields: Schema.Array(Schema.String),
641 node_types: TypeNames,
642 edge_fields: Schema.Array(Schema.String),
643 edge_types: TypeNames,
644 }),
645 }),
646 nodes: Schema.Array(Schema.Number),
647 edges: Schema.Array(Schema.Number),
648 strings: Schema.Array(Schema.String),
649});
650type HeapSnapshot = typeof HeapSnapshot.Type;
651
652/** Self size by constructor from a V8 heap snapshot. */
653export function heapByConstructor(snapshot: HeapSnapshot) {
654 const fields = snapshot.snapshot.meta.node_fields;
655 const typeNames = snapshot.snapshot.meta.node_types[0];
656 const types = Array.isArray(typeNames) ? typeNames : [];
657 const typeAt = fields.indexOf("type");
658 const nameAt = fields.indexOf("name");
659 const sizeAt = fields.indexOf("self_size");
660 const totals = new Map<string, { count: number; bytes: number }>();
661 for (let index = 0; index < snapshot.nodes.length; index += fields.length) {
662 const type = types[snapshot.nodes[index + typeAt]!] ?? "?";
663 const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? "";
664 const name =
665 type === "object"
666 ? label.slice(0, 80)
667 : type === "closure"
668 ? `(closure) ${label.slice(0, 60)}`
669 : `(${type.replace(/^(concatenated|sliced) /, "")})`;
670 const entry = totals.get(name) ?? { count: 0, bytes: 0 };
671 entry.count++;
672 entry.bytes += snapshot.nodes[index + sizeAt]!;
673 totals.set(name, entry);
674 }
675 return totals;
676}
677
678/** The constructors whose heap grew most from one snapshot to the next. */
679export function heapGrowth(
680 before: ReturnType<typeof heapByConstructor>,
681 after: ReturnType<typeof heapByConstructor>,
682) {
683 return [...after]
684 .map(([name, { count, bytes }]) => ({
685 constructor: name,
686 count: count - (before.get(name)?.count ?? 0),
687 bytes: bytes - (before.get(name)?.bytes ?? 0),
688 }))
689 .filter((entry) => entry.bytes > 0)
690 .toSorted((a, b) => b.bytes - a.bytes)
691 .slice(0, 25)
692 .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));
693}
694
695interface Retainer {
696 readonly retained: number;
697 /** The id of the node that dominates this one, none for the root. */
698 readonly dominator: number | undefined;
699 /** Empty below `pathBytes`: such a node is only kept to compare sizes across snapshots. */
700 readonly path: string;
701}
702
703const TEXT_NODES = new Set(["string", "concatenated string", "sliced string", "regexp", "number"]);
704const IDENTIFIER = /^[A-Za-z_$#][\w$]{0,48}$/;
705
706/**
707 * Retained size by node id for every node retaining at least `minBytes`, and for those retaining
708 * `pathBytes` the shortest strong path from the root to it. Node ids are stable within one process, so snapshots of one
709 * server line up. Paths name only code: string contents and non-identifier keys are left out.
710 */
711export function heapRetainers(snapshot: HeapSnapshot, minBytes = 16_000, pathBytes = 256_000) {
712 const { meta } = snapshot.snapshot;
713 const nodeFields = meta.node_fields.length;
714 const edgeFields = meta.edge_fields.length;
715 const list = (names: typeof meta.node_types) => {
716 const first = names[0];
717 return Array.isArray(first) ? first : [];
718 };
719 const nodeTypes = list(meta.node_types);
720 const edgeTypes = list(meta.edge_types);
721 const [typeAt, nameAt, idAt, sizeAt, edgeCountAt] = [
722 "type",
723 "name",
724 "id",
725 "self_size",
726 "edge_count",
727 ].map((field) => meta.node_fields.indexOf(field)) as [number, number, number, number, number];
728 const [edgeTypeAt, edgeNameAt, toAt] = ["type", "name_or_index", "to_node"].map((field) =>
729 meta.edge_fields.indexOf(field),
730 ) as [number, number, number];
731 const { nodes, edges, strings } = snapshot;
732 const count = nodes.length / nodeFields;
733 const firstEdge = new Uint32Array(count + 1);
734 for (let node = 0, offset = 0; node < count; node++) {
735 firstEdge[node] = offset;
736 offset += nodes[node * nodeFields + edgeCountAt]! * edgeFields;
737 firstEdge[node + 1] = offset;
738 }
739 const weak = edgeTypes.indexOf("weak");
740 const shortcut = edgeTypes.indexOf("shortcut");
741 const strong = (edge: number) =>
742 edges[edge + edgeTypeAt] !== weak && edges[edge + edgeTypeAt] !== shortcut;
743 const target = (edge: number) => edges[edge + toAt]! / nodeFields;
744
745 // Postorder from the root, then dominators by Cooper, Harvey and Kennedy's iteration.
746 const postorder = new Int32Array(count).fill(-1);
747 const order = new Int32Array(count);
748 const stack = new Int32Array(count);
749 const cursor = new Uint32Array(count);
750 const seen = new Uint8Array(count);
751 let depth = 0;
752 let visited = 0;
753 stack[depth++] = 0;
754 seen[0] = 1;
755 cursor[0] = firstEdge[0]!;
756 while (depth > 0) {
757 const node = stack[depth - 1]!;
758 if (cursor[node]! < firstEdge[node + 1]!) {
759 const edge = cursor[node]!;
760 cursor[node] = edge + edgeFields;
761 const next = target(edge);
762 if (strong(edge) && !seen[next]) {
763 seen[next] = 1;
764 cursor[next] = firstEdge[next]!;
765 stack[depth++] = next;
766 }
767 } else {
768 depth--;
769 postorder[node] = visited;
770 order[visited++] = node;
771 }
772 }
773 const predecessorStart = new Uint32Array(count + 1);
774 for (let node = 0; node < count; node++) {
775 if (!seen[node]) continue;
776 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
777 if (strong(edge)) predecessorStart[target(edge) + 1]!++;
778 }
779 }
780 for (let node = 0; node < count; node++) predecessorStart[node + 1]! += predecessorStart[node]!;
781 const predecessors = new Int32Array(predecessorStart[count]!);
782 const fill = predecessorStart.slice(0, count);
783 for (let node = 0; node < count; node++) {
784 if (!seen[node]) continue;
785 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
786 if (strong(edge)) predecessors[fill[target(edge)]!++] = node;
787 }
788 }
789 const dominator = new Int32Array(count).fill(-1);
790 dominator[0] = 0;
791 const intersect = (left: number, right: number) => {
792 while (left !== right) {
793 while (postorder[left]! < postorder[right]!) left = dominator[left]!;
794 while (postorder[right]! < postorder[left]!) right = dominator[right]!;
795 }
796 return left;
797 };
798 for (let changed = true; changed;) {
799 changed = false;
800 for (let index = visited - 2; index >= 0; index--) {
801 const node = order[index]!;
802 let found = -1;
803 for (let at = predecessorStart[node]!; at < predecessorStart[node + 1]!; at++) {
804 const predecessor = predecessors[at]!;
805 if (dominator[predecessor] === -1) continue;
806 found = found === -1 ? predecessor : intersect(predecessor, found);
807 }
808 if (found !== -1 && dominator[node] !== found) {
809 dominator[node] = found;
810 changed = true;
811 }
812 }
813 }
814 const retained = new Float64Array(count);
815 for (let node = 0; node < count; node++) retained[node] = nodes[node * nodeFields + sizeAt]!;
816 for (let index = 0; index < visited - 1; index++) {
817 const node = order[index]!;
818 retained[dominator[node]!]! += retained[node]!;
819 }
820
821 const parent = new Int32Array(count).fill(-1);
822 const parentEdge = new Int32Array(count).fill(-1);
823 const queue = new Int32Array(count);
824 let head = 0;
825 let tail = 0;
826 queue[tail++] = 0;
827 parent[0] = 0;
828 while (head < tail) {
829 const node = queue[head++]!;
830 for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) {
831 const next = target(edge);
832 if (!strong(edge) || parent[next] !== -1) continue;
833 parent[next] = node;
834 parentEdge[next] = edge;
835 queue[tail++] = next;
836 }
837 }
838 const nodeType = (node: number) => nodeTypes[nodes[node * nodeFields + typeAt]!] ?? "?";
839 const label = (node: number) => {
840 const type = nodeType(node);
841 if (TEXT_NODES.has(type)) return `(${type})`;
842 const name = strings[nodes[node * nodeFields + nameAt]!] ?? "";
843 const shown = name.length > 60 || /["'`\n\\]|:\/\/|(^|\s)\/[\w.]/.test(name) ? "?" : name;
844 if (type === "object") return shown;
845 if (type === "closure") return `${shown || "(anonymous)"}()`;
846 return `(${type}${shown ? ` ${shown}` : ""})`;
847 };
848 const edgeName = (edge: number) => {
849 const type = edgeTypes[edges[edge + edgeTypeAt]!];
850 const value = edges[edge + edgeNameAt]!;
851 if (type === "element" || type === "hidden") return `[${value}]`;
852 const name = strings[value] ?? "";
853 return IDENTIFIER.test(name) ? name : "<key>";
854 };
855 const pathTo = (node: number) => {
856 const steps: string[] = [];
857 for (let at = node; at !== 0 && steps.length < 40; at = parent[at]!) {
858 if (parent[at] === -1) return "(unreachable)";
859 const from = parent[at]!;
860 steps.push(
861 from === 0 || nodeType(from) === "synthetic"
862 ? edgeName(parentEdge[at]!)
863 : `${label(from)}.${edgeName(parentEdge[at]!)}`,
864 );
865 if (nodeType(from) === "synthetic") break;
866 }
867 const shown = steps.reverse();
868 return [...(shown.length > 6 ? ["…", ...shown.slice(-6)] : shown), label(node)].join(" → ");
869 };
870 const result = new Map<number, Retainer>();
871 for (let node = 0; node < count; node++) {
872 if (!seen[node] || retained[node]! < minBytes) continue;
873 result.set(nodes[node * nodeFields + idAt]!, {
874 retained: retained[node]!,
875 dominator: node === 0 ? undefined : nodes[dominator[node]! * nodeFields + idAt]!,
876 path:
877 retained[node]! < pathBytes
878 ? ""
879 : nodeType(node) === "synthetic"
880 ? label(node)
881 : pathTo(node),
882 });
883 }
884 return result;
885}
886
887/**
888 * The objects whose retained size grew from each snapshot to the next, at least `minBytes` in all.
889 * An object is left out when a reported object it dominates holds at least 80% of its growth: of
890 * a chain that grew by about the same amount, only the deepest is kept, the container holding the
891 * growth. Nested objects whose growth differs are each reported.
892 */
893export function retainerGrowth(
894 snapshots: ReadonlyArray<ReadonlyMap<number, Retainer>>,
895 minBytes = 1_000_000,
896) {
897 const last = snapshots.at(-1);
898 if (last === undefined || snapshots.length < 2) return [];
899 const growth = new Map<number, number>();
900 for (const [id, { retained, path }] of last) {
901 if (path === "" || path.startsWith("(synthetic")) continue;
902 const sizes = [
903 ...snapshots.slice(0, -1).map((snapshot) => snapshot.get(id)?.retained ?? 0),
904 retained,
905 ];
906 const grewEachTime = sizes.every((size, index) => index === 0 || size > sizes[index - 1]!);
907 const grown = retained - sizes[0]!;
908 if (grewEachTime && grown >= minBytes) growth.set(id, grown);
909 }
910 const ancestors = (id: number) => {
911 const found: number[] = [];
912 for (let at = last.get(id)?.dominator; at !== undefined && found.length < 500;) {
913 found.push(at);
914 at = last.get(at)?.dominator;
915 }
916 return found;
917 };
918 // Deepest first, so every descendant is decided before its ancestors: a row is left out
919 // only when a reported descendant holds at least 80% of its growth.
920 const heldBelow = new Map<number, number>();
921 const kept: Array<[number, number]> = [];
922 const depth = new Map([...growth.keys()].map((id) => [id, ancestors(id).length]));
923 const order = [...growth].toSorted((a, b) => depth.get(b[0])! - depth.get(a[0])!);
924 for (const [id, grown] of order) {
925 if ((heldBelow.get(id) ?? 0) >= grown * 0.8) continue;
926 kept.push([id, grown]);
927 for (const ancestor of ancestors(id)) {
928 heldBelow.set(ancestor, Math.max(heldBelow.get(ancestor) ?? 0, grown));
929 }
930 }
931 const rows: RetainerGrowth[] = kept
932 .toSorted((a, b) => b[1] - a[1])
933 .slice(0, 10)
934 .map(([id, grown]) => ({
935 path: last.get(id)!.path,
936 MB: round(grown / 1e6, 2),
937 retainedMB: round(last.get(id)!.retained / 1e6, 2),
938 }));
939 return rows;
940}
941
942const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String));
943const spellings: ReadonlyArray<(path: string) => string> = [
944 (path) => path,
945 // Inside a JSON string, with every escape JSON applies: backslashes, quotes, control characters.
946 (path) => encodeJsonString(path).slice(1, -1),
947 (path) => path.replaceAll("\\", "/"),
948];
949
950/** How a path can appear in a database's text: as written, JSON-escaped, with forward slashes. */
951export function pathSpellings(path: string) {
952 return [...new Set(spellings.map((spell) => spell(path)))];
953}
954
955/** Each spelling of `from` with the same spelling of `to`, for a textual rewrite. */
956export function pathRewrites(from: string, to: string) {
957 const pairs = new Map(spellings.map((spell) => [spell(from), spell(to)] as const));
958 return [...pairs];
959}
960
961/**
962 * When the next activity report goes out, `intervalMs` after the previous send, and whether it
963 * starts too late to renew the lease that send took: past `latestMs`, a renewal can land after it
964 * lapsed.
965 */
966export function nextActivityReport(
967 lastSentAt: number,
968 now: number,
969 intervalMs = 25_000,
970 latestMs = 40_000,
971) {
972 const due = lastSentAt + intervalMs;
973 return { waitMs: Math.max(0, due - now), late: Math.max(due, now) - lastSentAt > latestMs };
974}
975
976/**
977 * Whether a renewal let the previous send's lease lapse: it went out past `latestMs` after that
978 * send (a stalled loop wakes late), or its answer came after the lease (`leaseMs`) ran out.
979 */
980export function activityRenewalMissed(
981 previousSentAt: number,
982 sentAt: number,
983 repliedAt: number,
984 latestMs = 40_000,
985 leaseMs = 45_000,
986) {
987 return sentAt - previousSentAt > latestMs || repliedAt - previousSentAt > leaseMs;
988}