ostia 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,49 +1,64 @@
1
- import { formatDuration, pickDurationUnit } from "../format.ts";
1
+ // The human format, for a person at a terminal: the verdict first, a dim
2
+ // line of context, the table, then a closing line that says what ran and
3
+ // what it cost. Color comes from `paint`, which the CLI gives only to a
4
+ // terminal no coding agent reads.
5
+
6
+ import { isAbsolute, relative } from "node:path";
7
+
8
+ import type { Unpaired } from "../ab/unpaired.ts";
2
9
  import { cpuSampleCount } from "../ir/cpu.ts";
3
10
  import type {
4
11
  AbSummary,
12
+ ComparedTask,
13
+ Comparison,
14
+ GitMetadata,
15
+ Measurement,
5
16
  ProfileDocument,
6
- Warning,
7
17
  Workload,
8
18
  } from "../ir/types.ts";
19
+ import { comparable, metricRatios } from "../measure/paired.ts";
9
20
  import {
10
- cpuTimes,
11
- formatCpuTimes,
12
- formatEnvironmentLine,
13
- formatHeapSummary,
14
- formatInstructions,
15
- formatNsAsMs,
16
- formatRelative,
17
- formatShellLine,
18
- formatSignedPct,
19
- formatSpan,
20
- formatUsAsMs,
21
- labelOrId,
22
- topSelfFrames,
23
- workloadLabel,
24
- } from "./format.ts";
21
+ branch,
22
+ closingLine,
23
+ failLine,
24
+ headerRow,
25
+ MEASURE,
26
+ MISSING,
27
+ type Paint,
28
+ PLAIN,
29
+ plural,
30
+ SEPARATOR,
31
+ textWidth,
32
+ truncatePath,
33
+ truncateWords,
34
+ } from "../terminal.ts";
35
+ import { cpuTimes, labelOrId, topSelfFrames, workloadLabel } from "./format.ts";
25
36
  import {
26
- abNotes,
27
- abRows,
28
- alsoHeader,
29
- formatAbHeader,
30
- formatAbSummary,
31
- formatNewSuites,
32
- formatThrew,
33
- memoryCells,
34
- memoryRows,
35
- pairedCells,
36
- } from "./paired.ts";
37
- import {
38
- groupOf,
39
- labelInGroup,
40
- relativeRatios,
41
- type TimingRow,
42
- } from "./relative.ts";
37
+ contextLines,
38
+ environmentParts,
39
+ fittedParts,
40
+ medianAbsoluteDeviation,
41
+ type NamedRow,
42
+ namedTable,
43
+ type Note,
44
+ noteLines,
45
+ numberIn,
46
+ RUN_WARNINGS,
47
+ toBytes,
48
+ toChange,
49
+ toCount,
50
+ toDuration,
51
+ toElapsed,
52
+ toNoise,
53
+ toShare,
54
+ toTimes,
55
+ toWarningNote,
56
+ } from "./human.ts";
57
+ import { abNotes, abRows, formatThrew, type PairedRun } from "./paired.ts";
58
+ import { groupOf, labelInGroup, relativeRatios } from "./relative.ts";
43
59
  import {
44
60
  comparedRows,
45
61
  environmentMismatch,
46
- memoryColumns,
47
62
  memoryReadings,
48
63
  noSampleRuns,
49
64
  oneSidedNote,
@@ -51,9 +66,7 @@ import {
51
66
  runWarnings,
52
67
  shownFrameDeltas,
53
68
  shownHeapDeltas,
54
- shownMemoryDeltas,
55
- skippedWorkloads,
56
- thresholdNote,
69
+ type TimingRun,
57
70
  timingRuns,
58
71
  workloadsById,
59
72
  } from "./select.ts";
@@ -61,413 +74,1192 @@ import type { Renderer, RenderResult } from "./types.ts";
61
74
 
62
75
  const TOP_FRAMES = 5;
63
76
  const TOP_TYPES = 5;
64
- const MIN_MEMORY_WIDTH = 10;
65
-
66
- interface Column<R> {
67
- header: string;
68
- width: number;
69
- cell: (data: R) => string;
70
- }
71
-
72
- interface TableRow<R> {
73
- label: string;
74
- group?: string | undefined;
75
- /** Absent when there is nothing to tabulate; `status` says why. */
76
- data?: R;
77
- /** The row's text when `data` is absent: `skipped` or `no samples`. */
78
- status?: string;
79
- warnings: Warning[];
80
- }
81
-
82
- function textTable<R>(columns: Column<R>[], rows: TableRow<R>[]): string[] {
83
- const indentOf = (row: TableRow<R>) => (row.group !== undefined ? " " : "");
84
- const shown = (row: TableRow<R>) => labelInGroup(row.label, row.group);
85
- let labelWidth = 4;
86
- for (const r of rows) {
87
- labelWidth = Math.max(labelWidth, indentOf(r).length + shown(r).length);
88
- }
89
- const header = `${"Task".padEnd(labelWidth)} ${columns.map((c) => c.header.padEnd(c.width)).join(" ")}`;
90
- const lines = [header, "-".repeat(header.length)];
91
- let lastGroup: string | undefined;
92
- for (const row of rows) {
93
- if (row.group !== undefined && row.group !== lastGroup) {
94
- lines.push(`${row.group}:`);
95
- }
96
- lastGroup = row.group;
97
- const indent = indentOf(row);
98
- const label = (indent + shown(row)).padEnd(labelWidth);
99
- const data = row.data;
100
- lines.push(
101
- data === undefined
102
- ? `${label} - ${row.status}`
103
- : `${label} ${columns.map((c) => c.cell(data).padEnd(c.width)).join(" ")}`,
104
- );
105
- if (row.warnings.length > 0) {
106
- lines.push(`${indent} ! ${row.warnings.map((w) => w.code).join(", ")}`);
107
- }
108
- }
109
- return lines;
110
- }
77
+ // The longest a name may run in a verdict line, so two fit on one line;
78
+ // a line that names one gives it more.
79
+ const VERDICT_NAME_WIDTH = 30;
80
+ const VERDICT_ONE_NAME_WIDTH = 40;
81
+ // Heap readings move with GC timing, so a small change is noise, not
82
+ // a note.
83
+ const MIN_MEMORY_NOTE_PCT = 10;
111
84
 
112
- function warningFootnotes(rows: TableRow<unknown>[]): string[] {
113
- const lines = rows.flatMap((row) =>
114
- row.warnings.map((w) => ` ${row.label}: ${w.message}`),
115
- );
116
- return lines.length > 0 ? ["", "Warnings:", ...lines] : [];
85
+ /** What the table renderer needs beyond the document, all optional. */
86
+ export interface TableOptions {
87
+ /** Color; plain when absent, as for a pipe or a file. */
88
+ paint?: Paint;
89
+ /** What was run (suite files), for the context line. */
90
+ ran?: string;
91
+ /** The command's wall time, for the closing line. */
92
+ elapsedMs?: number;
93
+ /** `compare`: where its thresholds came from, and each side's git state. */
94
+ compare?: {
95
+ thresholds: string;
96
+ baseGit?: GitMetadata | undefined;
97
+ candGit?: GitMetadata | undefined;
98
+ };
99
+ /** `ab` that paired nothing: each side's task count, and why. */
100
+ unpaired?: Unpaired;
101
+ /** `ci`: the baseline it gated against, and what the cache saved. */
102
+ ci?: {
103
+ baseline: string;
104
+ workloads: number;
105
+ cached: number;
106
+ executed: number;
107
+ /** Workloads that failed to measure. */
108
+ failed: readonly string[];
109
+ missingBaseline: number;
110
+ };
117
111
  }
118
112
 
119
- function finish(lines: string[]): RenderResult {
120
- return { text: `${lines.map((l) => l.trimEnd()).join("\n")}\n` };
113
+ interface Report {
114
+ verdict: string;
115
+ context: string[];
116
+ /** The table, then any further blocks, each set off by a blank line. */
117
+ blocks: string[][];
118
+ closing: string;
121
119
  }
122
120
 
123
- export const terminalRenderer: Renderer = {
121
+ export const terminalRenderer: Renderer<TableOptions> = {
124
122
  name: "table",
125
- render(doc: ProfileDocument): Promise<RenderResult> {
123
+ render(doc: ProfileDocument, options: TableOptions): Promise<RenderResult> {
126
124
  return Promise.try(() => {
127
- const env = [
128
- ...(doc.environment ? [formatEnvironmentLine(doc.environment)] : []),
129
- ...(doc.shell ? [formatShellLine(doc.shell)] : []),
125
+ const report = toReport(doc, options, options.paint ?? PLAIN);
126
+ if (!report) return { text: "nothing measured\n" };
127
+ const instrumented = instrumentedBlocks(doc, options.paint ?? PLAIN);
128
+ const blocks = [...report.blocks, ...instrumented].filter(
129
+ (block) => block.length > 0,
130
+ );
131
+ const lines = [
132
+ report.verdict,
133
+ ...report.context,
134
+ ...blocks.flatMap((block) => ["", ...block]),
135
+ "",
136
+ report.closing,
130
137
  ];
131
- if (env.length > 0) env.push("");
132
-
133
- // Only `ab()` writes paired measurements, and it always stamps `ab`.
134
- if (doc.ab) return finish(renderPaired(doc, doc.ab, env));
135
-
136
- const runs = timingRuns(doc);
137
- const empty = noSampleRuns(doc);
138
- const comparisons = renderComparisons(doc);
139
- if (
140
- runs.length === 0 &&
141
- empty.length === 0 &&
142
- skippedWorkloads(doc, runs).length === 0
143
- ) {
144
- return comparisons.length > 0
145
- ? finish([...env, ...comparisons])
146
- : { text: "(no timing runs)\n" };
147
- }
148
-
149
- const lines = [...env, ...renderTiming(doc, runs, empty)];
150
- const instrumented = renderInstrumentedRuns(doc);
151
- if (instrumented.length > 0) lines.push("", ...instrumented);
152
- if (comparisons.length > 0) lines.push("", ...comparisons);
153
- return finish(lines);
138
+ return { text: `${lines.map((l) => l.trimEnd()).join("\n")}\n` };
154
139
  });
155
140
  },
156
141
  };
157
142
 
158
- function renderTiming(
143
+ function toReport(
159
144
  doc: ProfileDocument,
160
- runs: ReturnType<typeof timingRuns>,
161
- noSamples: ReturnType<typeof noSampleRuns>,
162
- ): string[] {
163
- const memory = memoryReadings(doc);
164
- const runByWorkloadId = new Map(runs.map((r) => [r.workloadId, r]));
165
- const noSampleByWorkloadId = new Map(noSamples.map((r) => [r.workloadId, r]));
166
-
167
- // doc.workloads order, so a skipped task prints in its group's place.
168
- const rows: TableRow<TimingRow>[] = [];
169
- const measured: TimingRow[] = [];
170
- for (const workload of doc.workloads) {
171
- const run = runByWorkloadId.get(workload.id);
172
- const label = workloadLabel(workload);
173
- const group = groupOf(workload);
174
- const noSample = noSampleByWorkloadId.get(workload.id);
175
- if (run) {
176
- const data = { run, workload };
177
- measured.push(data);
178
- rows.push({ label, group, data, warnings: runWarnings(run, memory) });
179
- } else if (noSample) {
180
- const warnings = runWarnings(noSample, memory);
181
- rows.push({ label, group, status: "no samples", warnings });
182
- } else if (workload.skipped) {
183
- rows.push({ label, group, status: "skipped", warnings: [] });
145
+ options: TableOptions,
146
+ paint: Paint,
147
+ ): Report | undefined {
148
+ // Only `ab()` writes paired measurements, and it always stamps `ab`.
149
+ if (doc.ab) return pairedReport(doc, doc.ab, options, paint);
150
+ if (options.ci || options.compare || comparedRows(doc).length > 0) {
151
+ return comparisonReport(doc, options, paint);
152
+ }
153
+ const rows = timingRows(doc);
154
+ if (rows.length > 0) return timingReport(doc, rows, options, paint);
155
+ if (doc.measurements.length > 0) return instrumentedReport(doc, paint);
156
+ return undefined;
157
+ }
158
+
159
+ // A failure's closing line, with the next step after it when the two fit
160
+ // 80 columns, else on a dim line of its own, whole, since a command cut
161
+ // short can't be pasted.
162
+ function failWith(paint: Paint, what: string, next: string): string {
163
+ const line = failLine(paint, what, next);
164
+ if (textWidth(line) <= MEASURE) return line;
165
+ return [failLine(paint, what), ...wrapWords(next, MEASURE - 2)]
166
+ .map((text, i) => (i === 0 ? text : paint.dim(` ${text}`)))
167
+ .join("\n");
168
+ }
169
+
170
+ // Lines of at most `width` columns, broken between words, so a long next
171
+ // step stays inside the measure instead of running off it.
172
+ function wrapWords(text: string, width: number): string[] {
173
+ const lines: string[] = [];
174
+ let line = "";
175
+ for (const word of text.split(" ")) {
176
+ if (line !== "" && textWidth(`${line} ${word}`) > width) {
177
+ lines.push(line);
178
+ line = word;
179
+ } else {
180
+ line = line === "" ? word : `${line} ${word}`;
184
181
  }
185
182
  }
183
+ return line === "" ? lines : [...lines, line];
184
+ }
185
+
186
+ const elapsedPart = (options: TableOptions) =>
187
+ options.elapsedMs === undefined ? "" : ` in ${toElapsed(options.elapsedMs)}`;
186
188
 
187
- const unitOf = ({ run }: TimingRow) => pickDurationUnit(run.timing.median);
188
- const cpuTimesByRow = new Map(
189
- measured.map((row) => [row, cpuTimes(row.run)]),
189
+ const shortName = (name: string, width = VERDICT_NAME_WIDTH) =>
190
+ truncateWords(name, width);
191
+
192
+ // Once each, under the table, since they're about the machine or the run,
193
+ // not any one row.
194
+ function runNotes(doc: ProfileDocument, paint: Paint): string[] {
195
+ const seen = new Set<string>();
196
+ const notes: string[] = [];
197
+ for (const m of doc.measurements) {
198
+ for (const w of m.warnings) {
199
+ if (!RUN_WARNINGS.has(w.code) || w.code === "aborted") continue;
200
+ if (seen.has(w.code)) continue;
201
+ seen.add(w.code);
202
+ notes.push(...noteLines(toWarningNote(w), " ", paint));
203
+ }
204
+ }
205
+ return notes;
206
+ }
207
+
208
+ const isAborted = (doc: ProfileDocument) =>
209
+ doc.measurements.some((m) => m.warnings.some((w) => w.code === "aborted"));
210
+
211
+ // A row's place in its group, so the group's label prints once, above
212
+ // its first row, and its last row closes it with └.
213
+ function grouped<T extends { group: string | undefined }>(
214
+ items: readonly T[],
215
+ ): { item: T; branch: string; label?: string }[] {
216
+ return items.map((item, i) => {
217
+ if (item.group === undefined) return { item, branch: "" };
218
+ let start = i;
219
+ while (start > 0 && items[start - 1]?.group === item.group) start--;
220
+ let end = i;
221
+ while (end < items.length - 1 && items[end + 1]?.group === item.group) {
222
+ end++;
223
+ }
224
+ return {
225
+ item,
226
+ branch: branch(i - start, end - start + 1),
227
+ ...(i === start && { label: item.group }),
228
+ };
229
+ });
230
+ }
231
+
232
+ // A group's label prints once, above its first task, so its rows can
233
+ // drop the group from their names.
234
+ function withGroupLabels(
235
+ rows: { branch: string; label?: string; row: NamedRow }[],
236
+ columns: number,
237
+ ): NamedRow[] {
238
+ return rows.flatMap(({ label, row }) =>
239
+ label === undefined
240
+ ? [row]
241
+ : [
242
+ {
243
+ branch: "",
244
+ name: label,
245
+ bold: true,
246
+ cells: Array.from({ length: columns }, () => ""),
247
+ },
248
+ row,
249
+ ],
250
+ );
251
+ }
252
+
253
+ const relativeFile = (file: string) =>
254
+ isAbsolute(file) ? relative(process.cwd(), file) : file;
255
+
256
+ // --filter takes a regex, so a task's name matches as written.
257
+ const filterFor = (label: string) =>
258
+ `'${label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/'/g, "'\\''")}'`;
259
+
260
+ // The suite a task came from, so the next step is a command a person
261
+ // can paste.
262
+ const suiteOf = (workload: Workload | undefined) =>
263
+ workload?.entry ? ` ${relativeFile(workload.entry.file)}` : "";
264
+
265
+ // --- time and bench ---
266
+
267
+ interface TimingRowItem {
268
+ workload: Workload;
269
+ group: string | undefined;
270
+ run?: TimingRun;
271
+ /** A run whose every trial failed, timed out or missed `timeSource`. */
272
+ empty?: Measurement;
273
+ }
274
+
275
+ function timingRows(doc: ProfileDocument): TimingRowItem[] {
276
+ const runs = new Map(timingRuns(doc).map((r) => [r.workloadId, r]));
277
+ const empty = new Map(noSampleRuns(doc).map((r) => [r.workloadId, r]));
278
+ // Workload order, so a skipped task prints in its group's place.
279
+ return doc.workloads.flatMap((workload): TimingRowItem[] => {
280
+ const run = runs.get(workload.id);
281
+ const none = empty.get(workload.id);
282
+ const group = groupOf(workload);
283
+ if (run) return [{ workload, group, run }];
284
+ if (none) return [{ workload, group, empty: none }];
285
+ if (workload.skipped) return [{ workload, group }];
286
+ return [];
287
+ });
288
+ }
289
+
290
+ const isFailedRow = (row: TimingRowItem) =>
291
+ row.empty !== undefined ||
292
+ (row.run?.warnings.some((w) => w.code === "nonzero-exit") ?? false);
293
+
294
+ function timingReport(
295
+ doc: ProfileDocument,
296
+ rows: TimingRowItem[],
297
+ options: TableOptions,
298
+ paint: Paint,
299
+ ): Report {
300
+ const commands = doc.workloads.every((w) => w.kind === "subprocess");
301
+ const noun = commands ? "command" : "task";
302
+ const memory = memoryReadings(doc);
303
+ const measured = rows.flatMap((row) =>
304
+ row.run ? [{ ...row, run: row.run }] : [],
190
305
  );
191
306
  const ratios = relativeRatios(measured);
307
+ const ratioById = new Map(
308
+ [...(ratios ?? [])].map(([row, ratio]) => [row.workload.id, ratio]),
309
+ );
310
+ const times = new Map(
311
+ measured.map((row) => [row.workload.id, cpuTimes(row.run)]),
312
+ );
313
+ const hasTimes = [...times.values()].some(Boolean);
314
+ const hasInstructions = measured.some((row) => row.run.instructions);
315
+ const hasRetained = [...memory.values()].some(
316
+ (r) => r.retained !== undefined,
317
+ );
318
+ const hasPeak = [...memory.values()].some((r) => r.peak !== undefined);
319
+ const hasBaseline = measured.some((row) => row.workload.baseline);
192
320
 
193
- const columns: Column<TimingRow>[] = [
194
- {
195
- header: "Median",
196
- width: 10,
197
- cell: (row) => formatDuration(row.run.timing.median, unitOf(row)),
198
- },
199
- {
200
- header: "Spread",
201
- width: 18,
202
- cell: (row) =>
203
- formatSpan(row.run.timing.p75, row.run.timing.p99, unitOf(row)),
204
- },
205
- {
206
- header: "Range",
207
- width: 18,
208
- cell: (row) =>
209
- formatSpan(row.run.timing.min, row.run.timing.max, unitOf(row)),
210
- },
321
+ const header = [
322
+ noun,
323
+ "median",
324
+ "noise",
325
+ ...(hasTimes ? ["user", "sys"] : []),
326
+ ...(hasInstructions ? ["instr/call"] : []),
327
+ ...(hasRetained ? ["retained/op"] : []),
328
+ ...(hasPeak ? ["peak mem"] : []),
329
+ ...(ratios ? [hasBaseline ? "vs baseline" : "vs fastest"] : []),
211
330
  ];
212
- if ([...cpuTimesByRow.values()].some(Boolean)) {
213
- columns.push({
214
- header: "User/Sys",
215
- width: 18,
216
- cell: (row) => {
217
- const times = cpuTimesByRow.get(row);
218
- return times ? formatCpuTimes(times) : "";
219
- },
220
- });
331
+
332
+ let warnings = 0;
333
+ const named = grouped(rows).map(({ item: row, branch, label }) => {
334
+ const name = labelInGroup(workloadLabel(row.workload), row.group);
335
+ const run = row.run;
336
+ const readings = memory.get(row.workload.id);
337
+ const blanks = header.length - 2;
338
+ const status = run
339
+ ? undefined
340
+ : row.empty
341
+ ? paint.bad("no samples")
342
+ : paint.dim("skipped");
343
+ const cells = run
344
+ ? [
345
+ toDuration(run.timing.median),
346
+ paint.dim(toNoise(run.timing.mad, run.timing.median)),
347
+ ...(hasTimes ? timesCells(times.get(row.workload.id)) : []),
348
+ ...(hasInstructions
349
+ ? [run.instructions ? toCount(run.instructions.median) : ""]
350
+ : []),
351
+ ...(hasRetained
352
+ ? [
353
+ readings?.retained === undefined
354
+ ? ""
355
+ : toBytes(readings.retained),
356
+ ]
357
+ : []),
358
+ ...(hasPeak
359
+ ? [readings?.peak === undefined ? "" : toBytes(readings.peak)]
360
+ : []),
361
+ ...(ratios
362
+ ? [ratioCell(ratioById.get(row.workload.id), row.workload, paint)]
363
+ : []),
364
+ ]
365
+ : [status ?? "", ...Array.from({ length: blanks }, () => "")];
366
+ const source = run ?? row.empty;
367
+ const notes: Note[] = source
368
+ ? runWarnings(source, memory)
369
+ .filter((w) => !RUN_WARNINGS.has(w.code))
370
+ .map((w) => toWarningNote(w, run?.timing))
371
+ : [];
372
+ warnings += notes.filter((n) => n.tone !== "dim").length;
373
+ return {
374
+ branch,
375
+ ...(label !== undefined && { label }),
376
+ row: { branch, name, cells, notes },
377
+ };
378
+ });
379
+
380
+ const failedCount = rows.filter(isFailedRow).length;
381
+ const run = runNotes(doc, paint);
382
+ warnings += run.length;
383
+ const table = namedTable(
384
+ headerRow(paint, header),
385
+ withGroupLabels(named, header.length - 1),
386
+ header.map((_, i) => i).slice(1),
387
+ paint,
388
+ );
389
+ return {
390
+ // A failed run's timings aren't the answer, so the failure leads.
391
+ verdict:
392
+ failedCount > 0
393
+ ? paint.bad(`${failedCount} of ${plural(rows.length, noun)} failed`)
394
+ : commands
395
+ ? timeVerdict(measured, rows.length, paint)
396
+ : benchVerdict(measured, rows.length, warnings, paint),
397
+ context: contextLines(
398
+ [
399
+ ...environmentParts(doc.environment),
400
+ ...(doc.shell
401
+ ? [
402
+ `${doc.shell.command} -c adds ${toDuration(doc.shell.startupNs)} to each`,
403
+ ]
404
+ : []),
405
+ options.ran ?? (commands ? runsPart(measured) : ""),
406
+ ],
407
+ paint,
408
+ ),
409
+ blocks: [table, run],
410
+ closing: timingClosing(doc, rows, measured, noun, options, paint),
411
+ };
412
+ }
413
+
414
+ function timesCells(
415
+ times: { userNs: number; systemNs: number } | undefined,
416
+ ): string[] {
417
+ return times
418
+ ? [toDuration(times.userNs), toDuration(times.systemNs)]
419
+ : ["", ""];
420
+ }
421
+
422
+ // The reference row says what it is, dim; a faster row says so, since a
423
+ // bare ratio under 1 reads as slower.
424
+ function ratioCell(
425
+ ratio: number | undefined,
426
+ workload: Workload,
427
+ paint: Paint,
428
+ ): string {
429
+ if (ratio === undefined) return "";
430
+ if (workload.baseline) return paint.dim("baseline");
431
+ if (ratio === 1) return paint.dim("fastest");
432
+ return ratio < 1 ? `${toTimes(1 / ratio)} faster` : toTimes(ratio);
433
+ }
434
+
435
+ function runsPart(measured: readonly { run: TimingRun }[]): string {
436
+ const counts = measured.map((row) => row.run.trials.length);
437
+ if (counts.length === 0) return "";
438
+ const least = Math.min(...counts);
439
+ const most = Math.max(...counts);
440
+ if (least === most) {
441
+ return counts.length === 1
442
+ ? `median of ${plural(least, "run")}`
443
+ : `median of ${plural(least, "run")} each`;
221
444
  }
222
- if (measured.some((row) => row.run.instructions)) {
223
- columns.push({
224
- header: "Instr/call",
225
- width: 10,
226
- cell: (row) =>
227
- row.run.instructions
228
- ? formatInstructions(row.run.instructions.median)
229
- : "",
230
- });
445
+ return `median of ${least} to ${most} runs`;
446
+ }
447
+
448
+ type MeasuredRow = TimingRowItem & { run: TimingRun };
449
+
450
+ const nameOf = (row: MeasuredRow) =>
451
+ labelInGroup(workloadLabel(row.workload), row.group);
452
+
453
+ // Which command is faster, and by how much; "within noise" when the gap
454
+ // is under twice the larger MAD, since then a rerun could flip it.
455
+ function timeVerdict(
456
+ measured: readonly MeasuredRow[],
457
+ total: number,
458
+ paint: Paint,
459
+ ): string {
460
+ const sorted = [...measured].sort(
461
+ (a, b) => a.run.timing.median - b.run.timing.median,
462
+ );
463
+ const [first, second] = sorted;
464
+ if (!first) return `${plural(total, "command")}${SEPARATOR}none measured`;
465
+ const a = paint.bold(shortName(nameOf(first)));
466
+ if (!second) return `${a} takes ${toDuration(first.run.timing.median)}`;
467
+ const b = paint.bold(shortName(nameOf(second)));
468
+ const gap = second.run.timing.median - first.run.timing.median;
469
+ const noise = 2 * Math.max(first.run.timing.mad, second.run.timing.mad);
470
+ const more =
471
+ sorted.length > 2 ? `${SEPARATOR}fastest of ${sorted.length}` : "";
472
+ if (gap < noise) return `${a} and ${b} are within noise${more}`;
473
+ const ratio = second.run.timing.median / first.run.timing.median;
474
+ return `${a} is ${toTimes(ratio)} faster than ${b}${more}`;
475
+ }
476
+
477
+ function benchVerdict(
478
+ measured: readonly MeasuredRow[],
479
+ total: number,
480
+ warnings: number,
481
+ paint: Paint,
482
+ ): string {
483
+ const warned =
484
+ warnings > 0
485
+ ? `${SEPARATOR}${paint.warn(plural(warnings, "warning"))}`
486
+ : "";
487
+ const fastest = measured.reduce<MeasuredRow | undefined>(
488
+ (best, row) =>
489
+ best === undefined || row.run.timing.median < best.run.timing.median
490
+ ? row
491
+ : best,
492
+ undefined,
493
+ );
494
+ if (!fastest)
495
+ return `${plural(total, "task")}${SEPARATOR}none measured${warned}`;
496
+ const name = paint.bold(shortName(nameOf(fastest), VERDICT_ONE_NAME_WIDTH));
497
+ const time = toDuration(fastest.run.timing.median);
498
+ if (total === 1) return `${name} takes ${time}${warned}`;
499
+ return `${plural(total, "task")}${SEPARATOR}fastest ${name} ${time}${warned}`;
500
+ }
501
+
502
+ function timingClosing(
503
+ doc: ProfileDocument,
504
+ rows: readonly TimingRowItem[],
505
+ measured: readonly MeasuredRow[],
506
+ noun: "command" | "task",
507
+ options: TableOptions,
508
+ paint: Paint,
509
+ ): string {
510
+ if (isAborted(doc)) {
511
+ return failWith(
512
+ paint,
513
+ "Cancelled",
514
+ `${measured.length} of ${plural(rows.length, noun)} measured`,
515
+ );
231
516
  }
232
- for (const col of memoryColumns(memory)) {
233
- columns.push({
234
- header: col.header,
235
- width: Math.max(col.header.length, MIN_MEMORY_WIDTH),
236
- cell: (row) => col.cell(row.run.workloadId) ?? "",
237
- });
517
+ const failed = rows.filter(isFailedRow);
518
+ const first = failed[0];
519
+ if (first) {
520
+ const names = failed.map((row) =>
521
+ labelInGroup(workloadLabel(row.workload), row.group),
522
+ );
523
+ const codes = new Set(
524
+ (first.run ?? first.empty)?.warnings.map((w) => w.code) ?? [],
525
+ );
526
+ const next = codes.has("time-source-no-match")
527
+ ? "check --time-source against --show-output"
528
+ : codes.has("timeout")
529
+ ? "raise --timeout"
530
+ : "see why with --show-output";
531
+ return failWith(
532
+ paint,
533
+ `${plural(failed.length, noun)} failed: ${truncateWords(names.join(", "), 40)}`,
534
+ next,
535
+ );
238
536
  }
239
- if (ratios) {
240
- columns.push({
241
- header: "Relative",
242
- width: 8,
243
- cell: (row) => {
244
- const ratio = ratios.get(row);
245
- return ratio === undefined
246
- ? ""
247
- : formatRelative(ratio, !!row.workload?.baseline);
248
- },
249
- });
537
+ const elapsed = elapsedPart(options);
538
+ if (noun === "command") {
539
+ const runs = measured.reduce((sum, row) => sum + row.run.trials.length, 0);
540
+ return closingLine(
541
+ paint,
542
+ `Timed ${plural(rows.length, "command")}`,
543
+ `${plural(runs, "run")}${elapsed}`,
544
+ );
250
545
  }
251
-
252
- return [...textTable(columns, rows), ...warningFootnotes(rows)];
546
+ const samples = measured.reduce(
547
+ (sum, row) => sum + row.run.timing.samples.length,
548
+ 0,
549
+ );
550
+ return closingLine(
551
+ paint,
552
+ `Measured ${plural(rows.length, "task")}`,
553
+ `${toCount(samples)} ${samples === 1 ? "sample" : "samples"}${elapsed}`,
554
+ );
253
555
  }
254
556
 
255
- function renderPaired(
557
+ // --- ab ---
558
+
559
+ type Flagged = { label: string; workload: Workload | undefined; what: string };
560
+
561
+ function pairedReport(
256
562
  doc: ProfileDocument,
257
563
  ab: AbSummary,
258
- env: string[],
259
- ): string[] {
564
+ options: TableOptions,
565
+ paint: Paint,
566
+ ): Report {
260
567
  const byWorkload = workloadsById(doc);
261
- const lines = [...env, `A/B: ${formatAbHeader(ab)}`, ""];
262
-
263
- const threw: { label: string; verdict: string; message: string }[] = [];
264
- const rows: TableRow<ReturnType<typeof pairedCells>>[] = abRows(doc).map(
265
- ({ kind, run }) => {
266
- const workload = byWorkload.get(run.workloadId);
267
- const label = labelOrId(workload, run.workloadId);
268
- let data: ReturnType<typeof pairedCells>;
269
- if (kind === "threw") {
270
- const verdict = formatThrew(run.threw);
271
- threw.push({ label, verdict, message: run.threw.message });
272
- data = {
273
- base: "-",
274
- candidate: "-",
275
- change: "",
276
- spread: "",
277
- also: "",
278
- verdict,
279
- };
280
- } else {
281
- data = pairedCells(run, ab.metric);
568
+ const metric = ab.metric;
569
+ const hasAlso =
570
+ metric === "instructions" ||
571
+ doc.measurements.some((m) => m.paired?.instructions);
572
+ const header = [
573
+ "task",
574
+ "base",
575
+ "candidate",
576
+ "change",
577
+ "noise",
578
+ ...(hasAlso ? [metric === "time" ? "instr" : "time"] : []),
579
+ "verdict",
580
+ ];
581
+ const regressed: Flagged[] = [];
582
+ const threw: Flagged[] = [];
583
+ const memoryRegressed: Flagged[] = [];
584
+
585
+ const items = abRows(doc).map((entry) => {
586
+ const workload = byWorkload.get(entry.run.workloadId);
587
+ return { entry, workload, group: groupOf(workload) };
588
+ });
589
+ const named = grouped(items).map(({ item, branch, label }) => {
590
+ const { entry, workload } = item;
591
+ const fullName = labelOrId(workload, entry.run.workloadId);
592
+ const name = labelInGroup(fullName, item.group);
593
+ let cells: string[];
594
+ const notes: Note[] = [];
595
+ if (entry.kind === "threw") {
596
+ const side = entry.run.threw.side;
597
+ const word = formatThrew(entry.run.threw);
598
+ if (side === "cand") {
599
+ threw.push({ label: fullName, workload, what: "throws" });
600
+ }
601
+ cells = [
602
+ "",
603
+ "",
604
+ "",
605
+ "",
606
+ ...(hasAlso ? [""] : []),
607
+ side === "cand" ? paint.bad(word) : paint.warn(word),
608
+ ];
609
+ const [message] = entry.run.threw.message.split("\n");
610
+ notes.push({ text: `${word}: ${message ?? ""}`, tone: "dim" });
611
+ } else {
612
+ cells = pairedCells(entry.run, metric, hasAlso, paint);
613
+ const p = entry.run.paired;
614
+ if (p.verdict === "regressed" && comparable(p)) {
615
+ const judged = metricRatios(p, metric);
616
+ regressed.push({
617
+ label: fullName,
618
+ workload,
619
+ what: `regressed ${judged ? toChange((judged.medianRatio - 1) * 100) : ""}`.trim(),
620
+ });
621
+ }
622
+ notes.push(...pairedNotes(entry.run, metric));
623
+ for (const [reading, change] of [
624
+ ["retained/op", p.retained],
625
+ ["peak", p.peak],
626
+ ] as const) {
627
+ if (!change) continue;
628
+ const pct =
629
+ change.baseBytes > 0
630
+ ? ((change.candBytes - change.baseBytes) / change.baseBytes) * 100
631
+ : Number.NaN;
632
+ // An unjudged reading that barely moved is noise, not a note.
633
+ if (
634
+ change.verdict === "unchanged" &&
635
+ !(Math.abs(pct) >= MIN_MEMORY_NOTE_PCT)
636
+ ) {
637
+ continue;
638
+ }
639
+ notes.push({
640
+ text: `${reading} ${toBytes(change.baseBytes)} → ${toBytes(change.candBytes)}${Number.isFinite(pct) ? ` (${toChange(pct)})` : ""}${change.verdict === "unchanged" ? "" : ` ${change.verdict}`}`,
641
+ tone:
642
+ change.verdict === "regressed"
643
+ ? "bad"
644
+ : change.verdict === "improved"
645
+ ? "good"
646
+ : "dim",
647
+ });
648
+ if (change.verdict === "regressed") {
649
+ memoryRegressed.push({
650
+ label: fullName,
651
+ workload,
652
+ what: `${reading} regressed`,
653
+ });
654
+ }
655
+ }
656
+ for (const w of entry.run.warnings) {
657
+ if (RUN_WARNINGS.has(w.code)) continue;
658
+ if (w.code === "suite-changed" && comparable(p)) continue;
659
+ // pairedNotes says it beside the repeats.
660
+ if (w.code === "repeats-disagree") continue;
661
+ notes.push(toWarningNote(w, entry.run.timing));
282
662
  }
283
- return { label, group: groupOf(workload), data, warnings: run.warnings };
663
+ }
664
+ return {
665
+ branch,
666
+ ...(label !== undefined && { label }),
667
+ row: { branch, name, cells, notes },
668
+ };
669
+ });
670
+
671
+ const table =
672
+ named.length > 0
673
+ ? namedTable(
674
+ headerRow(paint, header),
675
+ withGroupLabels(named, header.length - 1),
676
+ header.map((_, i) => i).slice(1, -1),
677
+ paint,
678
+ )
679
+ : [];
680
+
681
+ const notes = abNotes(doc);
682
+ const after: string[] = [
683
+ ...(ab.newSuites?.length
684
+ ? [
685
+ paint.dim(
686
+ truncateWords(
687
+ ` ${ab.newSuites.length > 1 ? "new suites" : "new suite"}, not at ${ab.base.ref}: ${ab.newSuites.join(", ")}`,
688
+ MEASURE,
689
+ ),
690
+ ),
691
+ ]
692
+ : []),
693
+ ...(notes.baseOnly.length > 0
694
+ ? [
695
+ paint.dim(
696
+ truncateWords(` base only: ${notes.baseOnly.join(", ")}`, MEASURE),
697
+ ),
698
+ ]
699
+ : []),
700
+ ...(notes.candOnly.length > 0
701
+ ? [
702
+ paint.dim(
703
+ truncateWords(
704
+ ` candidate only: ${notes.candOnly.join(", ")}`,
705
+ MEASURE,
706
+ ),
707
+ ),
708
+ ]
709
+ : []),
710
+ ...runNotes(doc, paint),
711
+ ];
712
+
713
+ return {
714
+ verdict: abVerdict(ab, paint),
715
+ context: contextLines(
716
+ [
717
+ ...environmentParts(doc.environment),
718
+ `${ab.base.ref} ${ab.base.sha.slice(0, 7)} vs working tree`,
719
+ `${ab.rounds} rounds`,
720
+ ...(metric === "instructions" ? ["by instructions/call"] : []),
721
+ `thresholds ${ab.thresholdPct}%, geomean ${ab.geomeanThresholdPct}%`,
722
+ ...(ab.memory ? [`memory threshold ${ab.memory.thresholdPct}%`] : []),
723
+ ],
724
+ paint,
725
+ ),
726
+ blocks: [table, after],
727
+ closing: abClosing(
728
+ ab,
729
+ { regressed, threw, memoryRegressed },
730
+ options,
731
+ paint,
732
+ ),
733
+ };
734
+ }
735
+
736
+ // The gate's verdict, colored, since here a change is judged: pass, or
737
+ // what regressed and what improved.
738
+ function abVerdict(ab: AbSummary, paint: Paint): string {
739
+ if (ab.matched + ab.threw === 0) return paint.bad("nothing paired");
740
+ const geomeanOver =
741
+ ab.geomeanPct !== null && ab.geomeanPct > ab.geomeanThresholdPct;
742
+ const geomean =
743
+ ab.geomeanPct === null ? "" : `geomean ${toChange(ab.geomeanPct)}`;
744
+ const memory = ab.memory;
745
+ return fittedParts([
746
+ {
747
+ text: ab.verdict === "pass" ? paint.good("pass") : paint.bad("fail"),
748
+ required: true,
284
749
  },
285
- );
286
- if (rows.length > 0) {
287
- const also = alsoHeader(doc, ab.metric);
288
- lines.push(
289
- ...textTable<ReturnType<typeof pairedCells>>(
290
- [
291
- { header: "Base", width: 10, cell: (c) => c.base },
292
- { header: "Candidate", width: 10, cell: (c) => c.candidate },
293
- { header: "Change", width: 9, cell: (c) => c.change },
294
- { header: "p25…p75", width: 18, cell: (c) => c.spread },
295
- ...(also
296
- ? [
297
- {
298
- header: also,
299
- width: 8,
300
- cell: (c: ReturnType<typeof pairedCells>) => c.also,
301
- },
302
- ]
303
- : []),
304
- { header: "Verdict", width: 7, cell: (c) => c.verdict },
305
- ],
306
- rows,
307
- ),
750
+ ...(ab.regressed > 0
751
+ ? [{ text: paint.bad(`${ab.regressed} regressed`), required: true }]
752
+ : []),
753
+ ...(ab.improved > 0
754
+ ? [{ text: paint.good(`${ab.improved} improved`), required: true }]
755
+ : []),
756
+ ...(ab.threw > 0 ? [{ text: `${ab.threw} threw`, required: true }] : []),
757
+ ...(geomean === ""
758
+ ? []
759
+ : [
760
+ {
761
+ text: geomeanOver ? paint.bad(geomean) : geomean,
762
+ required: geomeanOver,
763
+ },
764
+ ]),
765
+ ...(memory && memory.regressed + memory.improved > 0
766
+ ? [
767
+ {
768
+ text:
769
+ memory.regressed > 0
770
+ ? paint.bad(`memory ${memory.regressed} regressed`)
771
+ : paint.good(`memory ${memory.improved} improved`),
772
+ required: memory.regressed > 0,
773
+ },
774
+ ]
775
+ : []),
776
+ { text: `${ab.unchanged} unchanged` },
777
+ ...(ab.unconfirmed > 0 ? [{ text: `${ab.unconfirmed} unconfirmed` }] : []),
778
+ ...(ab.notComparable > 0
779
+ ? [{ text: `${ab.notComparable} not comparable` }]
780
+ : []),
781
+ ]);
782
+ }
783
+
784
+ function pairedCells(
785
+ run: PairedRun,
786
+ metric: AbSummary["metric"],
787
+ hasAlso: boolean,
788
+ paint: Paint,
789
+ ): string[] {
790
+ const p = run.paired;
791
+ const i = p.instructions;
792
+ const judged = metricRatios(p, metric);
793
+ const other = metricRatios(p, metric === "time" ? "instructions" : "time");
794
+ const ratios = metric === "time" ? p.ratios : (i?.ratios ?? []);
795
+ const [base, candidate] =
796
+ metric === "time"
797
+ ? [toDuration(p.baseMedianNs), toDuration(run.timing.median)]
798
+ : i
799
+ ? [toCount(i.baseMedian), toCount(i.candMedian)]
800
+ : [MISSING, MISSING];
801
+ const mad = medianAbsoluteDeviation(ratios);
802
+ const changePct = judged ? (judged.medianRatio - 1) * 100 : Number.NaN;
803
+ const noisePct = (mad / (judged?.medianRatio ?? 1)) * 100;
804
+ // A change inside the noise reads ~0, so a person doesn't chase it.
805
+ const change = !judged
806
+ ? ""
807
+ : Math.abs(changePct) < noisePct
808
+ ? "~0%"
809
+ : toChange(changePct);
810
+ const paintChange =
811
+ !comparable(p) || p.verdict === "unchanged"
812
+ ? (s: string) => s
813
+ : p.verdict === "regressed"
814
+ ? paint.bad
815
+ : paint.good;
816
+ return [
817
+ base,
818
+ candidate,
819
+ paintChange(change),
820
+ judged ? paint.dim(toNoise(mad, judged.medianRatio)) : "",
821
+ ...(hasAlso ? [other ? toChange((other.medianRatio - 1) * 100) : ""] : []),
822
+ pairedVerdict(run, paint),
823
+ ];
824
+ }
825
+
826
+ function pairedVerdict(run: PairedRun, paint: Paint): string {
827
+ const p = run.paired;
828
+ if (!comparable(p)) return paint.dim("not comparable");
829
+ if (p.verdict === "regressed") return paint.bad("regressed");
830
+ if (p.verdict === "improved") return paint.good("improved");
831
+ // Flagged here, but a fresh process disagreed.
832
+ if (p.flagged) return paint.dim(`${p.flagged}?`);
833
+ return "";
834
+ }
835
+
836
+ function pairedNotes(run: PairedRun, metric: AbSummary["metric"]): Note[] {
837
+ const p = run.paired;
838
+ const notes: Note[] = [];
839
+ if (p.repeats?.length) {
840
+ const changes = p.repeats.map((r) => {
841
+ const ratio = metricRatios(r, metric)?.medianRatio;
842
+ return ratio === undefined ? MISSING : toChange((ratio - 1) * 100);
843
+ });
844
+ const apart = numberIn(
845
+ run.warnings.find((w) => w.code === "repeats-disagree")?.data,
846
+ "factor",
308
847
  );
848
+ if (apart === undefined) {
849
+ notes.push({ text: `repeats ${changes.join(", ")}`, tone: "dim" });
850
+ } else {
851
+ notes.push(
852
+ {
853
+ text: `repeats ${changes.join(", ")}: ${toTimes(apart)} apart from the paired run`,
854
+ tone: "warn",
855
+ },
856
+ {
857
+ text: "another task in this process may shape it; --filter to measure it alone",
858
+ tone: "dim",
859
+ },
860
+ );
861
+ }
862
+ }
863
+ // A changed suite whose output changed says so in its verdict.
864
+ if (!p.sameOutput && comparable(p)) {
865
+ notes.push({ text: "output differs from the base", tone: "dim" });
309
866
  }
867
+ return notes;
868
+ }
310
869
 
311
- const memory = memoryRows(doc);
312
- if (memory.length > 0) {
313
- lines.push(
314
- "",
315
- "Memory:",
316
- ...textTable<ReturnType<typeof memoryCells>>(
317
- [
318
- { header: "Reading", width: 11, cell: (c) => c.reading },
319
- { header: "Base", width: 10, cell: (c) => c.base },
320
- { header: "Candidate", width: 10, cell: (c) => c.candidate },
321
- { header: "Change", width: 18, cell: (c) => c.change },
322
- { header: "Verdict", width: 7, cell: (c) => c.verdict },
323
- ],
324
- memory.map((row) => {
325
- const workload = byWorkload.get(row.run.workloadId);
326
- return {
327
- label: labelOrId(workload, row.run.workloadId),
328
- group: groupOf(workload),
329
- data: memoryCells(row),
330
- warnings: [],
331
- };
332
- }),
333
- ),
870
+ function abClosing(
871
+ ab: AbSummary,
872
+ flagged: {
873
+ regressed: readonly Flagged[];
874
+ threw: readonly Flagged[];
875
+ memoryRegressed: readonly Flagged[];
876
+ },
877
+ options: TableOptions,
878
+ paint: Paint,
879
+ ): string {
880
+ if (ab.matched + ab.threw === 0) {
881
+ return options.unpaired
882
+ ? failWith(paint, options.unpaired.what, options.unpaired.next)
883
+ : failWith(paint, "Nothing paired", "no task is on both sides");
884
+ }
885
+ if (ab.verdict === "pass") {
886
+ return closingLine(
887
+ paint,
888
+ "A/B passes",
889
+ `${plural(ab.matched, "task")} paired${elapsedPart(options)}`,
334
890
  );
335
891
  }
336
-
337
- const notes = abNotes(doc);
338
- if (threw.length > 0) {
339
- lines.push("", `Threw (${threw.length}):`);
340
- for (const row of threw) {
341
- const [first, ...rest] = row.message.split("\n");
342
- lines.push(` ${row.label}: ${row.verdict}: ${first}`);
343
- for (const more of rest) lines.push(` ${more}`);
344
- }
892
+ const what = (list: readonly Flagged[]) => {
893
+ const [first] = list;
894
+ if (!first) return "";
895
+ const more = list.length > 1 ? ` and ${list.length - 1} more` : "";
896
+ return `${shortName(first.label)} ${first.what}${more}`;
897
+ };
898
+ const [regressed] = flagged.regressed;
899
+ if (regressed) {
900
+ return failWith(
901
+ paint,
902
+ `A/B fails: ${what(flagged.regressed)}`,
903
+ `profile it: ostia bench${suiteOf(regressed.workload)} --cpu --filter ${filterFor(regressed.label)}`,
904
+ );
345
905
  }
346
- if (notes.outputDiffers.length > 0) {
347
- lines.push(
348
- "",
349
- `Output differs from the base (${notes.outputDiffers.length}):`,
350
- ...notes.outputDiffers.map((label) => ` ${label}`),
906
+ const [threw] = flagged.threw;
907
+ if (threw) {
908
+ return failWith(
909
+ paint,
910
+ `A/B fails: ${what(flagged.threw)}`,
911
+ `run it: ostia bench${suiteOf(threw.workload)} --filter ${filterFor(threw.label)}`,
351
912
  );
352
913
  }
353
- const newSuites = formatNewSuites(ab);
354
- if (newSuites) lines.push("", newSuites);
355
- if (notes.baseOnly.length > 0 || notes.candOnly.length > 0) {
356
- lines.push("", "Unmatched:");
357
- if (notes.baseOnly.length > 0)
358
- lines.push(` base only: ${notes.baseOnly.join(", ")}`);
359
- if (notes.candOnly.length > 0)
360
- lines.push(` candidate only: ${notes.candOnly.join(", ")}`);
914
+ const [memory] = flagged.memoryRegressed;
915
+ if (memory) {
916
+ return failWith(
917
+ paint,
918
+ `A/B fails: ${what(flagged.memoryRegressed)}`,
919
+ `measure it: ostia bench${suiteOf(memory.workload)} --alloc --peak-mem --filter ${filterFor(memory.label)}`,
920
+ );
361
921
  }
362
-
363
- lines.push(...warningFootnotes(rows), "", formatAbSummary(ab));
364
- return lines;
922
+ return failWith(
923
+ paint,
924
+ `A/B fails: geomean ${toChange(ab.geomeanPct ?? 0)}, over ${ab.geomeanThresholdPct}%`,
925
+ ab.unconfirmed > 0
926
+ ? "recheck the unconfirmed tasks with a higher --confirm"
927
+ : `a broad slowdown, no one task past ${ab.thresholdPct}%`,
928
+ );
365
929
  }
366
930
 
367
- function renderComparisons(doc: ProfileDocument): string[] {
368
- const rows = comparedRows(doc);
369
- if (rows.length === 0) return [];
370
- const lines: string[] = [];
931
+ // --- compare and ci ---
371
932
 
372
- const mismatch = environmentMismatch(doc);
373
- if (mismatch) lines.push(`⚠ ${mismatch.message}`, "");
374
- const note = thresholdNote(doc);
375
- if (note) lines.push(note, "");
376
-
377
- const footnotes: string[] = [];
378
- const notCompared: string[] = [];
933
+ const MEMORY_LABELS: Record<
934
+ NonNullable<ComparedTask["memory"]>[number]["reading"],
935
+ string
936
+ > = {
937
+ heapUsedBefore: "heap used before",
938
+ heapUsedAfter: "heap used after",
939
+ retained: "retained/op",
940
+ peak: "peak",
941
+ maxRss: "max RSS",
942
+ };
379
943
 
380
- for (const { row, cmp } of rows) {
944
+ function comparisonReport(
945
+ doc: ProfileDocument,
946
+ options: TableOptions,
947
+ paint: Paint,
948
+ ): Report {
949
+ const rows = comparedRows(doc);
950
+ const header = ["task", "base", "candidate", "change", "verdict"];
951
+ const regressed: ComparedTask[] = [];
952
+ const items = rows.map((entry) => ({ ...entry, group: entry.row.group }));
953
+ const named = grouped(items).map(({ item, branch, label }) => {
954
+ const { row, cmp } = item;
955
+ const name = labelInGroup(row.task, row.group);
956
+ const notes: Note[] = [];
957
+ let cells: string[];
381
958
  if (row.verdict === "missing-base" || row.verdict === "missing-cand") {
382
- notCompared.push(` ${row.task}: ${oneSidedNote(row.verdict)}`);
383
- continue;
384
- }
385
- lines.push(`${row.pass === false ? "✗" : "✓"} ${row.task}`);
386
- if (row.renamedFrom) lines.push(` renamed from ${row.renamedFrom.task}`);
387
-
388
- if (row.timing) {
389
- const { baseMedian, candMedian, medianDeltaPct, ci95, pValue } =
390
- row.timing;
391
- const unit = pickDurationUnit(Math.max(baseMedian, candMedian));
392
- const medians = `${formatDuration(baseMedian, unit)} -> ${formatDuration(candMedian, unit)}`;
393
- if (ci95 && pValue !== undefined) {
394
- const p = pValue < 0.001 ? "p<0.001" : `p=${pValue.toFixed(3)}`;
395
- lines.push(
396
- ` timing: ${medians}, ${formatSignedPct(medianDeltaPct)} median, 95% CI [${formatSignedPct(ci95[0])}, ${formatSignedPct(ci95[1])}], ${p} (${row.verdict})`,
397
- );
398
- } else {
399
- lines.push(
400
- ` timing: ${medians}, ${formatSignedPct(medianDeltaPct)} median (${row.verdict})`,
401
- );
402
- }
403
- }
404
- const memory = shownMemoryDeltas(row, "->");
405
- if (memory.length > 0) lines.push(` memory: ${memory.join(", ")}`);
406
- if (!cmp) continue;
407
- for (const f of shownFrameDeltas(cmp, TOP_FRAMES)) {
408
- lines.push(
409
- ` frame ${f.name}: ${formatSignedPct(f.deltaPct)} self-time (${formatUsAsMs(f.baseSelfUs)}ms -> ${formatUsAsMs(f.candSelfUs)}ms)`,
410
- );
411
- }
412
- for (const h of shownHeapDeltas(cmp, TOP_TYPES)) {
413
- lines.push(
414
- ` heap ${h.type}: ${formatSignedPct(h.deltaPct)} count (${h.baseCount} -> ${h.candCount})`,
415
- );
959
+ const note = oneSidedNote(row.verdict);
960
+ const word = note.slice(0, note.indexOf(" ("));
961
+ cells = ["", "", "", paint.dim(word)];
962
+ notes.push({
963
+ text: note.slice(word.length + 2, -1).replace(/`/g, ""),
964
+ tone: "dim",
965
+ });
966
+ } else {
967
+ if (row.pass === false) regressed.push(row);
968
+ cells = comparedCells(row, paint);
969
+ notes.push(...comparedNotes(row, cmp));
416
970
  }
971
+ return {
972
+ branch,
973
+ ...(label !== undefined && { label }),
974
+ row: { branch, name, cells, notes },
975
+ };
976
+ });
977
+ const table = namedTable(
978
+ headerRow(paint, header),
979
+ withGroupLabels(named, header.length - 1),
980
+ [1, 2, 3],
981
+ paint,
982
+ );
983
+ const mismatch = environmentMismatch(doc);
984
+ const after = [
985
+ ...(mismatch ? noteLines(toWarningNote(mismatch), " ", paint) : []),
986
+ ...runNotes(doc, paint),
987
+ ];
988
+ return {
989
+ verdict: comparedVerdict(doc, rows, options, paint),
990
+ context: contextLines(
991
+ [...environmentParts(doc.environment), ...compareContext(doc, options)],
992
+ paint,
993
+ ),
994
+ blocks: [table, after],
995
+ closing: comparedClosing(rows, regressed, options, paint),
996
+ };
997
+ }
998
+
999
+ function comparedCells(row: ComparedTask, paint: Paint): string[] {
1000
+ const t = row.timing;
1001
+ const word =
1002
+ row.verdict === "regressed"
1003
+ ? paint.bad("regressed")
1004
+ : row.verdict === "improved"
1005
+ ? paint.good("improved")
1006
+ : row.pass === false
1007
+ ? paint.bad("fail")
1008
+ : "";
1009
+ if (!t) return ["", "", "", word];
1010
+ const change = toChange(t.medianDeltaPct);
1011
+ return [
1012
+ toDuration(t.baseMedian),
1013
+ toDuration(t.candMedian),
1014
+ row.verdict === "regressed"
1015
+ ? paint.bad(change)
1016
+ : row.verdict === "improved"
1017
+ ? paint.good(change)
1018
+ : change,
1019
+ word,
1020
+ ];
1021
+ }
417
1022
 
418
- const warnings = rowComparisonWarnings(cmp);
419
- if (warnings.length > 0) {
420
- lines.push(` ! ${warnings.map((w) => w.code).join(", ")}`);
421
- for (const w of warnings) footnotes.push(` ${row.task}: ${w.message}`);
1023
+ function comparedNotes(row: ComparedTask, cmp: Comparison | undefined): Note[] {
1024
+ const notes: Note[] = [];
1025
+ if (row.renamedFrom) {
1026
+ notes.push({ text: `renamed from ${row.renamedFrom.task}`, tone: "dim" });
1027
+ }
1028
+ const t = row.timing;
1029
+ if (t?.ci95 && row.verdict !== "unchanged") {
1030
+ const p =
1031
+ t.pValue === undefined
1032
+ ? ""
1033
+ : `${SEPARATOR}${t.pValue < 0.001 ? "p<0.001" : `p=${t.pValue.toFixed(3)}`}`;
1034
+ notes.push({
1035
+ text: `95% CI ${toChange(t.ci95[0])}…${toChange(t.ci95[1])}${p}`,
1036
+ tone: "dim",
1037
+ });
1038
+ }
1039
+ for (const m of row.memory ?? []) {
1040
+ if (Math.abs(m.deltaPct) < MIN_MEMORY_NOTE_PCT) continue;
1041
+ notes.push({
1042
+ text: `${MEMORY_LABELS[m.reading]} ${toBytes(m.baseBytes)} → ${toBytes(m.candBytes)} (${Number.isFinite(m.deltaPct) ? toChange(m.deltaPct) : "new"})`,
1043
+ tone: "dim",
1044
+ });
1045
+ }
1046
+ if (!cmp) return notes;
1047
+ for (const f of shownFrameDeltas(cmp, TOP_FRAMES)) {
1048
+ notes.push({
1049
+ text: `${f.name} ${toChange(f.deltaPct)} self time (${toDuration(f.baseSelfUs * 1e3)} → ${toDuration(f.candSelfUs * 1e3)})`,
1050
+ tone: "dim",
1051
+ });
1052
+ }
1053
+ for (const h of shownHeapDeltas(cmp, TOP_TYPES)) {
1054
+ notes.push({
1055
+ text: `${h.type} ${toChange(h.deltaPct)} objects (${h.baseCount} → ${h.candCount})`,
1056
+ tone: "dim",
1057
+ });
1058
+ }
1059
+ for (const w of rowComparisonWarnings(cmp)) notes.push(toWarningNote(w));
1060
+ return notes;
1061
+ }
1062
+
1063
+ const shortGit = (git: GitMetadata) =>
1064
+ `${git.sha.slice(0, 7)} (${git.branch}${git.dirty ? ", dirty" : ""})`;
1065
+
1066
+ function compareContext(doc: ProfileDocument, options: TableOptions): string[] {
1067
+ const parts: string[] = [];
1068
+ const ci = options.ci;
1069
+ if (ci) {
1070
+ parts.push(
1071
+ `baseline ${ci.baseline}`,
1072
+ `${ci.cached} cached, ${ci.executed} executed`,
1073
+ );
1074
+ }
1075
+ const compare = options.compare;
1076
+ if (compare) {
1077
+ parts.push(`thresholds from ${compare.thresholds}`);
1078
+ if (compare.baseGit && compare.candGit) {
1079
+ parts.push(
1080
+ `base ${shortGit(compare.baseGit)}`,
1081
+ `cand ${shortGit(compare.candGit)}`,
1082
+ );
422
1083
  }
423
1084
  }
1085
+ const summary = doc.comparisonSummary;
1086
+ const base = doc.comparisons?.[0]?.thresholds.timingPct;
1087
+ if (summary && base !== undefined) {
1088
+ const drift =
1089
+ summary.driftPct !== undefined && summary.driftPct > 0
1090
+ ? ` and ${summary.driftPct.toFixed(1)}% drift`
1091
+ : "";
1092
+ parts.push(
1093
+ summary.effectiveTimingPct > base
1094
+ ? `threshold ${base.toFixed(1)}%, ${summary.effectiveTimingPct.toFixed(1)}% with noise${drift}`
1095
+ : `threshold ${base.toFixed(1)}%`,
1096
+ );
1097
+ }
1098
+ return parts;
1099
+ }
424
1100
 
425
- if (notCompared.length > 0) lines.push("", "Not compared:", ...notCompared);
426
- if (footnotes.length > 0)
427
- lines.push("", "Comparison warnings:", ...footnotes);
428
- return lines;
1101
+ function comparedVerdict(
1102
+ doc: ProfileDocument,
1103
+ rows: readonly { row: ComparedTask }[],
1104
+ options: TableOptions,
1105
+ paint: Paint,
1106
+ ): string {
1107
+ const count = (verdict: ComparedTask["verdict"]) =>
1108
+ rows.filter(({ row }) => row.verdict === verdict).length;
1109
+ const failed = options.ci?.failed.length ?? 0;
1110
+ const pass =
1111
+ (doc.comparisonSummary?.verdict ??
1112
+ (rows.some(({ row }) => row.pass === false) ? "fail" : "pass")) ===
1113
+ "pass" && failed === 0;
1114
+ const regressed = count("regressed");
1115
+ const improved = count("improved");
1116
+ const geomean = doc.comparisonSummary?.geomeanPct;
1117
+ return [
1118
+ pass ? paint.good("pass") : paint.bad("fail"),
1119
+ ...(regressed > 0 ? [paint.bad(`${regressed} regressed`)] : []),
1120
+ ...(improved > 0 ? [paint.good(`${improved} improved`)] : []),
1121
+ `${count("unchanged")} unchanged`,
1122
+ ...(failed > 0 ? [paint.bad(`${failed} failed`)] : []),
1123
+ ...(options.ci && options.ci.missingBaseline > 0
1124
+ ? [`${options.ci.missingBaseline} not in the baseline`]
1125
+ : []),
1126
+ ...(geomean === null || geomean === undefined
1127
+ ? []
1128
+ : [`geomean ${toChange(geomean)}`]),
1129
+ ].join(SEPARATOR);
429
1130
  }
430
1131
 
431
- function renderInstrumentedRuns(doc: ProfileDocument): string[] {
432
- const byWorkload: Map<string, Workload> = workloadsById(doc);
433
- const lines: string[] = [];
1132
+ function comparedClosing(
1133
+ rows: readonly { row: ComparedTask }[],
1134
+ regressed: readonly ComparedTask[],
1135
+ options: TableOptions,
1136
+ paint: Paint,
1137
+ ): string {
1138
+ const ci = options.ci;
1139
+ const name = ci ? "Profile CI" : "Compare";
1140
+ if (ci && ci.failed.length > 0) {
1141
+ return failWith(
1142
+ paint,
1143
+ `${name} fails: ${plural(ci.failed.length, "workload")} failed to measure: ${truncateWords(ci.failed.join(", "), 30)}`,
1144
+ "see the error above",
1145
+ );
1146
+ }
1147
+ const [first] = regressed;
1148
+ if (first) {
1149
+ const change = first.timing
1150
+ ? ` ${toChange(first.timing.medianDeltaPct)}`
1151
+ : "";
1152
+ const more =
1153
+ regressed.length > 1 ? ` and ${regressed.length - 1} more` : "";
1154
+ return failWith(
1155
+ paint,
1156
+ `${name} fails: ${shortName(first.task)} regressed${change}${more}`,
1157
+ ci
1158
+ ? "fix it, or accept it: ostia ci --save-baseline"
1159
+ : "profile both sides with --cpu to see where",
1160
+ );
1161
+ }
1162
+ const matched = rows.filter(
1163
+ ({ row }) =>
1164
+ row.verdict !== "missing-base" && row.verdict !== "missing-cand",
1165
+ ).length;
1166
+ if (matched === 0) {
1167
+ return failWith(paint, "Nothing compared", "no workload is on both sides");
1168
+ }
1169
+ return closingLine(
1170
+ paint,
1171
+ `${name} passes`,
1172
+ ci
1173
+ ? `${plural(ci.workloads, "workload")}${elapsedPart(options)}`
1174
+ : `${plural(matched, "task")} compared${elapsedPart(options)}`,
1175
+ );
1176
+ }
434
1177
 
435
- for (const run of doc.measurements) {
436
- if (run.phase !== "cpu" && run.phase !== "heap") continue;
437
- const workload = byWorkload.get(run.workloadId);
438
- const label = labelOrId(workload, run.workloadId);
1178
+ // --- CPU and heap captures ---
1179
+
1180
+ function instrumentedReport(doc: ProfileDocument, paint: Paint): Report {
1181
+ const captures = doc.measurements.filter(
1182
+ (m) => m.phase === "cpu" || m.phase === "heap",
1183
+ ).length;
1184
+ return {
1185
+ verdict: plural(captures, "capture"),
1186
+ context: contextLines(environmentParts(doc.environment), paint),
1187
+ blocks: [],
1188
+ closing: closingLine(paint, `Captured ${plural(captures, "profile")}`),
1189
+ };
1190
+ }
439
1191
 
1192
+ // The label is cut to fit, not the detail, since the detail says what the
1193
+ // numbers below it are.
1194
+ function captureHeading(
1195
+ paint: Paint,
1196
+ kind: string,
1197
+ label: string,
1198
+ detail: string,
1199
+ ): string {
1200
+ const room = MEASURE - textWidth(`${kind} ${SEPARATOR}${detail}`);
1201
+ return `${paint.bold(kind)} ${truncateWords(label, Math.max(room, 12))}${paint.dim(`${SEPARATOR}${detail}`)}`;
1202
+ }
1203
+
1204
+ // One block per CPU profile or heap snapshot, since each is a run of its
1205
+ // own: what it captured, then its heaviest frames or commonest types.
1206
+ function instrumentedBlocks(doc: ProfileDocument, paint: Paint): string[][] {
1207
+ const byWorkload = workloadsById(doc);
1208
+ return doc.measurements.flatMap((run): string[][] => {
1209
+ if (run.phase !== "cpu" && run.phase !== "heap") return [];
1210
+ const label = labelOrId(byWorkload.get(run.workloadId), run.workloadId);
1211
+ const lines: string[] = [];
440
1212
  if (run.phase === "cpu") {
1213
+ const detail = run.cpu
1214
+ ? `${toCount(cpuSampleCount(run.cpu))} samples at ${toDuration(run.cpu.samplingIntervalUs * 1e3)}`
1215
+ : "nothing captured";
1216
+ lines.push(captureHeading(paint, "CPU profile", label, detail));
441
1217
  if (run.cpu) {
442
- lines.push(
443
- `CPU capture - ${label} (instrumented, ${run.cpu.samplingIntervalUs}µs interval, ${cpuSampleCount(run.cpu)} samples, diagnostic wall ${formatNsAsMs(run.diagnosticWallNs ?? 0)}ms)`,
1218
+ // A frame with no self time, as (root) and (module) mostly are,
1219
+ // isn't where the time went.
1220
+ const frames = topSelfFrames(run.cpu, TOP_FRAMES).filter(
1221
+ (f) => f.selfUs > 0,
444
1222
  );
445
- for (const f of topSelfFrames(run.cpu, TOP_FRAMES)) {
446
- lines.push(
447
- ` ${f.pct.padStart(5)}% ${formatUsAsMs(f.selfUs).padStart(8)}ms self ${f.frame?.name ?? "?"}`,
448
- );
449
- }
450
- } else {
451
1223
  lines.push(
452
- `CPU capture - ${label} (instrumented, no evidence captured)`,
1224
+ ...namedTable(
1225
+ headerRow(paint, ["function", "self", "share"]),
1226
+ frames.map((f) => ({
1227
+ branch: "",
1228
+ name: f.frame?.name || "(anonymous)",
1229
+ cells: [toDuration(f.selfUs * 1e3), toShare(Number(f.pct))],
1230
+ })),
1231
+ [1, 2],
1232
+ paint,
1233
+ ),
453
1234
  );
454
1235
  }
455
- } else if (run.heap) {
456
- lines.push(
457
- `Heap snapshot - ${label} (instrumented, ${formatHeapSummary(run.heap)})`,
458
- );
459
- for (const tc of run.heap.typeCounts.slice(0, TOP_TYPES)) {
460
- lines.push(` ${String(tc.count).padStart(6)} ${tc.type}`);
461
- }
462
1236
  } else {
463
- lines.push(
464
- `Heap snapshot - ${label} (instrumented, no evidence captured)`,
465
- );
1237
+ const heap = run.heap;
1238
+ const detail = heap
1239
+ ? `${toCount(heap.objectCount ?? 0)} objects${SEPARATOR}${toBytes(heap.heapSizeBytes ?? 0)}`
1240
+ : "nothing captured";
1241
+ lines.push(captureHeading(paint, "Heap snapshot", label, detail));
1242
+ if (heap) {
1243
+ lines.push(
1244
+ ...namedTable(
1245
+ headerRow(paint, ["type", "objects"]),
1246
+ heap.typeCounts.slice(0, TOP_TYPES).map((tc) => ({
1247
+ branch: "",
1248
+ name: tc.type,
1249
+ cells: [toCount(tc.count)],
1250
+ })),
1251
+ [1],
1252
+ paint,
1253
+ ),
1254
+ );
1255
+ }
466
1256
  }
467
-
468
- for (const a of run.artifacts) lines.push(` artifact: ${a.path}`);
469
- for (const w of run.warnings) lines.push(` ! ${w.message}`);
470
- }
471
-
472
- return lines;
1257
+ for (const a of run.artifacts) {
1258
+ lines.push(paint.dim(` ${truncatePath(a.path, 76)}`));
1259
+ }
1260
+ for (const w of run.warnings) {
1261
+ lines.push(...noteLines(toWarningNote(w), " ", paint));
1262
+ }
1263
+ return [lines];
1264
+ });
473
1265
  }