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

report.ts

520 lines20.1 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 /** What React rendered in the window, with nothing clicked or typed (`--renders`). */
118 renders: Schema.optional(Renders),
119});
120export type Idle = typeof Idle.Type;
121​
122const SoakSample = Schema.Struct({
123 iteration: Schema.Number,
124 heapMB: Schema.Number,
125 domNodes: Schema.Number,
126 listeners: Schema.Number,
127});
128export type SoakSample = typeof SoakSample.Type;
129​
130const Run = Schema.Struct({
131 switches: Schema.Array(Switch),
132 steps: Schema.optional(Schema.Array(Step)),
133 panels: Schema.optional(Schema.Array(Panel)),
134 memory: Schema.Array(Memory),
135 idle: Schema.Array(Idle),
136 trace: Schema.optional(Schema.Array(TraceStep)),
137 /** Memory after GC while every case repeats (`--soak`). */
138 soak: Schema.optional(Schema.Array(SoakSample)),
139 /** Cases this checkout could not run, and why. */
140 skipped: Schema.optional(
141 Schema.Array(Schema.Struct({ case: Schema.String, reason: Schema.String })),
142 ),
143 machine: Schema.optional(MachineState),
144});
145export type Run = typeof Run.Type;
146​
147export const ClientMetrics = Schema.Struct({
148 meta: Schema.Record(
149 Schema.String,
150 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
151 ),
152 runs: Schema.Array(Run),
153 /** Top call sites of forced style and layout in input tasks, from the last traced run. */
154 callSites: Schema.optional(Schema.Array(CallSite)),
155});
156export type ClientMetrics = typeof ClientMetrics.Type;
157​
158/** The cases a `--cases` list names, in benchmark order; an error names unknown ones. */
159export function parseCases(list: string): { cases: ReadonlyArray<Case> } | { error: string } {
160 const named = list
161 .split(",")
162 .map((entry) => entry.trim())
163 .filter((entry) => entry.length > 0);
164 if (named.length === 0) return { cases: CASES };
165 const groups: Record<string, ReadonlyArray<Case>> = {
166 switches: SWITCH_CASES,
167 interactions: INTERACTION_CASES,
168 };
169 const unknown = named.filter(
170 (entry) => !(CASES as ReadonlyArray<string>).includes(entry) && !Object.hasOwn(groups, entry),
171 );
172 if (unknown.length > 0) {
173 return {
174 error: `unknown cases: ${unknown.join(", ")}; choose from switches, interactions, ${CASES.join(", ")}`,
175 };
176 }
177 const chosen = new Set(
178 named.flatMap((entry): ReadonlyArray<string> =>
179 Object.hasOwn(groups, entry) ? groups[entry]! : [entry],
180 ),
181 );
182 return { cases: CASES.filter((entry) => chosen.has(entry)) };
184​
185const present = (values: ReadonlyArray<number | null>) =>
186 values.filter((value): value is number => value !== null);
187​
188/**
189 * Growth per iteration over a soak's later half. Warm-up (caches filling, code compiling) slows
190 * down as it settles while a leak keeps its rate, so the later half keeps a leak and drops warm-up.
191 */
192export function soakSlopes(samples: ReadonlyArray<SoakSample>) {
193 const last = samples.at(-1)?.iteration ?? 0;
194 const settled = samples.filter((sample) => sample.iteration >= last / 2);
195 const fit = (pick: (sample: SoakSample) => number) =>
196 slope(settled.map((sample) => [sample.iteration, pick(sample)] as const));
197 return {
198 heapMB: fit((sample) => sample.heapMB),
199 domNodes: fit((sample) => sample.domNodes),
200 listeners: fit((sample) => sample.listeners),
201 };
203​
204/** The soak measures growing past their leak bars. */
205export function soakLeaks(samples: ReadonlyArray<SoakSample>) {
206 const slopes = soakSlopes(samples);
207 return (Object.keys(SOAK_LEAK) as Array<keyof typeof SOAK_LEAK>).filter(
208 (key) => slopes[key] > SOAK_LEAK[key],
209 );
211​
212/** Event Timing reports only paints of 16 ms or more; a null paint is under it, so counts as 16. */
213export const PAINT_THRESHOLD_MS = 16;
214const censoredPaint = (value: number | null) => value ?? PAINT_THRESHOLD_MS;
215​
216/**
217 * Every compared metric of a file, one value per run: the median of the run's switches or steps
218 * for latencies and renders, so samples from one page never pass for independent runs.
219 */
220export function flatten(metrics: ClientMetrics): Map<string, number[]> {
221 const values = new Map<string, number[]>();
222 for (const run of metrics.runs) {
223 const inRun = new Map<string, number[]>();
224 const add = (key: string, value: number | null | undefined) => {
225 if (value === null || value === undefined || !Number.isFinite(value)) return;
226 inRun.set(key, [...(inRun.get(key) ?? []), value]);
227 };
228 const groups = new Map<string, Switch[]>();
229 for (const entry of run.switches) {
230 const key = `switch.${entry.case}.${entry.visit}`;
231 groups.set(key, [...(groups.get(key) ?? []), entry]);
232 add(`${key}.paintMs`, censoredPaint(entry.paintMs));
233 add(`${key}.contentMs`, entry.contentMs);
234 add(`${key}.loafMs`, entry.loafMs);
235 add(`${key}.renders`, entry.renders?.renders);
236 add(`${key}.commits`, entry.renders?.commits);
237 }
238 for (const [key, entries] of groups) {
239 const missed = entries.filter((entry) => !entry.firstFrameContent).length;
240 add(`${key}.firstFrameMissPct`, (missed / entries.length) * 100);
241 }
242 for (const entry of run.steps ?? []) {
243 const key = `step.${entry.case}.${entry.step}`;
244 add(`${key}.paintMs`, censoredPaint(entry.paintMs));
245 add(`${key}.loafMs`, entry.loafMs);
246 add(`${key}.droppedPct`, entry.droppedPct);
247 add(`${key}.renders`, entry.renders?.renders);
248 add(`${key}.commits`, entry.renders?.commits);
249 }
250 for (const entry of run.panels ?? []) add(`panel.${entry.case}.domNodes`, entry.panelNodes);
251 for (const entry of run.trace ?? []) {
252 add(`trace.${entry.label}.inputTaskMs`, entry.inputTaskMs);
253 add(
254 `trace.${entry.label}.forcedMs`,
255 entry.forcedMs ?? entry.forcedStyleMs + entry.forcedLayoutMs,
256 );
257 }
258 for (const entry of run.memory) {
259 add(`memory.${entry.label}.heapMB`, entry.heapMB);
260 add(`memory.${entry.label}.domNodes`, entry.domNodes);
261 }
262 for (const entry of run.idle) {
263 // A counted window's CPU includes the probe, so it is not compared, least of all against an uncounted one.
264 if (entry.renders === undefined) add(`idle.${entry.label}.taskPct`, entry.taskPct);
265 add(`idle.${entry.label}.renders`, entry.renders?.renders);
266 add(`idle.${entry.label}.commits`, entry.renders?.commits);
267 }
268 if (run.soak && run.soak.length > 2) {
269 const slopes = soakSlopes(run.soak);
270 add("soak.heapMBPerIteration", slopes.heapMB);
271 add("soak.domNodesPerIteration", slopes.domNodes);
272 add("soak.listenersPerIteration", slopes.listeners);
273 }
274 for (const [key, samples] of inRun)
275 values.set(key, [...(values.get(key) ?? []), median(samples)!]);
276 }
277 return values;
279​
280/** Settings that change what shared metrics measure, recorded in each file's meta. */
281export const WORKLOAD_KEYS = ["cases", "switchRounds", "longTurns"] as const;
282/** Settings that change timing without changing the workload: the render probe and the build. */
283export const PROBE_KEYS = ["renders", "minified"] as const;
284​
285/** Settings two files disagree on, and those one of them did not record. */
286export function workloadDifferences(
287 before: ClientMetrics,
288 after: ClientMetrics,
289 keys: ReadonlyArray<string> = WORKLOAD_KEYS,
290) {
291 const differ: string[] = [];
292 const unrecorded: string[] = [];
293 for (const key of keys) {
294 const a = before.meta[key];
295 const b = after.meta[key];
296 if (a === undefined || b === undefined) {
297 if (a !== b) unrecorded.push(key);
298 } else if (a !== b) {
299 differ.push(`${key} ${a} vs ${b}`);
300 }
301 }
302 return { differ, unrecorded };
304​
305const listOf = (entries: ReadonlyArray<{ readonly name: string; readonly count: number }>) =>
306 entries.map((entry) => `${entry.name} ${entry.count}`).join(", ") || "–";
307const weightsOf = (entries: ReadonlyArray<{ readonly name: string; readonly ms: number }>) =>
308 entries.map((entry) => `\`${entry.name}\` ${entry.ms}`).join(", ") || "–";
309​
310/** The run's markdown: per case latency, renders, trace breakdown, memory, idle CPU and soak. */
311export function summaryTable(metrics: ClientMetrics) {
312 const switches = metrics.runs.flatMap((run) => run.switches);
313 const steps = metrics.runs.flatMap((run) => run.steps ?? []);
314 const lines = [
315 "### Client metrics (ms, lower is better)",
316 "",
317 `\`${metrics.meta.commit}\`, ${metrics.runs.length} run(s), ${metrics.meta.platform}, Chromium ${metrics.meta.chromium}`,
318 ];
319 if (switches.length > 0) {
320 lines.push(
321 "",
322 "| switch to | visit | n | paint p50 | paint p90 | content p50 | not in 1st frame | LoAF p50 | LoAF p90 |",
323 "| :-- | :-- | --: | --: | --: | --: | --: | --: | --: |",
324 );
325 for (const name of new Set(switches.map((entry) => entry.case))) {
326 for (const visit of ["first", "revisit"] as const) {
327 const rows = switches.filter((entry) => entry.case === name && entry.visit === visit);
328 if (rows.length === 0) continue;
329 const paint = present(rows.map((entry) => entry.paintMs));
330 const content = present(rows.map((entry) => entry.contentMs));
331 const loaf = rows.map((entry) => entry.loafMs);
332 const missed = rows.filter((entry) => !entry.firstFrameContent).length;
333 lines.push(
334 `| ${name} | ${visit} | ${rows.length} | ${cell(median(paint))} | ${cell(percentile(paint, 90))} | ${cell(median(content))} | ${missed}/${rows.length} | ${cell(median(loaf))} | ${cell(percentile(loaf, 90))} |`,
335 );
336 }
337 }
338 }
339 const stepKeys = [...new Set(steps.map((entry) => `${entry.case}\u0000${entry.step}`))];
340 if (stepKeys.length > 0) {
341 lines.push(
342 "",
343 "| interaction | step | n | paint p50 | paint p90 | paints ≥16 ms | LoAF p50 | LoAF p90 | dropped frames p50 |",
344 "| :-- | :-- | --: | --: | --: | --: | --: | --: | --: |",
345 );
346 for (const key of stepKeys) {
347 const [name, step] = key.split("\u0000") as [string, string];
348 const rows = steps.filter((entry) => entry.case === name && entry.step === step);
349 const paint = present(rows.map((entry) => entry.paintMs));
350 const loaf = rows.map((entry) => entry.loafMs);
351 lines.push(
352 `| ${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)))}% |`,
353 );
354 }
355 }
356 const rendered = [
357 ...switches.map((entry) => ({ key: `switch to ${entry.case} (${entry.visit})`, ...entry })),
358 ...steps.map((entry) => ({ key: `${entry.case}: ${entry.step}`, ...entry })),
359 ...metrics.runs.flatMap((run) =>
360 run.idle.map((entry) => ({
361 key: `streaming: ${entry.label}`,
362 renders: entry.renders,
363 })),
364 ),
365 ].filter((entry) => entry.renders !== undefined);
366 if (rendered.length > 0) {
367 lines.push(
368 "",
369 "| renders per step | n | commits p50 | renders p50 | renders max | top components (mean per step) | top causes |",
370 "| :-- | --: | --: | --: | --: | :-- | :-- |",
371 );
372 for (const key of new Set(rendered.map((entry) => entry.key))) {
373 const rows = rendered.filter((entry) => entry.key === key).map((entry) => entry.renders!);
374 const counts = rows.map((entry) => entry.renders);
375 lines.push(
376 `| ${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(
377 topCounts(
378 rows.map((entry) => entry.causes),
379 3,
380 ),
381 )} |`,
382 );
383 }
384 if (metrics.meta.minified === true) {
385 lines.push(
386 "",
387 "Component names are minified in this build; rerun with `--unminified` to read them.",
388 );
389 }
390 }
391 const panels = metrics.runs.flatMap((run) => run.panels ?? []);
392 if (panels.length > 0) {
393 lines.push(
394 "",
395 "| panel | DOM nodes in the surface | DOM nodes in the page |",
396 "| :-- | --: | --: |",
397 );
398 for (const name of new Set(panels.map((entry) => entry.case))) {
399 const rows = panels.filter((entry) => entry.case === name);
400 lines.push(
401 `| ${name} | ${cell(median(rows.map((entry) => entry.panelNodes)))} | ${cell(median(rows.map((entry) => entry.documentNodes)))} |`,
402 );
403 }
404 }
405 const traced = metrics.runs.at(-1)?.trace ?? [];
406 if (traced.length > 0) {
407 lines.push(
408 "",
409 "| traced step (last run) | windows | input task | forced style | forced layout | sampled JS | long tasks after |",
410 "| :-- | --: | --: | --: | --: | --: | :-- |",
411 );
412 for (const step of traced) {
413 lines.push(
414 `| ${step.label} | ${step.windows} | ${step.inputTaskMs} | ${step.forcedStyleMs} | ${step.forcedLayoutMs} | ${step.sampledMs} | ${step.longTasks.map((task) => `+${task.atMs}: ${task.ms}`).join(", ") || "–"} |`,
415 );
416 }
417 lines.push("", "Where each traced step's input task spent its JS (ms per window):", "");
418 for (const step of traced) {
419 if (step.selfByPackage.length === 0 && step.longTasks.length === 0) continue;
420 lines.push(
421 `- **${step.label}**: self ${weightsOf(step.selfByPackage.slice(0, 4))}; libraries ${weightsOf(step.byPackage.slice(0, 4))}; sources ${weightsOf(step.bySource.slice(0, 5))}`,
422 );
423 for (const task of step.longTasks) {
424 lines.push(` - long task +${task.atMs} ms, ${task.ms} ms: ${weightsOf(task.top)}`);
425 }
426 }
427 }
428 const memory = metrics.runs.flatMap((run) => run.memory);
429 if (memory.length > 0) {
430 lines.push(
431 "",
432 "| memory after GC | heap MB | DOM nodes | listeners |",
433 "| :-- | --: | --: | --: |",
434 );
435 for (const label of new Set(memory.map((entry) => entry.label))) {
436 const rows = memory.filter((entry) => entry.label === label);
437 lines.push(
438 `| ${label} | ${cell(median(rows.map((entry) => entry.heapMB)), 1)} | ${cell(median(rows.map((entry) => entry.domNodes)))} | ${cell(median(rows.map((entry) => entry.listeners)))} |`,
439 );
440 }
441 }
442 const idle = metrics.runs.flatMap((run) => run.idle);
443 if (idle.length > 0) {
444 lines.push(
445 "",
446 "| renderer CPU while a thread streams | task % | script % | style % | layout % |",
447 "| :-- | --: | --: | --: | --: |",
448 );
449 for (const label of new Set(idle.map((entry) => entry.label))) {
450 const rows = idle.filter((entry) => entry.label === label);
451 const at = (pick: (entry: Idle) => number) => cell(median(rows.map(pick)), 1);
452 lines.push(
453 `| ${label} | ${at((entry) => entry.taskPct)} | ${at((entry) => entry.scriptPct)} | ${at((entry) => entry.stylePct)} | ${at((entry) => entry.layoutPct)} |`,
454 );
455 }
456 }
457 metrics.runs.forEach((run, index) => {
458 if (!run.soak || run.soak.length < 3) return;
459 const slopes = soakSlopes(run.soak);
460 const leaking = soakLeaks(run.soak);
461 lines.push(
462 "",
463 `| soak, run ${index + 1}: iteration | heap MB | DOM nodes | listeners |`,
464 "| --: | --: | --: | --: |",
465 ...run.soak.map(
466 (sample) =>
467 `| ${sample.iteration} | ${sample.heapMB} | ${sample.domNodes} | ${sample.listeners} |`,
468 ),
469 `| growth per iteration | ${round(slopes.heapMB, 3)} | ${round(slopes.domNodes, 1)} | ${round(slopes.listeners, 2)} |`,
470 "",
471 leaking.length > 0
472 ? `**Growing:** ${leaking.join(", ")} past ${leaking.map((key) => `${SOAK_LEAK[key]}`).join(", ")} per iteration over the soak's later half.`
473 : "No growth past the leak bars over the soak's later half.",
474 );
475 });
476 const skipped = metrics.runs.flatMap((run) => run.skipped ?? []);
477 for (const entry of skipped) lines.push("", `Skipped ${entry.case}: ${entry.reason}`);
478 if (metrics.callSites && metrics.callSites.length > 0) {
479 lines.push(
480 "",
481 "| forced style+layout call site (traced round) | ms | count |",
482 "| :-- | --: | --: |",
483 );
484 for (const site of metrics.callSites) {
485 lines.push(`| \`${site.site}\` | ${round(site.ms, 1)} | ${site.count} |`);
486 }
487 }
488 return lines.join("\n");
490​
491/** `compareSeries` over two files' per-run medians. */
492export function compareClientMetrics(
493 before: ClientMetrics,
494 after: ClientMetrics,
495 threshold = 10,
496 floors?: Floors,
497) {
498 return compareSeries(
499 flatten(before),
500 flatten(after),
501 [
502 "### Client metrics (lower is better)",
503 "",
504 `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs)${floors ? `, floors calibrated on ${floors.platform}` : ""}`,
505 ],
506 threshold,
507 floors,
508 );
510​
511/** `noiseOfSeries` over A/A pairs of files. */
512export function noiseReport(
513 pairs: ReadonlyArray<readonly [ClientMetrics, ClientMetrics]>,
514 platform: string,
515) {
516 return noiseOfSeries(
517 pairs.map(([before, after]) => [flatten(before), flatten(after)] as const),
518 platform,
519 );