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