From 027d515f713f0221bd317c3daa4ca433a685df78 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:37:31 -0800 Subject: [PATCH 1/7] feat(scripts): server metrics record machine load and derive noise floors from A/A runs Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 224 +++++++++++++++++++++++++------ scripts/server-metrics.test.ts | 86 ++++++++++++ scripts/server-metrics.ts | 134 +++++++++++++++++- 3 files changed, 402 insertions(+), 42 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c11cfca1589a7..4e68d26304f94 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -39,8 +39,19 @@ const Soak = Schema.Struct({ rssMBPerHour: Schema.Number, }); +const MachineState = Schema.Struct({ + /** The higher 1-minute load average of the run's start and end; none on Windows. */ + load1: Schema.NullOr(Schema.Number), + /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */ + otherCpuCores: Schema.NullOr(Schema.Number), + minutes: Schema.Number, +}); +export type MachineState = typeof MachineState.Type; + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ + /** What else the machine was doing during the pass; never compared, only warned about. */ + machine: Schema.optional(MachineState), startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), rest: Schema.optional(Window), firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), @@ -202,20 +213,80 @@ export function flatten(measured: Measured): Map { return values; } -function noiseFloor(metric: string) { - if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; - if (metric.startsWith("soak.")) return 20; - if (metric.endsWith("cpuPct")) return 1; - if (metric.endsWith("wakeupsPerSec")) return 20; - if (metric.endsWith("MB")) return 15; - if (metric.endsWith("KB")) return 20; - if (metric.includes(".shellMs.") || metric.includes(".openMs.")) return 50; - if (metric.endsWith("loopDelayP50Ms")) return 2; - if (metric.endsWith("loopDelayP99Ms")) return 5; - if (metric.endsWith("loopDelayMaxMs")) return 20; - if (metric.endsWith("gcPauseMs")) return 10; - if (metric.endsWith("gcCount")) return 20; - return 300; +/** + * How far a metric moves between runs of the same commit, and whether it moves little enough to + * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see + * docs/internals/performance-regressions.md for the runs these came from. + */ +export interface NoiseRule { + readonly pattern: RegExp; + /** Absolute change a metric must clear on top of the relative threshold. */ + readonly floor: number; + /** False for metrics an A/A run moves too far to gate on: shown, never counted. */ + readonly gate: boolean; +} + +export const NOISE_RULES: ReadonlyArray = [ + { pattern: /^scaling\..*cpuPctPerThread$/, floor: 0.2, gate: true }, + { pattern: /^scaling\./, floor: 2, gate: true }, + { pattern: /^soak\./, floor: 20, gate: true }, + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /KB$/, floor: 20, gate: true }, + { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true }, + { pattern: /loopDelayP50Ms$/, floor: 2, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, + { pattern: /gcPauseMs$/, floor: 10, gate: true }, + { pattern: /gcCount$/, floor: 20, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + +export function noiseRule(metric: string, rules: ReadonlyArray = NOISE_RULES) { + return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; +} + +/** Fields that describe a run rather than measure it. */ +const isMetric = (metric: string) => + !( + metric === "soak.minutes" || + metric.startsWith("machine.") || + metric.endsWith("loopSamples") || + metric === "busy.projects" || + metric === "busy.ballastMB" || + metric.endsWith(".clients") || + metric.endsWith(".threads") || + metric === "busy.largeThread.messages" || + metric.startsWith("scaling.points") + ); + +/** + * A run is loaded when other node, T3 and agent processes kept this share of the cores busy, or, + * where that is unknown, when the 1-minute load passed this much per CPU. The load counts the + * run's own agents too, so it is only the fallback. + */ +export const HEAVY_LOAD_PER_CPU = 0.75; +export const HEAVY_OTHER_CPU_SHARE = 0.25; + +/** One line per side whose runs shared the machine with heavy load, so its numbers are suspect. */ +export function loadWarnings(side: string, metrics: ServerMetrics) { + const cpus = typeof metrics.meta.cpus === "number" ? metrics.meta.cpus : null; + if (cpus === null) return []; + const loaded = metrics.runs.flatMap(({ machine }) => + machine && + (machine.otherCpuCores === null + ? (machine.load1 ?? 0) >= cpus * HEAVY_LOAD_PER_CPU + : machine.otherCpuCores >= cpus * HEAVY_OTHER_CPU_SHARE) + ? [machine] + : [], + ); + if (loaded.length === 0) return []; + const worstLoad = Math.max(...loaded.map(({ load1 }) => load1 ?? 0)); + const worstOther = Math.max(...loaded.map(({ otherCpuCores }) => otherCpuCores ?? 0)); + return [ + `${side} ran under heavy load in ${loaded.length} of ${metrics.runs.length} runs (load up to ${worstLoad} on ${cpus} CPUs, other node/T3/agent processes up to ${worstOther} cores); rerun on a quieter machine before trusting a change`, + ]; } const median = (values: ReadonlyArray) => { @@ -241,16 +312,96 @@ export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyA return [differences[49]!, differences[1_949]!] as const; } -export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const collect = (metrics: ServerMetrics) => { - const values = new Map(); - for (const run of metrics.runs) { - for (const [metric, value] of flatten(run)) { - values.set(metric, [...(values.get(metric) ?? []), value]); - } +/** Every metric's values across a file's runs. */ +const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); } - return values; - }; + } + return values; +}; + +/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */ +const ceilSignificant = (value: number) => { + if (value <= 0) return 0; + const step = 10 ** (Math.floor(Math.log10(value)) - 1); + return round(Math.ceil(value / step) * step, 6); +}; + +/** A swing past this share of a metric's median makes it informational. */ +export const NOISY_SHARE = 0.5; + +export interface NoiseRow { + readonly metric: string; + readonly median: number; + /** Half the pooled range: how far one run lands from the middle. */ + readonly halfRange: number; + /** The largest |median(A) - median(B)| over the A/A pairs. */ + readonly aaDifference: number; + readonly floor: number; + readonly suggestedFloor: number; + readonly gate: boolean; + readonly suggestedGate: boolean; +} + +/** + * Run-to-run spread of every metric over A/A pairs (one commit against itself), and the floor + * each needs so the same commit never counts as a change: at least half the pooled range of one + * pair and the A/A median difference, over every pair. + */ +export function noiseReport( + pairs: ReadonlyArray, + rules: ReadonlyArray = NOISE_RULES, +) { + const found = new Map(); + for (const [before, after] of pairs) { + const a = collect(before); + const b = collect(after); + for (const [metric, x] of a) { + const y = b.get(metric); + if (!y || !isMetric(metric)) continue; + const pooled = [...x, ...y]; + const entry = found.get(metric) ?? { medians: [], halfRange: 0, aaDifference: 0 }; + entry.medians.push(median(pooled)); + entry.halfRange = Math.max(entry.halfRange, (Math.max(...pooled) - Math.min(...pooled)) / 2); + entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x))); + found.set(metric, entry); + } + } + const rows: NoiseRow[] = [...found].map(([metric, entry]) => { + const middle = median(entry.medians); + const rule = noiseRule(metric, rules); + const suggestedFloor = ceilSignificant(Math.max(entry.halfRange, entry.aaDifference)); + return { + metric, + median: round(middle, 2), + halfRange: round(entry.halfRange, 2), + aaDifference: round(entry.aaDifference, 2), + floor: rule.floor, + suggestedFloor, + gate: rule.gate, + suggestedGate: entry.halfRange <= Math.abs(middle) * NOISY_SHARE, + }; + }); + const lines = [ + "| metric | median | ± half range | A/A diff | floor | suggested | gated | suggested |", + "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", + ...rows.map( + (row) => + `| ${row.metric} | ${row.median} | ${row.halfRange} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, + ), + ]; + return { rows, table: lines.join("\n") }; +} + +export function compareMetrics( + before: ServerMetrics, + after: ServerMetrics, + threshold = 10, + rules: ReadonlyArray = NOISE_RULES, +) { const a = collect(before); const b = collect(after); const lines = [ @@ -264,18 +415,9 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const regressed: string[] = []; const improved: string[] = []; let compared = 0; + const informational: string[] = []; for (const metric of new Set([...a.keys(), ...b.keys()])) { - if ( - metric === "soak.minutes" || - metric.endsWith("loopSamples") || - metric === "busy.projects" || - metric === "busy.ballastMB" || - metric === "clients.storm.clients" || - metric === "busy.largeThread.messages" || - metric.startsWith("scaling.points") - ) { - continue; - } + if (!isMetric(metric)) continue; const x = a.get(metric); const y = b.get(metric); if (!x || !y) { @@ -299,12 +441,15 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const mx = median(x); const my = median(y); // A change counts only past both the relative threshold and the absolute noise floor. - const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const rule = noiseRule(metric, rules); + const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; - if (verdict === "worse") regressed.push(metric); - if (verdict === "better") improved.push(metric); + const moved = low > limit ? "worse" : high < -limit ? "better" : ""; + if (moved && !rule.gate) informational.push(metric); + else if (moved === "worse") regressed.push(metric); + else if (moved === "better") improved.push(metric); + const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy"; const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; const shown = Number.isFinite(percent) ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` @@ -314,7 +459,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, ); } - return { table: lines.join("\n"), regressed, improved, compared }; + const warnings = [...loadWarnings("before", before), ...loadWarnings("after", after)]; + return { table: lines.join("\n"), regressed, improved, informational, compared, warnings }; } const CallFrame = Schema.Struct({ diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 760c850dbbbea..054ffc85f7697 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -5,7 +5,9 @@ import { compareMetrics, activityRenewalMissed, heapGrowth, + loadWarnings, nextActivityReport, + noiseReport, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -129,6 +131,90 @@ describe("compareMetrics", () => { }); }); +describe("compareMetrics with noise rules", () => { + const rules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: false }, + { pattern: /./, floor: 1_000, gate: true }, + ]; + it.each([ + ["a gated metric past its floor", { cpuPct: 5 }, ["quiet.cpuPct"], []], + ["an ungated metric far past its floor", { loopDelayMaxMs: 300 }, [], ["quiet.loopDelayMaxMs"]], + ["an ungated metric under its floor", { loopDelayMaxMs: 20 }, [], []], + ])("%s", (_name, change, regressed, informational) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change }), 10, rules); + expect(result.regressed).toEqual(regressed); + expect(result.informational).toEqual(informational); + }); + + it("marks an ungated metric in the table either way", () => { + const result = compareMetrics(quietRuns(base), quietRuns(base), 10, rules); + expect(result.table).toContain("| quiet.loopDelayMaxMs | 8 | 8 | 0% | | noisy |"); + }); +}); + +describe("loadWarnings", () => { + const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) => + ({ + meta: { ...meta, cpus }, + runs: machines.map(([load1, otherCpuCores]) => ({ + machine: { load1, otherCpuCores, minutes: 10 }, + })), + }) satisfies ServerMetrics; + it.each([ + ["a quiet machine", loaded(16, [4, 1], [5, 2]), 0], + ["load past 0.75 per CPU with other processes unknown", loaded(16, [4, null], [12.5, null]), 1], + ["high load from the run's own agents", loaded(16, [21, 1]), 0], + ["other processes on a quarter of the cores", loaded(16, [4, 4.1]), 1], + ["no CPU count", loaded(null, [40, 40]), 0], + ["no machine state, as in older files", { meta: { ...meta, cpus: 16 }, runs: [{}] }, 0], + ])("%s", (_name, metrics, count) => { + expect(loadWarnings("before", metrics)).toHaveLength(count); + }); + + it("names the worst run", () => { + expect(loadWarnings("after", loaded(16, [13, 4.5], [14.2, 5]))[0]).toContain( + "after ran under heavy load in 2 of 2 runs (load up to 14.2 on 16 CPUs, other node/T3/agent processes up to 5 cores)", + ); + }); + + it("is reported by compareMetrics", () => { + expect(compareMetrics(quietRuns(base), loaded(16, [20, null])).warnings).toHaveLength(1); + }); +}); + +describe("noiseReport", () => { + it("suggests a floor covering the pooled swing and the A/A difference, rounded up", () => { + const [row] = noiseReport([[cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3)]]).rows.filter( + ({ metric }) => metric === "quiet.cpuPct", + ); + // Pooled 2 to 3.1: half range 0.55; medians 2.2 and 2.3. + expect(row).toMatchObject({ median: 2.25, halfRange: 0.55, aaDifference: 0.1 }); + expect(row?.suggestedFloor).toBe(0.55); + expect(row?.suggestedGate).toBe(true); + }); + + it("takes the widest pair, and calls a metric noisy past half its median", () => { + const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const; + const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const; + const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row?.halfRange).toBe(1.5); + expect(row?.suggestedGate).toBe(false); + }); + + it("leaves out fields that describe a run", () => { + const withMachine = (metrics: ServerMetrics): ServerMetrics => ({ + ...metrics, + runs: metrics.runs.map((run) => ({ + ...run, + machine: { load1: 3, otherCpuCores: 1, minutes: 9 }, + })), + }); + const rows = noiseReport([[withMachine(cpuRuns(1)), withMachine(cpuRuns(1))]]).rows; + expect(rows.some(({ metric }) => metric.startsWith("machine."))).toBe(false); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 8ab475f38a5ad..46e73b19e1dd3 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -58,6 +58,8 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + loadWarnings, + noiseReport, round, ServerMetrics, slope, @@ -70,6 +72,7 @@ import { parseRunSelection, summarizeProfiles, type FirstWord, + type MachineState, type Measured, type ProfileSummary, type Window, @@ -1333,6 +1336,7 @@ interface RunOptions { const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); const api = yield* serveFakeAnthropic(); const environment: Environment = { @@ -1619,6 +1623,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + measured.machine = yield* machine; return { measured: measured as Measured, profiles, soakHeapGrowth }; }, Effect.scoped); @@ -1641,6 +1646,87 @@ const machineLoad = Effect.gen(function* () { ), ); +/** Comm names of the processes that compete with a measured server on a developer's machine. */ +const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/; + +/** + * CPU seconds by pid of every node, T3, claude or codex process outside this script's own tree. + * Linux only; elsewhere none, and the run records only the load average. + */ +const competingCpuSeconds = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return Option.none>(); + const fs = yield* FileSystem.FileSystem; + const self = Number(yield* fs.readLink("/proc/self")); + const parents = new Map(); + const cpu = new Map(); + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const open = stat.indexOf(" ("); + const close = stat.lastIndexOf(") "); + if (open < 0 || close < 0) continue; + const fields = stat.slice(close + 2).split(" "); + const pid = Number(entry); + parents.set(pid, Number(fields[1])); + if (COMPETING.test(stat.slice(open + 2, close))) { + cpu.set(pid, (Number(fields[11]) + Number(fields[12])) / 100); + } + } + const ours = (pid: number) => { + for (let at: number | undefined = pid; at !== undefined && at > 1; at = parents.get(at)) { + if (at === self) return true; + } + return false; + }; + return Option.some(new Map([...cpu].filter(([pid]) => !ours(pid)))); +}).pipe(Effect.orElseSucceed(() => Option.none>())); + +/** CPU seconds the competing processes spent between two reads; a process that exited is lost. */ +const competingBetween = ( + before: ReadonlyMap, + after: ReadonlyMap, +) => [...after].reduce((total, [pid, seconds]) => total + seconds - (before.get(pid) ?? 0), 0); + +const load1 = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") return Option.none(); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(text, (value) => Number(value.split(" ")[0])); + } + const text = yield* output("sysctl", ["-n", "vm.loadavg"]); + return Option.map(text, (value) => Number(value.replace(/[{}]/g, "").trim().split(/\s+/)[0])); +}).pipe(Effect.map(Option.filter(Number.isFinite))); + +/** + * Starts watching the machine for one run; the returned effect reads what competed with it: the + * highest 1-minute load seen and the cores other T3, node and agent processes kept busy. + */ +const watchMachine = Effect.gen(function* () { + const startedAt = yield* nowMs; + const loadBefore = yield* load1; + const cpuBefore = yield* competingCpuSeconds; + return Effect.gen(function* () { + const elapsed = ((yield* nowMs) - startedAt) / 1_000; + const loadAfter = yield* load1; + const cpuAfter = yield* competingCpuSeconds; + const loads = [loadBefore, loadAfter].flatMap((load) => Option.toArray(load)); + const machine: MachineState = { + load1: loads.length ? round(Math.max(...loads), 2) : null, + otherCpuCores: + Option.isSome(cpuBefore) && Option.isSome(cpuAfter) && elapsed > 0 + ? round(competingBetween(cpuBefore.value, cpuAfter.value) / elapsed, 2) + : null, + minutes: round(elapsed / 60, 1), + }; + return machine; + }); +}); + const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; @@ -1694,13 +1780,21 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { - const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + const { table, regressed, improved, informational, compared, warnings } = compareMetrics( + before, + after, + threshold, + ); yield* Console.log(table); + for (const warning of warnings) yield* Console.error(`Warning: ${warning}`); if (compared === 0) { return yield* new MetricsError({ message: "the two files share no metric, so nothing was compared", }); } + if (informational.length) { + yield* Console.error(`Moved, but too noisy to gate on: ${informational.join(", ")}`); + } if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); if (regressed.length === 0) return; yield* Console.error(`Worse: ${regressed.join(", ")}`); @@ -1937,7 +2031,41 @@ const compareCommand = Command.make( }), ).pipe( Command.withDescription( - "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + "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, measured from A/A runs (see `noise`). Metrics too noisy to gate on are shown but never counted. Warns when either side ran under heavy machine load. Exits 1 on a regression.", + ), +); + +const noiseCommand = Command.make( + "noise", + { + dirs: Argument.String("dir").pipe( + Argument.withDescription("An `ab` out dir (a.json and b.json) of one commit against itself."), + Argument.atLeast(1), + ), + }, + Effect.fn("serverMetrics.noise")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + const pairs = yield* Effect.forEach(input.dirs, (dir) => + Effect.all([read(path.join(dir, "a.json")), read(path.join(dir, "b.json"))] as const), + ); + for (const [side, metrics] of pairs.flatMap( + ([a, b]) => + [ + ["a", a], + ["b", b], + ] as const, + )) { + for (const warning of loadWarnings(side, metrics)) + yield* Console.error(`Warning: ${warning}`); + } + yield* Console.log(noiseReport(pairs).table); + }), +).pipe( + Command.withDescription( + "Spread of every metric over A/A runs (`ab `), the floor each needs so the same commit never counts as a change, and which are too noisy to gate on. ⚠ marks a floor under what was seen.", ), ); @@ -1945,7 +2073,7 @@ const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", ), - Command.withSubcommands([runCommand, abCommand, compareCommand]), + Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); if (import.meta.main) { From 3fdc204e108e22f8344faa9b3bd44df0035c124f Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:48:19 -0800 Subject: [PATCH 2/7] fix(scripts): noise floors take only same-commit pairs and same-method wakeups, and competing CPU survives pid reuse and exits Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 58 ++++++++++++++----- scripts/server-metrics.test.ts | 60 +++++++++++++++++--- scripts/server-metrics.ts | 97 +++++++++++++++++++++----------- 3 files changed, 163 insertions(+), 52 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 4e68d26304f94..b1afb6fdb0a8a 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -40,7 +40,7 @@ const Soak = Schema.Struct({ }); const MachineState = Schema.Struct({ - /** The higher 1-minute load average of the run's start and end; none on Windows. */ + /** The highest 1-minute load average read through the run; none on Windows. */ load1: Schema.NullOr(Schema.Number), /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */ otherCpuCores: Schema.NullOr(Schema.Number), @@ -312,6 +312,44 @@ export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyA return [differences[49]!, differences[1_949]!] as const; } +/** + * False for a wakeup count where only one side had the delay sampler: wakeups include the + * sampler's only when `loopSamples` sits beside them, so the two measured different things. The + * per-thread fit comes from the quiet windows, so it follows their method. + */ +function sameWakeupMethod( + metric: string, + a: ReadonlyMap, + b: ReadonlyMap, +) { + const window = + metric === "scaling.wakeupsPerThread" + ? "quiet." + : metric.endsWith("wakeupsPerSec") + ? metric.slice(0, -"wakeupsPerSec".length) + : ""; + return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`); +} + +/** CPU seconds spent between two reads keyed by pid and start time; a process that exited is lost. */ +export function competingBetween( + before: ReadonlyMap, + after: ReadonlyMap, +) { + return [...after].reduce((total, [key, seconds]) => total + seconds - (before.get(key) ?? 0), 0); +} + +/** Why a directory is not an A/A pair: its files must record one and the same commit. */ +export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) { + const commits = [a.meta.commit, b.meta.commit]; + if (commits.some((commit) => typeof commit !== "string" || commit === "")) { + return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`; + } + return commits[0] === commits[1] + ? undefined + : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`; +} + /** Every metric's values across a file's runs. */ const collect = (metrics: ServerMetrics) => { const values = new Map(); @@ -347,9 +385,9 @@ export interface NoiseRow { } /** - * Run-to-run spread of every metric over A/A pairs (one commit against itself), and the floor - * each needs so the same commit never counts as a change: at least half the pooled range of one - * pair and the A/A median difference, over every pair. + * Run-to-run spread of every metric over A/A pairs (one commit against itself), and an estimated + * floor: the widest half range of a pair's pooled runs or A/A median difference these runs + * showed. A later A/A run can still land outside it; more pairs make it a better estimate. */ export function noiseReport( pairs: ReadonlyArray, @@ -361,7 +399,7 @@ export function noiseReport( const b = collect(after); for (const [metric, x] of a) { const y = b.get(metric); - if (!y || !isMetric(metric)) continue; + if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue; const pooled = [...x, ...y]; const entry = found.get(metric) ?? { medians: [], halfRange: 0, aaDifference: 0 }; entry.medians.push(median(pooled)); @@ -386,7 +424,7 @@ export function noiseReport( }; }); const lines = [ - "| metric | median | ± half range | A/A diff | floor | suggested | gated | suggested |", + "| metric | median | ± half range | A/A diff | floor | estimated floor | gated | suggest gating |", "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", ...rows.map( (row) => @@ -427,13 +465,7 @@ export function compareMetrics( // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file // from before the sampler and one from after measured different things. The per-thread fit // comes from the quiet windows. - const window = - metric === "scaling.wakeupsPerThread" - ? "quiet." - : metric.endsWith("wakeupsPerSec") - ? metric.slice(0, -"wakeupsPerSec".length) - : ""; - if (window && a.has(`${window}loopSamples`) !== b.has(`${window}loopSamples`)) { + if (!sameWakeupMethod(metric, a, b)) { lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`); continue; } diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 054ffc85f7697..080c4ae34372e 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,11 +3,13 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + competingBetween, activityRenewalMissed, heapGrowth, loadWarnings, nextActivityReport, noiseReport, + noisePairProblem, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -153,6 +155,38 @@ describe("compareMetrics with noise rules", () => { }); }); +describe("noisePairProblem", () => { + const at = (commit: string | null): ServerMetrics => ({ meta: { ...meta, commit }, runs: [] }); + it.each([ + ["one commit against itself", at("abc"), at("abc"), undefined], + [ + "an A/B directory", + at("abc"), + at("def"), + "ab-out: a.json is abc and b.json def; noise floors need one commit against itself", + ], + [ + "a file with no commit", + at(null), + at(null), + "ab-out: a.json or b.json records no commit, so it cannot be shown to be an A/A run", + ], + ])("%s", (_name, a, b, problem) => { + expect(noisePairProblem("ab-out", a, b)).toBe(problem); + }); +}); + +describe("competingBetween", () => { + it.each([ + ["a process that kept running", [["10:500", 900]], [["10:500", 960]], 60], + ["a new process, counted whole", [], [["11:700", 30]], 30], + ["a reused pid is a new process", [["10:500", 900]], [["10:800", 300]], 300], + ["a process that exited is lost", [["10:500", 900]], [], 0], + ] as const)("%s", (_name, before, after, seconds) => { + expect(competingBetween(new Map(before), new Map(after))).toBe(seconds); + }); +}); + describe("loadWarnings", () => { const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) => ({ @@ -184,14 +218,26 @@ describe("loadWarnings", () => { }); describe("noiseReport", () => { - it("suggests a floor covering the pooled swing and the A/A difference, rounded up", () => { - const [row] = noiseReport([[cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3)]]).rows.filter( - ({ metric }) => metric === "quiet.cpuPct", - ); + it.each([ // Pooled 2 to 3.1: half range 0.55; medians 2.2 and 2.3. - expect(row).toMatchObject({ median: 2.25, halfRange: 0.55, aaDifference: 0.1 }); - expect(row?.suggestedFloor).toBe(0.55); - expect(row?.suggestedGate).toBe(true); + ["the pooled swing", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.55, 0.1, 0.55], + // Pooled 2 to 3.25: half range 0.625; medians 2 and 3.25 differ by more. + ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0.63, 1.25, 1.3], + ])("estimates a floor from %s, rounded up", (_name, a, b, halfRange, aaDifference, floor) => { + const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row).toMatchObject({ halfRange, aaDifference, suggestedFloor: floor }); + }); + + it("leaves out wakeups counted with the delay sampler on one side only", () => { + const sampled: ServerMetrics = { + meta, + runs: quietRuns({ ...base, wakeupsPerSec: 160 }).runs.map((run) => ({ + quiet: { ...run.quiet, loopSamples: 2_900 }, + })), + }; + const metrics = noiseReport([[quietRuns(base), sampled]]).rows.map(({ metric }) => metric); + expect(metrics).not.toContain("quiet.wakeupsPerSec"); + expect(metrics).toContain("quiet.cpuPct"); }); it("takes the widest pair, and calls a metric noisy past half its median", () => { diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 46e73b19e1dd3..7dc8708e28e1a 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -58,8 +58,10 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + competingBetween, loadWarnings, noiseReport, + noisePairProblem, round, ServerMetrics, slope, @@ -1650,16 +1652,17 @@ const machineLoad = Effect.gen(function* () { const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/; /** - * CPU seconds by pid of every node, T3, claude or codex process outside this script's own tree. - * Linux only; elsewhere none, and the run records only the load average. + * CPU seconds of every node, T3, claude or codex process outside this script's own tree, keyed by + * pid and start time so a reused pid is a new process. Linux only; elsewhere none, and the run + * records only the load average. */ const competingCpuSeconds = Effect.gen(function* () { const platform = yield* HostProcess.Platform; - if (platform !== "linux") return Option.none>(); + if (platform !== "linux") return Option.none>(); const fs = yield* FileSystem.FileSystem; const self = Number(yield* fs.readLink("/proc/self")); const parents = new Map(); - const cpu = new Map(); + const cpu = new Map(); for (const entry of yield* fs.readDirectory("/proc")) { if (!/^\d+$/.test(entry)) continue; const stat = yield* fs @@ -1672,7 +1675,11 @@ const competingCpuSeconds = Effect.gen(function* () { const pid = Number(entry); parents.set(pid, Number(fields[1])); if (COMPETING.test(stat.slice(open + 2, close))) { - cpu.set(pid, (Number(fields[11]) + Number(fields[12])) / 100); + // Fields after the name start at the state, field 3: utime 14, stime 15, starttime 22. + cpu.set(pid, { + key: `${pid}:${fields[19]}`, + seconds: (Number(fields[11]) + Number(fields[12])) / 100, + }); } } const ours = (pid: number) => { @@ -1681,14 +1688,13 @@ const competingCpuSeconds = Effect.gen(function* () { } return false; }; - return Option.some(new Map([...cpu].filter(([pid]) => !ours(pid)))); -}).pipe(Effect.orElseSucceed(() => Option.none>())); + return Option.some( + new Map([...cpu].filter(([pid]) => !ours(pid)).map(([, { key, seconds }]) => [key, seconds])), + ); +}).pipe(Effect.orElseSucceed(() => Option.none>())); -/** CPU seconds the competing processes spent between two reads; a process that exited is lost. */ -const competingBetween = ( - before: ReadonlyMap, - after: ReadonlyMap, -) => [...after].reduce((total, [pid, seconds]) => total + seconds - (before.get(pid) ?? 0), 0); +/** How often the machine watcher reads competing CPU; a process that exits loses at most this. */ +const MACHINE_SAMPLE_SECONDS = 10; const load1 = Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -1708,19 +1714,36 @@ const load1 = Effect.gen(function* () { */ const watchMachine = Effect.gen(function* () { const startedAt = yield* nowMs; - const loadBefore = yield* load1; - const cpuBefore = yield* competingCpuSeconds; + const loads: number[] = []; + // Unknown (none) once any read fails, so a partial sum never passes for the whole run. + let competing: Option.Option = Option.some(0); + let previous = yield* competingCpuSeconds; + if (Option.isNone(previous)) competing = Option.none(); + const read = Effect.gen(function* () { + loads.push(...Option.toArray(yield* load1)); + if (Option.isNone(previous) || Option.isNone(competing)) return; + const next = yield* competingCpuSeconds; + if (Option.isNone(next)) { + competing = Option.none(); + return; + } + competing = Option.some(competing.value + competingBetween(previous.value, next.value)); + previous = next; + }); + yield* read; + // Reading through the run, not only at its ends, keeps a busy process that exits mid-run. + yield* read.pipe( + Effect.delay(Duration.seconds(MACHINE_SAMPLE_SECONDS)), + Effect.forever, + Effect.forkScoped, + ); return Effect.gen(function* () { + yield* read; const elapsed = ((yield* nowMs) - startedAt) / 1_000; - const loadAfter = yield* load1; - const cpuAfter = yield* competingCpuSeconds; - const loads = [loadBefore, loadAfter].flatMap((load) => Option.toArray(load)); const machine: MachineState = { load1: loads.length ? round(Math.max(...loads), 2) : null, otherCpuCores: - Option.isSome(cpuBefore) && Option.isSome(cpuAfter) && elapsed > 0 - ? round(competingBetween(cpuBefore.value, cpuAfter.value) / elapsed, 2) - : null, + Option.isSome(competing) && elapsed > 0 ? round(competing.value / elapsed, 2) : null, minutes: round(elapsed / 60, 1), }; return machine; @@ -2049,23 +2072,33 @@ const noiseCommand = Command.make( const read = (file: string) => fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); const pairs = yield* Effect.forEach(input.dirs, (dir) => - Effect.all([read(path.join(dir, "a.json")), read(path.join(dir, "b.json"))] as const), + Effect.gen(function* () { + const a = yield* read(path.join(dir, "a.json")); + const b = yield* read(path.join(dir, "b.json")); + const problem = noisePairProblem(dir, a, b); + if (problem !== undefined) return yield* new MetricsError({ message: problem }); + for (const [file, metrics] of [ + ["a.json", a], + ["b.json", b], + ] as const) { + for (const warning of loadWarnings(path.join(dir, file), metrics)) { + yield* Console.error(`Warning: ${warning}`); + } + } + return [a, b] as const; + }), ); - for (const [side, metrics] of pairs.flatMap( - ([a, b]) => - [ - ["a", a], - ["b", b], - ] as const, - )) { - for (const warning of loadWarnings(side, metrics)) - yield* Console.error(`Warning: ${warning}`); + const { rows, table } = noiseReport(pairs); + if (rows.length === 0) { + return yield* new MetricsError({ + message: "no metric was measured on both sides of any pair, so nothing was calibrated", + }); } - yield* Console.log(noiseReport(pairs).table); + yield* Console.log(table); }), ).pipe( Command.withDescription( - "Spread of every metric over A/A runs (`ab `), the floor each needs so the same commit never counts as a change, and which are too noisy to gate on. ⚠ marks a floor under what was seen.", + "Spread of every metric over A/A runs (`ab `), an estimated floor covering the half ranges and median differences these runs showed, and which metrics are too noisy to gate on. ⚠ marks a current floor under the estimate. Refuses directories whose two files record different commits.", ), ); From e5c2a458584a27b67d217ec78a51a25ccdaea776 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:21:00 -0800 Subject: [PATCH 3/7] fix(scripts): noise floors come from the A/A interval compare gates on, not one run's swing Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 33 ++++++++++++++++---------------- scripts/server-metrics.test.ts | 16 ++++++++-------- 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index b1afb6fdb0a8a..6d6533a2bd26d 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -368,14 +368,14 @@ const ceilSignificant = (value: number) => { return round(Math.ceil(value / step) * step, 6); }; -/** A swing past this share of a metric's median makes it informational. */ +/** An A/A interval wider than this share of a metric's median makes it informational. */ export const NOISY_SHARE = 0.5; export interface NoiseRow { readonly metric: string; readonly median: number; - /** Half the pooled range: how far one run lands from the middle. */ - readonly halfRange: number; + /** The widest half-width of an A/A pair's 95% interval of the median difference. */ + readonly halfWidth: number; /** The largest |median(A) - median(B)| over the A/A pairs. */ readonly aaDifference: number; readonly floor: number; @@ -385,25 +385,25 @@ export interface NoiseRow { } /** - * Run-to-run spread of every metric over A/A pairs (one commit against itself), and an estimated - * floor: the widest half range of a pair's pooled runs or A/A median difference these runs - * showed. A later A/A run can still land outside it; more pairs make it a better estimate. + * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The + * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far + * an A/A interval must miss zero to flag. It is an estimate, not a bound. */ export function noiseReport( pairs: ReadonlyArray, rules: ReadonlyArray = NOISE_RULES, ) { - const found = new Map(); + const found = new Map(); for (const [before, after] of pairs) { const a = collect(before); const b = collect(after); for (const [metric, x] of a) { const y = b.get(metric); if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue; - const pooled = [...x, ...y]; - const entry = found.get(metric) ?? { medians: [], halfRange: 0, aaDifference: 0 }; - entry.medians.push(median(pooled)); - entry.halfRange = Math.max(entry.halfRange, (Math.max(...pooled) - Math.min(...pooled)) / 2); + const [low, high] = bootstrapMedianDifference(x, y); + const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 }; + entry.medians.push(median([...x, ...y])); + entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2); entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x))); found.set(metric, entry); } @@ -411,24 +411,23 @@ export function noiseReport( const rows: NoiseRow[] = [...found].map(([metric, entry]) => { const middle = median(entry.medians); const rule = noiseRule(metric, rules); - const suggestedFloor = ceilSignificant(Math.max(entry.halfRange, entry.aaDifference)); return { metric, median: round(middle, 2), - halfRange: round(entry.halfRange, 2), + halfWidth: round(entry.halfWidth, 2), aaDifference: round(entry.aaDifference, 2), floor: rule.floor, - suggestedFloor, + suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)), gate: rule.gate, - suggestedGate: entry.halfRange <= Math.abs(middle) * NOISY_SHARE, + suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE, }; }); const lines = [ - "| metric | median | ± half range | A/A diff | floor | estimated floor | gated | suggest gating |", + "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |", "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", ...rows.map( (row) => - `| ${row.metric} | ${row.median} | ${row.halfRange} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, + `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, ), ]; return { rows, table: lines.join("\n") }; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 080c4ae34372e..fa473a2e08b09 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -219,13 +219,13 @@ describe("loadWarnings", () => { describe("noiseReport", () => { it.each([ - // Pooled 2 to 3.1: half range 0.55; medians 2.2 and 2.3. - ["the pooled swing", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.55, 0.1, 0.55], - // Pooled 2 to 3.25: half range 0.625; medians 2 and 3.25 differ by more. - ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0.63, 1.25, 1.3], - ])("estimates a floor from %s, rounded up", (_name, a, b, halfRange, aaDifference, floor) => { + // Resampled medians differ by -0.3 to 1.1: half-width 0.7, so the floor is 0.35. + ["the A/A interval", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.7, 0.1, 0.35], + // Constant sides: no interval, and medians 2 and 3.25 differ by 1.25. + ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0, 1.25, 1.3], + ])("estimates a floor from %s, rounded up", (_name, a, b, halfWidth, aaDifference, floor) => { const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); - expect(row).toMatchObject({ halfRange, aaDifference, suggestedFloor: floor }); + expect(row).toMatchObject({ halfWidth, aaDifference, suggestedFloor: floor }); }); it("leaves out wakeups counted with the delay sampler on one side only", () => { @@ -240,11 +240,11 @@ describe("noiseReport", () => { expect(metrics).toContain("quiet.cpuPct"); }); - it("takes the widest pair, and calls a metric noisy past half its median", () => { + it("takes the widest pair, and calls a metric noisy when its interval passes half its median", () => { const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const; const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const; const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); - expect(row?.halfRange).toBe(1.5); + expect(row?.halfWidth).toBe(1.5); expect(row?.suggestedGate).toBe(false); }); From f2c6bc311b90ac390ad6845d31bdb138e57ec2b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:00:29 -0800 Subject: [PATCH 4/7] feat(scripts): server metrics noise floors and gating come from A/A runs on cups Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 39 ++++++++++++++++++++++++-------- scripts/server-metrics.test.ts | 24 ++++++++++++++++---- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 6d6533a2bd26d..f7c01ce82c2cf 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -226,20 +226,41 @@ export interface NoiseRule { readonly gate: boolean; } +/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */ +const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false }); + +// Estimated from 5-round A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, rounded up. +// busy and soak had no A/A run and keep the earlier floors. export const NOISE_RULES: ReadonlyArray = [ - { pattern: /^scaling\..*cpuPctPerThread$/, floor: 0.2, gate: true }, - { pattern: /^scaling\./, floor: 2, gate: true }, + informational(/loopDelayP50Ms$/), + informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), + informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), + informational(/^(streaming|pipeline)\.gcPauseMs$/), + informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), + informational(/^scaling\.(cpuPct|wakeups)PerThread$/), + informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), + { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, { pattern: /^soak\./, floor: 20, gate: true }, - { pattern: /cpuPct$/, floor: 1, gate: true }, - { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /^startup\.readyMs$/, floor: 450, gate: true }, + { pattern: /^firstWord\./, floor: 600, gate: true }, + { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, + { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, + { pattern: /^clients\.storm\.resubscribedMs$/, floor: 200, gate: true }, + { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, + { pattern: /cpuPct$/, floor: 3.5, gate: true }, + { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 110, gate: true }, + { pattern: /rssPeakMB$/, floor: 16, gate: true }, + { pattern: /rssMB$/, floor: 4, gate: true }, + { pattern: /heapAfterGcMB$/, floor: 1, gate: true }, { pattern: /MB$/, floor: 15, gate: true }, { pattern: /KB$/, floor: 20, gate: true }, { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true }, - { pattern: /loopDelayP50Ms$/, floor: 2, gate: true }, - { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, - { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, - { pattern: /gcPauseMs$/, floor: 10, gate: true }, - { pattern: /gcCount$/, floor: 20, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 3, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 22, gate: true }, + { pattern: /gcPauseMs$/, floor: 55, gate: true }, + { pattern: /gcCount$/, floor: 6, gate: true }, { pattern: /./, floor: 300, gate: true }, ]; diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index fa473a2e08b09..de3237d3c0d23 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -47,6 +47,17 @@ const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; const cpuRuns = (...values: number[]) => quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); +// Fixed floors, so these cases test how compare gates rather than the calibrated table. +const gatedRules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, + { pattern: /gcPauseMs$/, floor: 10, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + describe("compareMetrics", () => { it.each([ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], @@ -64,7 +75,12 @@ describe("compareMetrics", () => { ["quiet.rssPeakMB"], ], ])("one run each: %s", (_name, change, regressed, improved) => { - const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + const result = compareMetrics( + quietRuns(base), + quietRuns({ ...base, ...change }), + 10, + gatedRules, + ); expect(result.regressed).toEqual(regressed); expect(result.improved).toEqual(improved); }); @@ -79,10 +95,10 @@ describe("compareMetrics", () => { it("flags repeated runs only when the whole interval clears the limit", () => { const steady = cpuRuns(26.1, 27.4, 25.8); const fixed = cpuRuns(2.2, 2.5, 2.1); - expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); - expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + expect(compareMetrics(steady, fixed, 10, gatedRules).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady, 10, gatedRules).regressed).toContain("quiet.cpuPct"); // The medians differ by 2.8 points, past the floor, but a resampled median can match. - expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); it("reads a file written before loop delay and GC were recorded", () => { From 505b1cec20ae443dca2931023efd2539ad59a544 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:54:23 -0800 Subject: [PATCH 5/7] fix(scripts): startup's noise floor covers the no-agent-scope A/A run Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index f7c01ce82c2cf..a53630b872f54 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -229,7 +229,8 @@ export interface NoiseRule { /** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */ const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false }); -// Estimated from 5-round A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, rounded up. +// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the +// agent scope, rounded up and taking the larger of the two. // busy and soak had no A/A run and keep the earlier floors. export const NOISE_RULES: ReadonlyArray = [ informational(/loopDelayP50Ms$/), @@ -242,7 +243,7 @@ export const NOISE_RULES: ReadonlyArray = [ { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, { pattern: /^soak\./, floor: 20, gate: true }, - { pattern: /^startup\.readyMs$/, floor: 450, gate: true }, + { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, { pattern: /^firstWord\./, floor: 600, gate: true }, { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, From 2b11feccb1876dd7557c5ff1645298e15aa2bcee Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:59:15 -0800 Subject: [PATCH 6/7] fix(scripts): an attached client's CPU and wakeups are informational, as their A/A interval passed half the median Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index a53630b872f54..0cd34b23935e9 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -239,6 +239,7 @@ export const NOISE_RULES: ReadonlyArray = [ informational(/^(streaming|pipeline)\.gcPauseMs$/), informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), informational(/^scaling\.(cpuPct|wakeups)PerThread$/), + informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, From 8969c5e22b20ce9b9d80349f16b38b83b1a79aad Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:14:35 -0800 Subject: [PATCH 7/7] fix(scripts): server metrics read competing CPU one read at a time Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 7dc8708e28e1a..7b814efcbdbf5 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -28,6 +28,7 @@ import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; @@ -1719,6 +1720,8 @@ const watchMachine = Effect.gen(function* () { let competing: Option.Option = Option.some(0); let previous = yield* competingCpuSeconds; if (Option.isNone(previous)) competing = Option.none(); + // The periodic and final reads would otherwise interleave across the await below. + const reading = yield* Semaphore.make(1); const read = Effect.gen(function* () { loads.push(...Option.toArray(yield* load1)); if (Option.isNone(previous) || Option.isNone(competing)) return; @@ -1729,7 +1732,7 @@ const watchMachine = Effect.gen(function* () { } competing = Option.some(competing.value + competingBetween(previous.value, next.value)); previous = next; - }); + }).pipe(reading.withPermits(1)); yield* read; // Reading through the run, not only at its ends, keeps a busy process that exits mid-run. yield* read.pipe(