Open History to see the last commit
1// What a Chromium trace of client-metrics.ts says about each measured step: the input's
2// task, the style and layout scripts forced inside it, where its JS time went by original source,
3// and the long tasks that followed. Pure, so it is tested on synthetic events.
4import type * as NodeModule from "node:module";
5
6import * as Schema from "effect/Schema";
7
8import { round } from "../core/report.ts";
9
10const StackFrame = Schema.Struct({
11 url: Schema.String,
12 functionName: Schema.optional(Schema.String),
13 lineNumber: Schema.Number,
14 columnNumber: Schema.Number,
15});
16const CallFrame = Schema.Struct({
17 functionName: Schema.optional(Schema.String),
18 url: Schema.optional(Schema.String),
19 /** 0-based, unlike stack trace frames. */
20 lineNumber: Schema.optional(Schema.Number),
21 columnNumber: Schema.optional(Schema.Number),
22});
23const ProfileNode = Schema.Struct({
24 id: Schema.Number,
25 parent: Schema.optional(Schema.Number),
26 callFrame: CallFrame,
27});
28export const TraceEvent = Schema.Struct({
29 name: Schema.optional(Schema.String),
30 cat: Schema.optional(Schema.String),
31 ph: Schema.optional(Schema.String),
32 pid: Schema.optional(Schema.Number),
33 tid: Schema.optional(Schema.Number),
34 ts: Schema.optional(Schema.Number),
35 dur: Schema.optional(Schema.Number),
36 id: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
37 args: Schema.optional(
38 Schema.Struct({
39 name: Schema.optional(Schema.String),
40 data: Schema.optional(
41 Schema.Struct({
42 type: Schema.optional(Schema.String),
43 startTime: Schema.optional(Schema.Number),
44 timeDeltas: Schema.optional(Schema.Array(Schema.Number)),
45 cpuProfile: Schema.optional(
46 Schema.Struct({
47 nodes: Schema.optional(Schema.Array(ProfileNode)),
48 samples: Schema.optional(Schema.Array(Schema.Number)),
49 }),
50 ),
51 }),
52 ),
53 beginData: Schema.optional(
54 Schema.Struct({ stackTrace: Schema.optional(Schema.Array(StackFrame)) }),
55 ),
56 }),
57 ),
58});
59export type TraceEvent = typeof TraceEvent.Type;
60export const Trace = Schema.Union([
61 Schema.Struct({ traceEvents: Schema.Array(TraceEvent) }),
62 Schema.Array(TraceEvent),
63]);
64
65/** Where a 0-based generated position came from, or undefined outside the build's sourcemaps. */
66export type SourceMapper = (
67 url: string,
68 line: number,
69 column: number,
70) => { readonly source: string; readonly line: number } | undefined;
71
72/** A 0-based generated position's original source and line, if the map gives one. */
73export function originalPosition(map: NodeModule.SourceMap, line: number, column: number) {
74 const entry = map.findEntry(line, column);
75 // Node returns an undefined source for a generated-only segment, despite its types.
76 if (!("originalSource" in entry) || entry.originalSource === undefined) return undefined;
77 return { source: entry.originalSource, line: entry.originalLine };
78}
79
80/**
81 * Steps are marked in the page with `performance.mark(MARK_PREFIX + label)` before their input,
82 * and `MARK_PREFIX + END_LABEL` once they settled.
83 */
84export const MARK_PREFIX = "client-metrics:";
85export const END_LABEL = "end";
86/** The longest a step is watched after its mark, when no end mark closes it sooner. */
87export const STEP_WINDOW_MS = 1_500;
88const LONG_TASK_MS = 50;
89const INPUT_EVENTS = new Set(["click", "keydown", "wheel"]);
90/** Every sample sits under these; counting them inclusively says nothing. */
91const WRAPPERS = /^(nm:react-dom|nm:scheduler|\(root\)|\(program\)|\(idle\))/;
92
93const Weighted = Schema.Struct({ name: Schema.String, ms: Schema.Number });
94export type Weighted = typeof Weighted.Type;
95const LongTask = Schema.Struct({
96 /** From the step's mark to the task's start. */
97 atMs: Schema.Number,
98 ms: Schema.Number,
99 top: Schema.Array(Weighted),
100});
101export const TraceStep = Schema.Struct({
102 label: Schema.String,
103 /** Marked windows of this label in the traced round; the times below are per window. */
104 windows: Schema.Number,
105 /** The task that ran the step's first click, keydown or wheel event. */
106 inputTaskMs: Schema.Number,
107 /** Style recalculation and layout a script forced inside the input task. */
108 forcedStyleMs: Schema.Number,
109 forcedLayoutMs: Schema.Number,
110 /** Median of each window's style plus layout, which the two medians above can both miss. */
111 forcedMs: Schema.optional(Schema.Number),
112 /** CPU samples inside the input task. */
113 sampledMs: Schema.Number,
114 /** Self time by package (app package, `nm:` library or V8 bucket); sums to `sampledMs`. */
115 selfByPackage: Schema.Array(Weighted),
116 /** Inclusive time by original source file, each file counted once per sample. */
117 bySource: Schema.Array(Weighted),
118 /** Inclusive time by library, each counted once per sample however deep it nests. */
119 byPackage: Schema.Array(Weighted),
120 /** Tasks over 50 ms after the input task (anywhere in the window without one), with their top sources. */
121 longTasks: Schema.Array(LongTask),
122});
123export type TraceStep = typeof TraceStep.Type;
124export const CallSite = Schema.Struct({
125 site: Schema.String,
126 ms: Schema.Number,
127 count: Schema.Number,
128});
129export type CallSite = typeof CallSite.Type;
130
131/** `nm:react-dom/cjs/x.js` → `nm:react-dom`; `apps/web/src/x.tsx` → `apps/web`. */
132export function packageOf(source: string) {
133 if (source.startsWith("nm:")) {
134 const parts = source.slice(3).split("/");
135 return `nm:${parts[0]?.startsWith("@") ? `${parts[0]}/${parts[1]}` : parts[0]}`;
136 }
137 const match = /^(apps|packages)\/[^/]+/.exec(source);
138 return match ? match[0] : source;
139}
140
141/** A sourcemapped path as a short, stable name: libraries as `nm:<path in the package>`. */
142export function normalizeSource(source: string) {
143 if (source.includes("node_modules/")) {
144 return `nm:${source
145 .split("node_modules/")
146 .pop()!
147 .replace(/^\.pnpm\/[^/]+\/node_modules\//, "")}`;
148 }
149 return source;
150}
151
152interface Thread {
153 readonly events: ReadonlyArray<TraceEvent>;
154 readonly pid: number;
155 readonly tid: number;
156}
157
158/** The renderer main thread with the most events: the page's. */
159function mainThread(events: ReadonlyArray<TraceEvent>): Thread | undefined {
160 const names = new Map<string, string>();
161 const counts = new Map<string, number>();
162 for (const event of events) {
163 const key = `${event.pid}:${event.tid}`;
164 counts.set(key, (counts.get(key) ?? 0) + 1);
165 if (event.ph === "M" && event.name === "thread_name" && event.args?.name !== undefined) {
166 names.set(key, event.args.name);
167 }
168 }
169 const key = [...counts]
170 .filter(([entry]) => names.get(entry) === "CrRendererMain")
171 .toSorted((a, b) => b[1] - a[1])[0]?.[0];
172 if (key === undefined) return undefined;
173 const [pid, tid] = key.split(":").map(Number);
174 return {
175 pid: pid!,
176 tid: tid!,
177 events: events.filter((event) => `${event.pid}:${event.tid}` === key && event.ts !== undefined),
178 };
179}
180
181interface Profile {
182 readonly frames: ReadonlyMap<number, typeof CallFrame.Type>;
183 readonly parents: ReadonlyMap<number, number>;
184 /** [timestamp µs, node id], in time order. */
185 readonly samples: ReadonlyArray<readonly [number, number]>;
186}
187
188/** The main thread's CPU profile, stitched from its chunks; empty without the profiler category. */
189export function cpuProfile(events: ReadonlyArray<TraceEvent>, thread: Thread): Profile {
190 const byId = new Map<string, TraceEvent[]>();
191 for (const event of events) {
192 if (event.pid !== thread.pid || event.id === undefined) continue;
193 if (event.name !== "Profile" && event.name !== "ProfileChunk") continue;
194 const id = String(event.id);
195 byId.set(id, [...(byId.get(id) ?? []), event]);
196 }
197 // A page can have worker profiles too; only one started on the main thread is its.
198 const chunks = [...byId.values()].find((entries) =>
199 entries.some((entry) => entry.name === "Profile" && entry.tid === thread.tid),
200 );
201 const frames = new Map<number, typeof CallFrame.Type>();
202 const parents = new Map<number, number>();
203 const samples: Array<readonly [number, number]> = [];
204 let ts = 0;
205 for (const chunk of chunks ?? []) {
206 const data = chunk.args?.data;
207 if (chunk.name === "Profile") {
208 ts = data?.startTime ?? ts;
209 continue;
210 }
211 for (const node of data?.cpuProfile?.nodes ?? []) {
212 frames.set(node.id, node.callFrame);
213 if (node.parent !== undefined) parents.set(node.id, node.parent);
214 }
215 const deltas = data?.timeDeltas ?? [];
216 (data?.cpuProfile?.samples ?? []).forEach((id, index) => {
217 ts += deltas[index] ?? 0;
218 samples.push([ts, id]);
219 });
220 }
221 samples.sort((a, b) => a[0] - b[0]);
222 return { frames, parents, samples };
223}
224
225const median = (values: ReadonlyArray<number>) => {
226 if (values.length === 0) return 0;
227 const sorted = values.toSorted((a, b) => a - b);
228 const middle = Math.floor(sorted.length / 2);
229 return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
230};
231
232const top = (totals: ReadonlyMap<string, number>, count: number, per = 1): Weighted[] =>
233 [...totals]
234 .toSorted((a, b) => b[1] - a[1])
235 .slice(0, count)
236 .map(([name, ms]) => ({ name, ms: round(ms / per, 1) }));
237
238const add = (totals: Map<string, number>, key: string, ms: number) =>
239 totals.set(key, (totals.get(key) ?? 0) + ms);
240
241/**
242 * Each marked step's input task, forced style/layout, CPU by source and later long tasks, plus the
243 * top forced call sites. Style or layout with a JS stack was forced mid-task. `skipCases` windows
244 * (label before the colon) still bound their neighbours but count nowhere.
245 */
246export function analyzeTrace(
247 events: ReadonlyArray<TraceEvent>,
248 mapper: SourceMapper,
249 options: {
250 readonly topSites?: number;
251 readonly topEntries?: number;
252 readonly skipCases?: ReadonlySet<string>;
253 } = {},
254) {
255 const thread = mainThread(events);
256 if (thread === undefined) return undefined;
257 const topEntries = options.topEntries ?? 8;
258 const onMain = thread.events;
259 const profile = cpuProfile(events, thread);
260 const labelCache = new Map<number, string>();
261 const sourceOf = (id: number) => {
262 const cached = labelCache.get(id);
263 if (cached !== undefined) return cached;
264 const frame = profile.frames.get(id);
265 let label = `(${frame?.functionName || "native"})`.replace(/^\(\((.*)\)\)$/, "($1)");
266 if (frame?.url) {
267 const mapped = mapper(frame.url, frame.lineNumber ?? 0, frame.columnNumber ?? 0);
268 label = mapped
269 ? normalizeSource(mapped.source)
270 : `(unmapped) ${frame.url.split("/").pop()?.split("?")[0]}`;
271 }
272 labelCache.set(id, label);
273 return label;
274 };
275 const sampleWeights = (start: number, end: number) => {
276 const out: Array<readonly [number, number]> = [];
277 const { samples } = profile;
278 let low = 0;
279 let high = samples.length;
280 while (low < high) {
281 const middle = (low + high) >> 1;
282 if (samples[middle]![0] < start) low = middle + 1;
283 else high = middle;
284 }
285 for (let index = low; index < samples.length - 1; index++) {
286 const [ts, id] = samples[index]!;
287 if (ts > end) break;
288 out.push([id, Math.min(samples[index + 1]![0] - ts, 2_000) / 1_000]);
289 }
290 return out;
291 };
292 const stackOf = (id: number) => {
293 const stack: string[] = [];
294 for (let node: number | undefined = id; node !== undefined; node = profile.parents.get(node)) {
295 stack.push(sourceOf(node));
296 }
297 return stack;
298 };
299
300 const marks = new Map<string, { label: string; ts: number }>();
301 for (const event of onMain) {
302 if (!event.name?.startsWith(MARK_PREFIX)) continue;
303 marks.set(`${event.name}@${event.ts}`, {
304 label: event.name.slice(MARK_PREFIX.length),
305 ts: event.ts!,
306 });
307 }
308 const ordered = [...marks.values()].toSorted((a, b) => a.ts - b.ts);
309 const starts = ordered.filter(
310 (mark) => mark.label !== END_LABEL && !options.skipCases?.has(mark.label.split(":")[0]!),
311 );
312 const tasks = onMain.filter((event) => event.name === "RunTask" && event.ph === "X");
313 const taskAt = (at: number) =>
314 tasks.find((task) => task.ts! <= at && task.ts! + (task.dur ?? 0) >= at);
315 const sites = new Map<string, { ms: number; count: number }>();
316
317 interface Window {
318 inputTaskMs: number;
319 style: number;
320 layout: number;
321 sampled: number;
322 self: Map<string, number>;
323 bySource: Map<string, number>;
324 byPackage: Map<string, number>;
325 longTasks: Array<typeof LongTask.Type>;
326 }
327 const windows = new Map<string, Window[]>();
328 for (const mark of starts) {
329 const next = ordered.find((candidate) => candidate.ts > mark.ts);
330 const end = Math.min(next?.ts ?? Infinity, mark.ts + STEP_WINDOW_MS * 1_000);
331 const input = onMain.find(
332 (event) =>
333 event.name === "EventDispatch" &&
334 event.ts! >= mark.ts &&
335 event.ts! < end &&
336 INPUT_EVENTS.has(event.args?.data?.type ?? ""),
337 );
338 const task = input === undefined ? undefined : taskAt(input.ts!);
339 const window: Window = {
340 inputTaskMs: 0,
341 style: 0,
342 layout: 0,
343 sampled: 0,
344 self: new Map(),
345 bySource: new Map(),
346 byPackage: new Map(),
347 longTasks: [],
348 };
349 if (task !== undefined) {
350 const start = task.ts!;
351 const stop = start + (task.dur ?? 0);
352 window.inputTaskMs = (task.dur ?? 0) / 1_000;
353 for (const event of onMain) {
354 if (event.ph !== "X" || event.ts! < start || event.ts! > stop) continue;
355 if (event.name !== "UpdateLayoutTree" && event.name !== "Layout") continue;
356 // Frames without a URL are the harness's own injected scripts (Playwright's hit tests).
357 const stack = event.args?.beginData?.stackTrace ?? [];
358 if (!stack.some((frame) => frame.url !== "")) continue;
359 const ms = (event.dur ?? 0) / 1_000;
360 if (event.name === "Layout") window.layout += ms;
361 else window.style += ms;
362 const site =
363 stack
364 .slice(0, 6)
365 .map((frame) => {
366 const mapped = mapper(frame.url, frame.lineNumber - 1, frame.columnNumber - 1);
367 return mapped
368 ? `${normalizeSource(mapped.source)}:${mapped.line + 1}`
369 : `${frame.functionName || "(anonymous)"}@${frame.url.split("/").pop()}`;
370 })
371 .filter((entry, position, all) => all.indexOf(entry) === position)
372 .slice(0, 3)
373 .join(" < ") || "(frame)";
374 const current = sites.get(site) ?? { ms: 0, count: 0 };
375 sites.set(site, { ms: current.ms + ms, count: current.count + 1 });
376 }
377 for (const [id, ms] of sampleWeights(start, stop)) {
378 window.sampled += ms;
379 const stack = stackOf(id);
380 add(window.self, packageOf(stack[0]!), ms);
381 for (const source of new Set(stack)) {
382 if (!WRAPPERS.test(source)) add(window.bySource, source, ms);
383 }
384 for (const name of new Set(stack.map(packageOf))) {
385 if (!WRAPPERS.test(name)) add(window.byPackage, name, ms);
386 }
387 }
388 }
389 const after = task === undefined ? mark.ts : task.ts! + (task.dur ?? 0);
390 for (const later of tasks) {
391 if (later === task || later.ts! < after || later.ts! >= end) continue;
392 if ((later.dur ?? 0) / 1_000 < LONG_TASK_MS) continue;
393 const totals = new Map<string, number>();
394 for (const [id, ms] of sampleWeights(later.ts!, later.ts! + (later.dur ?? 0))) {
395 for (const source of new Set(stackOf(id))) {
396 if (!WRAPPERS.test(source)) add(totals, source, ms);
397 }
398 }
399 window.longTasks.push({
400 atMs: round((later.ts! - mark.ts) / 1_000, 0),
401 ms: round((later.dur ?? 0) / 1_000, 1),
402 top: top(totals, 4),
403 });
404 }
405 windows.set(mark.label, [...(windows.get(mark.label) ?? []), window]);
406 }
407
408 const steps: TraceStep[] = [...windows].map(([label, entries]) => {
409 const merged = (pick: (window: Window) => Map<string, number>) => {
410 const totals = new Map<string, number>();
411 for (const window of entries) for (const [key, ms] of pick(window)) add(totals, key, ms);
412 return totals;
413 };
414 return {
415 label,
416 windows: entries.length,
417 inputTaskMs: round(median(entries.map((entry) => entry.inputTaskMs)), 1),
418 forcedStyleMs: round(median(entries.map((entry) => entry.style)), 1),
419 forcedLayoutMs: round(median(entries.map((entry) => entry.layout)), 1),
420 forcedMs: round(median(entries.map((entry) => entry.style + entry.layout)), 1),
421 sampledMs: round(median(entries.map((entry) => entry.sampled)), 1),
422 selfByPackage: top(
423 merged((window) => window.self),
424 topEntries,
425 entries.length,
426 ),
427 bySource: top(
428 merged((window) => window.bySource),
429 topEntries,
430 entries.length,
431 ),
432 byPackage: top(
433 merged((window) => window.byPackage),
434 topEntries,
435 entries.length,
436 ),
437 longTasks: entries
438 .flatMap((entry) => entry.longTasks)
439 .toSorted((a, b) => b.ms - a.ms)
440 .slice(0, 3),
441 };
442 });
443 const callSites: CallSite[] = [...sites]
444 .toSorted((a, b) => b[1].ms - a[1].ms)
445 .slice(0, options.topSites ?? 12)
446 .map(([site, { ms, count }]) => ({ site, ms: round(ms, 1), count }));
447 return { steps, callSites, profiled: profile.samples.length > 0 };
448}