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

trace.ts

438 lines16.4 KB

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