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

report.ts

372 lines14.6 KB

1// The pure half of mobile-metrics.ts: what one probe window measured, the JSON a run
2// writes, its tables, and the series `compare` and `noise` share with client-metrics.
3import * as Schema from "effect/Schema";
4​
5import { frameStats } from "../../mobile-behavior/grade.ts";
6import { MachineState, median, percentile, round, slope, topCounts } from "../core/report.ts";
7​
8/** One perf window as the probe's `perfStop` returns it (see behavior-probe.ts). */
9export interface PerfWindow {
10 readonly startedAt: number;
11 readonly inputs: ReadonlyArray<{ readonly kind: string; readonly at: number }>;
12 readonly commits: ReadonlyArray<{ readonly at: number; readonly ms: number }>;
13 readonly content: ReadonlyArray<{
14 readonly thread: string;
15 readonly at: number;
16 readonly frameAt: number | null;
17 }>;
18 readonly keys: ReadonlyArray<number>;
19 readonly js: ReadonlyArray<number>;
20 readonly ui: ReadonlyArray<number>;
21 readonly renders: {
22 readonly commits: number;
23 readonly totalRenders: number;
24 readonly components: ReadonlyArray<{ readonly key: string; readonly count: number }>;
25 readonly causes: ReadonlyArray<{ readonly key: string; readonly count: number }>;
26 } | null;
27 readonly heapBytes: number | null;
29​
30const Count = Schema.Struct({ name: Schema.String, count: Schema.Number });
31const Renders = Schema.Struct({
32 commits: Schema.Number,
33 renders: Schema.Number,
34 top: Schema.Array(Count),
35 causes: Schema.Array(Count),
36});
37​
38const Step = Schema.Struct({
39 case: Schema.String,
40 step: Schema.String,
41 /** A thread's first open in this app launch, or a later one; other steps say `step`. */
42 visit: Schema.Literals(["first", "revisit", "step"]),
43 round: Schema.Number,
44 /** Input to the frame after the commit that showed the target thread's rows. */
45 contentMs: Schema.NullOr(Schema.Number),
46 /** Input to the last React commit before the app went quiet. */
47 settledMs: Schema.NullOr(Schema.Number),
48 commits: Schema.Number,
49 /** Render work React timed in those commits (development builds only). */
50 commitMs: Schema.Number,
51 jsDroppedPct: Schema.NullOr(Schema.Number),
52 jsMaxFrameMs: Schema.NullOr(Schema.Number),
53 uiDroppedPct: Schema.NullOr(Schema.Number),
54 uiMaxFrameMs: Schema.NullOr(Schema.Number),
55 /** Composer key to the next JS frame, for typing steps. */
56 keyP50Ms: Schema.NullOr(Schema.Number),
57 keyP90Ms: Schema.NullOr(Schema.Number),
58 renders: Schema.optional(Renders),
59});
60export type Step = typeof Step.Type;
61​
62const Memory = Schema.Struct({
63 label: Schema.String,
64 /** Hermes heap after a collection. */
65 heapMB: Schema.NullOr(Schema.Number),
66 /** The app process's footprint from agent-device (`perf memory sample`). */
67 processMB: Schema.NullOr(Schema.Number),
68});
69export type Memory = typeof Memory.Type;
70​
71/** Memory after each repeat of the switch cases (`--soak`). */
72const SoakSample = Schema.Struct({
73 iteration: Schema.Number,
74 /** The case that just ran; iteration 0 is the sample before the first. */
75 case: Schema.String,
76 heapMB: Schema.NullOr(Schema.Number),
77 processMB: Schema.NullOr(Schema.Number),
78});
79export type SoakSample = typeof SoakSample.Type;
80​
81const Run = Schema.Struct({
82 steps: Schema.Array(Step),
83 memory: Schema.Array(Memory),
84 soak: Schema.optional(Schema.Array(SoakSample)),
85 skipped: Schema.optional(
86 Schema.Array(Schema.Struct({ case: Schema.String, reason: Schema.String })),
87 ),
88 machine: Schema.optional(MachineState),
89});
90export type Run = typeof Run.Type;
91​
92export const MobileMetrics = Schema.Struct({
93 meta: Schema.Record(
94 Schema.String,
95 Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]),
96 ),
97 runs: Schema.Array(Run),
98});
99export type MobileMetrics = typeof MobileMetrics.Type;
100​
101/** Settings that change what shared metrics measure. */
102export const WORKLOAD_KEYS = ["cases", "rounds", "longTurns", "device", "build"] as const;
103/** Settings that change timing without changing the workload. */
104export const PROBE_KEYS = ["renders"] as const;
105​
106/**
107 * Where a tap's latency counts from: the first touch's end, or a native menu item's JS handler
108 * (a tap inside a native menu never reaches JS as a touch), else the touch's start.
109 */
110export function inputAt(window: Pick<PerfWindow, "inputs">) {
111 const end = window.inputs.find(
112 (input) => input.kind === "touch-end" || input.kind === "menu-action",
113 );
114 return (end ?? window.inputs.find((input) => input.kind === "touch-start"))?.at ?? null;
116​
117/**
118 * One step's metrics from its window. `thread` names the thread whose rows count as content;
119 * commits before the input belong to the harness's own calls, so they are left out.
120 */
121export function stepOf(
122 window: PerfWindow,
123 step: Pick<Step, "case" | "step" | "visit" | "round">,
124 thread: string | null,
125): Step {
126 const keyed = window.keys.length > 0;
127 const from = keyed ? window.inputs.find((input) => input.kind === "key")?.at : inputAt(window);
128 const start = from ?? window.startedAt;
129 const commits = window.commits.filter((commit) => commit.at >= start);
130 const shown = thread
131 ? window.content.find((entry) => entry.thread.endsWith(thread) && entry.at >= start)
132 : undefined;
133 const since = (at: number | null | undefined) =>
134 from === undefined || from === null || at === null || at === undefined
135 ? null
136 : round(Math.max(0, at - from), 0);
137 const frames = (timestamps: ReadonlyArray<number>, prefix: "js" | "ui") => {
138 const stats = frameStats(
139 timestamps.filter((at) => at >= start),
140 prefix,
141 );
142 const dropped = stats[`${prefix}DroppedPct`];
143 const max = stats[`${prefix}MaxMs`];
144 return {
145 dropped: typeof dropped === "number" ? dropped : null,
146 max: typeof max === "number" ? max : null,
147 };
148 };
149 const js = frames(window.js, "js");
150 const ui = frames(window.ui, "ui");
151 const keys = window.keys.toSorted((a, b) => a - b);
152 return {
153 ...step,
154 contentMs: since(shown?.frameAt),
155 settledMs: since(commits.at(-1)?.at),
156 commits: commits.length,
157 commitMs: round(
158 commits.reduce((sum, commit) => sum + commit.ms, 0),
159 0,
160 ),
161 jsDroppedPct: js.dropped,
162 jsMaxFrameMs: js.max,
163 uiDroppedPct: ui.dropped,
164 uiMaxFrameMs: ui.max,
165 keyP50Ms: keys.length ? round(median(keys)!, 1) : null,
166 keyP90Ms: keys.length ? round(percentile(keys, 90)!, 1) : null,
167 ...(window.renders
168 ? {
169 renders: {
170 commits: window.renders.commits,
171 renders: window.renders.totalRenders,
172 top: window.renders.components
173 .slice(0, 8)
174 .map(({ key, count }) => ({ name: key, count })),
175 causes: window.renders.causes
176 .slice(0, 8)
177 .map(({ key, count }) => ({ name: key, count })),
178 },
179 }
180 : {}),
181 };
183​
184const NUMERIC = [
185 "contentMs",
186 "settledMs",
187 "commits",
188 "commitMs",
189 "jsDroppedPct",
190 "jsMaxFrameMs",
191 "uiDroppedPct",
192 "uiMaxFrameMs",
193 "keyP50Ms",
194 "keyP90Ms",
195] as const;
196​
197/** Every compared metric, one value per run: the median of the run's samples of it. */
198export function flatten(metrics: MobileMetrics): Map<string, number[]> {
199 const values = new Map<string, number[]>();
200 for (const run of metrics.runs) {
201 const inRun = new Map<string, number[]>();
202 const add = (key: string, value: number | null | undefined) => {
203 if (value === null || value === undefined || !Number.isFinite(value)) return;
204 inRun.set(key, [...(inRun.get(key) ?? []), value]);
205 };
206 for (const entry of run.steps) {
207 const key = `${entry.case}.${entry.step}${entry.visit === "step" ? "" : `.${entry.visit}`}`;
208 for (const field of NUMERIC) add(`${key}.${field}`, entry[field]);
209 add(`${key}.renders`, entry.renders?.renders);
210 }
211 for (const entry of run.memory) {
212 add(`memory.${entry.label}.heapMB`, entry.heapMB);
213 add(`memory.${entry.label}.processMB`, entry.processMB);
214 }
215 if (run.soak && run.soak.length > 2) {
216 const growth = soakGrowth(run.soak);
217 add("soak.heapMBPerIteration", growth.heapMB);
218 add("soak.processMBPerIteration", growth.processMB);
219 }
220 for (const [key, samples] of inRun)
221 values.set(key, [...(values.get(key) ?? []), median(samples)!]);
222 }
223 return values;
225​
226/** Growth per soak iteration past the first (warm-up) sample, and over the last half alone. */
227export function soakGrowth(samples: ReadonlyArray<SoakSample>) {
228 const fit = (rows: ReadonlyArray<SoakSample>, pick: (sample: SoakSample) => number | null) =>
229 slope(
230 rows.flatMap((sample) => {
231 const value = pick(sample);
232 return value === null ? [] : [[sample.iteration, value] as const];
233 }),
234 );
235 // One point per iteration: the sample after its last case.
236 const perIteration = [...new Map(samples.map((sample) => [sample.iteration, sample])).values()];
237 const settled = perIteration.slice(1);
238 const late = perIteration.slice(Math.floor(perIteration.length / 2));
239 return {
240 heapMB: fit(settled, (sample) => sample.heapMB),
241 processMB: fit(settled, (sample) => sample.processMB),
242 lateHeapMB: fit(late, (sample) => sample.heapMB),
243 perIteration,
244 };
246​
247/** Mean Hermes heap change across each case's runs in a soak: which steps grow it. */
248export function soakCaseDeltas(samples: ReadonlyArray<SoakSample>) {
249 const deltas = new Map<string, number[]>();
250 for (let index = 1; index < samples.length; index++) {
251 const before = samples[index - 1]!.heapMB;
252 const after = samples[index]!.heapMB;
253 if (before === null || after === null) continue;
254 const name = samples[index]!.case;
255 deltas.set(name, [...(deltas.get(name) ?? []), after - before]);
256 }
257 return [...deltas].map(([name, values]) => ({
258 case: name,
259 meanMB: values.reduce((sum, value) => sum + value, 0) / values.length,
260 medianMB: median(values)!,
261 }));
263​
264/** Settings two files disagree on, and those one of them did not record. */
265export function workloadDifferences(
266 before: MobileMetrics,
267 after: MobileMetrics,
268 keys: ReadonlyArray<string> = WORKLOAD_KEYS,
269) {
270 const differ: string[] = [];
271 const unrecorded: string[] = [];
272 for (const key of keys) {
273 const a = before.meta[key];
274 const b = after.meta[key];
275 if (a === undefined || b === undefined) {
276 if (a !== b) unrecorded.push(key);
277 } else if (a !== b) differ.push(`${key} ${a} vs ${b}`);
278 }
279 return { differ, unrecorded };
281​
282const cell = (value: number | null | undefined, digits = 0) =>
283 value === null || value === undefined ? "–" : `${round(value, digits)}`;
284const present = (values: ReadonlyArray<number | null>) =>
285 values.filter((value): value is number => value !== null);
286const listOf = (entries: ReadonlyArray<{ readonly name: string; readonly count: number }>) =>
287 entries.map((entry) => `${entry.name} ${entry.count}`).join(", ") || "–";
288​
289/** The run's markdown: per step latency and frames, renders, memory. */
290export function summaryTable(metrics: MobileMetrics) {
291 const steps = metrics.runs.flatMap((run) => run.steps);
292 const lines = [
293 "### Mobile metrics (ms, lower is better)",
294 "",
295 `\`${metrics.meta.commit}\`, ${metrics.runs.length} run(s), ${metrics.meta.device}, ${metrics.meta.build} build`,
296 ];
297 const keys = [
298 ...new Set(steps.map((entry) => `${entry.case}\u0000${entry.step}\u0000${entry.visit}`)),
299 ];
300 if (keys.length > 0) {
301 lines.push(
302 "",
303 "| case | step | visit | n | content p50 | content p90 | settled p50 | settled p90 | commits p50 | commit ms p50 | JS dropped % p50 | JS max frame p50 | UI dropped % p50 | key p50 |",
304 "| :-- | :-- | :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |",
305 );
306 for (const key of keys) {
307 const [name, step, visit] = key.split("\u0000") as [string, string, string];
308 const rows = steps.filter(
309 (entry) => entry.case === name && entry.step === step && entry.visit === visit,
310 );
311 const pick = (field: (typeof NUMERIC)[number]) => present(rows.map((entry) => entry[field]));
312 lines.push(
313 `| ${name} | ${step} | ${visit === "step" ? "" : visit} | ${rows.length} | ${cell(median(pick("contentMs")))} | ${cell(percentile(pick("contentMs"), 90))} | ${cell(median(pick("settledMs")))} | ${cell(percentile(pick("settledMs"), 90))} | ${cell(median(pick("commits")))} | ${cell(median(pick("commitMs")))} | ${cell(median(pick("jsDroppedPct")), 1)} | ${cell(median(pick("jsMaxFrameMs")))} | ${cell(median(pick("uiDroppedPct")), 1)} | ${cell(median(pick("keyP50Ms")), 1)} |`,
314 );
315 }
316 }
317 const rendered = steps.filter((entry) => entry.renders !== undefined);
318 if (rendered.length > 0) {
319 lines.push(
320 "",
321 "| renders per step | n | renders p50 | top components (mean per step) | top causes |",
322 "| :-- | --: | --: | :-- | :-- |",
323 );
324 for (const key of new Set(rendered.map((entry) => `${entry.case}: ${entry.step}`))) {
325 const rows = rendered
326 .filter((entry) => `${entry.case}: ${entry.step}` === key)
327 .map((entry) => entry.renders!);
328 lines.push(
329 `| ${key} | ${rows.length} | ${cell(median(rows.map((entry) => entry.renders)))} | ${listOf(topCounts(rows.map((entry) => entry.top)))} | ${listOf(
330 topCounts(
331 rows.map((entry) => entry.causes),
332 3,
333 ),
334 )} |`,
335 );
336 }
337 }
338 const memory = metrics.runs.flatMap((run) => run.memory);
339 if (memory.length > 0) {
340 lines.push("", "| memory | Hermes heap MB | process MB |", "| :-- | --: | --: |");
341 for (const label of new Set(memory.map((entry) => entry.label))) {
342 const rows = memory.filter((entry) => entry.label === label);
343 lines.push(
344 `| ${label} | ${cell(median(present(rows.map((entry) => entry.heapMB))), 1)} | ${cell(median(present(rows.map((entry) => entry.processMB))), 1)} |`,
345 );
346 }
347 }
348 metrics.runs.forEach((run, index) => {
349 if (!run.soak || run.soak.length < 3) return;
350 const growth = soakGrowth(run.soak);
351 lines.push(
352 "",
353 `| soak, run ${index + 1}: iteration | Hermes heap MB | process MB |`,
354 "| --: | --: | --: |",
355 ...growth.perIteration.map(
356 (sample) =>
357 `| ${sample.iteration} | ${cell(sample.heapMB, 1)} | ${cell(sample.processMB, 1)} |`,
358 ),
359 `| growth per iteration (after warm-up) | ${cell(growth.heapMB, 2)} | ${cell(growth.processMB, 2)} |`,
360 `| growth per iteration (last half) | ${cell(growth.lateHeapMB, 2)} | |`,
361 "",
362 "| soak case | heap change per run, mean MB | median MB |",
363 "| :-- | --: | --: |",
364 ...soakCaseDeltas(run.soak).map(
365 (entry) => `| ${entry.case} | ${cell(entry.meanMB, 2)} | ${cell(entry.medianMB, 2)} |`,
366 ),
367 );
368 });
369 for (const entry of metrics.runs.flatMap((run) => run.skipped ?? []))
370 lines.push("", `Not measured in a round, ${entry.case}: ${entry.reason}`);
371 return lines.join("\n");