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

report.ts

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