diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c024e9737ef46..95cd1c18f9fe8 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -7,6 +7,19 @@ const Window = Schema.Struct({ rssPeakMB: Schema.Number, rssMB: Schema.Number, heapAfterGcMB: Schema.Number, + // Files written before these were recorded still decode, and compare shows them as n/a. + /** Event-loop delay past the 10 ms sampling interval, from a histogram inside the server. */ + loopDelayP50Ms: Schema.optional(Schema.Number), + loopDelayP99Ms: Schema.optional(Schema.Number), + loopDelayMaxMs: Schema.optional(Schema.Number), + /** + * Delay samples taken. Each can wake an idle loop, so they sit inside `wakeupsPerSec` (up to + * 100/s at rest, near none under load, when the loop is already awake); not compared. + */ + loopSamples: Schema.optional(Schema.Number), + /** GC events and their summed pause in the window, from a `gc` PerformanceObserver. */ + gcCount: Schema.optional(Schema.Number), + gcPauseMs: Schema.optional(Schema.Number), }); export type Window = typeof Window.Type; const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number }); @@ -143,6 +156,11 @@ function noiseFloor(metric: string) { if (metric.endsWith("cpuPct")) return 1; if (metric.endsWith("wakeupsPerSec")) return 20; if (metric.endsWith("MB")) return 15; + 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; } @@ -193,13 +211,32 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const improved: string[] = []; let compared = 0; for (const metric of new Set([...a.keys(), ...b.keys()])) { - if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; + if ( + metric === "soak.minutes" || + metric.endsWith("loopSamples") || + metric.startsWith("scaling.points") + ) { + continue; + } const x = a.get(metric); const y = b.get(metric); if (!x || !y) { lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); continue; } + // 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`)) { + lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`); + continue; + } compared++; const mx = median(x); const my = median(y); diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index fe87cbbd39c68..addafee5461ec 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,3 +1,4 @@ +import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import { @@ -5,16 +6,34 @@ import { heapGrowth, parsePsCpuTime, parseRunSelection, + ServerMetrics, slope, - type ServerMetrics, } from "./server-metrics-report.ts"; -type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; +const decodeMetrics = Schema.decodeSync(ServerMetrics); + +type Quiet = { + cpuPct: number; + wakeupsPerSec: number | null; + rssPeakMB: number; + loopDelayP99Ms?: number; + loopDelayMaxMs?: number; + gcPauseMs?: number; +}; +const loopAtRest = { + loopDelayP50Ms: 0.1, + loopDelayP99Ms: 1.5, + loopDelayMaxMs: 8, + gcCount: 12, + gcPauseMs: 6, +}; const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; const quietRuns = (...runs: Quiet[]) => ({ meta, - runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })), + runs: runs.map((quiet) => ({ + quiet: { ...loopAtRest, ...quiet, rssMB: 500, heapAfterGcMB: 200 }, + })), }) satisfies ServerMetrics; const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; const cpuRuns = (...values: number[]) => @@ -26,6 +45,10 @@ describe("compareMetrics", () => { ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, [], []], ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, [], []], ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"], []], + ["a doubled p99 loop delay under the 5 ms floor", { loopDelayP99Ms: 3 }, [], []], + ["a p99 loop delay past it", { loopDelayP99Ms: 40 }, ["quiet.loopDelayP99Ms"], []], + ["one longer stall under the 20 ms max floor", { loopDelayMaxMs: 25 }, [], []], + ["GC pauses past the 10 ms floor", { gcPauseMs: 30 }, ["quiet.gcPauseMs"], []], [ "an improvement past the floors", { cpuPct: 0.1, wakeupsPerSec: 7, rssPeakMB: 400 }, @@ -54,10 +77,51 @@ describe("compareMetrics", () => { expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); }); + it("reads a file written before loop delay and GC were recorded", () => { + const older = decodeMetrics({ + meta, + runs: [ + { + quiet: { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }, + }, + ], + }); + const result = compareMetrics(older, quietRuns(base)); + expect(result.compared).toBe(5); + expect(result.table).toContain("| quiet.loopDelayP99Ms | – | 1.5 | n/a | | |"); + }); + + it("does not compare wakeups counted with and without the delay sampler", () => { + const sampled = quietRuns({ ...base, wakeupsPerSec: 160 }); + const withSamples: ServerMetrics = { + meta, + runs: sampled.runs.map((run) => ({ quiet: { ...run.quiet, loopSamples: 2_900 } })), + }; + const result = compareMetrics(quietRuns(base), withSamples); + expect(result.regressed).toEqual([]); + expect(result.table).toContain("| quiet.wakeupsPerSec | 7 | 160 | not comparable | | |"); + // The per-thread fit comes from the quiet windows, so it follows their method. + const scaling = (wakeupsPerThread: number) => ({ + heapMBPerThread: 1, + rssMBPerThread: 2, + cpuPctPerThread: 0.1, + wakeupsPerThread, + points: [], + }); + const fitted = (metrics: ServerMetrics, wakeupsPerThread: number): ServerMetrics => ({ + meta, + runs: metrics.runs.map((run) => ({ ...run, scaling: scaling(wakeupsPerThread) })), + }); + const fit = compareMetrics(fitted(quietRuns(base), 0.5), fitted(withSamples, 6)); + expect(fit.regressed).toEqual([]); + expect(fit.table).toContain("| scaling.wakeupsPerThread | 0.5 | 6 | not comparable | | |"); + expect(compareMetrics(withSamples, withSamples).compared).toBe(10); + }); + it("counts how many metrics both sides share", () => { const startupOnly: ServerMetrics = { meta, runs: [{ startup: { readyMs: 9_000 } }] }; expect(compareMetrics(startupOnly, quietRuns(base)).compared).toBe(0); - expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(5); + expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(10); }); }); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 6a905f94dccea..c447be05621a1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -56,6 +56,16 @@ import { const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; +/** Event-loop delay sampling interval; each sample wakes the loop once. */ +const LOOP_RESOLUTION_MS = 10; +const LoopStats = Schema.Struct({ + p50: Schema.Number, + p99: Schema.Number, + max: Schema.Number, + samples: Schema.Number, + gcCount: Schema.Number, + gcMs: Schema.Number, +}); export class MetricsError extends Schema.TaggedError()("MetricsError", { message: Schema.String, @@ -269,6 +279,9 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { const decodeEvaluated = Schema.decodeUnknownEffect( Schema.Struct({ result: Schema.Struct({ value: Schema.Number }) }), ); + const decodeLoop = Schema.decodeUnknownEffect( + Schema.Struct({ result: Schema.Struct({ value: Schema.fromJsonString(LoopStats) }) }), + ); const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile })); const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile })); return { @@ -281,6 +294,54 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { Effect.flatMap(decodeEvaluated), Effect.map(({ result }) => result.value), ), + // One histogram and GC observer live in the server; a window resets them and reads them back. + // Node delivers GC entries to observers from a later setImmediate, which takeRecords() cannot + // reach, so each boundary first lets two turns pass and the pending entries land on its side. + loopStart: send("Runtime.evaluate", { + awaitPromise: true, + expression: `(async () => { + const bench = (globalThis.__t3ServerMetrics ??= (() => { + const { monitorEventLoopDelay, PerformanceObserver } = process.getBuiltinModule("node:perf_hooks"); + const state = { delay: monitorEventLoopDelay({ resolution: ${LOOP_RESOLUTION_MS} }), gcCount: 0, gcMs: 0 }; + state.count = (entries) => { + for (const entry of entries) { state.gcCount++; state.gcMs += entry.duration; } + }; + state.gc = new PerformanceObserver((list) => state.count(list.getEntries())); + state.gc.observe({ entryTypes: ["gc"] }); + return state; + })()); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + bench.gc.takeRecords(); + bench.delay.reset(); + bench.delay.enable(); + bench.gcCount = 0; + bench.gcMs = 0; + })()`, + }).pipe(Effect.asVoid), + loopRead: send("Runtime.evaluate", { + awaitPromise: true, + expression: `(async () => { + const bench = globalThis.__t3ServerMetrics; + bench.delay.disable(); + await new Promise((resolve) => setImmediate(resolve)); + await new Promise((resolve) => setImmediate(resolve)); + bench.count(bench.gc.takeRecords()); + const ms = (ns) => Math.max(0, ns / 1e6 - ${LOOP_RESOLUTION_MS}); + return JSON.stringify({ + p50: ms(bench.delay.percentile(50)), + p99: ms(bench.delay.percentile(99)), + max: ms(bench.delay.max), + samples: bench.delay.count, + gcCount: bench.gcCount, + gcMs: bench.gcMs, + }); + })()`, + returnByValue: true, + }).pipe( + Effect.flatMap(decodeLoop), + Effect.map(({ result }) => result.value), + ), heapAfterGc: Effect.gen(function* () { yield* send("HeapProfiler.collectGarbage"); yield* send("HeapProfiler.collectGarbage"); @@ -514,7 +575,8 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe( Effect.timeout(Duration.seconds(1)), - Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }), + // A seeded database or a loaded machine can keep startup past a minute. + Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 3_000 }), Effect.andThen(nowMs), Effect.map((now) => Math.round(now - started)), Effect.catch(() => @@ -555,6 +617,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const value = yield* read; return { value, at: (before + (yield* nowMs)) / 2 }; }); + yield* devtools.loopStart; const firstSwitches = yield* timed(countSwitches); const firstSample = yield* timed(sample(pid)); const first = firstSample.value; @@ -568,11 +631,13 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( const last = lastSample.value; const cpuElapsed = (lastSample.at - start) / 1_000; const lastSwitches = yield* timed(countSwitches); + // Read before the forced GC below, which would count as a pause. + const loop = yield* devtools.loopRead; const switchesElapsed = (lastSwitches.at - firstSwitches.at) / 1_000; const switches = firstSwitches.value === null || lastSwitches.value === null ? null - : lastSwitches.value - firstSwitches.value; + : Math.max(0, lastSwitches.value - firstSwitches.value); const heap = yield* devtools.heapAfterGc; const window: Window = { cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), @@ -580,6 +645,12 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( rssPeakMB: Math.round(Math.max(rssPeak, last.rss) / 1e6), rssMB: Math.round((yield* sample(pid)).rss / 1e6), heapAfterGcMB: round(heap / 1e6), + loopDelayP50Ms: round(loop.p50), + loopDelayP99Ms: round(loop.p99), + loopDelayMaxMs: round(loop.max), + loopSamples: loop.samples, + gcCount: loop.gcCount, + gcPauseMs: round(loop.gcMs), }; return window; });