ostia 0.4.0 → 0.6.0

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.
Files changed (64) hide show
  1. package/README.md +31 -30
  2. package/docs/agent-protocol.md +13 -9
  3. package/docs/cli.md +174 -126
  4. package/docs/config.md +2 -2
  5. package/docs/document-schema.md +15 -12
  6. package/docs/library.md +32 -21
  7. package/docs/preload-recipes.md +4 -4
  8. package/docs/statistics.md +14 -13
  9. package/index.d.ts +202 -60
  10. package/package.json +1 -1
  11. package/src/ab/ab-runner.ts +6 -6
  12. package/src/ab/index.ts +56 -6
  13. package/src/ab/unpaired.ts +54 -0
  14. package/src/bench/index.ts +40 -3
  15. package/src/bench/registry.ts +6 -4
  16. package/src/bench/run-tasks.ts +16 -2
  17. package/src/bench/runner.ts +10 -3
  18. package/src/bench/support.ts +8 -4
  19. package/src/bench/sweep.ts +2 -2
  20. package/src/cache/fingerprint.ts +2 -2
  21. package/src/capture/bunflags.ts +2 -2
  22. package/src/capture/cpu.ts +2 -2
  23. package/src/capture/heap-parse.ts +2 -2
  24. package/src/ci/index.ts +39 -48
  25. package/src/cli/agent.ts +54 -0
  26. package/src/cli/flags.ts +58 -9
  27. package/src/cli/help.ts +670 -245
  28. package/src/cli/main.ts +2 -3
  29. package/src/cli/output.ts +17 -14
  30. package/src/cli/run.ts +317 -92
  31. package/src/compare/index.ts +4 -4
  32. package/src/config/index.ts +14 -10
  33. package/src/config/validate.ts +4 -4
  34. package/src/glob.ts +2 -2
  35. package/src/index.ts +3 -2
  36. package/src/ir/document.ts +2 -2
  37. package/src/ir/types.ts +49 -24
  38. package/src/measure/alloc.ts +2 -2
  39. package/src/measure/cpu.ts +2 -2
  40. package/src/measure/environment.ts +11 -6
  41. package/src/measure/inprocess.ts +14 -10
  42. package/src/measure/instructions.ts +2 -2
  43. package/src/measure/noise.ts +51 -13
  44. package/src/measure/paired.ts +2 -2
  45. package/src/measure/peak.ts +4 -4
  46. package/src/measure/timing.ts +27 -6
  47. package/src/profile.ts +6 -4
  48. package/src/renderers/collapsed.ts +2 -2
  49. package/src/renderers/concise.ts +148 -0
  50. package/src/renderers/format.ts +13 -4
  51. package/src/renderers/human.ts +402 -0
  52. package/src/renderers/index.ts +9 -2
  53. package/src/renderers/markdown.ts +2 -2
  54. package/src/renderers/mermaid.ts +2 -2
  55. package/src/renderers/minimal.ts +8 -7
  56. package/src/renderers/relative.ts +2 -2
  57. package/src/renderers/select.ts +2 -2
  58. package/src/renderers/terminal.ts +1178 -383
  59. package/src/renderers/types.ts +3 -0
  60. package/src/spawn/index.ts +47 -14
  61. package/src/stats/bootstrap.ts +2 -2
  62. package/src/stats/index.ts +2 -2
  63. package/src/terminal.ts +321 -0
  64. package/src/time.ts +124 -20
@@ -1,48 +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
- formatSignedPct,
18
- formatSpan,
19
- formatUsAsMs,
20
- labelOrId,
21
- topSelfFrames,
22
- workloadLabel,
23
- } 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";
24
36
  import {
25
- abNotes,
26
- abRows,
27
- alsoHeader,
28
- formatAbHeader,
29
- formatAbSummary,
30
- formatNewSuites,
31
- formatThrew,
32
- memoryCells,
33
- memoryRows,
34
- pairedCells,
35
- } from "./paired.ts";
36
- import {
37
- groupOf,
38
- labelInGroup,
39
- relativeRatios,
40
- type TimingRow,
41
- } 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";
42
59
  import {
43
60
  comparedRows,
44
61
  environmentMismatch,
45
- memoryColumns,
46
62
  memoryReadings,
47
63
  noSampleRuns,
48
64
  oneSidedNote,
@@ -50,9 +66,7 @@ import {
50
66
  runWarnings,
51
67
  shownFrameDeltas,
52
68
  shownHeapDeltas,
53
- shownMemoryDeltas,
54
- skippedWorkloads,
55
- thresholdNote,
69
+ type TimingRun,
56
70
  timingRuns,
57
71
  workloadsById,
58
72
  } from "./select.ts";
@@ -60,411 +74,1192 @@ import type { Renderer, RenderResult } from "./types.ts";
60
74
 
61
75
  const TOP_FRAMES = 5;
62
76
  const TOP_TYPES = 5;
63
- const MIN_MEMORY_WIDTH = 10;
64
-
65
- interface Column<R> {
66
- header: string;
67
- width: number;
68
- cell: (data: R) => string;
69
- }
70
-
71
- interface TableRow<R> {
72
- label: string;
73
- group?: string | undefined;
74
- /** Absent when there is nothing to tabulate; `status` says why. */
75
- data?: R;
76
- /** The row's text when `data` is absent: `skipped` or `no samples`. */
77
- status?: string;
78
- warnings: Warning[];
79
- }
80
-
81
- function textTable<R>(columns: Column<R>[], rows: TableRow<R>[]): string[] {
82
- const indentOf = (row: TableRow<R>) => (row.group !== undefined ? " " : "");
83
- const shown = (row: TableRow<R>) => labelInGroup(row.label, row.group);
84
- let labelWidth = 4;
85
- for (const r of rows) {
86
- labelWidth = Math.max(labelWidth, indentOf(r).length + shown(r).length);
87
- }
88
- const header = `${"Task".padEnd(labelWidth)} ${columns.map((c) => c.header.padEnd(c.width)).join(" ")}`;
89
- const lines = [header, "-".repeat(header.length)];
90
- let lastGroup: string | undefined;
91
- for (const row of rows) {
92
- if (row.group !== undefined && row.group !== lastGroup) {
93
- lines.push(`${row.group}:`);
94
- }
95
- lastGroup = row.group;
96
- const indent = indentOf(row);
97
- const label = (indent + shown(row)).padEnd(labelWidth);
98
- const data = row.data;
99
- lines.push(
100
- data === undefined
101
- ? `${label} - ${row.status}`
102
- : `${label} ${columns.map((c) => c.cell(data).padEnd(c.width)).join(" ")}`,
103
- );
104
- if (row.warnings.length > 0) {
105
- lines.push(`${indent} ! ${row.warnings.map((w) => w.code).join(", ")}`);
106
- }
107
- }
108
- return lines;
109
- }
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;
110
84
 
111
- function warningFootnotes(rows: TableRow<unknown>[]): string[] {
112
- const lines = rows.flatMap((row) =>
113
- row.warnings.map((w) => ` ${row.label}: ${w.message}`),
114
- );
115
- 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
+ };
116
111
  }
117
112
 
118
- function finish(lines: string[]): RenderResult {
119
- 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;
120
119
  }
121
120
 
122
- export const terminalRenderer: Renderer = {
121
+ export const terminalRenderer: Renderer<TableOptions> = {
123
122
  name: "table",
124
- render(doc: ProfileDocument): Promise<RenderResult> {
123
+ render(doc: ProfileDocument, options: TableOptions): Promise<RenderResult> {
125
124
  return Promise.try(() => {
126
- const env = doc.environment
127
- ? [formatEnvironmentLine(doc.environment), ""]
128
- : [];
129
-
130
- // Only `ab()` writes paired measurements, and it always stamps `ab`.
131
- if (doc.ab) return finish(renderPaired(doc, doc.ab, env));
132
-
133
- const runs = timingRuns(doc);
134
- const empty = noSampleRuns(doc);
135
- const comparisons = renderComparisons(doc);
136
- if (
137
- runs.length === 0 &&
138
- empty.length === 0 &&
139
- skippedWorkloads(doc, runs).length === 0
140
- ) {
141
- return comparisons.length > 0
142
- ? finish([...env, ...comparisons])
143
- : { text: "(no timing runs)\n" };
144
- }
145
-
146
- const lines = [...env, ...renderTiming(doc, runs, empty)];
147
- const instrumented = renderInstrumentedRuns(doc);
148
- if (instrumented.length > 0) lines.push("", ...instrumented);
149
- if (comparisons.length > 0) lines.push("", ...comparisons);
150
- return finish(lines);
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,
137
+ ];
138
+ return { text: `${lines.map((l) => l.trimEnd()).join("\n")}\n` };
151
139
  });
152
140
  },
153
141
  };
154
142
 
155
- function renderTiming(
143
+ function toReport(
156
144
  doc: ProfileDocument,
157
- runs: ReturnType<typeof timingRuns>,
158
- noSamples: ReturnType<typeof noSampleRuns>,
159
- ): string[] {
160
- const memory = memoryReadings(doc);
161
- const runByWorkloadId = new Map(runs.map((r) => [r.workloadId, r]));
162
- const noSampleByWorkloadId = new Map(noSamples.map((r) => [r.workloadId, r]));
163
-
164
- // doc.workloads order, so a skipped task prints in its group's place.
165
- const rows: TableRow<TimingRow>[] = [];
166
- const measured: TimingRow[] = [];
167
- for (const workload of doc.workloads) {
168
- const run = runByWorkloadId.get(workload.id);
169
- const label = workloadLabel(workload);
170
- const group = groupOf(workload);
171
- const noSample = noSampleByWorkloadId.get(workload.id);
172
- if (run) {
173
- const data = { run, workload };
174
- measured.push(data);
175
- rows.push({ label, group, data, warnings: runWarnings(run, memory) });
176
- } else if (noSample) {
177
- const warnings = runWarnings(noSample, memory);
178
- rows.push({ label, group, status: "no samples", warnings });
179
- } else if (workload.skipped) {
180
- 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}`;
181
181
  }
182
182
  }
183
+ return line === "" ? lines : [...lines, line];
184
+ }
185
+
186
+ const elapsedPart = (options: TableOptions) =>
187
+ options.elapsedMs === undefined ? "" : ` in ${toElapsed(options.elapsedMs)}`;
183
188
 
184
- const unitOf = ({ run }: TimingRow) => pickDurationUnit(run.timing.median);
185
- const cpuTimesByRow = new Map(
186
- 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 }] : [],
187
305
  );
188
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);
189
320
 
190
- const columns: Column<TimingRow>[] = [
191
- {
192
- header: "Median",
193
- width: 10,
194
- cell: (row) => formatDuration(row.run.timing.median, unitOf(row)),
195
- },
196
- {
197
- header: "Spread",
198
- width: 18,
199
- cell: (row) =>
200
- formatSpan(row.run.timing.p75, row.run.timing.p99, unitOf(row)),
201
- },
202
- {
203
- header: "Range",
204
- width: 18,
205
- cell: (row) =>
206
- formatSpan(row.run.timing.min, row.run.timing.max, unitOf(row)),
207
- },
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"] : []),
208
330
  ];
209
- if ([...cpuTimesByRow.values()].some(Boolean)) {
210
- columns.push({
211
- header: "User/Sys",
212
- width: 18,
213
- cell: (row) => {
214
- const times = cpuTimesByRow.get(row);
215
- return times ? formatCpuTimes(times) : "";
216
- },
217
- });
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`;
218
444
  }
219
- if (measured.some((row) => row.run.instructions)) {
220
- columns.push({
221
- header: "Instr/call",
222
- width: 10,
223
- cell: (row) =>
224
- row.run.instructions
225
- ? formatInstructions(row.run.instructions.median)
226
- : "",
227
- });
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
+ );
228
516
  }
229
- for (const col of memoryColumns(memory)) {
230
- columns.push({
231
- header: col.header,
232
- width: Math.max(col.header.length, MIN_MEMORY_WIDTH),
233
- cell: (row) => col.cell(row.run.workloadId) ?? "",
234
- });
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
+ );
235
536
  }
236
- if (ratios) {
237
- columns.push({
238
- header: "Relative",
239
- width: 8,
240
- cell: (row) => {
241
- const ratio = ratios.get(row);
242
- return ratio === undefined
243
- ? ""
244
- : formatRelative(ratio, !!row.workload?.baseline);
245
- },
246
- });
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
+ );
247
545
  }
248
-
249
- 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
+ );
250
555
  }
251
556
 
252
- function renderPaired(
557
+ // --- ab ---
558
+
559
+ type Flagged = { label: string; workload: Workload | undefined; what: string };
560
+
561
+ function pairedReport(
253
562
  doc: ProfileDocument,
254
563
  ab: AbSummary,
255
- env: string[],
256
- ): string[] {
564
+ options: TableOptions,
565
+ paint: Paint,
566
+ ): Report {
257
567
  const byWorkload = workloadsById(doc);
258
- const lines = [...env, `A/B: ${formatAbHeader(ab)}`, ""];
259
-
260
- const threw: { label: string; verdict: string; message: string }[] = [];
261
- const rows: TableRow<ReturnType<typeof pairedCells>>[] = abRows(doc).map(
262
- ({ kind, run }) => {
263
- const workload = byWorkload.get(run.workloadId);
264
- const label = labelOrId(workload, run.workloadId);
265
- let data: ReturnType<typeof pairedCells>;
266
- if (kind === "threw") {
267
- const verdict = formatThrew(run.threw);
268
- threw.push({ label, verdict, message: run.threw.message });
269
- data = {
270
- base: "-",
271
- candidate: "-",
272
- change: "",
273
- spread: "",
274
- also: "",
275
- verdict,
276
- };
277
- } else {
278
- 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));
279
662
  }
280
- 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,
281
749
  },
282
- );
283
- if (rows.length > 0) {
284
- const also = alsoHeader(doc, ab.metric);
285
- lines.push(
286
- ...textTable<ReturnType<typeof pairedCells>>(
287
- [
288
- { header: "Base", width: 10, cell: (c) => c.base },
289
- { header: "Candidate", width: 10, cell: (c) => c.candidate },
290
- { header: "Change", width: 9, cell: (c) => c.change },
291
- { header: "p25…p75", width: 18, cell: (c) => c.spread },
292
- ...(also
293
- ? [
294
- {
295
- header: also,
296
- width: 8,
297
- cell: (c: ReturnType<typeof pairedCells>) => c.also,
298
- },
299
- ]
300
- : []),
301
- { header: "Verdict", width: 7, cell: (c) => c.verdict },
302
- ],
303
- rows,
304
- ),
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",
305
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" });
306
866
  }
867
+ return notes;
868
+ }
307
869
 
308
- const memory = memoryRows(doc);
309
- if (memory.length > 0) {
310
- lines.push(
311
- "",
312
- "Memory:",
313
- ...textTable<ReturnType<typeof memoryCells>>(
314
- [
315
- { header: "Reading", width: 11, cell: (c) => c.reading },
316
- { header: "Base", width: 10, cell: (c) => c.base },
317
- { header: "Candidate", width: 10, cell: (c) => c.candidate },
318
- { header: "Change", width: 18, cell: (c) => c.change },
319
- { header: "Verdict", width: 7, cell: (c) => c.verdict },
320
- ],
321
- memory.map((row) => {
322
- const workload = byWorkload.get(row.run.workloadId);
323
- return {
324
- label: labelOrId(workload, row.run.workloadId),
325
- group: groupOf(workload),
326
- data: memoryCells(row),
327
- warnings: [],
328
- };
329
- }),
330
- ),
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)}`,
331
890
  );
332
891
  }
333
-
334
- const notes = abNotes(doc);
335
- if (threw.length > 0) {
336
- lines.push("", `Threw (${threw.length}):`);
337
- for (const row of threw) {
338
- const [first, ...rest] = row.message.split("\n");
339
- lines.push(` ${row.label}: ${row.verdict}: ${first}`);
340
- for (const more of rest) lines.push(` ${more}`);
341
- }
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
+ );
342
905
  }
343
- if (notes.outputDiffers.length > 0) {
344
- lines.push(
345
- "",
346
- `Output differs from the base (${notes.outputDiffers.length}):`,
347
- ...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)}`,
348
912
  );
349
913
  }
350
- const newSuites = formatNewSuites(ab);
351
- if (newSuites) lines.push("", newSuites);
352
- if (notes.baseOnly.length > 0 || notes.candOnly.length > 0) {
353
- lines.push("", "Unmatched:");
354
- if (notes.baseOnly.length > 0)
355
- lines.push(` base only: ${notes.baseOnly.join(", ")}`);
356
- if (notes.candOnly.length > 0)
357
- 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
+ );
358
921
  }
359
-
360
- lines.push(...warningFootnotes(rows), "", formatAbSummary(ab));
361
- 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
+ );
362
929
  }
363
930
 
364
- function renderComparisons(doc: ProfileDocument): string[] {
365
- const rows = comparedRows(doc);
366
- if (rows.length === 0) return [];
367
- const lines: string[] = [];
931
+ // --- compare and ci ---
368
932
 
369
- const mismatch = environmentMismatch(doc);
370
- if (mismatch) lines.push(`⚠ ${mismatch.message}`, "");
371
- const note = thresholdNote(doc);
372
- if (note) lines.push(note, "");
373
-
374
- const footnotes: string[] = [];
375
- 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
+ };
376
943
 
377
- 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[];
378
958
  if (row.verdict === "missing-base" || row.verdict === "missing-cand") {
379
- notCompared.push(` ${row.task}: ${oneSidedNote(row.verdict)}`);
380
- continue;
381
- }
382
- lines.push(`${row.pass === false ? "✗" : "✓"} ${row.task}`);
383
- if (row.renamedFrom) lines.push(` renamed from ${row.renamedFrom.task}`);
384
-
385
- if (row.timing) {
386
- const { baseMedian, candMedian, medianDeltaPct, ci95, pValue } =
387
- row.timing;
388
- const unit = pickDurationUnit(Math.max(baseMedian, candMedian));
389
- const medians = `${formatDuration(baseMedian, unit)} -> ${formatDuration(candMedian, unit)}`;
390
- if (ci95 && pValue !== undefined) {
391
- const p = pValue < 0.001 ? "p<0.001" : `p=${pValue.toFixed(3)}`;
392
- lines.push(
393
- ` timing: ${medians}, ${formatSignedPct(medianDeltaPct)} median, 95% CI [${formatSignedPct(ci95[0])}, ${formatSignedPct(ci95[1])}], ${p} (${row.verdict})`,
394
- );
395
- } else {
396
- lines.push(
397
- ` timing: ${medians}, ${formatSignedPct(medianDeltaPct)} median (${row.verdict})`,
398
- );
399
- }
400
- }
401
- const memory = shownMemoryDeltas(row, "->");
402
- if (memory.length > 0) lines.push(` memory: ${memory.join(", ")}`);
403
- if (!cmp) continue;
404
- for (const f of shownFrameDeltas(cmp, TOP_FRAMES)) {
405
- lines.push(
406
- ` frame ${f.name}: ${formatSignedPct(f.deltaPct)} self-time (${formatUsAsMs(f.baseSelfUs)}ms -> ${formatUsAsMs(f.candSelfUs)}ms)`,
407
- );
408
- }
409
- for (const h of shownHeapDeltas(cmp, TOP_TYPES)) {
410
- lines.push(
411
- ` heap ${h.type}: ${formatSignedPct(h.deltaPct)} count (${h.baseCount} -> ${h.candCount})`,
412
- );
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));
413
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
+ }
414
1022
 
415
- const warnings = rowComparisonWarnings(cmp);
416
- if (warnings.length > 0) {
417
- lines.push(` ! ${warnings.map((w) => w.code).join(", ")}`);
418
- 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
+ );
419
1083
  }
420
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
+ }
421
1100
 
422
- if (notCompared.length > 0) lines.push("", "Not compared:", ...notCompared);
423
- if (footnotes.length > 0)
424
- lines.push("", "Comparison warnings:", ...footnotes);
425
- 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);
426
1130
  }
427
1131
 
428
- function renderInstrumentedRuns(doc: ProfileDocument): string[] {
429
- const byWorkload: Map<string, Workload> = workloadsById(doc);
430
- 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
+ }
431
1177
 
432
- for (const run of doc.measurements) {
433
- if (run.phase !== "cpu" && run.phase !== "heap") continue;
434
- const workload = byWorkload.get(run.workloadId);
435
- 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
+ }
436
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[] = [];
437
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));
438
1217
  if (run.cpu) {
439
- lines.push(
440
- `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,
441
1222
  );
442
- for (const f of topSelfFrames(run.cpu, TOP_FRAMES)) {
443
- lines.push(
444
- ` ${f.pct.padStart(5)}% ${formatUsAsMs(f.selfUs).padStart(8)}ms self ${f.frame?.name ?? "?"}`,
445
- );
446
- }
447
- } else {
448
1223
  lines.push(
449
- `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
+ ),
450
1234
  );
451
1235
  }
452
- } else if (run.heap) {
453
- lines.push(
454
- `Heap snapshot - ${label} (instrumented, ${formatHeapSummary(run.heap)})`,
455
- );
456
- for (const tc of run.heap.typeCounts.slice(0, TOP_TYPES)) {
457
- lines.push(` ${String(tc.count).padStart(6)} ${tc.type}`);
458
- }
459
1236
  } else {
460
- lines.push(
461
- `Heap snapshot - ${label} (instrumented, no evidence captured)`,
462
- );
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
+ }
463
1256
  }
464
-
465
- for (const a of run.artifacts) lines.push(` artifact: ${a.path}`);
466
- for (const w of run.warnings) lines.push(` ! ${w.message}`);
467
- }
468
-
469
- 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
+ });
470
1265
  }