ostia 0.2.12 → 0.3.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.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  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 +923 -679
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +487 -0
  13. package/src/ab/index.ts +1160 -0
  14. package/src/baseline/index.ts +69 -0
  15. package/src/bench/index.ts +516 -0
  16. package/src/bench/projects.ts +43 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +426 -0
  19. package/src/bench/run-tasks.ts +179 -0
  20. package/src/bench/run.ts +52 -0
  21. package/src/bench/runner.ts +162 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +41 -0
  24. package/src/cache/fingerprint.ts +62 -0
  25. package/src/cache/store.ts +40 -0
  26. package/src/capture/bunflags.ts +92 -0
  27. package/src/capture/cpu-parse.ts +131 -0
  28. package/src/capture/cpu.ts +47 -0
  29. package/src/capture/frames.ts +60 -0
  30. package/src/capture/heap-parse.ts +111 -0
  31. package/src/capture/heap.ts +36 -0
  32. package/src/capture/inspector.ts +47 -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 +440 -0
  37. package/src/cli/flags.ts +263 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +179 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +624 -0
  43. package/src/config/env.ts +13 -0
  44. package/src/config/index.ts +283 -0
  45. package/src/config/validate.ts +273 -0
  46. package/src/errors.ts +8 -0
  47. package/src/format.ts +35 -0
  48. package/src/glob.ts +45 -0
  49. package/src/index.ts +60 -0
  50. package/src/ir/cpu.ts +10 -0
  51. package/src/ir/defined.ts +12 -0
  52. package/src/ir/document.ts +491 -0
  53. package/src/ir/fp.ts +28 -0
  54. package/src/ir/git.ts +37 -0
  55. package/src/ir/types.ts +615 -0
  56. package/src/measure/alloc.ts +56 -0
  57. package/src/measure/cpu.ts +91 -0
  58. package/src/measure/environment.ts +38 -0
  59. package/src/measure/inprocess.ts +191 -0
  60. package/src/measure/instructions.ts +139 -0
  61. package/src/measure/loop.ts +64 -0
  62. package/src/measure/noise.ts +55 -0
  63. package/src/measure/paired.ts +304 -0
  64. package/src/measure/peak.ts +201 -0
  65. package/src/measure/timing.ts +263 -0
  66. package/src/profile.ts +110 -0
  67. package/src/renderers/collapsed.ts +42 -0
  68. package/src/renderers/cpu-tree.ts +191 -0
  69. package/src/renderers/cpuprofile.ts +43 -0
  70. package/src/renderers/format.ts +132 -0
  71. package/src/renderers/index.ts +37 -0
  72. package/src/renderers/json.ts +10 -0
  73. package/src/renderers/jsonl.ts +19 -0
  74. package/src/renderers/markdown.ts +543 -0
  75. package/src/renderers/mermaid.ts +90 -0
  76. package/src/renderers/minimal.ts +602 -0
  77. package/src/renderers/paired.ts +223 -0
  78. package/src/renderers/relative.ts +60 -0
  79. package/src/renderers/select.ts +264 -0
  80. package/src/renderers/speedscope.ts +73 -0
  81. package/src/renderers/terminal.ts +470 -0
  82. package/src/renderers/types.ts +27 -0
  83. package/src/spawn/index.ts +387 -0
  84. package/src/stats/bootstrap.ts +151 -0
  85. package/src/stats/index.ts +144 -0
  86. package/src/stats/mannwhitney.ts +82 -0
  87. package/src/time.ts +337 -0
  88. package/src/version.ts +3 -0
  89. package/ab-runner.ts +0 -8
  90. package/chunk-05jfst35.js +0 -28
  91. package/chunk-1g1x9zz2.js +0 -15
  92. package/chunk-23g2rwrn.js +0 -3
  93. package/chunk-468h5412.js +0 -25
  94. package/chunk-4esjfc2m.js +0 -2
  95. package/chunk-ct2xsezd.js +0 -14
  96. package/cli.js +0 -3
  97. package/index.js +0 -2
  98. package/runner.ts +0 -7
@@ -0,0 +1,543 @@
1
+ import { formatDuration, pickDurationUnit } from "../format.ts";
2
+ import { cpuSampleCount } from "../ir/cpu.ts";
3
+ import type {
4
+ Measurement,
5
+ ProfileDocument,
6
+ Warning,
7
+ Workload,
8
+ } from "../ir/types.ts";
9
+ import {
10
+ cpuTimes,
11
+ escapeMdCell,
12
+ formatCpuTimes,
13
+ formatEnvironmentLine,
14
+ formatGit,
15
+ formatHeapSummary,
16
+ formatInstructions,
17
+ formatNsAsMs,
18
+ formatRelative,
19
+ formatSignedPct,
20
+ formatSpan,
21
+ formatUsAsMs,
22
+ frameName,
23
+ labelOrId,
24
+ topSelfFrames,
25
+ } from "./format.ts";
26
+ import {
27
+ abNotes,
28
+ alsoHeader,
29
+ formatAbHeader,
30
+ formatAbSummary,
31
+ formatNewSuites,
32
+ formatThrew,
33
+ memoryCells,
34
+ memoryRows,
35
+ pairedCells,
36
+ pairedRuns,
37
+ threwRuns,
38
+ } from "./paired.ts";
39
+ import { groupOf, relativeRatios, type TimingRow } from "./relative.ts";
40
+ import {
41
+ comparedRows,
42
+ environmentMismatch,
43
+ memoryColumns,
44
+ memoryReadings,
45
+ noSampleRuns,
46
+ oneSidedNote,
47
+ rowComparisonWarnings,
48
+ runWarnings,
49
+ shownFrameDeltas,
50
+ shownHeapDeltas,
51
+ shownMemoryDeltas,
52
+ skippedWorkloads,
53
+ thresholdNote,
54
+ timingRuns,
55
+ workloadsById,
56
+ } from "./select.ts";
57
+ import type { Renderer, RenderResult } from "./types.ts";
58
+
59
+ const TOP_FRAMES = 10;
60
+ const TOP_TYPES = 10;
61
+
62
+ type ParamValue = string | number | boolean;
63
+
64
+ const cell = (v: ParamValue): string => escapeMdCell(String(v));
65
+
66
+ function mdTable(headers: string[], rows: string[][]): string[] {
67
+ return [
68
+ `| ${headers.join(" | ")} |`,
69
+ `|${headers.map(() => "---").join("|")}|`,
70
+ ...rows.map((r) => `| ${r.join(" | ")} |`),
71
+ ];
72
+ }
73
+
74
+ function paramsSuffix(w: Workload | undefined): string {
75
+ if (!w?.params) return "";
76
+ const pairs = Object.entries(w.params).map(([k, v]) => `${k}=${v}`);
77
+ return ` (${pairs.join(", ")})`;
78
+ }
79
+
80
+ function taskCell(w: Workload | undefined, id: string): string {
81
+ return cell(labelOrId(w, id) + paramsSuffix(w));
82
+ }
83
+
84
+ function warningNote(w: Warning): string {
85
+ return `${w.message} (\`${w.code}\`)`;
86
+ }
87
+
88
+ function warningBullets(label: string, warnings: Warning[]): string[] {
89
+ return warnings.map((w) => `- **${label}**: ${warningNote(w)}`);
90
+ }
91
+
92
+ // The two param keys every workload shares, when each has exactly those
93
+ // two (a `sweep()` over two dimensions): the shape a pivot table needs.
94
+ function pivotKeysFor(
95
+ workloads: (Workload | undefined)[],
96
+ ): [string, string] | undefined {
97
+ let keys: [string, string] | undefined;
98
+ for (const w of workloads) {
99
+ const k = w?.params ? Object.keys(w.params) : [];
100
+ const [first, second] = k;
101
+ if (k.length !== 2 || first === undefined || second === undefined) {
102
+ return undefined;
103
+ }
104
+ if (keys === undefined) keys = [first, second];
105
+ else if (keys[0] !== first || keys[1] !== second) return undefined;
106
+ }
107
+ return keys;
108
+ }
109
+
110
+ export const markdownRenderer: Renderer = {
111
+ name: "markdown",
112
+ render(doc: ProfileDocument): Promise<RenderResult> {
113
+ return Promise.try(() => {
114
+ const byWorkload = workloadsById(doc);
115
+ const gitSuffix = doc.git ? ` · ${formatGit(doc.git)}` : "";
116
+ const mismatch = environmentMismatch(doc);
117
+
118
+ const lines = [
119
+ "# Profile Report",
120
+ "",
121
+ `Bun ${doc.bunVersion} · ostia ${doc.toolVersion} · ${doc.platform.os}/${doc.platform.arch} · ${doc.createdAt}${gitSuffix}`,
122
+ "",
123
+ ...(doc.environment
124
+ ? [formatEnvironmentLine(doc.environment), ""]
125
+ : []),
126
+ ...(mismatch ? [`> ⚠ ${mismatch.message}`, ""] : []),
127
+ // Only `ab()` writes paired measurements, and it always stamps `ab`.
128
+ ...(doc.ab ? abSection(doc, doc.ab, byWorkload) : []),
129
+ ...timingSection(doc, byWorkload),
130
+ ...captureSections(doc, byWorkload),
131
+ ...comparisonSection(doc),
132
+ ];
133
+ return { text: lines.join("\n") };
134
+ });
135
+ },
136
+ };
137
+
138
+ function abSection(
139
+ doc: ProfileDocument,
140
+ ab: NonNullable<ProfileDocument["ab"]>,
141
+ byWorkload: Map<string, Workload>,
142
+ ): string[] {
143
+ const paired = pairedRuns(doc);
144
+ const lines = ["## A/B", "", formatAbHeader(ab), ""];
145
+ if (paired.length > 0) {
146
+ const also = alsoHeader(doc, ab.metric);
147
+ lines.push(
148
+ ...mdTable(
149
+ [
150
+ "Task",
151
+ "Base",
152
+ "Candidate",
153
+ "Change",
154
+ "p25…p75",
155
+ ...(also ? [also] : []),
156
+ "Verdict",
157
+ ],
158
+ paired.map((run) => {
159
+ const c = pairedCells(run, ab.metric);
160
+ const row = [
161
+ taskCell(byWorkload.get(run.workloadId), run.workloadId),
162
+ c.base,
163
+ c.candidate,
164
+ c.change,
165
+ c.spread,
166
+ ];
167
+ if (also) row.push(c.also);
168
+ row.push(c.verdict ? `**${cell(c.verdict)}**` : "");
169
+ return row;
170
+ }),
171
+ ),
172
+ "",
173
+ );
174
+ }
175
+ const memory = memoryRows(doc);
176
+ if (memory.length > 0) {
177
+ lines.push(
178
+ ...mdTable(
179
+ ["Task", "Memory", "Base", "Candidate", "Change", "Verdict"],
180
+ memory.map((row) => {
181
+ const c = memoryCells(row);
182
+ return [
183
+ taskCell(byWorkload.get(row.run.workloadId), row.run.workloadId),
184
+ c.reading,
185
+ c.base,
186
+ c.candidate,
187
+ c.change,
188
+ c.verdict ? `**${c.verdict}**` : "",
189
+ ];
190
+ }),
191
+ ),
192
+ "",
193
+ );
194
+ }
195
+ const threw = threwRuns(doc);
196
+ if (threw.length > 0) {
197
+ lines.push(`Threw (${threw.length}):`, "");
198
+ for (const run of threw) {
199
+ const message = (run.threw.message.split("\n")[0] ?? "").replaceAll(
200
+ "`",
201
+ "'",
202
+ );
203
+ lines.push(
204
+ `- **${taskCell(byWorkload.get(run.workloadId), run.workloadId)}**: ${formatThrew(run.threw)}: \`${message}\``,
205
+ );
206
+ }
207
+ lines.push("");
208
+ }
209
+ const notes = abNotes(doc);
210
+ const listed = (title: string, labels: string[]) =>
211
+ labels.length > 0 ? `${title}: ${labels.map(cell).join(", ")}` : undefined;
212
+ for (const note of [
213
+ listed("Output differs from the base", notes.outputDiffers),
214
+ formatNewSuites(ab),
215
+ listed("Base only", notes.baseOnly),
216
+ listed("Candidate only", notes.candOnly),
217
+ ]) {
218
+ if (note) lines.push(note, "");
219
+ }
220
+ const bullets = paired.flatMap((run) =>
221
+ warningBullets(
222
+ labelOrId(byWorkload.get(run.workloadId), run.workloadId),
223
+ run.warnings,
224
+ ),
225
+ );
226
+ if (bullets.length > 0) lines.push(...bullets, "");
227
+ lines.push(`**${formatAbSummary(ab)}**`, "");
228
+ return lines;
229
+ }
230
+
231
+ function timingSection(
232
+ doc: ProfileDocument,
233
+ byWorkload: Map<string, Workload>,
234
+ ): string[] {
235
+ const runs = timingRuns(doc);
236
+ const noSamples = noSampleRuns(doc);
237
+ const memory = memoryReadings(doc);
238
+ const empty: {
239
+ id: string;
240
+ workload: Workload | undefined;
241
+ status: string;
242
+ }[] = [
243
+ ...skippedWorkloads(doc, runs).map((workload) => ({
244
+ id: workload.id,
245
+ workload,
246
+ status: "skipped",
247
+ })),
248
+ ...noSamples.map((run) => ({
249
+ id: run.workloadId,
250
+ workload: byWorkload.get(run.workloadId),
251
+ status: "no samples",
252
+ })),
253
+ ];
254
+ if (runs.length === 0 && empty.length === 0) return [];
255
+
256
+ const lines = ["## Timing", ""];
257
+
258
+ // A group pivots into its own table when all its tasks share the same two
259
+ // param keys; everything else is a normal row, with a `key=value` suffix
260
+ // when it carries params.
261
+ const rows: TimingRow[] = runs.map((run) => ({
262
+ run,
263
+ workload: byWorkload.get(run.workloadId),
264
+ }));
265
+ const byGroup = new Map<string, TimingRow[]>();
266
+ const flat: TimingRow[] = [];
267
+ for (const row of rows) {
268
+ const group = groupOf(row.workload);
269
+ if (group === undefined) {
270
+ flat.push(row);
271
+ continue;
272
+ }
273
+ const groupRows = byGroup.get(group);
274
+ if (groupRows) groupRows.push(row);
275
+ else byGroup.set(group, [row]);
276
+ }
277
+ const pivots: { group: string; keys: [string, string]; rows: TimingRow[] }[] =
278
+ [];
279
+ for (const [group, groupRows] of byGroup) {
280
+ const keys = pivotKeysFor(groupRows.map((r) => r.workload));
281
+ if (keys) pivots.push({ group, keys, rows: groupRows });
282
+ else flat.push(...groupRows);
283
+ }
284
+
285
+ if (flat.length > 0 || empty.length > 0) {
286
+ const ratios = relativeRatios(rows);
287
+ const optional: { header: string; cell: (row: TimingRow) => string }[] = [];
288
+ const cpuByRow = new Map(flat.map((row) => [row, cpuTimes(row.run)]));
289
+ if ([...cpuByRow.values()].some(Boolean)) {
290
+ optional.push({
291
+ header: "User/Sys",
292
+ cell: (row) => {
293
+ const times = cpuByRow.get(row);
294
+ return times ? formatCpuTimes(times) : "-";
295
+ },
296
+ });
297
+ }
298
+ if (flat.some((row) => row.run.instructions)) {
299
+ optional.push({
300
+ header: "Instr/call",
301
+ cell: (row) =>
302
+ row.run.instructions
303
+ ? formatInstructions(row.run.instructions.median)
304
+ : "-",
305
+ });
306
+ }
307
+ for (const col of memoryColumns(memory)) {
308
+ optional.push({
309
+ header: col.header,
310
+ cell: (row) => col.cell(row.run.workloadId) ?? "-",
311
+ });
312
+ }
313
+ if (ratios) {
314
+ optional.push({
315
+ header: "Relative",
316
+ cell: (row) => {
317
+ const ratio = ratios.get(row);
318
+ return ratio === undefined
319
+ ? "-"
320
+ : formatRelative(ratio, !!row.workload?.baseline);
321
+ },
322
+ });
323
+ }
324
+
325
+ lines.push(
326
+ ...mdTable(
327
+ [
328
+ "Task",
329
+ "Median",
330
+ "Spread (p75…p99)",
331
+ "Mean ± SD",
332
+ "Range",
333
+ "MAD",
334
+ ...optional.map((c) => c.header),
335
+ ],
336
+ [
337
+ ...flat.map((row) => {
338
+ const t = row.run.timing;
339
+ const unit = pickDurationUnit(t.median);
340
+ return [
341
+ taskCell(row.workload, row.run.workloadId),
342
+ formatDuration(t.median, unit),
343
+ formatSpan(t.p75, t.p99, unit),
344
+ `${formatDuration(t.mean, unit)} ± ${formatDuration(t.stddev, unit)}`,
345
+ formatSpan(t.min, t.max, unit),
346
+ formatDuration(t.mad, unit),
347
+ ...optional.map((c) => c.cell(row)),
348
+ ];
349
+ }),
350
+ ...empty.map(({ id, workload, status }) => [
351
+ taskCell(workload, id),
352
+ `- ${status}`,
353
+ "-",
354
+ "-",
355
+ "-",
356
+ "-",
357
+ ...optional.map(() => "-"),
358
+ ]),
359
+ ],
360
+ ),
361
+ "",
362
+ );
363
+ }
364
+
365
+ for (const {
366
+ group,
367
+ keys: [key1, key2],
368
+ rows: groupRows,
369
+ } of pivots) {
370
+ const rowValues: ParamValue[] = [];
371
+ const colValues: ParamValue[] = [];
372
+ const medianAt = new Map<string, number>();
373
+ for (const { run, workload } of groupRows) {
374
+ const v1 = workload?.params?.[key1];
375
+ const v2 = workload?.params?.[key2];
376
+ // invariant: `pivotKeysFor` pivots only rows whose params hold both
377
+ // keys.
378
+ if (v1 === undefined || v2 === undefined) continue;
379
+ if (!rowValues.includes(v1)) rowValues.push(v1);
380
+ if (!colValues.includes(v2)) colValues.push(v2);
381
+ medianAt.set(`${v1} ${v2}`, run.timing.median);
382
+ }
383
+ lines.push(
384
+ `### ${cell(group)} (${cell(key1)} × ${cell(key2)})`,
385
+ "",
386
+ ...mdTable(
387
+ [`${cell(key1)} \\ ${cell(key2)}`, ...colValues.map(cell)],
388
+ rowValues.map((v1) => [
389
+ cell(v1),
390
+ ...colValues.map((v2) => {
391
+ const median = medianAt.get(`${v1} ${v2}`);
392
+ return median === undefined ? "-" : formatDuration(median);
393
+ }),
394
+ ]),
395
+ ),
396
+ "",
397
+ );
398
+ }
399
+
400
+ const warned = [...runs, ...noSamples].flatMap((run) =>
401
+ warningBullets(
402
+ labelOrId(byWorkload.get(run.workloadId), run.workloadId),
403
+ runWarnings(run, memory),
404
+ ),
405
+ );
406
+ if (warned.length > 0) lines.push("### Warnings", "", ...warned, "");
407
+ return lines;
408
+ }
409
+
410
+ function captureSections(
411
+ doc: ProfileDocument,
412
+ byWorkload: Map<string, Workload>,
413
+ ): string[] {
414
+ const lines: string[] = [];
415
+ for (const run of doc.measurements) {
416
+ if (run.phase !== "cpu" && run.phase !== "heap") continue;
417
+ const label = labelOrId(byWorkload.get(run.workloadId), run.workloadId);
418
+ lines.push(
419
+ run.phase === "cpu"
420
+ ? `## CPU capture - ${label}`
421
+ : `## Heap snapshot - ${label}`,
422
+ "",
423
+ `instrumented, diagnostic wall ${formatNsAsMs(run.diagnosticWallNs ?? 0)}ms`,
424
+ "",
425
+ ...(run.phase === "cpu" ? cpuDetail(run) : heapDetail(run)),
426
+ );
427
+
428
+ const notes = [
429
+ ...run.artifacts.map((a) => `- artifact: \`${a.path}\``),
430
+ ...run.warnings.map((w) => `- ! ${warningNote(w)}`),
431
+ ];
432
+ if (notes.length > 0) lines.push(...notes, "");
433
+ }
434
+ return lines;
435
+ }
436
+
437
+ function cpuDetail(run: Measurement): string[] {
438
+ const { cpu } = run;
439
+ if (!cpu) return [];
440
+ const lines = [
441
+ `origin: \`${cpu.origin}\`, interval: ${cpu.samplingIntervalUs}µs, samples: ${cpuSampleCount(cpu)}`,
442
+ "",
443
+ ...mdTable(
444
+ ["Self %", "Self (ms)", "Total (ms)", "Frame"],
445
+ topSelfFrames(cpu, TOP_FRAMES).map((f) => [
446
+ `${f.pct}%`,
447
+ formatUsAsMs(f.selfUs),
448
+ formatUsAsMs(f.totalUs),
449
+ cell(frameName(f.frame)),
450
+ ]),
451
+ ),
452
+ "",
453
+ ];
454
+ if (run.jit) {
455
+ const tiers = run.jit.tiers;
456
+ lines.push(
457
+ `JIT tiers: LLInt ${tiers.llint} · Baseline ${tiers.baseline} · DFG ${tiers.dfg} · FTL ${tiers.ftl}`,
458
+ "",
459
+ );
460
+ }
461
+ return lines;
462
+ }
463
+
464
+ function heapDetail(run: Measurement): string[] {
465
+ const { heap } = run;
466
+ if (!heap) return [];
467
+ return [
468
+ formatHeapSummary(heap),
469
+ "",
470
+ ...mdTable(
471
+ ["Count", "Type"],
472
+ heap.typeCounts
473
+ .slice(0, TOP_TYPES)
474
+ .map((tc) => [String(tc.count), cell(tc.type)]),
475
+ ),
476
+ "",
477
+ ];
478
+ }
479
+
480
+ function comparisonSection(doc: ProfileDocument): string[] {
481
+ const rows = comparedRows(doc);
482
+ if (rows.length === 0) return [];
483
+ const lines = ["## Comparisons", ""];
484
+ const note = thresholdNote(doc);
485
+ if (note) lines.push(`${note}.`, "");
486
+ const notCompared: string[] = [];
487
+ for (const { row, cmp } of rows) {
488
+ if (row.verdict === "missing-base" || row.verdict === "missing-cand") {
489
+ notCompared.push(`- \`${cell(row.task)}\`: ${oneSidedNote(row.verdict)}`);
490
+ continue;
491
+ }
492
+ lines.push(`### ${row.pass === false ? "✗" : "✓"} ${row.task}`, "");
493
+ if (row.renamedFrom) {
494
+ lines.push(`- renamed from \`${cell(row.renamedFrom.task)}\``);
495
+ }
496
+ if (row.timing) {
497
+ const { baseMedian, candMedian, medianDeltaPct, ci95, pValue } =
498
+ row.timing;
499
+ const alpha = cmp?.thresholds.alpha;
500
+ // "~": the delta rounds to non-zero but isn't significant (p past alpha).
501
+ const tilde =
502
+ row.verdict === "unchanged" &&
503
+ pValue !== undefined &&
504
+ alpha !== undefined &&
505
+ pValue >= alpha
506
+ ? "~"
507
+ : "";
508
+ const unit = pickDurationUnit(Math.max(baseMedian, candMedian));
509
+ const detail = [`n=${row.timing.candSamples}`];
510
+ if (ci95)
511
+ detail.push(
512
+ `95% CI [${formatSignedPct(ci95[0])}, ${formatSignedPct(ci95[1])}]`,
513
+ );
514
+ if (pValue !== undefined) detail.push(`p=${pValue.toFixed(4)}`);
515
+ detail.push(`threshold ${row.timing.thresholdPct.toFixed(1)}%`);
516
+ lines.push(
517
+ `- timing: ${formatDuration(baseMedian, unit)} → ${formatDuration(candMedian, unit)}, ${tilde}${formatSignedPct(medianDeltaPct)} median, ${detail.join(", ")} (**${row.verdict}**)`,
518
+ );
519
+ }
520
+ const memory = shownMemoryDeltas(row);
521
+ if (memory.length > 0) lines.push(`- memory: ${memory.join(", ")}`);
522
+ if (cmp) {
523
+ for (const f of shownFrameDeltas(cmp, TOP_FRAMES)) {
524
+ lines.push(
525
+ `- frame \`${cell(f.name)}\`: ${formatSignedPct(f.deltaPct)} self-time (${formatUsAsMs(f.baseSelfUs)}ms → ${formatUsAsMs(f.candSelfUs)}ms)`,
526
+ );
527
+ }
528
+ for (const h of shownHeapDeltas(cmp, TOP_TYPES)) {
529
+ lines.push(
530
+ `- heap \`${cell(h.type)}\`: ${formatSignedPct(h.deltaPct)} count (${h.baseCount} → ${h.candCount})`,
531
+ );
532
+ }
533
+ for (const w of rowComparisonWarnings(cmp)) {
534
+ lines.push(`- ! ${warningNote(w)}`);
535
+ }
536
+ }
537
+ lines.push("");
538
+ }
539
+ if (notCompared.length > 0) {
540
+ lines.push("### Not compared", "", ...notCompared, "");
541
+ }
542
+ return lines;
543
+ }
@@ -0,0 +1,90 @@
1
+ import type { ProfileDocument } from "../ir/types.ts";
2
+ import {
3
+ buildDenseTree,
4
+ computeDenseNodeTimes,
5
+ renderCpuFiles,
6
+ } from "./cpu-tree.ts";
7
+ import { formatUsAsMs, frameName } from "./format.ts";
8
+ import type { Renderer, RenderResult, VizOptions } from "./types.ts";
9
+
10
+ const DEFAULT_TOP_N = 15;
11
+
12
+ export interface MermaidOptions extends VizOptions {
13
+ topN?: number;
14
+ }
15
+
16
+ function label(name: string, selfUs: number, totalUs: number): string {
17
+ return `${name.replace(/"/g, "'")} (self ${formatUsAsMs(selfUs)}ms, total ${formatUsAsMs(totalUs)}ms)`;
18
+ }
19
+
20
+ // Insertion into a sorted window instead of a full sort, since n is
21
+ // small: O(count * n).
22
+ function topNBySelf(
23
+ selfUs: Float64Array,
24
+ count: number,
25
+ exclude: number,
26
+ n: number,
27
+ ): number[] {
28
+ const top: number[] = [];
29
+ if (n <= 0) return top;
30
+ const selfAt = (ix: number | undefined) =>
31
+ ix === undefined ? 0 : (selfUs[ix] ?? 0);
32
+ for (let i = 0; i < count; i++) {
33
+ if (i === exclude) continue;
34
+ const v = selfAt(i);
35
+ if (top.length === n && v <= selfAt(top[n - 1])) continue;
36
+ let j = top.length;
37
+ while (j > 0 && selfAt(top[j - 1]) < v) j--;
38
+ top.splice(j, 0, i);
39
+ if (top.length > n) top.pop();
40
+ }
41
+ return top;
42
+ }
43
+
44
+ export const mermaidRenderer: Renderer<MermaidOptions> = {
45
+ name: "mermaid",
46
+ render(
47
+ doc: ProfileDocument,
48
+ options: MermaidOptions = {},
49
+ ): Promise<RenderResult> {
50
+ return Promise.try(() => {
51
+ const topN = options.topN ?? DEFAULT_TOP_N;
52
+
53
+ return renderCpuFiles(doc, options, "mermaid.md", ({ cpu }) => {
54
+ const { nodes, frames } = cpu;
55
+ const tree = buildDenseTree(cpu);
56
+ const { selfUs, totalUs } = computeDenseNodeTimes(cpu, tree);
57
+ const { parentIx } = tree;
58
+ const rootIx = tree.roots[0] ?? -1;
59
+
60
+ // The top-N self-time nodes plus every ancestor, so each has a path to the
61
+ // root.
62
+ const included = new Set<number>(rootIx !== -1 ? [rootIx] : []);
63
+ for (const ix of topNBySelf(selfUs, tree.count, rootIx, topN)) {
64
+ const path: number[] = [];
65
+ for (let cur = ix; cur !== -1; cur = parentIx[cur] ?? -1) {
66
+ path.push(cur);
67
+ }
68
+ for (const p of path.toReversed()) included.add(p);
69
+ }
70
+
71
+ const id = (ix: number) => `n${nodes[ix]?.id}`;
72
+ const lines = ["graph TD"];
73
+ for (const ix of included) {
74
+ const node = nodes[ix];
75
+ if (node === undefined) continue;
76
+ const name = frameName(frames[node.frameIx]);
77
+ lines.push(
78
+ ` ${id(ix)}["${label(name, selfUs[ix] ?? 0, totalUs[ix] ?? 0)}"]`,
79
+ );
80
+ }
81
+ for (const ix of included) {
82
+ const p = parentIx[ix] ?? -1;
83
+ if (p !== -1 && included.has(p))
84
+ lines.push(` ${id(p)} --> ${id(ix)}`);
85
+ }
86
+ return `${lines.join("\n")}\n`;
87
+ });
88
+ });
89
+ },
90
+ };