ostia 0.2.11 → 0.3.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 (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -353
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +942 -642
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-scvezzm9.js → src/cli/help.ts} +31 -15
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-5m601yfv.js +0 -15
  89. package/chunk-82vs1rw1.js +0 -2
  90. package/chunk-dvqggjkn.js +0 -14
  91. package/chunk-fc36fd0b.js +0 -3
  92. package/chunk-pdv5zb3w.js +0 -27
  93. package/chunk-r6hwb84z.js +0 -25
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,229 @@
1
+ import { formatDuration, pickDurationUnit } from "../format.ts";
2
+ import type {
3
+ AbSummary,
4
+ Measurement,
5
+ MemoryChange,
6
+ PairedEvidence,
7
+ ProfileDocument,
8
+ } from "../ir/types.ts";
9
+ import { comparable, metricRatios, sideLabel } from "../measure/paired.ts";
10
+ import {
11
+ formatBytes,
12
+ formatInstructions,
13
+ formatSignedPct,
14
+ labelOrId,
15
+ } from "./format.ts";
16
+ import { workloadsById } from "./select.ts";
17
+
18
+ export type PairedRun = Measurement & {
19
+ timing: NonNullable<Measurement["timing"]>;
20
+ paired: PairedEvidence;
21
+ };
22
+
23
+ export type ThrewRun = Measurement & {
24
+ threw: NonNullable<Measurement["threw"]>;
25
+ };
26
+
27
+ /** A task that threw, on either side, in its first process or a repeat. */
28
+ function isThrewRun(m: Measurement): m is ThrewRun {
29
+ return m.phase === "paired" && m.threw !== undefined;
30
+ }
31
+
32
+ /** A task judged on its time: measured, and it never threw. */
33
+ function isPairedRun(m: Measurement): m is PairedRun {
34
+ return (
35
+ m.phase === "paired" &&
36
+ m.threw === undefined &&
37
+ m.timing !== undefined &&
38
+ m.paired !== undefined
39
+ );
40
+ }
41
+
42
+ export function pairedRuns(doc: ProfileDocument): PairedRun[] {
43
+ return doc.measurements.filter(isPairedRun);
44
+ }
45
+
46
+ /** An `ab()` document's tasks that threw. */
47
+ export function threwRuns(doc: ProfileDocument): ThrewRun[] {
48
+ return doc.measurements.filter(isThrewRun);
49
+ }
50
+
51
+ export type AbRow =
52
+ { kind: "timed"; run: PairedRun } | { kind: "threw"; run: ThrewRun };
53
+
54
+ /** Every row of an A/B table, timed or threw, in document order. */
55
+ export function abRows(doc: ProfileDocument): AbRow[] {
56
+ const rows: AbRow[] = [];
57
+ for (const m of doc.measurements) {
58
+ if (isThrewRun(m)) rows.push({ kind: "threw", run: m });
59
+ else if (isPairedRun(m)) rows.push({ kind: "timed", run: m });
60
+ }
61
+ return rows;
62
+ }
63
+
64
+ /**
65
+ * `base threw`, `candidate threw`, `both threw`, with `(repeat 1)` when it
66
+ * threw in a confirmation repeat. */
67
+ export function formatThrew(threw: ThrewRun["threw"]): string {
68
+ return `${sideLabel(threw.side)} threw${threw.repeat ? ` (repeat ${threw.repeat})` : ""}`;
69
+ }
70
+
71
+ /** A candidate/base ratio as a signed percent change: `1.032` is `+3.2%`. */
72
+ function formatRatio(ratio: number): string {
73
+ return formatSignedPct((ratio - 1) * 100);
74
+ }
75
+
76
+ // Blank for unchanged; a flagged workload that fresh processes didn't
77
+ // reproduce reads `unconfirmed`. Repeats follow so the confirmation is
78
+ // visible. A changed suite with changed output reads `not comparable`.
79
+ function pairedVerdict(p: PairedEvidence, metric: AbSummary["metric"]): string {
80
+ if (!comparable(p)) return "not comparable";
81
+ if (!p.flagged) return "";
82
+ const repeats = p.repeats?.length
83
+ ? ` (repeats: ${p.repeats.map((r) => formatRatio(metricRatios(r, metric)?.medianRatio ?? Number.NaN)).join(", ")})`
84
+ : "";
85
+ if (p.confirmed === undefined) return `${p.flagged}${repeats}`;
86
+ return `${p.confirmed ? `${p.flagged}, confirmed` : `${p.flagged}? unconfirmed`}${repeats}`;
87
+ }
88
+
89
+ /** `New suites, not at HEAD: bench/new.bench.ts`, or nothing. */
90
+ export function formatNewSuites(ab: AbSummary): string | undefined {
91
+ if (!ab.newSuites?.length) return undefined;
92
+ return `New suite${ab.newSuites.length > 1 ? "s" : ""}, not at ${ab.base.ref}: ${ab.newSuites.join(", ")}`;
93
+ }
94
+
95
+ /**
96
+ * The text of one paired row's table cells: `metric`'s per-call medians
97
+ * and change, then in `also` the other metric's change (see `alsoHeader`),
98
+ * blank on a task without an instruction count. */
99
+ export function pairedCells(run: PairedRun, metric: AbSummary["metric"]) {
100
+ const p = run.paired;
101
+ const i = p.instructions;
102
+ const judged = metricRatios(p, metric);
103
+ const other = metricRatios(p, metric === "time" ? "instructions" : "time");
104
+ let base = "-";
105
+ let candidate = "-";
106
+ if (metric === "time") {
107
+ const unit = pickDurationUnit(Math.min(p.baseMedianNs, run.timing.median));
108
+ base = formatDuration(p.baseMedianNs, unit);
109
+ candidate = formatDuration(run.timing.median, unit);
110
+ } else if (i) {
111
+ base = formatInstructions(i.baseMedian);
112
+ candidate = formatInstructions(i.candMedian);
113
+ }
114
+ return {
115
+ base,
116
+ candidate,
117
+ change: judged ? formatRatio(judged.medianRatio) : "",
118
+ spread: judged
119
+ ? `${formatRatio(judged.ratioP25)}…${formatRatio(judged.ratioP75)}`
120
+ : "",
121
+ also: other ? formatRatio(other.medianRatio) : "",
122
+ verdict: pairedVerdict(p, metric),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * The header of `pairedCells`'s `also` column, or undefined when no row
128
+ * would fill it. */
129
+ export function alsoHeader(
130
+ doc: ProfileDocument,
131
+ metric: AbSummary["metric"],
132
+ ): string | undefined {
133
+ if (metric === "instructions") return "Time";
134
+ return doc.measurements.some((m) => m.paired?.instructions)
135
+ ? "Instr"
136
+ : undefined;
137
+ }
138
+
139
+ export interface MemoryRow {
140
+ run: PairedRun;
141
+ reading: "retained/op" | "peak";
142
+ change: MemoryChange;
143
+ }
144
+
145
+ /** Each timed task's memory readings, retained before peak. */
146
+ export function memoryRows(doc: ProfileDocument): MemoryRow[] {
147
+ return pairedRuns(doc).flatMap((run) => {
148
+ const rows: MemoryRow[] = [];
149
+ const { retained, peak } = run.paired;
150
+ if (retained) rows.push({ run, reading: "retained/op", change: retained });
151
+ if (peak) rows.push({ run, reading: "peak", change: peak });
152
+ return rows;
153
+ });
154
+ }
155
+
156
+ /**
157
+ * `+1.50MiB (+87.4%)`, in whole bytes; no percent when the base is under
158
+ * the noise floor, where it would be huge and meaningless. */
159
+ function formatByteChange(c: MemoryChange): string {
160
+ const base = Math.round(c.baseBytes);
161
+ const diff = Math.round(c.candBytes) - base;
162
+ if (diff === 0) return "0B";
163
+ const bytes = `${diff > 0 ? "+" : "-"}${formatBytes(Math.abs(diff))}`;
164
+ if (base === 0 || c.baseBytes < c.floorBytes) return bytes;
165
+ return `${bytes} (${formatSignedPct((diff / base) * 100)})`;
166
+ }
167
+
168
+ /** The text of one memory row's table cells. */
169
+ export function memoryCells({ reading, change: c }: MemoryRow) {
170
+ return {
171
+ reading,
172
+ base: formatBytes(c.baseBytes),
173
+ candidate: formatBytes(c.candBytes),
174
+ change: formatByteChange(c),
175
+ verdict: c.verdict === "unchanged" ? "" : c.verdict,
176
+ };
177
+ }
178
+
179
+ /**
180
+ * `working tree vs HEAD (26e7d0d) · 15 rounds · threshold 10% · geomean
181
+ * threshold 1.5%`, with `· by instructions/call` after the rounds when
182
+ * that's the metric. */
183
+ export function formatAbHeader(ab: AbSummary): string {
184
+ const metric = ab.metric === "instructions" ? " · by instructions/call" : "";
185
+ const memory = ab.memory
186
+ ? ` · memory threshold ${ab.memory.thresholdPct}%`
187
+ : "";
188
+ return `working tree vs ${ab.base.ref} (${ab.base.sha.slice(0, 7)}) · ${ab.rounds} rounds${metric} · threshold ${ab.thresholdPct}% · geomean threshold ${ab.geomeanThresholdPct}%${memory}`;
189
+ }
190
+
191
+ /**
192
+ * `Geomean +2.1% (threshold 1.5%) · 1 regressed, 0 improved, 47 unchanged
193
+ * of 48 (1 unconfirmed) · memory: 0 regressed, 1 improved · fail`
194
+ */
195
+ export function formatAbSummary(ab: AbSummary): string {
196
+ const geomean =
197
+ ab.geomeanPct === null
198
+ ? "Geomean -"
199
+ : `Geomean ${formatSignedPct(ab.geomeanPct)} (threshold ${ab.geomeanThresholdPct}%)`;
200
+ const notes = [
201
+ ab.unconfirmed > 0 && `${ab.unconfirmed} unconfirmed`,
202
+ ab.notComparable > 0 && `${ab.notComparable} not comparable`,
203
+ ab.threw > 0 && `${ab.threw} threw`,
204
+ ].filter(Boolean);
205
+ const unconfirmed = notes.length > 0 ? ` (${notes.join(", ")})` : "";
206
+ const memory = ab.memory
207
+ ? ` · memory: ${ab.memory.regressed} regressed, ${ab.memory.improved} improved`
208
+ : "";
209
+ return `${geomean} · ${ab.regressed} regressed, ${ab.improved} improved, ${ab.unchanged} unchanged of ${ab.matched}${unconfirmed}${memory} · ${ab.verdict}`;
210
+ }
211
+
212
+ /**
213
+ * Labels of workloads whose output differed between sides, and of those
214
+ * present on only one side. */
215
+ export function abNotes(doc: ProfileDocument): {
216
+ outputDiffers: string[];
217
+ baseOnly: string[];
218
+ candOnly: string[];
219
+ } {
220
+ const byId = workloadsById(doc);
221
+ const label = (id: string) => labelOrId(byId.get(id), id);
222
+ return {
223
+ outputDiffers: pairedRuns(doc)
224
+ .filter((m) => !m.paired.sameOutput)
225
+ .map((m) => label(m.workloadId)),
226
+ baseOnly: (doc.unmatched?.baseOnly ?? []).map(label),
227
+ candOnly: (doc.unmatched?.candOnly ?? []).map(label),
228
+ };
229
+ }
@@ -0,0 +1,64 @@
1
+ import type { Workload } from "../ir/types.ts";
2
+ import type { TimingRun } from "./select.ts";
3
+
4
+ export interface TimingRow {
5
+ run: TimingRun;
6
+ workload: Workload | undefined;
7
+ }
8
+
9
+ /**
10
+ * The explicit `entry.group` the bench runner records, else the
11
+ * "group/name" id split on its last "/" (documents from before that field
12
+ * existed). */
13
+ export function groupOf(workload: Workload | undefined): string | undefined {
14
+ if (!workload?.entry) return undefined;
15
+ if (workload.entry.group !== undefined) return workload.entry.group;
16
+ const id = workload.entry.task;
17
+ const idx = id.lastIndexOf("/");
18
+ return idx === -1 ? undefined : id.slice(0, idx);
19
+ }
20
+
21
+ /**
22
+ * A row's label under its group's header: the task name alone, since the
23
+ * header already shows the group. */
24
+ export function labelInGroup(label: string, group: string | undefined): string {
25
+ return group !== undefined && label.startsWith(`${group}/`)
26
+ ? label.slice(group.length + 1)
27
+ : label;
28
+ }
29
+
30
+ /**
31
+ * Each row's median over its reference median: its group's
32
+ * `task(..., { baseline: true })` task, else the group's fastest.
33
+ * Ungrouped rows use the fastest in the document; tasks never compare
34
+ * across groups. Undefined with fewer than two rows, where "relative"
35
+ * means nothing. */
36
+ export function relativeRatios<R extends TimingRow>(
37
+ rows: R[],
38
+ ): Map<R, number> | undefined {
39
+ if (rows.length < 2) return undefined;
40
+ const fastestMedian = Math.min(...rows.map((r) => r.run.timing.median));
41
+ const siblingsByGroup = new Map<string, R[]>();
42
+ for (const row of rows) {
43
+ const key = groupOf(row.workload);
44
+ if (key === undefined) continue;
45
+ const siblings = siblingsByGroup.get(key);
46
+ if (siblings) siblings.push(row);
47
+ else siblingsByGroup.set(key, [row]);
48
+ }
49
+
50
+ const ratios = new Map<R, number>();
51
+ for (const row of rows) {
52
+ const key = groupOf(row.workload);
53
+ let reference = fastestMedian;
54
+ if (key !== undefined) {
55
+ const siblings = siblingsByGroup.get(key)!;
56
+ const baselineRow = siblings.find((s) => s.workload?.baseline);
57
+ reference = baselineRow
58
+ ? baselineRow.run.timing.median
59
+ : Math.min(...siblings.map((s) => s.run.timing.median));
60
+ }
61
+ ratios.set(row, row.run.timing.median / reference);
62
+ }
63
+ return ratios;
64
+ }
@@ -0,0 +1,286 @@
1
+ import type {
2
+ ComparedTask,
3
+ Comparison,
4
+ Measurement,
5
+ MemoryDelta,
6
+ ProfileDocument,
7
+ Warning,
8
+ Workload,
9
+ } from "../ir/types.ts";
10
+ import {
11
+ formatBytes,
12
+ formatSignedPct,
13
+ labelOrId,
14
+ workloadLabel,
15
+ } from "./format.ts";
16
+
17
+ // Below this absolute percent a frame/heap-type delta is noise, not a row.
18
+ const MIN_DISPLAY_DELTA_PCT = 0.5;
19
+
20
+ export type TimingRun = Measurement & {
21
+ timing: NonNullable<Measurement["timing"]>;
22
+ };
23
+
24
+ export type FrameDelta = NonNullable<Comparison["frames"]>[number];
25
+ export type HeapTypeDelta = NonNullable<Comparison["heapTypes"]>[number];
26
+
27
+ export function workloadsById(doc: ProfileDocument): Map<string, Workload> {
28
+ return new Map(doc.workloads.map((w) => [w.id, w]));
29
+ }
30
+
31
+ export function timingRuns(doc: ProfileDocument): TimingRun[] {
32
+ return doc.measurements.filter(
33
+ (r): r is TimingRun => r.phase === "timing" && r.timing !== undefined,
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Timing measurements that produced no samples (every trial timed out or
39
+ * missed the `timeSource` pattern). Renderers show them as "no samples"
40
+ * rows so their warnings stay visible. */
41
+ export function noSampleRuns(doc: ProfileDocument): Measurement[] {
42
+ return doc.measurements.filter(
43
+ (r) => r.phase === "timing" && r.timing === undefined,
44
+ );
45
+ }
46
+
47
+ /**
48
+ * `task.skip()`'d workloads with no measurement, rendered as "- skipped"
49
+ * rows.
50
+ */
51
+ export function skippedWorkloads(
52
+ doc: ProfileDocument,
53
+ runs: { workloadId: string }[],
54
+ ): Workload[] {
55
+ const measured = new Set(runs.map((r) => r.workloadId));
56
+ return doc.workloads.filter((w) => w.skipped && !measured.has(w.id));
57
+ }
58
+
59
+ /**
60
+ * `environment-mismatch` is the same on every comparison (it concerns the
61
+ * base/cand pair): renderers print it once, from here, and drop it per
62
+ * row. */
63
+ export function environmentMismatch(doc: ProfileDocument): Warning | undefined {
64
+ for (const c of doc.comparisons ?? []) {
65
+ const w = c.warnings?.find((w) => w.code === "environment-mismatch");
66
+ if (w) return w;
67
+ }
68
+ return undefined;
69
+ }
70
+
71
+ export function rowComparisonWarnings(cmp: Comparison): Warning[] {
72
+ return (cmp.warnings ?? []).filter((w) => w.code !== "environment-mismatch");
73
+ }
74
+
75
+ /**
76
+ * Resolves a comparison to its candidate measurement and workload, plus
77
+ * the workload id (the display fallback when the document lacks the
78
+ * workload). A skipped candidate has no measurement, so
79
+ * `candidateMeasurementId` then holds the workload id itself. */
80
+ function comparisonResolver(doc: ProfileDocument) {
81
+ const workloads = workloadsById(doc);
82
+ const runs = new Map(doc.measurements.map((m) => [m.id, m]));
83
+ return (cmp: Comparison) => {
84
+ const run = runs.get(cmp.candidateMeasurementId);
85
+ const workloadId = run?.workloadId ?? cmp.candidateMeasurementId;
86
+ return { run, workloadId, workload: workloads.get(workloadId) };
87
+ };
88
+ }
89
+
90
+ export function shownFrameDeltas(cmp: Comparison, limit: number): FrameDelta[] {
91
+ return (cmp.frames ?? [])
92
+ .slice(0, limit)
93
+ .filter((f) => Math.abs(f.deltaPct) >= MIN_DISPLAY_DELTA_PCT);
94
+ }
95
+
96
+ export function shownHeapDeltas(
97
+ cmp: Comparison,
98
+ limit: number,
99
+ ): HeapTypeDelta[] {
100
+ return (cmp.heapTypes ?? [])
101
+ .slice(0, limit)
102
+ .filter((h) => Math.abs(h.deltaPct) >= MIN_DISPLAY_DELTA_PCT);
103
+ }
104
+
105
+ export interface MemoryReadings {
106
+ /** `--alloc`: heap each call retains, bytes. */
107
+ retained?: number;
108
+ /** `--peak-mem`: RSS rise of one call, bytes. */
109
+ peak?: number;
110
+ /** The `memstats` measurements' warnings (e.g. `peak-hidden`). */
111
+ warnings: Warning[];
112
+ }
113
+
114
+ export function memoryReadings(
115
+ doc: ProfileDocument,
116
+ ): Map<string, MemoryReadings> {
117
+ const byWorkload = new Map<string, MemoryReadings>();
118
+ for (const m of doc.measurements) {
119
+ if (m.phase !== "memstats" || !m.memory) continue;
120
+ const readings = byWorkload.get(m.workloadId) ?? { warnings: [] };
121
+ if (m.memory.bytesPerOp !== undefined)
122
+ readings.retained = m.memory.bytesPerOp;
123
+ if (m.memory.peakBytes !== undefined) readings.peak = m.memory.peakBytes;
124
+ readings.warnings.push(...m.warnings);
125
+ byWorkload.set(m.workloadId, readings);
126
+ }
127
+ return byWorkload;
128
+ }
129
+
130
+ /** A timing run's warnings plus its workload's `memstats` warnings. */
131
+ export function runWarnings(
132
+ run: Measurement,
133
+ memory: Map<string, MemoryReadings>,
134
+ ): Warning[] {
135
+ const extra = memory.get(run.workloadId)?.warnings;
136
+ return extra?.length ? [...run.warnings, ...extra] : run.warnings;
137
+ }
138
+
139
+ export interface MemoryColumn {
140
+ header: string;
141
+ /** Formatted bytes, or undefined when this workload has no reading. */
142
+ cell: (workloadId: string) => string | undefined;
143
+ }
144
+
145
+ /**
146
+ * `Retained/op` and `Peak mem` columns, each only when some workload has
147
+ * it.
148
+ */
149
+ export function memoryColumns(
150
+ memory: Map<string, MemoryReadings>,
151
+ ): MemoryColumn[] {
152
+ const candidates = [
153
+ { header: "Retained/op", read: (r: MemoryReadings) => r.retained },
154
+ { header: "Peak mem", read: (r: MemoryReadings) => r.peak },
155
+ ];
156
+ return candidates
157
+ .filter((c) => {
158
+ for (const r of memory.values()) if (c.read(r) !== undefined) return true;
159
+ return false;
160
+ })
161
+ .map((c) => ({
162
+ header: c.header,
163
+ cell: (id) => {
164
+ const readings = memory.get(id);
165
+ const bytes = readings && c.read(readings);
166
+ return bytes === undefined ? undefined : formatBytes(bytes);
167
+ },
168
+ }));
169
+ }
170
+
171
+ /**
172
+ * The document's `compared` rows, each with its `Comparison` (absent on a
173
+ * one-sided task). A document compared before `compared` existed gets rows
174
+ * rebuilt from `comparisons` and `unmatched`: no sample counts or memory,
175
+ * the base median derived from the change, base-only tasks named by id. */
176
+ export function comparedRows(
177
+ doc: ProfileDocument,
178
+ ): { row: ComparedTask; cmp: Comparison | undefined }[] {
179
+ // Most documents were never compared: skip building the lookups.
180
+ if (!doc.compared && !doc.comparisons?.length && !doc.unmatched) return [];
181
+ const byId = new Map((doc.comparisons ?? []).map((c) => [c.id, c]));
182
+ const rows = doc.compared ?? rebuildCompared(doc);
183
+ return rows.map((row) => ({
184
+ row,
185
+ cmp:
186
+ row.comparisonId === undefined ? undefined : byId.get(row.comparisonId),
187
+ }));
188
+ }
189
+
190
+ function rebuildCompared(doc: ProfileDocument): ComparedTask[] {
191
+ const resolve = comparisonResolver(doc);
192
+ const workloads = workloadsById(doc);
193
+ const oneSided = (
194
+ id: string,
195
+ verdict: "missing-base" | "missing-cand",
196
+ ): ComparedTask => {
197
+ const w = workloads.get(id);
198
+ return {
199
+ workloadId: id,
200
+ task: labelOrId(w, id),
201
+ ...(w?.entry?.group !== undefined && { group: w.entry.group }),
202
+ verdict,
203
+ };
204
+ };
205
+ return [
206
+ ...(doc.comparisons ?? []).map((cmp): ComparedTask => {
207
+ const { run, workload, workloadId } = resolve(cmp);
208
+ const row: ComparedTask = {
209
+ workloadId,
210
+ task: workload ? workloadLabel(workload) : workloadId,
211
+ ...(workload?.entry?.group !== undefined && {
212
+ group: workload.entry.group,
213
+ }),
214
+ verdict: cmp.timing?.verdict ?? "unchanged",
215
+ comparisonId: cmp.id,
216
+ pass: cmp.verdict === "pass",
217
+ };
218
+ if (cmp.timing && run?.timing) {
219
+ const { medianDeltaPct, ci95, pValue } = cmp.timing;
220
+ row.timing = {
221
+ unit: "ns",
222
+ baseMedian: run.timing.median / (1 + medianDeltaPct / 100),
223
+ candMedian: run.timing.median,
224
+ candSamples: run.timing.samples.length,
225
+ medianDeltaPct,
226
+ ...(ci95 && { ci95 }),
227
+ ...(pValue !== undefined && { pValue }),
228
+ thresholdPct: cmp.thresholds.effectiveTimingPct,
229
+ };
230
+ }
231
+ return row;
232
+ }),
233
+ ...(doc.unmatched?.candOnly ?? []).map((id) =>
234
+ oneSided(id, "missing-base"),
235
+ ),
236
+ ...(doc.unmatched?.baseOnly ?? []).map((id) =>
237
+ oneSided(id, "missing-cand"),
238
+ ),
239
+ ];
240
+ }
241
+
242
+ // Heap readings move with GC timing, so a small change is noise, not a
243
+ // line.
244
+ const MIN_MEMORY_DISPLAY_PCT = 10;
245
+
246
+ const MEMORY_READING_LABELS: Record<MemoryDelta["reading"], string> = {
247
+ heapUsedBefore: "heap used before",
248
+ heapUsedAfter: "heap used after",
249
+ retained: "retained/op",
250
+ peak: "peak",
251
+ maxRss: "max RSS",
252
+ };
253
+
254
+ /**
255
+ * `heap used before 12.00MiB → 16.80MiB (+40.0%)` for each memory reading
256
+ * that moved at least 10%. */
257
+ export function shownMemoryDeltas(row: ComparedTask, arrow = "→"): string[] {
258
+ return (row.memory ?? [])
259
+ .filter((m) => !(Math.abs(m.deltaPct) < MIN_MEMORY_DISPLAY_PCT))
260
+ .map(
261
+ (m) =>
262
+ `${MEMORY_READING_LABELS[m.reading]} ${formatBytes(m.baseBytes)} ${arrow} ${formatBytes(m.candBytes)} (${Number.isFinite(m.deltaPct) ? formatSignedPct(m.deltaPct) : "new"})`,
263
+ );
264
+ }
265
+
266
+ /**
267
+ * `Timing threshold 5.0%, widened to 17.3% by machine noise and drift
268
+ * (12.3%)`, when noise or drift widened it; else undefined. */
269
+ export function thresholdNote(doc: ProfileDocument): string | undefined {
270
+ const summary = doc.comparisonSummary;
271
+ const base = doc.comparisons?.[0]?.thresholds.timingPct;
272
+ if (!summary || base === undefined) return undefined;
273
+ if (!(summary.effectiveTimingPct > base)) return undefined;
274
+ const drift =
275
+ summary.driftPct !== undefined && summary.driftPct > 0
276
+ ? ` and drift (${summary.driftPct.toFixed(1)}%); \`ostia ab\` alternates base and candidate in one process, so drift can't favor either`
277
+ : "";
278
+ return `Timing threshold ${base.toFixed(1)}%, widened to ${summary.effectiveTimingPct.toFixed(1)}% by machine noise${drift}`;
279
+ }
280
+
281
+ /** "base only" / "candidate only", and what that usually means. */
282
+ export function oneSidedNote(verdict: "missing-base" | "missing-cand"): string {
283
+ return verdict === "missing-base"
284
+ ? "candidate only (new, or renamed without `aliases`)"
285
+ : "base only (removed, or renamed without `aliases`)";
286
+ }
@@ -0,0 +1,69 @@
1
+ import type { ProfileDocument } from "../ir/types.ts";
2
+ import { buildDenseTree, renderCpuFiles } from "./cpu-tree.ts";
3
+ import { frameName } from "./format.ts";
4
+ import { workloadsById } from "./select.ts";
5
+ import type { Renderer, RenderResult, VizOptions } from "./types.ts";
6
+
7
+ const SCHEMA_URL = "https://www.speedscope.app/file-format-schema.json";
8
+
9
+ export const speedscopeRenderer: Renderer<VizOptions> = {
10
+ name: "speedscope",
11
+ async render(
12
+ doc: ProfileDocument,
13
+ options: VizOptions = {},
14
+ ): Promise<RenderResult> {
15
+ const byWorkload = workloadsById(doc);
16
+
17
+ return renderCpuFiles(doc, options, "speedscope.json", (run) => {
18
+ const { cpu } = run;
19
+ const { nodes } = cpu;
20
+ const tree = buildDenseTree(cpu);
21
+ const nodeIds = cpu.samples?.nodeIds ?? [];
22
+ const weights = cpu.samples?.timeDeltasUs ?? [];
23
+
24
+ const stackOf: number[][] = new Array(tree.count);
25
+ for (const i of tree.order) {
26
+ const p = tree.parentIx[i]!;
27
+ const frameIx = nodes[i]!.frameIx;
28
+ stackOf[i] = p === -1 ? [frameIx] : [...stackOf[p]!, frameIx];
29
+ }
30
+
31
+ const samples = nodeIds.map((id) => {
32
+ const ix = tree.indexOf(id);
33
+ return ix === -1 ? [] : stackOf[ix]!;
34
+ });
35
+ const workload = byWorkload.get(run.workloadId);
36
+ const name =
37
+ workload?.label ??
38
+ workload?.command?.join(" ") ??
39
+ workload?.entry?.task ??
40
+ "profile";
41
+
42
+ const document = {
43
+ $schema: SCHEMA_URL,
44
+ exporter: "ostia",
45
+ name,
46
+ activeProfileIndex: 0,
47
+ shared: {
48
+ frames: cpu.frames.map((f) => ({
49
+ name: frameName(f),
50
+ file: f.url,
51
+ line: f.line !== undefined ? f.line + 1 : undefined,
52
+ })),
53
+ },
54
+ profiles: [
55
+ {
56
+ type: "sampled",
57
+ name,
58
+ unit: "microseconds",
59
+ startValue: 0,
60
+ endValue: weights.reduce((sum, w) => sum + w, 0),
61
+ samples,
62
+ weights,
63
+ },
64
+ ],
65
+ };
66
+ return `${JSON.stringify(document, null, 2)}\n`;
67
+ });
68
+ },
69
+ };