Open History to see the last commit
1import * as Schema from "effect/Schema";
2import { describe, expect, it } from "vite-plus/test";
3
4import { slope } from "../core/report.ts";
5import { rendersOf } from "./probes.ts";
6import {
7 CASES,
8 ClientMetrics,
9 compareClientMetrics,
10 flatten,
11 INTERACTION_CASES,
12 noiseReport,
13 parseCases,
14 PROBE_KEYS,
15 soakLeaks,
16 soakSlopes,
17 summaryTable,
18 workloadDifferences,
19 type Step,
20 type Switch,
21} from "./report.ts";
22import {
23 analyzeTrace,
24 END_LABEL,
25 MARK_PREFIX,
26 normalizeSource,
27 packageOf,
28 type TraceEvent,
29} from "./trace.ts";
30
31const decode = Schema.decodeSync(ClientMetrics);
32
33const switchTo = (name: string, paintMs: number, overrides: Partial<Switch> = {}): Switch => ({
34 case: name,
35 visit: "revisit",
36 round: 1,
37 paintMs,
38 contentMs: paintMs,
39 firstFrameContent: true,
40 loafMs: paintMs,
41 ...overrides,
42});
43
44const renders = (count: number) => ({
45 commits: 3,
46 renders: count,
47 top: [{ name: "TimelineRow", count }],
48 causes: [{ name: "TimelineRow mount", count }],
49});
50
51const step = (overrides: Partial<Step> = {}): Step => ({
52 case: "type-long",
53 step: "key",
54 round: 0,
55 paintMs: 24,
56 loafMs: 0,
57 droppedPct: 0,
58 ...overrides,
59});
60
61const file = (commit: string, paints: ReadonlyArray<ReadonlyArray<number>>) =>
62 decode({
63 meta: { commit, platform: "linux-x64", chromium: "1", cpus: 8 },
64 runs: paints.map((run) => ({
65 switches: run.map((paint) => switchTo("diff", paint)),
66 memory: [{ label: "loaded", heapMB: 60, domNodes: 2_000, listeners: 1_000 }],
67 idle: [
68 {
69 label: "on the working thread",
70 seconds: 10,
71 taskPct: 10,
72 scriptPct: 5,
73 stylePct: 1,
74 layoutPct: 0,
75 },
76 ],
77 })),
78 });
79
80const withRenders = (commit: string, counts: ReadonlyArray<ReadonlyArray<number>>) =>
81 decode({
82 meta: { commit, platform: "linux-x64" },
83 runs: counts.map((run) => ({
84 switches: [],
85 steps: run.map((count) => step({ renders: renders(count) })),
86 memory: [],
87 idle: [],
88 })),
89 });
90
91describe("parseCases", () => {
92 it("defaults to every case and keeps benchmark order", () => {
93 expect(parseCases("")).toEqual({ cases: CASES });
94 expect(parseCases("settings, device, short")).toEqual({
95 cases: ["short", "device", "settings"],
96 });
97 });
98
99 it("expands the groups", () => {
100 expect(parseCases("interactions")).toEqual({ cases: INTERACTION_CASES });
101 expect(parseCases("switches,palette")).toEqual({
102 cases: CASES.filter(
103 (name) => !INTERACTION_CASES.includes(name as never) || name === "palette",
104 ),
105 });
106 });
107
108 it("names unknown cases", () => {
109 const parsed = parseCases("short,diffs");
110 expect("error" in parsed && parsed.error).toMatch(/^unknown cases: diffs; choose from/);
111 const inherited = parseCases("short,toString");
112 expect("error" in inherited && inherited.error).toMatch(/^unknown cases: toString;/);
113 });
114});
115
116describe("report math", () => {
117 it("keeps a first-frame miss share per run, and counts paints under 16 ms as 16", () => {
118 const metrics = decode({
119 meta: { commit: "a" },
120 runs: [
121 {
122 switches: [
123 switchTo("short", 100, { firstFrameContent: false }),
124 switchTo("short", 120),
125 switchTo("short", 0, { paintMs: null }),
126 ],
127 memory: [],
128 idle: [],
129 },
130 ],
131 });
132 const flat = flatten(metrics);
133 // One value per run: the median of 100, 120 and 16, where dropping the null would give 110.
134 expect(flat.get("switch.short.revisit.paintMs")).toEqual([100]);
135 expect(flat.get("switch.short.revisit.firstFrameMissPct")).toEqual([(1 / 3) * 100]);
136 });
137
138 it("flattens steps, renders, panels and traces", () => {
139 const flat = flatten(
140 decode({
141 meta: { commit: "a" },
142 runs: [
143 {
144 switches: [switchTo("long", 100, { renders: renders(400) })],
145 steps: [step({ paintMs: null, droppedPct: 12, renders: renders(9) })],
146 panels: [{ case: "diff", panelNodes: 5_000, documentNodes: 9_000 }],
147 trace: [
148 {
149 label: "switch:long",
150 windows: 1,
151 inputTaskMs: 80,
152 forcedStyleMs: 3,
153 forcedLayoutMs: 4,
154 sampledMs: 70,
155 selfByPackage: [],
156 bySource: [],
157 byPackage: [],
158 longTasks: [],
159 },
160 ],
161 memory: [],
162 idle: [],
163 },
164 ],
165 }),
166 );
167 expect(flat.get("switch.long.revisit.renders")).toEqual([400]);
168 expect(flat.get("step.type-long.key.paintMs")).toEqual([16]);
169 expect(flat.get("step.type-long.key.droppedPct")).toEqual([12]);
170 expect(flat.get("step.type-long.key.renders")).toEqual([9]);
171 expect(flat.get("step.type-long.key.commits")).toEqual([3]);
172 expect(flat.get("panel.diff.domNodes")).toEqual([5_000]);
173 expect(flat.get("trace.switch:long.forcedMs")).toEqual([7]);
174 });
175
176 it("calls a change worse only past the threshold and the floor", () => {
177 const before = file("a", [
178 [100, 102, 98],
179 [101, 99, 100],
180 ]);
181 const worse = compareClientMetrics(
182 before,
183 file("b", [
184 [150, 152, 149],
185 [151, 148, 150],
186 ]),
187 );
188 expect(worse.regressed).toEqual([
189 "switch.diff.revisit.contentMs",
190 "switch.diff.revisit.loafMs",
191 "switch.diff.revisit.paintMs",
192 ]);
193 const same = compareClientMetrics(
194 before,
195 file("b", [
196 [104, 101, 103],
197 [100, 102, 105],
198 ]),
199 );
200 expect(same.regressed).toEqual([]);
201 expect(same.improved).toEqual([]);
202 });
203
204 it("calls paints that grew from under 16 ms worse", () => {
205 const paints = (commit: string, paint: number | null) =>
206 decode({
207 meta: { commit },
208 runs: [0, 1].map(() => ({
209 switches: [0, 1, 2].map(() => switchTo("diff", 0, { paintMs: paint })),
210 memory: [],
211 idle: [],
212 })),
213 });
214 const result = compareClientMetrics(paints("a", null), paints("b", 64));
215 expect(result.regressed).toContain("switch.diff.revisit.paintMs");
216 });
217
218 it("gates only across runs, never on samples from one page", () => {
219 const result = compareClientMetrics(
220 file("a", [[24, 24, 24, 24]]),
221 file("b", [[48, 48, 48, 48]]),
222 );
223 expect(result.regressed).toEqual([]);
224 expect(result.noisy).toContain("switch.diff.revisit.paintMs");
225 expect(result.table).toContain("one run, not gated");
226 });
227
228 it("names probe settings A/A pairs disagree on", () => {
229 const withMeta = (renders: boolean) => decode({ meta: { commit: "a", renders }, runs: [] });
230 expect(workloadDifferences(withMeta(true), withMeta(false), PROBE_KEYS).differ).toEqual([
231 "renders true vs false",
232 ]);
233 });
234
235 it("names workload settings two files disagree on", () => {
236 const withMeta = (meta: Record<string, string | number>) =>
237 decode({ meta: { commit: "a", ...meta }, runs: [] });
238 const full = { cases: "long", switchRounds: 4, longTurns: 12 };
239 expect(workloadDifferences(withMeta(full), withMeta(full))).toEqual({
240 differ: [],
241 unrecorded: [],
242 });
243 expect(workloadDifferences(withMeta(full), withMeta({ ...full, longTurns: 1 }))).toEqual({
244 differ: ["longTurns 12 vs 1"],
245 unrecorded: [],
246 });
247 expect(workloadDifferences(withMeta({}), withMeta(full))).toEqual({
248 differ: [],
249 unrecorded: ["cases", "switchRounds", "longTurns"],
250 });
251 });
252
253 it("gates on render counts, which barely move between runs", () => {
254 const before = withRenders("a", [
255 [40, 40, 41],
256 [40, 40, 40],
257 ]);
258 const result = compareClientMetrics(
259 before,
260 withRenders("b", [
261 [52, 52, 52],
262 [52, 53, 52],
263 ]),
264 );
265 expect(result.regressed).toEqual(["step.type-long.key.renders"]);
266 });
267
268 it("uses calibrated floors, and never counts a metric too noisy to gate on", () => {
269 const before = file("a", [
270 [100, 102, 98],
271 [101, 99, 100],
272 ]);
273 const after = file("b", [
274 [150, 152, 149],
275 [151, 148, 150],
276 ]);
277 const result = compareClientMetrics(before, after, 10, {
278 platform: "linux-x64",
279 floors: {
280 "switch.diff.revisit.paintMs": { floor: 80, gate: true },
281 "switch.diff.revisit.loafMs": { floor: 1, gate: false },
282 },
283 });
284 expect(result.regressed).toEqual(["switch.diff.revisit.contentMs"]);
285 expect(result.noisy).toEqual(["switch.diff.revisit.loafMs"]);
286 });
287
288 it("summarizes every case, renders, memory and idle CPU", () => {
289 const table = summaryTable(file("abc", [[100, 200]]));
290 expect(table).toContain("| diff | revisit | 2 | 150 | 200 |");
291 expect(table).toContain("| loaded | 60 | 2000 | 1000 |");
292 expect(table).toContain("| on the working thread | 10 | 5 | 1 | 0 |");
293 const rendered = summaryTable({
294 ...withRenders("abc", [[10, 30]]),
295 meta: { commit: "abc", minified: true },
296 });
297 expect(rendered).toContain("| type-long: key | 2 | 3 | 20 | 30 | TimelineRow 20 |");
298 expect(rendered).toContain("Component names are minified");
299 });
300});
301
302describe("soak", () => {
303 it("fits growth per iteration past the warm-up sample", () => {
304 expect(
305 slope([
306 [0, 1],
307 [1, 3],
308 [2, 5],
309 ]),
310 ).toBe(2);
311 expect(slope([[1, 4]])).toBe(0);
312 const slopes = soakSlopes([
313 { iteration: 0, heapMB: 50, domNodes: 1_000, listeners: 100 },
314 { iteration: 2, heapMB: 80, domNodes: 3_000, listeners: 140 },
315 { iteration: 4, heapMB: 80, domNodes: 3_040, listeners: 140 },
316 { iteration: 6, heapMB: 80, domNodes: 3_080, listeners: 140 },
317 ]);
318 expect(slopes).toEqual({ heapMB: 0, domNodes: 20, listeners: 0 });
319 });
320
321 const curve = (heapAt: (iteration: number) => number) =>
322 [0, 4, 8, 12, 16, 20, 24].map((iteration) => ({
323 iteration,
324 heapMB: heapAt(iteration),
325 domNodes: 3_000,
326 listeners: 1_350,
327 }));
328
329 it("does not call a warm-up that settles a leak", () => {
330 // 1 MB per iteration at first, settling over ten iterations: caches filling, code compiling.
331 expect(soakLeaks(curve((iteration) => 74 + 10 * (1 - Math.exp(-iteration / 4))))).toEqual([]);
332 });
333
334 it("calls steady growth a leak", () => {
335 expect(soakLeaks(curve((iteration) => 74 + 0.2 * iteration))).toEqual(["heapMB"]);
336 });
337});
338
339describe("noiseReport", () => {
340 it("derives a floor from the A/A spread and flags metrics too noisy to gate", () => {
341 const steady = withRenders("a", [
342 [40, 40, 40],
343 [41, 41, 41],
344 ]);
345 const { floors, rows } = noiseReport([[steady, steady]], "linux-x64");
346 expect(floors.platform).toBe("linux-x64");
347 expect(floors.floors["step.type-long.key.renders"]).toEqual({ floor: 0.5, gate: true });
348 const noisy = (paints: ReadonlyArray<number>) =>
349 decode({
350 meta: { commit: "a", platform: "linux-x64" },
351 runs: paints.map((paint) => ({
352 switches: [switchTo("long", paint)],
353 memory: [],
354 idle: [],
355 })),
356 });
357 const loose = noiseReport([[noisy([20, 200, 30, 180]), noisy([190, 25, 210, 22])]], "x");
358 const row = loose.rows.find((entry) => entry.metric === "switch.long.revisit.paintMs");
359 expect(row?.gate).toBe(false);
360 expect(rows.length).toBeGreaterThan(0);
361 });
362});
363
364describe("probe readings", () => {
365 it("keeps the top entries of a render reading", () => {
366 const top = Array.from({ length: 30 }, (_, index) => ({
367 name: `C${index}`,
368 count: 30 - index,
369 }));
370 const kept = rendersOf({ commits: 2, renders: 465, top, causes: top, slots: ["C0 #1=x"] }, 3);
371 expect(kept).toEqual({
372 commits: 2,
373 renders: 465,
374 top: top.slice(0, 3),
375 causes: top.slice(0, 3),
376 });
377 });
378});
379
380describe("source names", () => {
381 it("shortens library paths and names their package", () => {
382 const source = normalizeSource(
383 "node_modules/.pnpm/@base-ui+react@1.0.0/node_modules/@base-ui/react/esm/tooltip.js",
384 );
385 expect(source).toBe("nm:@base-ui/react/esm/tooltip.js");
386 expect(packageOf(source)).toBe("nm:@base-ui/react");
387 expect(packageOf("nm:react-dom/cjs/react-dom.js")).toBe("nm:react-dom");
388 expect(packageOf("apps/web/src/components/ChatView.tsx")).toBe("apps/web");
389 expect(packageOf("(garbage collector)")).toBe("(garbage collector)");
390 });
391});
392
393describe("analyzeTrace", () => {
394 const main = { pid: 1, tid: 2 };
395 const stack = [{ url: "http://x/assets/app.js", lineNumber: 1, columnNumber: 10 }];
396 const frame = (url: string, line: number) => ({
397 functionName: "f",
398 url,
399 lineNumber: line,
400 columnNumber: 0,
401 });
402 const events: ReadonlyArray<TraceEvent> = [
403 { ...main, ph: "M", name: "thread_name", args: { name: "CrRendererMain" } },
404 { ...main, ph: "R", name: `${MARK_PREFIX}switch:diff`, ts: 500 },
405 { ...main, ph: "X", name: "RunTask", ts: 1_000, dur: 20_500 },
406 {
407 ...main,
408 ph: "X",
409 name: "EventDispatch",
410 ts: 1_100,
411 dur: 40_000,
412 args: { data: { type: "click" } },
413 },
414 {
415 ...main,
416 ph: "X",
417 name: "UpdateLayoutTree",
418 ts: 2_000,
419 dur: 4_000,
420 args: { beginData: { stackTrace: stack } },
421 },
422 {
423 ...main,
424 ph: "X",
425 name: "Layout",
426 ts: 7_000,
427 dur: 6_000,
428 args: { beginData: { stackTrace: stack } },
429 },
430 // The frame's own layout carries no stack, so it is not forced.
431 { ...main, ph: "X", name: "Layout", ts: 30_000, dur: 9_000 },
432 // A long task after the click's, and one after the step settled.
433 { ...main, ph: "X", name: "RunTask", ts: 200_000, dur: 60_000 },
434 { ...main, ph: "R", name: `${MARK_PREFIX}${END_LABEL}`, ts: 300_000 },
435 { ...main, ph: "X", name: "RunTask", ts: 400_000, dur: 90_000 },
436 // A step whose input task carries nothing to sample.
437 { ...main, ph: "R", name: `${MARK_PREFIX}palette:key`, ts: 2_000_000 },
438 { ...main, ph: "X", name: "RunTask", ts: 2_000_100, dur: 5_000 },
439 {
440 ...main,
441 ph: "X",
442 name: "EventDispatch",
443 ts: 2_000_200,
444 dur: 1_000,
445 args: { data: { type: "keydown" } },
446 },
447 { ...main, ph: "P", name: "Profile", id: "0x1", args: { data: { startTime: 0 } } },
448 {
449 ...main,
450 ph: "P",
451 name: "ProfileChunk",
452 id: "0x1",
453 args: {
454 data: {
455 cpuProfile: {
456 nodes: [
457 { id: 1, callFrame: { functionName: "(root)" } },
458 { id: 2, parent: 1, callFrame: frame("http://x/assets/react.js", 0) },
459 { id: 3, parent: 2, callFrame: frame("http://x/assets/app.js", 0) },
460 // The same file twice on one stack still counts once per sample.
461 { id: 4, parent: 3, callFrame: frame("http://x/assets/app.js", 5) },
462 { id: 5, parent: 4, callFrame: frame("http://x/assets/lib.js", 0) },
463 ],
464 // 1 ms apart: 10 ms in the app, 10 in the library under it, an idle sample, then
465 // 10 ms in the long task.
466 samples: [...Array(10).fill(4), ...Array(10).fill(5), 1, ...Array(10).fill(3), 1],
467 },
468 timeDeltas: [2_000, ...Array(20).fill(1_000), 178_000, ...Array(10).fill(1_000)],
469 },
470 },
471 },
472 ];
473 const mapper = (url: string, line: number) => {
474 if (url.endsWith("react.js")) return { source: "node_modules/react-dom/index.js", line: 0 };
475 if (url.endsWith("lib.js")) {
476 return { source: "node_modules/.pnpm/x@1/node_modules/@base-ui/react/a.js", line: 0 };
477 }
478 if (url.endsWith("app.js")) return { source: "apps/web/src/Panel.tsx", line: line + 11 };
479 return undefined;
480 };
481
482 it("splits each marked step's input task into forced work and JS by source", () => {
483 const result = analyzeTrace(events, mapper)!;
484 expect(result.profiled).toBe(true);
485 expect(result.callSites).toEqual([{ site: "apps/web/src/Panel.tsx:12", ms: 10, count: 2 }]);
486 const diff = result.steps.find((entry) => entry.label === "switch:diff")!;
487 expect(diff).toMatchObject({
488 windows: 1,
489 inputTaskMs: 20.5,
490 forcedStyleMs: 4,
491 forcedLayoutMs: 6,
492 sampledMs: 20,
493 });
494 expect(diff.selfByPackage).toEqual([
495 { name: "apps/web", ms: 10 },
496 { name: "nm:@base-ui/react", ms: 10 },
497 ]);
498 expect(diff.bySource).toEqual([
499 { name: "apps/web/src/Panel.tsx", ms: 20 },
500 { name: "nm:@base-ui/react/a.js", ms: 10 },
501 ]);
502 expect(diff.byPackage).toEqual([
503 { name: "apps/web", ms: 20 },
504 { name: "nm:@base-ui/react", ms: 10 },
505 ]);
506 expect(diff.longTasks).toEqual([
507 { atMs: 200, ms: 60, top: [{ name: "apps/web/src/Panel.tsx", ms: 10 }] },
508 ]);
509 const key = result.steps.find((entry) => entry.label === "palette:key")!;
510 expect(key).toMatchObject({ inputTaskMs: 5, sampledMs: 0, longTasks: [] });
511 expect(result.steps.map((entry) => entry.label)).toEqual(["switch:diff", "palette:key"]);
512 });
513
514 it("takes the median of each window's forced total", () => {
515 const window = (at: number, style: number, layout: number): ReadonlyArray<TraceEvent> => [
516 { ...main, ph: "R", name: `${MARK_PREFIX}palette:key`, ts: at },
517 { ...main, ph: "X", name: "RunTask", ts: at + 100, dur: 20_000 },
518 {
519 ...main,
520 ph: "X",
521 name: "EventDispatch",
522 ts: at + 200,
523 dur: 1_000,
524 args: { data: { type: "keydown" } },
525 },
526 ...(style > 0
527 ? [
528 {
529 ...main,
530 ph: "X",
531 name: "UpdateLayoutTree",
532 ts: at + 300,
533 dur: style * 1_000,
534 args: { beginData: { stackTrace: stack } },
535 },
536 ]
537 : []),
538 ...(layout > 0
539 ? [
540 {
541 ...main,
542 ph: "X",
543 name: "Layout",
544 ts: at + 300,
545 dur: layout * 1_000,
546 args: { beginData: { stackTrace: stack } },
547 },
548 ]
549 : []),
550 ];
551 const result = analyzeTrace(
552 [events[0]!, ...window(0, 8, 0), ...window(2_000_000, 0, 8), ...window(4_000_000, 0, 0)],
553 mapper,
554 )!;
555 expect(result.steps[0]).toMatchObject({ forcedStyleMs: 0, forcedLayoutMs: 0, forcedMs: 8 });
556 });
557
558 it("counts only long tasks that start after the input task", () => {
559 const result = analyzeTrace(
560 [
561 events[0]!,
562 { ...main, ph: "R", name: `${MARK_PREFIX}palette:key`, ts: 0 },
563 { ...main, ph: "X", name: "RunTask", ts: 100, dur: 60_000 },
564 { ...main, ph: "X", name: "RunTask", ts: 70_000, dur: 5_000 },
565 {
566 ...main,
567 ph: "X",
568 name: "EventDispatch",
569 ts: 70_100,
570 dur: 1_000,
571 args: { data: { type: "keydown" } },
572 },
573 ],
574 mapper,
575 )!;
576 expect(result.steps[0]!.longTasks).toEqual([]);
577 });
578
579 it("never reads a worker's profile as the main thread's", () => {
580 const worker = { pid: main.pid, tid: 9 };
581 const moved = events.map((event) =>
582 event.name === "Profile" || event.name === "ProfileChunk" ? { ...event, ...worker } : event,
583 );
584 const result = analyzeTrace(moved, mapper)!;
585 expect(result.profiled).toBe(false);
586 expect(result.steps[0]!.sampledMs).toBe(0);
587 });
588
589 it("leaves a failed case's windows out of the steps and the call sites", () => {
590 const result = analyzeTrace(events, mapper, { skipCases: new Set(["switch"]) })!;
591 expect(result.callSites).toEqual([]);
592 expect(result.steps.some((entry) => entry.label.startsWith("switch:"))).toBe(false);
593 });
594
595 it("needs a renderer main thread", () => {
596 expect(analyzeTrace(events.slice(1), mapper)).toBeUndefined();
597 });
598});