Repository navigation
feat(scripts): a server metrics run catches CPU, memory and first-request regressions #41159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,659
−1
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
56de5c4
feat(scripts): measure server CPU, wakeups, memory and first-request …
juliusmarminge ac5bd58
feat(scripts): server metrics run on macOS and Windows, compare by in…
juliusmarminge 7a0569d
refactor(scripts): server metrics runs on Effect
juliusmarminge 6c14cf3
fix(scripts): server metrics fails loudly instead of reporting bad nu…
juliusmarminge 5310068
fix(scripts): server metrics leaves a task it could not read out of t…
juliusmarminge bda5eb5
fix(scripts): server metrics counts wakeups with the process's lifeti…
juliusmarminge e2fd6be
fix(scripts): server metrics rejects zero counts and malformed ps CPU…
juliusmarminge 109be74
fix(scripts): server metrics waits only for streams this launch started
juliusmarminge 8f34f0e
fix(scripts): server metrics force-kills a server that ignores SIGTERM
juliusmarminge 16c957d
fix(scripts): server metrics times each probe at its midpoint and tes…
juliusmarminge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,339 @@ | ||
| // The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare. | ||
| import * as Schema from "effect/Schema"; | ||
|
|
||
| const Window = Schema.Struct({ | ||
| cpuPct: Schema.Number, | ||
| wakeupsPerSec: Schema.NullOr(Schema.Number), | ||
| rssPeakMB: Schema.Number, | ||
| rssMB: Schema.Number, | ||
| heapAfterGcMB: Schema.Number, | ||
| }); | ||
| export type Window = typeof Window.Type; | ||
| const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number }); | ||
| const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread }); | ||
| export type FirstWord = typeof FirstWord.Type; | ||
| const Scaling = Schema.Struct({ | ||
| heapMBPerThread: Schema.Number, | ||
| rssMBPerThread: Schema.Number, | ||
| cpuPctPerThread: Schema.Number, | ||
| wakeupsPerThread: Schema.NullOr(Schema.Number), | ||
| /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ | ||
| points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))), | ||
| }); | ||
| const Soak = Schema.Struct({ | ||
| minutes: Schema.Number, | ||
| heapMBPerHour: Schema.Number, | ||
| rssMBPerHour: Schema.Number, | ||
| }); | ||
|
|
||
| /** One pass over the scenarios. */ | ||
| export const Measured = Schema.Struct({ | ||
| startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), | ||
| rest: Schema.optional(Window), | ||
| firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), | ||
| quiet: Schema.optional(Window), | ||
| scaling: Schema.optional(Scaling), | ||
| streaming: Schema.optional(Window), | ||
| soak: Schema.optional(Soak), | ||
| }); | ||
| export type Measured = typeof Measured.Type; | ||
|
|
||
| const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number }); | ||
| export type Hotspot = typeof Hotspot.Type; | ||
| const ProfileSummary = Schema.Struct({ | ||
| cpuMs: Schema.Array(Hotspot), | ||
| allocatedMB: Schema.Array(Hotspot), | ||
| }); | ||
| export type ProfileSummary = typeof ProfileSummary.Type; | ||
| export const HeapGrowth = Schema.Struct({ | ||
| constructor: Schema.String, | ||
| count: Schema.Number, | ||
| MB: Schema.Number, | ||
| }); | ||
|
|
||
| export const ServerMetrics = Schema.Struct({ | ||
| meta: Schema.Record( | ||
| Schema.String, | ||
| Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), | ||
| ), | ||
| runs: Schema.Array(Measured), | ||
| /** Top CPU self time (ms) and allocated MB by function, from the last run. */ | ||
| profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), | ||
| soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), | ||
| }); | ||
| export type ServerMetrics = typeof ServerMetrics.Type; | ||
|
|
||
| export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; | ||
|
|
||
| /** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */ | ||
| export function parsePsCpuTime(text: string) { | ||
| const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); | ||
| if (match === null) return Number.NaN; | ||
| const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match; | ||
| return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds); | ||
| } | ||
|
|
||
| /** | ||
| * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay | ||
| * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else. | ||
| */ | ||
| export function parseRunSelection(input: { | ||
| readonly only: string; | ||
| readonly threads: string; | ||
| readonly soak: number; | ||
| readonly scenarios: ReadonlyArray<string>; | ||
| }): | ||
| | { readonly only: ReadonlyArray<string>; readonly threads: ReadonlyArray<number> } | ||
| | { readonly error: string } { | ||
| const only = input.only.split(",").filter(Boolean); | ||
| const unknown = only.filter((name) => !input.scenarios.includes(name)); | ||
| if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` }; | ||
| const threads = input.threads | ||
| .split(",") | ||
| .map((count) => (count.trim() === "" ? Number.NaN : Number(count))); | ||
| if ( | ||
| threads.some( | ||
| (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), | ||
| ) | ||
| ) { | ||
| return { error: "--threads takes ascending counts such as 0,5,10,20" }; | ||
| } | ||
| if (!Number.isInteger(input.soak) || input.soak < 0) | ||
| return { error: "--soak takes minutes, 0 for none" }; | ||
| return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads }; | ||
| } | ||
|
|
||
| export function spread(values: ReadonlyArray<number>) { | ||
| const sorted = values.toSorted((a, b) => a - b); | ||
| const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; | ||
| return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; | ||
| } | ||
|
|
||
| /** Least-squares slope of y over x. */ | ||
| export function slope(points: ReadonlyArray<readonly [number, number]>) { | ||
| const n = points.length; | ||
| if (n < 2) return 0; | ||
| const mx = points.reduce((sum, [x]) => sum + x, 0) / n; | ||
| const my = points.reduce((sum, [, y]) => sum + y, 0) / n; | ||
| let numerator = 0; | ||
| let denominator = 0; | ||
| for (const [x, y] of points) { | ||
| numerator += (x - mx) * (y - my); | ||
| denominator += (x - mx) ** 2; | ||
| } | ||
| return denominator === 0 ? 0 : numerator / denominator; | ||
| } | ||
|
|
||
| /** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ | ||
| export function flatten(measured: Measured): Map<string, number> { | ||
| const values = new Map<string, number>(); | ||
| const visit = (value: unknown, path: string) => { | ||
| if (typeof value === "number") values.set(path, value); | ||
| else if (value && typeof value === "object") { | ||
| for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); | ||
| } | ||
| }; | ||
| visit(measured, ""); | ||
| 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; | ||
| return 300; | ||
| } | ||
|
|
||
| const median = (values: ReadonlyArray<number>) => { | ||
| const sorted = values.toSorted((a, b) => a - b); | ||
| const middle = Math.floor(sorted.length / 2); | ||
| return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; | ||
| }; | ||
|
|
||
| /** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ | ||
| export function bootstrapMedianDifference(a: ReadonlyArray<number>, b: ReadonlyArray<number>) { | ||
| let seed = 0x5eed; | ||
| const random = () => { | ||
| seed = (seed + 0x6d2b79f5) | 0; | ||
| let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); | ||
| t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; | ||
| return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; | ||
| }; | ||
| const resample = (values: ReadonlyArray<number>) => | ||
| median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); | ||
| const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( | ||
| (x, y) => x - y, | ||
| ); | ||
| 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<string, number[]>(); | ||
| for (const run of metrics.runs) { | ||
| for (const [metric, value] of flatten(run)) { | ||
| values.set(metric, [...(values.get(metric) ?? []), value]); | ||
| } | ||
| } | ||
| return values; | ||
| }; | ||
| const a = collect(before); | ||
| const b = collect(after); | ||
| const lines = [ | ||
| "### Server metrics (lower is better)", | ||
| "", | ||
| `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" : ""}`, | ||
| "", | ||
| "| metric | before | after | change | 95% interval | |", | ||
| "| :-- | --: | --: | --: | --: | :-- |", | ||
| ]; | ||
| const regressed: string[] = []; | ||
| 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; | ||
| 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; | ||
| } | ||
| compared++; | ||
| 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 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 percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; | ||
| const shown = Number.isFinite(percent) | ||
| ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` | ||
| : "new"; | ||
| const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : ""; | ||
| lines.push( | ||
| `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, | ||
| ); | ||
| } | ||
| return { table: lines.join("\n"), regressed, improved, compared }; | ||
| } | ||
|
|
||
| const CallFrame = Schema.Struct({ | ||
| functionName: Schema.String, | ||
| url: Schema.String, | ||
| lineNumber: Schema.Number, | ||
| }); | ||
| type CallFrame = typeof CallFrame.Type; | ||
| export const CpuProfile = Schema.Struct({ | ||
| nodes: Schema.Array( | ||
| Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }), | ||
| ), | ||
| samples: Schema.optional(Schema.Array(Schema.Number)), | ||
| startTime: Schema.Number, | ||
| endTime: Schema.Number, | ||
| }); | ||
| interface HeapProfileNode { | ||
| readonly callFrame: CallFrame; | ||
| readonly selfSize: number; | ||
| readonly children: ReadonlyArray<HeapProfileNode>; | ||
| } | ||
| const HeapProfileNode: Schema.Codec<HeapProfileNode> = Schema.Struct({ | ||
| callFrame: CallFrame, | ||
| selfSize: Schema.Number, | ||
| children: Schema.Array(Schema.suspend(() => HeapProfileNode)), | ||
| }); | ||
| export const HeapProfile = Schema.Struct({ head: HeapProfileNode }); | ||
|
|
||
| const shortUrl = (url: string) => | ||
| url | ||
| .replace(/^file:\/\//, "") | ||
| .split(/[\\/]/) | ||
| .slice(-3) | ||
| .join("/"); | ||
| const frameName = (frame: CallFrame) => | ||
| `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); | ||
| const top = (totals: Map<string, number>, digits: number): Hotspot[] => | ||
| [...totals] | ||
| .toSorted((a, b) => b[1] - a[1]) | ||
| .slice(0, 10) | ||
| .map(([frame, value]) => ({ frame, value: round(value, digits) })); | ||
|
|
||
| /** Top CPU self time in ms and allocated MB, by function. */ | ||
| export function summarizeProfiles( | ||
| cpu: typeof CpuProfile.Type, | ||
| heap: typeof HeapProfile.Type, | ||
| ): ProfileSummary { | ||
| const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); | ||
| const cpuTotals = new Map<string, number>(); | ||
| for (const node of cpu.nodes) { | ||
| if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; | ||
| const name = frameName(node.callFrame); | ||
| cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); | ||
| } | ||
| const allocations = new Map<string, number>(); | ||
| const visit = (node: HeapProfileNode) => { | ||
| const name = frameName(node.callFrame); | ||
| allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); | ||
| for (const child of node.children) visit(child); | ||
| }; | ||
| visit(heap.head); | ||
| return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; | ||
| } | ||
|
|
||
| export const HeapSnapshot = Schema.Struct({ | ||
| snapshot: Schema.Struct({ | ||
| meta: Schema.Struct({ | ||
| node_fields: Schema.Array(Schema.String), | ||
| node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), | ||
| }), | ||
| }), | ||
| nodes: Schema.Array(Schema.Number), | ||
| strings: Schema.Array(Schema.String), | ||
| }); | ||
|
|
||
| /** Self size by constructor from a V8 heap snapshot. */ | ||
| export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { | ||
| const fields = snapshot.snapshot.meta.node_fields; | ||
| const typeNames = snapshot.snapshot.meta.node_types[0]; | ||
| const types = Array.isArray(typeNames) ? typeNames : []; | ||
| const typeAt = fields.indexOf("type"); | ||
| const nameAt = fields.indexOf("name"); | ||
| const sizeAt = fields.indexOf("self_size"); | ||
| const totals = new Map<string, { count: number; bytes: number }>(); | ||
| for (let index = 0; index < snapshot.nodes.length; index += fields.length) { | ||
| const type = types[snapshot.nodes[index + typeAt]!] ?? "?"; | ||
| const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? ""; | ||
| const name = | ||
| type === "object" | ||
| ? label.slice(0, 80) | ||
| : type === "closure" | ||
| ? `(closure) ${label.slice(0, 60)}` | ||
| : `(${type.replace(/^(concatenated|sliced) /, "")})`; | ||
| const entry = totals.get(name) ?? { count: 0, bytes: 0 }; | ||
| entry.count++; | ||
| entry.bytes += snapshot.nodes[index + sizeAt]!; | ||
| totals.set(name, entry); | ||
| } | ||
| return totals; | ||
| } | ||
|
|
||
| /** The constructors whose heap grew most from one snapshot to the next. */ | ||
| export function heapGrowth( | ||
| before: ReturnType<typeof heapByConstructor>, | ||
| after: ReturnType<typeof heapByConstructor>, | ||
| ) { | ||
| return [...after] | ||
| .map(([name, { count, bytes }]) => ({ | ||
| constructor: name, | ||
| count: count - (before.get(name)?.count ?? 0), | ||
| bytes: bytes - (before.get(name)?.bytes ?? 0), | ||
| })) | ||
| .filter((entry) => entry.bytes > 0) | ||
| .toSorted((a, b) => b.bytes - a.bytes) | ||
| .slice(0, 25) | ||
| .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.