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

report.ts

507 lines19.5 KB

1// The pure half of client-metrics.ts: the JSON it writes, its tables, how two files
2// compare, and the noise floors A/A runs suggest.
3import * as Schema from "effect/Schema";
4​
5import {
6 cell,
7 compareSeries,
8 Count,
9 Floors,
10 MachineState,
11 median,
12 noiseOfSeries,
13 percentile,
14 round,
15 slope,
16 SOAK_LEAK,
17 topCounts,
18} from "../core/report.ts";
19import { CallSite, TraceStep } from "./trace.ts";
20​
21/** Thread switches: each case is its own thread, switched to from a small hub thread. */
22export const SWITCH_CASES = [
23 "short",
24 "long",
25 "working",
26 "approval",
27 "medium",
28 "diff",
29 "pull-request",
30 "browser",
31 "device",
32] as const;
33/** Interactions inside one thread, each a few measured steps. */
34export const INTERACTION_CASES = [
35 "type-short",
36 "type-long",
37 "scroll-long",
38 "palette",
39 "pr-tabs",
40 "surfaces",
41 "terminal",
42 "settings",
43] as const;
44/** Every case the benchmark can run, in the order it runs them. */
45export const CASES = [...SWITCH_CASES, ...INTERACTION_CASES] as const;
46export type SwitchCase = (typeof SWITCH_CASES)[number];
47export type InteractionCase = (typeof INTERACTION_CASES)[number];
48export type Case = (typeof CASES)[number];
49export const isSwitchCase = (name: Case): name is SwitchCase =>
50 (SWITCH_CASES as ReadonlyArray<string>).includes(name);
51​
52/** What React rendered during one step, from the render probe (`--renders`). */
53const Renders = Schema.Struct({
54 commits: Schema.Number,
55 /** Component renders, a bailed-out subtree not counted. */
56 renders: Schema.Number,
57 top: Schema.Array(Count),
58 /** `Component cause`: mount, state#<hook slot>, props:<changed keys>, parent-same-props<-Parent or context. */
59 causes: Schema.Array(Count),
60});
61export type Renders = typeof Renders.Type;
62​
63const Switch = Schema.Struct({
64 case: Schema.String,
65 visit: Schema.Literals(["first", "revisit"]),
66 round: Schema.Number,
67 /** Click to the next paint: the Event Timing entry's duration; null when under 16 ms. */
68 paintMs: Schema.NullOr(Schema.Number),
69 /** Click to the first frame that showed the new thread's timeline rows. */
70 contentMs: Schema.NullOr(Schema.Number),
71 /** Whether that frame was the first one painted on the new route. */
72 firstFrameContent: Schema.Boolean,
73 /** Summed long-animation-frame duration in the 1.5 s after the click. */
74 loafMs: Schema.Number,
75 renders: Schema.optional(Renders),
76});
77export type Switch = typeof Switch.Type;
78​
79const Step = Schema.Struct({
80 case: Schema.String,
81 step: Schema.String,
82 round: Schema.Number,
83 /** Input to next paint: the step's slowest Event Timing entry; null when under 16 ms or none. */
84 paintMs: Schema.NullOr(Schema.Number),
85 /** Summed long-animation-frame duration while the step was watched. */
86 loafMs: Schema.Number,
87 /** Share of 60 Hz frames the page missed while the step was watched. */
88 droppedPct: Schema.Number,
89 renders: Schema.optional(Renders),
90});
91export type Step = typeof Step.Type;
92​
93/** DOM a panel case's surface holds once open: deterministic, so a cheap gate on panel weight. */
94const Panel = Schema.Struct({
95 case: Schema.String,
96 panelNodes: Schema.Number,
97 documentNodes: Schema.Number,
98});
99export type Panel = typeof Panel.Type;
100​
101const Memory = Schema.Struct({
102 label: Schema.String,
103 heapMB: Schema.Number,
104 domNodes: Schema.Number,
105 listeners: Schema.Number,
106});
107export type Memory = typeof Memory.Type;
108​
109const Idle = Schema.Struct({
110 label: Schema.String,
111 seconds: Schema.Number,
112 /** Renderer main-thread busy time as a share of the window, from CDP Performance metrics. */
113 taskPct: Schema.Number,
114 scriptPct: Schema.Number,
115 stylePct: Schema.Number,
116 layoutPct: Schema.Number,
117});
118export type Idle = typeof Idle.Type;
119​
120const SoakSample = Schema.Struct({
121 iteration: Schema.Number,
122 heapMB: Schema.Number,
123 domNodes: Schema.Number,
124 listeners: Schema.Number,
125});
126export type SoakSample = typeof SoakSample.Type;
127​
128const Run = Schema.Struct({
129 switches: Schema.Array(Switch),
130 steps: Schema.optional(Schema.Array(Step)),
131 panels: Schema.optional(Schema.Array(Panel)),
132 memory: Schema.Array(Memory),
133 idle: Schema.Array(Idle),
134 trace: Schema.optional(Schema.Array(TraceStep)),
135 /** Memory after GC while every case repeats (`--soak`). */
136 soak: Schema.optional(Schema.Array(SoakSample)),
137 /** Cases this checkout could not run, and why. */
138 skipped: Schema.optional(
139 Schema.Array(Schema.Struct({ case: Schema.String, reason: Schema.String })),
140 ),
141 machine: Schema.optional(MachineState),
142});
143export type Run = typeof Run.Type;
144​
145export const ClientMetrics = Schema.Struct({
146 meta: Schema.Record(
147 Schema.String,
148 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
149 ),
150 runs: Schema.Array(Run),
151 /** Top call sites of forced style and layout in input tasks, from the last traced run. */
152 callSites: Schema.optional(Schema.Array(CallSite)),
153});
154export type ClientMetrics = typeof ClientMetrics.Type;
155​
156/** The cases a `--cases` list names, in benchmark order; an error names unknown ones. */
157export function parseCases(list: string): { cases: ReadonlyArray<Case> } | { error: string } {
158 const named = list
159 .split(",")
160 .map((entry) => entry.trim())
161 .filter((entry) => entry.length > 0);
162 if (named.length === 0) return { cases: CASES };
163 const groups: Record<string, ReadonlyArray<Case>> = {
164 switches: SWITCH_CASES,
165 interactions: INTERACTION_CASES,
166 };
167 const unknown = named.filter(
168 (entry) => !(CASES as ReadonlyArray<string>).includes(entry) && !Object.hasOwn(groups, entry),
169 );
170 if (unknown.length > 0) {
171 return {
172 error: `unknown cases: ${unknown.join(", ")}; choose from switches, interactions, ${CASES.join(", ")}`,
173 };
174 }
175 const chosen = new Set(
176 named.flatMap((entry): ReadonlyArray<string> =>
177 Object.hasOwn(groups, entry) ? groups[entry]! : [entry],
178 ),
179 );
180 return { cases: CASES.filter((entry) => chosen.has(entry)) };
182​
183const present = (values: ReadonlyArray<number | null>) =>
184 values.filter((value): value is number => value !== null);
185​
186/**
187 * Growth per iteration over a soak's later half. Warm-up (caches filling, code compiling) slows
188 * down as it settles while a leak keeps its rate, so the later half keeps a leak and drops warm-up.
189 */
190export function soakSlopes(samples: ReadonlyArray<SoakSample>) {
191 const last = samples.at(-1)?.iteration ?? 0;
192 const settled = samples.filter((sample) => sample.iteration >= last / 2);
193 const fit = (pick: (sample: SoakSample) => number) =>
194 slope(settled.map((sample) => [sample.iteration, pick(sample)] as const));
195 return {
196 heapMB: fit((sample) => sample.heapMB),
197 domNodes: fit((sample) => sample.domNodes),
198 listeners: fit((sample) => sample.listeners),
199 };
201​
202/** The soak measures growing past their leak bars. */
203export function soakLeaks(samples: ReadonlyArray<SoakSample>) {
204 const slopes = soakSlopes(samples);
205 return (Object.keys(SOAK_LEAK) as Array<keyof typeof SOAK_LEAK>).filter(
206 (key) => slopes[key] > SOAK_LEAK[key],
207 );
209​
210/** Event Timing reports only paints of 16 ms or more; a null paint is under it, so counts as 16. */
211export const PAINT_THRESHOLD_MS = 16;
212const censoredPaint = (value: number | null) => value ?? PAINT_THRESHOLD_MS;
213​
214/**
215 * Every compared metric of a file, one value per run: the median of the run's switches or steps
216 * for latencies and renders, so samples from one page never pass for independent runs.
217 */
218export function flatten(metrics: ClientMetrics): Map<string, number[]> {
219 const values = new Map<string, number[]>();
220 for (const run of metrics.runs) {
221 const inRun = new Map<string, number[]>();
222 const add = (key: string, value: number | null | undefined) => {
223 if (value === null || value === undefined || !Number.isFinite(value)) return;
224 inRun.set(key, [...(inRun.get(key) ?? []), value]);
225 };
226 const groups = new Map<string, Switch[]>();
227 for (const entry of run.switches) {
228 const key = `switch.${entry.case}.${entry.visit}`;
229 groups.set(key, [...(groups.get(key) ?? []), entry]);
230 add(`${key}.paintMs`, censoredPaint(entry.paintMs));
231 add(`${key}.contentMs`, entry.contentMs);
232 add(`${key}.loafMs`, entry.loafMs);
233 add(`${key}.renders`, entry.renders?.renders);
234 add(`${key}.commits`, entry.renders?.commits);
235 }
236 for (const [key, entries] of groups) {
237 const missed = entries.filter((entry) => !entry.firstFrameContent).length;
238 add(`${key}.firstFrameMissPct`, (missed / entries.length) * 100);
239 }
240 for (const entry of run.steps ?? []) {
241 const key = `step.${entry.case}.${entry.step}`;
242 add(`${key}.paintMs`, censoredPaint(entry.paintMs));
243 add(`${key}.loafMs`, entry.loafMs);
244 add(`${key}.droppedPct`, entry.droppedPct);
245 add(`${key}.renders`, entry.renders?.renders);
246 add(`${key}.commits`, entry.renders?.commits);
247 }
248 for (const entry of run.panels ?? []) add(`panel.${entry.case}.domNodes`, entry.panelNodes);
249 for (const entry of run.trace ?? []) {
250 add(`trace.${entry.label}.inputTaskMs`, entry.inputTaskMs);
251 add(
252 `trace.${entry.label}.forcedMs`,
253 entry.forcedMs ?? entry.forcedStyleMs + entry.forcedLayoutMs,
254 );
255 }
256 for (const entry of run.memory) {
257 add(`memory.${entry.label}.heapMB`, entry.heapMB);
258 add(`memory.${entry.label}.domNodes`, entry.domNodes);
259 }
260 for (const entry of run.idle) add(`idle.${entry.label}.taskPct`, entry.taskPct);
261 if (run.soak && run.soak.length > 2) {
262 const slopes = soakSlopes(run.soak);
263 add("soak.heapMBPerIteration", slopes.heapMB);
264 add("soak.domNodesPerIteration", slopes.domNodes);
265 add("soak.listenersPerIteration", slopes.listeners);
266 }
267 for (const [key, samples] of inRun)
268 values.set(key, [...(values.get(key) ?? []), median(samples)!]);
269 }
270 return values;
272​
273/** Settings that change what shared metrics measure, recorded in each file's meta. */
274export const WORKLOAD_KEYS = ["cases", "switchRounds", "longTurns"] as const;
275/** Settings that change timing without changing the workload: the render probe and the build. */
276export const PROBE_KEYS = ["renders", "minified"] as const;
277​
278/** Settings two files disagree on, and those one of them did not record. */
279export function workloadDifferences(
280 before: ClientMetrics,
281 after: ClientMetrics,
282 keys: ReadonlyArray<string> = WORKLOAD_KEYS,
283) {
284 const differ: string[] = [];
285 const unrecorded: string[] = [];
286 for (const key of keys) {
287 const a = before.meta[key];
288 const b = after.meta[key];
289 if (a === undefined || b === undefined) {
290 if (a !== b) unrecorded.push(key);
291 } else if (a !== b) {
292 differ.push(`${key} ${a} vs ${b}`);
293 }
294 }
295 return { differ, unrecorded };
297​
298const listOf = (entries: ReadonlyArray<{ readonly name: string; readonly count: number }>) =>
299 entries.map((entry) => `${entry.name} ${entry.count}`).join(", ") || "–";
300const weightsOf = (entries: ReadonlyArray<{ readonly name: string; readonly ms: number }>) =>
301 entries.map((entry) => `\`${entry.name}\` ${entry.ms}`).join(", ") || "–";
302​
303/** The run's markdown: per case latency, renders, trace breakdown, memory, idle CPU and soak. */
304export function summaryTable(metrics: ClientMetrics) {
305 const switches = metrics.runs.flatMap((run) => run.switches);
306 const steps = metrics.runs.flatMap((run) => run.steps ?? []);
307 const lines = [
308 "### Client metrics (ms, lower is better)",
309 "",
310 `\`${metrics.meta.commit}\`, ${metrics.runs.length} run(s), ${metrics.meta.platform}, Chromium ${metrics.meta.chromium}`,
311 ];
312 if (switches.length > 0) {
313 lines.push(
314 "",
315 "| switch to | visit | n | paint p50 | paint p90 | content p50 | not in 1st frame | LoAF p50 | LoAF p90 |",
316 "| :-- | :-- | --: | --: | --: | --: | --: | --: | --: |",
317 );
318 for (const name of new Set(switches.map((entry) => entry.case))) {
319 for (const visit of ["first", "revisit"] as const) {
320 const rows = switches.filter((entry) => entry.case === name && entry.visit === visit);
321 if (rows.length === 0) continue;
322 const paint = present(rows.map((entry) => entry.paintMs));
323 const content = present(rows.map((entry) => entry.contentMs));
324 const loaf = rows.map((entry) => entry.loafMs);
325 const missed = rows.filter((entry) => !entry.firstFrameContent).length;
326 lines.push(
327 `| ${name} | ${visit} | ${rows.length} | ${cell(median(paint))} | ${cell(percentile(paint, 90))} | ${cell(median(content))} | ${missed}/${rows.length} | ${cell(median(loaf))} | ${cell(percentile(loaf, 90))} |`,
328 );
329 }
330 }
331 }
332 const stepKeys = [...new Set(steps.map((entry) => `${entry.case}\u0000${entry.step}`))];
333 if (stepKeys.length > 0) {
334 lines.push(
335 "",
336 "| interaction | step | n | paint p50 | paint p90 | paints ≥16 ms | LoAF p50 | LoAF p90 | dropped frames p50 |",
337 "| :-- | :-- | --: | --: | --: | --: | --: | --: | --: |",
338 );
339 for (const key of stepKeys) {
340 const [name, step] = key.split("\u0000") as [string, string];
341 const rows = steps.filter((entry) => entry.case === name && entry.step === step);
342 const paint = present(rows.map((entry) => entry.paintMs));
343 const loaf = rows.map((entry) => entry.loafMs);
344 lines.push(
345 `| ${name} | ${step} | ${rows.length} | ${cell(median(paint))} | ${cell(percentile(paint, 90))} | ${paint.length}/${rows.length} | ${cell(median(loaf))} | ${cell(percentile(loaf, 90))} | ${cell(median(rows.map((entry) => entry.droppedPct)))}% |`,
346 );
347 }
348 }
349 const rendered = [
350 ...switches.map((entry) => ({ key: `switch to ${entry.case} (${entry.visit})`, ...entry })),
351 ...steps.map((entry) => ({ key: `${entry.case}: ${entry.step}`, ...entry })),
352 ].filter((entry) => entry.renders !== undefined);
353 if (rendered.length > 0) {
354 lines.push(
355 "",
356 "| renders per step | n | commits p50 | renders p50 | renders max | top components (mean per step) | top causes |",
357 "| :-- | --: | --: | --: | --: | :-- | :-- |",
358 );
359 for (const key of new Set(rendered.map((entry) => entry.key))) {
360 const rows = rendered.filter((entry) => entry.key === key).map((entry) => entry.renders!);
361 const counts = rows.map((entry) => entry.renders);
362 lines.push(
363 `| ${key} | ${rows.length} | ${cell(median(rows.map((entry) => entry.commits)))} | ${cell(median(counts))} | ${cell(Math.max(...counts))} | ${listOf(topCounts(rows.map((entry) => entry.top)))} | ${listOf(
364 topCounts(
365 rows.map((entry) => entry.causes),
366 3,
367 ),
368 )} |`,
369 );
370 }
371 if (metrics.meta.minified === true) {
372 lines.push(
373 "",
374 "Component names are minified in this build; rerun with `--unminified` to read them.",
375 );
376 }
377 }
378 const panels = metrics.runs.flatMap((run) => run.panels ?? []);
379 if (panels.length > 0) {
380 lines.push(
381 "",
382 "| panel | DOM nodes in the surface | DOM nodes in the page |",
383 "| :-- | --: | --: |",
384 );
385 for (const name of new Set(panels.map((entry) => entry.case))) {
386 const rows = panels.filter((entry) => entry.case === name);
387 lines.push(
388 `| ${name} | ${cell(median(rows.map((entry) => entry.panelNodes)))} | ${cell(median(rows.map((entry) => entry.documentNodes)))} |`,
389 );
390 }
391 }
392 const traced = metrics.runs.at(-1)?.trace ?? [];
393 if (traced.length > 0) {
394 lines.push(
395 "",
396 "| traced step (last run) | windows | input task | forced style | forced layout | sampled JS | long tasks after |",
397 "| :-- | --: | --: | --: | --: | --: | :-- |",
398 );
399 for (const step of traced) {
400 lines.push(
401 `| ${step.label} | ${step.windows} | ${step.inputTaskMs} | ${step.forcedStyleMs} | ${step.forcedLayoutMs} | ${step.sampledMs} | ${step.longTasks.map((task) => `+${task.atMs}: ${task.ms}`).join(", ") || "–"} |`,
402 );
403 }
404 lines.push("", "Where each traced step's input task spent its JS (ms per window):", "");
405 for (const step of traced) {
406 if (step.selfByPackage.length === 0 && step.longTasks.length === 0) continue;
407 lines.push(
408 `- **${step.label}**: self ${weightsOf(step.selfByPackage.slice(0, 4))}; libraries ${weightsOf(step.byPackage.slice(0, 4))}; sources ${weightsOf(step.bySource.slice(0, 5))}`,
409 );
410 for (const task of step.longTasks) {
411 lines.push(` - long task +${task.atMs} ms, ${task.ms} ms: ${weightsOf(task.top)}`);
412 }
413 }
414 }
415 const memory = metrics.runs.flatMap((run) => run.memory);
416 if (memory.length > 0) {
417 lines.push(
418 "",
419 "| memory after GC | heap MB | DOM nodes | listeners |",
420 "| :-- | --: | --: | --: |",
421 );
422 for (const label of new Set(memory.map((entry) => entry.label))) {
423 const rows = memory.filter((entry) => entry.label === label);
424 lines.push(
425 `| ${label} | ${cell(median(rows.map((entry) => entry.heapMB)), 1)} | ${cell(median(rows.map((entry) => entry.domNodes)))} | ${cell(median(rows.map((entry) => entry.listeners)))} |`,
426 );
427 }
428 }
429 const idle = metrics.runs.flatMap((run) => run.idle);
430 if (idle.length > 0) {
431 lines.push(
432 "",
433 "| renderer CPU while a thread streams | task % | script % | style % | layout % |",
434 "| :-- | --: | --: | --: | --: |",
435 );
436 for (const label of new Set(idle.map((entry) => entry.label))) {
437 const rows = idle.filter((entry) => entry.label === label);
438 const at = (pick: (entry: Idle) => number) => cell(median(rows.map(pick)), 1);
439 lines.push(
440 `| ${label} | ${at((entry) => entry.taskPct)} | ${at((entry) => entry.scriptPct)} | ${at((entry) => entry.stylePct)} | ${at((entry) => entry.layoutPct)} |`,
441 );
442 }
443 }
444 metrics.runs.forEach((run, index) => {
445 if (!run.soak || run.soak.length < 3) return;
446 const slopes = soakSlopes(run.soak);
447 const leaking = soakLeaks(run.soak);
448 lines.push(
449 "",
450 `| soak, run ${index + 1}: iteration | heap MB | DOM nodes | listeners |`,
451 "| --: | --: | --: | --: |",
452 ...run.soak.map(
453 (sample) =>
454 `| ${sample.iteration} | ${sample.heapMB} | ${sample.domNodes} | ${sample.listeners} |`,
455 ),
456 `| growth per iteration | ${round(slopes.heapMB, 3)} | ${round(slopes.domNodes, 1)} | ${round(slopes.listeners, 2)} |`,
457 "",
458 leaking.length > 0
459 ? `**Growing:** ${leaking.join(", ")} past ${leaking.map((key) => `${SOAK_LEAK[key]}`).join(", ")} per iteration over the soak's later half.`
460 : "No growth past the leak bars over the soak's later half.",
461 );
462 });
463 const skipped = metrics.runs.flatMap((run) => run.skipped ?? []);
464 for (const entry of skipped) lines.push("", `Skipped ${entry.case}: ${entry.reason}`);
465 if (metrics.callSites && metrics.callSites.length > 0) {
466 lines.push(
467 "",
468 "| forced style+layout call site (traced round) | ms | count |",
469 "| :-- | --: | --: |",
470 );
471 for (const site of metrics.callSites) {
472 lines.push(`| \`${site.site}\` | ${round(site.ms, 1)} | ${site.count} |`);
473 }
474 }
475 return lines.join("\n");
477​
478/** `compareSeries` over two files' per-run medians. */
479export function compareClientMetrics(
480 before: ClientMetrics,
481 after: ClientMetrics,
482 threshold = 10,
483 floors?: Floors,
484) {
485 return compareSeries(
486 flatten(before),
487 flatten(after),
488 [
489 "### Client metrics (lower is better)",
490 "",
491 `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs)${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
492 ],
493 threshold,
494 floors,
495 );
497​
498/** `noiseOfSeries` over A/A pairs of files. */
499export function noiseReport(
500 pairs: ReadonlyArray<readonly [ClientMetrics, ClientMetrics]>,
501 platform: string,
502) {
503 return noiseOfSeries(
504 pairs.map(([before, after]) => [flatten(before), flatten(after)] as const),
505 platform,
506 );