Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server-metrics-report.ts

339 lines13.1 KB

1// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare.
2import * as Schema from "effect/Schema";
3​
4const Window = Schema.Struct({
5 cpuPct: Schema.Number,
6 wakeupsPerSec: Schema.NullOr(Schema.Number),
7 rssPeakMB: Schema.Number,
8 rssMB: Schema.Number,
9 heapAfterGcMB: Schema.Number,
10});
11export type Window = typeof Window.Type;
12const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number });
13const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread });
14export type FirstWord = typeof FirstWord.Type;
15const Scaling = Schema.Struct({
16 heapMBPerThread: Schema.Number,
17 rssMBPerThread: Schema.Number,
18 cpuPctPerThread: Schema.Number,
19 wakeupsPerThread: Schema.NullOr(Schema.Number),
20 /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */
21 points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))),
22});
23const Soak = Schema.Struct({
24 minutes: Schema.Number,
25 heapMBPerHour: Schema.Number,
26 rssMBPerHour: Schema.Number,
27});
28​
29/** One pass over the scenarios. */
30export const Measured = Schema.Struct({
31 startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })),
32 rest: Schema.optional(Window),
33 firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })),
34 quiet: Schema.optional(Window),
35 scaling: Schema.optional(Scaling),
36 streaming: Schema.optional(Window),
37 soak: Schema.optional(Soak),
38});
39export type Measured = typeof Measured.Type;
40​
41const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number });
42export type Hotspot = typeof Hotspot.Type;
43const ProfileSummary = Schema.Struct({
44 cpuMs: Schema.Array(Hotspot),
45 allocatedMB: Schema.Array(Hotspot),
46});
47export type ProfileSummary = typeof ProfileSummary.Type;
48export const HeapGrowth = Schema.Struct({
49 constructor: Schema.String,
50 count: Schema.Number,
51 MB: Schema.Number,
52});
53​
54export const ServerMetrics = Schema.Struct({
55 meta: Schema.Record(
56 Schema.String,
57 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
58 ),
59 runs: Schema.Array(Measured),
60 /** Top CPU self time (ms) and allocated MB by function, from the last run. */
61 profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)),
62 soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)),
63});
64export type ServerMetrics = typeof ServerMetrics.Type;
65​
66export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits;
67​
68/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */
69export function parsePsCpuTime(text: string) {
70 const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim());
71 if (match === null) return Number.NaN;
72 const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match;
73 return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
75​
76/**
77 * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay
78 * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else.
79 */
80export function parseRunSelection(input: {
81 readonly only: string;
82 readonly threads: string;
83 readonly soak: number;
84 readonly scenarios: ReadonlyArray<string>;
85}):
86 | { readonly only: ReadonlyArray<string>; readonly threads: ReadonlyArray<number> }
87 | { readonly error: string } {
88 const only = input.only.split(",").filter(Boolean);
89 const unknown = only.filter((name) => !input.scenarios.includes(name));
90 if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` };
91 const threads = input.threads
92 .split(",")
93 .map((count) => (count.trim() === "" ? Number.NaN : Number(count)));
94 if (
95 threads.some(
96 (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0),
97 )
98 ) {
99 return { error: "--threads takes ascending counts such as 0,5,10,20" };
100 }
101 if (!Number.isInteger(input.soak) || input.soak < 0)
102 return { error: "--soak takes minutes, 0 for none" };
103 return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads };
105​
106export function spread(values: ReadonlyArray<number>) {
107 const sorted = values.toSorted((a, b) => a - b);
108 const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)];
109 return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) };
111​
112/** Least-squares slope of y over x. */
113export function slope(points: ReadonlyArray<readonly [number, number]>) {
114 const n = points.length;
115 if (n < 2) return 0;
116 const mx = points.reduce((sum, [x]) => sum + x, 0) / n;
117 const my = points.reduce((sum, [, y]) => sum + y, 0) / n;
118 let numerator = 0;
119 let denominator = 0;
120 for (const [x, y] of points) {
121 numerator += (x - mx) * (y - my);
122 denominator += (x - mx) ** 2;
123 }
124 return denominator === 0 ? 0 : numerator / denominator;
126​
127/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */
128export function flatten(measured: Measured): Map<string, number> {
129 const values = new Map<string, number>();
130 const visit = (value: unknown, path: string) => {
131 if (typeof value === "number") values.set(path, value);
132 else if (value && typeof value === "object") {
133 for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key);
134 }
135 };
136 visit(measured, "");
137 return values;
139​
140function noiseFloor(metric: string) {
141 if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2;
142 if (metric.startsWith("soak.")) return 20;
143 if (metric.endsWith("cpuPct")) return 1;
144 if (metric.endsWith("wakeupsPerSec")) return 20;
145 if (metric.endsWith("MB")) return 15;
146 return 300;
148​
149const median = (values: ReadonlyArray<number>) => {
150 const sorted = values.toSorted((a, b) => a - b);
151 const middle = Math.floor(sorted.length / 2);
152 return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
153};
154​
155/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */
156export function bootstrapMedianDifference(a: ReadonlyArray<number>, b: ReadonlyArray<number>) {
157 let seed = 0x5eed;
158 const random = () => {
159 seed = (seed + 0x6d2b79f5) | 0;
160 let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
161 t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
162 return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
163 };
164 const resample = (values: ReadonlyArray<number>) =>
165 median(Array.from(values, () => values[Math.floor(random() * values.length)]!));
166 const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted(
167 (x, y) => x - y,
168 );
169 return [differences[49]!, differences[1_949]!] as const;
171​
172export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) {
173 const collect = (metrics: ServerMetrics) => {
174 const values = new Map<string, number[]>();
175 for (const run of metrics.runs) {
176 for (const [metric, value] of flatten(run)) {
177 values.set(metric, [...(values.get(metric) ?? []), value]);
178 }
179 }
180 return values;
181 };
182 const a = collect(before);
183 const b = collect(after);
184 const lines = [
185 "### Server metrics (lower is better)",
186 "",
187 `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" : ""}`,
188 "",
189 "| metric | before | after | change | 95% interval | |",
190 "| :-- | --: | --: | --: | --: | :-- |",
191 ];
192 const regressed: string[] = [];
193 const improved: string[] = [];
194 let compared = 0;
195 for (const metric of new Set([...a.keys(), ...b.keys()])) {
196 if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue;
197 const x = a.get(metric);
198 const y = b.get(metric);
199 if (!x || !y) {
200 lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`);
201 continue;
202 }
203 compared++;
204 const mx = median(x);
205 const my = median(y);
206 // A change counts only past both the relative threshold and the absolute noise floor.
207 const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100);
208 const repeated = x.length > 1 && y.length > 1;
209 const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx];
210 const verdict = low > limit ? "worse" : high < -limit ? "better" : "";
211 if (verdict === "worse") regressed.push(metric);
212 if (verdict === "better") improved.push(metric);
213 const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100;
214 const shown = Number.isFinite(percent)
215 ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%`
216 : "new";
217 const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : "";
218 lines.push(
219 `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`,
220 );
221 }
222 return { table: lines.join("\n"), regressed, improved, compared };
224​
225const CallFrame = Schema.Struct({
226 functionName: Schema.String,
227 url: Schema.String,
228 lineNumber: Schema.Number,
229});
230type CallFrame = typeof CallFrame.Type;
231export const CpuProfile = Schema.Struct({
232 nodes: Schema.Array(
233 Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }),
234 ),
235 samples: Schema.optional(Schema.Array(Schema.Number)),
236 startTime: Schema.Number,
237 endTime: Schema.Number,
238});
239interface HeapProfileNode {
240 readonly callFrame: CallFrame;
241 readonly selfSize: number;
242 readonly children: ReadonlyArray<HeapProfileNode>;
244const HeapProfileNode: Schema.Codec<HeapProfileNode> = Schema.Struct({
245 callFrame: CallFrame,
246 selfSize: Schema.Number,
247 children: Schema.Array(Schema.suspend(() => HeapProfileNode)),
248});
249export const HeapProfile = Schema.Struct({ head: HeapProfileNode });
250​
251const shortUrl = (url: string) =>
252 url
253 .replace(/^file:\/\//, "")
254 .split(/[\\/]/)
255 .slice(-3)
256 .join("/");
257const frameName = (frame: CallFrame) =>
258 `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim();
259const top = (totals: Map<string, number>, digits: number): Hotspot[] =>
260 [...totals]
261 .toSorted((a, b) => b[1] - a[1])
262 .slice(0, 10)
263 .map(([frame, value]) => ({ frame, value: round(value, digits) }));
264​
265/** Top CPU self time in ms and allocated MB, by function. */
266export function summarizeProfiles(
267 cpu: typeof CpuProfile.Type,
268 heap: typeof HeapProfile.Type,
269): ProfileSummary {
270 const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1);
271 const cpuTotals = new Map<string, number>();
272 for (const node of cpu.nodes) {
273 if (!node.hitCount || node.callFrame.functionName === "(idle)") continue;
274 const name = frameName(node.callFrame);
275 cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs);
276 }
277 const allocations = new Map<string, number>();
278 const visit = (node: HeapProfileNode) => {
279 const name = frameName(node.callFrame);
280 allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6);
281 for (const child of node.children) visit(child);
282 };
283 visit(heap.head);
284 return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) };
286​
287export const HeapSnapshot = Schema.Struct({
288 snapshot: Schema.Struct({
289 meta: Schema.Struct({
290 node_fields: Schema.Array(Schema.String),
291 node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])),
292 }),
293 }),
294 nodes: Schema.Array(Schema.Number),
295 strings: Schema.Array(Schema.String),
296});
297​
298/** Self size by constructor from a V8 heap snapshot. */
299export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) {
300 const fields = snapshot.snapshot.meta.node_fields;
301 const typeNames = snapshot.snapshot.meta.node_types[0];
302 const types = Array.isArray(typeNames) ? typeNames : [];
303 const typeAt = fields.indexOf("type");
304 const nameAt = fields.indexOf("name");
305 const sizeAt = fields.indexOf("self_size");
306 const totals = new Map<string, { count: number; bytes: number }>();
307 for (let index = 0; index < snapshot.nodes.length; index += fields.length) {
308 const type = types[snapshot.nodes[index + typeAt]!] ?? "?";
309 const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? "";
310 const name =
311 type === "object"
312 ? label.slice(0, 80)
313 : type === "closure"
314 ? `(closure) ${label.slice(0, 60)}`
315 : `(${type.replace(/^(concatenated|sliced) /, "")})`;
316 const entry = totals.get(name) ?? { count: 0, bytes: 0 };
317 entry.count++;
318 entry.bytes += snapshot.nodes[index + sizeAt]!;
319 totals.set(name, entry);
320 }
321 return totals;
323​
324/** The constructors whose heap grew most from one snapshot to the next. */
325export function heapGrowth(
326 before: ReturnType<typeof heapByConstructor>,
327 after: ReturnType<typeof heapByConstructor>,
328) {
329 return [...after]
330 .map(([name, { count, bytes }]) => ({
331 constructor: name,
332 count: count - (before.get(name)?.count ?? 0),
333 bytes: bytes - (before.get(name)?.bytes ?? 0),
334 }))
335 .filter((entry) => entry.bytes > 0)
336 .toSorted((a, b) => b.bytes - a.bytes)
337 .slice(0, 25)
338 .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));