ostia 0.3.0 → 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 (70) hide show
  1. package/index.d.ts +62 -35
  2. package/package.json +1 -1
  3. package/src/ab/ab-runner.ts +57 -44
  4. package/src/ab/index.ts +186 -112
  5. package/src/baseline/index.ts +3 -9
  6. package/src/bench/index.ts +177 -123
  7. package/src/bench/projects.ts +14 -10
  8. package/src/bench/registry.ts +68 -66
  9. package/src/bench/run-tasks.ts +26 -23
  10. package/src/bench/run.ts +2 -1
  11. package/src/bench/runner.ts +20 -5
  12. package/src/bench/support.ts +26 -26
  13. package/src/bench/sweep.ts +6 -4
  14. package/src/cache/fingerprint.ts +9 -6
  15. package/src/cache/store.ts +17 -5
  16. package/src/capture/bunflags.ts +12 -11
  17. package/src/capture/cpu-parse.ts +36 -24
  18. package/src/capture/cpu.ts +7 -4
  19. package/src/capture/frames.ts +7 -1
  20. package/src/capture/heap-parse.ts +30 -5
  21. package/src/capture/heap.ts +9 -5
  22. package/src/capture/inspector.ts +8 -7
  23. package/src/capture/jsc-parse.ts +8 -8
  24. package/src/capture/jsc.ts +4 -4
  25. package/src/ci/index.ts +64 -40
  26. package/src/cli/flags.ts +42 -43
  27. package/src/cli/output.ts +29 -35
  28. package/src/cli/run.ts +95 -95
  29. package/src/compare/index.ts +39 -32
  30. package/src/config/env.ts +13 -0
  31. package/src/config/index.ts +31 -23
  32. package/src/config/validate.ts +33 -27
  33. package/src/format.ts +5 -6
  34. package/src/glob.ts +9 -12
  35. package/src/index.ts +1 -3
  36. package/src/ir/cpu.ts +2 -2
  37. package/src/ir/defined.ts +12 -0
  38. package/src/ir/document.ts +93 -73
  39. package/src/ir/fp.ts +7 -10
  40. package/src/ir/git.ts +4 -3
  41. package/src/measure/alloc.ts +7 -8
  42. package/src/measure/cpu.ts +12 -20
  43. package/src/measure/environment.ts +5 -8
  44. package/src/measure/inprocess.ts +15 -15
  45. package/src/measure/instructions.ts +22 -16
  46. package/src/measure/loop.ts +24 -17
  47. package/src/measure/noise.ts +8 -8
  48. package/src/measure/paired.ts +39 -47
  49. package/src/measure/peak.ts +20 -21
  50. package/src/measure/timing.ts +23 -23
  51. package/src/profile.ts +2 -1
  52. package/src/renderers/collapsed.ts +28 -21
  53. package/src/renderers/cpu-tree.ts +43 -35
  54. package/src/renderers/format.ts +16 -26
  55. package/src/renderers/index.ts +14 -4
  56. package/src/renderers/json.ts +2 -2
  57. package/src/renderers/jsonl.ts +11 -7
  58. package/src/renderers/markdown.ts +54 -36
  59. package/src/renderers/mermaid.ts +43 -31
  60. package/src/renderers/minimal.ts +12 -12
  61. package/src/renderers/paired.ts +31 -37
  62. package/src/renderers/relative.ts +10 -14
  63. package/src/renderers/select.ts +17 -39
  64. package/src/renderers/speedscope.ts +52 -48
  65. package/src/renderers/terminal.ts +37 -33
  66. package/src/spawn/index.ts +38 -47
  67. package/src/stats/bootstrap.ts +56 -58
  68. package/src/stats/index.ts +16 -12
  69. package/src/stats/mannwhitney.ts +11 -10
  70. package/src/time.ts +51 -39
@@ -9,10 +9,9 @@ export interface MemorySnapshot {
9
9
  liveBytes: number;
10
10
  }
11
11
 
12
- /**
13
- * Taken before the suite loads so `measurePeakMem` can split the starting
14
- * RSS into live data and memory setup freed that the allocator still
15
- * holds. */
12
+ // Taken before the suite loads so `measurePeakMem` can split the starting
13
+ // RSS into live data and memory setup freed that the allocator still
14
+ // holds.
16
15
  export function memorySnapshot(): MemorySnapshot {
17
16
  const { heapSize, extraMemorySize } = heapStats();
18
17
  const rssBytes = process.memoryUsage.rss();
@@ -32,9 +31,10 @@ function residentBytes(): number | undefined {
32
31
  return readResident();
33
32
  }
34
33
 
34
+ // eslint-disable-next-line no-restricted-syntax -- a lazy cache: dlopen once per process
35
35
  let readResident: (() => number | undefined) | undefined;
36
36
 
37
- // Asks the kernel directly: spawning `ps` costs a few ms a call.
37
+ // Asks the kernel directly, since spawning `ps` costs a few ms a call.
38
38
  function residentReader(): () => number | undefined {
39
39
  const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
40
40
  proc_pid_rusage: {
@@ -42,8 +42,8 @@ function residentReader(): () => number | undefined {
42
42
  returns: FFIType.i32,
43
43
  },
44
44
  });
45
- // rusage_info_v0: a 16-byte uuid, then u64s; ri_resident_size is at byte
46
- // 64.
45
+ // spec: rusage_info_v0 is a 16-byte uuid, then u64s; ri_resident_size is
46
+ // at byte 64.
47
47
  const info = new BigUint64Array(12);
48
48
  return () =>
49
49
  symbols.proc_pid_rusage(process.pid, 0, ptr(info)) === 0
@@ -101,9 +101,9 @@ export async function startRssSampler(
101
101
  });
102
102
  try {
103
103
  worker.postMessage(slots.buffer);
104
- const deadline = Date.now() + HANDSHAKE_TIMEOUT_MS;
104
+ const deadline = Bun.nanoseconds() + HANDSHAKE_TIMEOUT_MS * 1e6;
105
105
  while (Atomics.load(slots, 0) !== CONTROL.ready) {
106
- if (Date.now() > deadline) {
106
+ if (Bun.nanoseconds() > deadline) {
107
107
  throw new Error("RSS sampler worker failed: did not start in time");
108
108
  }
109
109
  await Promise.race([Bun.sleep(1), died]);
@@ -127,9 +127,9 @@ export async function startRssSampler(
127
127
  ) {
128
128
  // Spin.
129
129
  }
130
- const deadline = Date.now() + HANDSHAKE_TIMEOUT_MS;
130
+ const deadline = Bun.nanoseconds() + HANDSHAKE_TIMEOUT_MS * 1e6;
131
131
  while (Atomics.load(slots, 0) !== CONTROL.sampling) {
132
- if (Date.now() > deadline) {
132
+ if (Bun.nanoseconds() > deadline) {
133
133
  throw new Error(
134
134
  "RSS sampler worker failed: did not start sampling",
135
135
  );
@@ -158,17 +158,16 @@ export interface PeakMemResult {
158
158
  wallNs: number;
159
159
  }
160
160
 
161
- /**
162
- * How far one call of `fn` raises this process's RSS, garbage included:
163
- * the higher of the worker-sampled peak and the `maxRSS` high-water mark
164
- * (if the call moved it), after a full GC. Sampling alone can miss a spike
165
- * between polls; the high-water mark alone misses any call peaking below
166
- * an earlier peak (on Linux, every call smaller than process startup).
167
- * Meant for the first call in a fresh process: memory an earlier call
168
- * freed but the allocator holds (macOS returns it seconds later) is reused
169
- * unseen. */
161
+ // How far one call of `fn` raises this process's RSS, garbage included:
162
+ // the higher of the worker-sampled peak and the `maxRSS` high-water mark
163
+ // (if the call moved it), after a full GC. Sampling alone can miss a spike
164
+ // between polls; the high-water mark alone misses any call peaking below
165
+ // an earlier peak (on Linux, every call smaller than process startup).
166
+ // Only meaningful for the first call in a fresh process, because memory
167
+ // an earlier call freed but the allocator holds (macOS returns it seconds
168
+ // later) is reused unseen.
170
169
  export async function measurePeakMem(
171
- fn: () => unknown | Promise<unknown>,
170
+ fn: () => unknown,
172
171
  since?: MemorySnapshot,
173
172
  sampler?: RssSampler,
174
173
  ): Promise<PeakMemResult> {
@@ -8,7 +8,7 @@ import {
8
8
  } from "../spawn/index.ts";
9
9
  import { computeTimingStats, timingWarnings } from "../stats/index.ts";
10
10
 
11
- export interface TimingPhaseOptions extends SpawnTrialOptions {
11
+ interface TimingPhaseOptions extends SpawnTrialOptions {
12
12
  /** Exact trial count; the budget is ignored. */
13
13
  samples?: number;
14
14
  /** Warmup trial count, discarded before sampling. */
@@ -29,7 +29,7 @@ const DEFAULT_MIN_SAMPLES = 10;
29
29
  const DEFAULT_BUDGET_MS = 3000;
30
30
  const DEFAULT_WARMUP = 3;
31
31
 
32
- export interface TimingPhaseResult {
32
+ interface TimingPhaseResult {
33
33
  trials: Trial[];
34
34
  /** Absent when no trial produced a sample (e.g. all timed out). */
35
35
  timing?: TimingStats;
@@ -40,7 +40,7 @@ export interface TimingPhaseResult {
40
40
  * One command's trial loop, a trial at a time so `time()` can round-robin
41
41
  * several commands (`--interleave`). `warmup()` first, then `step()` until
42
42
  * it returns false. */
43
- export interface TimingPhaseIterator {
43
+ interface TimingPhaseIterator {
44
44
  warmup(): Promise<void>;
45
45
  /**
46
46
  * Runs one more trial unless the stopping criterion is met; returns
@@ -51,10 +51,8 @@ export interface TimingPhaseIterator {
51
51
  result(): TimingPhaseResult;
52
52
  }
53
53
 
54
- /**
55
- * `undefined` is a timed-out trial: killed, so it has no exit code to fail
56
- * on.
57
- */
54
+ // `undefined` is a timed-out trial: killed, so it has no exit code to fail
55
+ // on.
58
56
  function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
59
57
  return code !== undefined && code !== 0 && !ignored.has(code);
60
58
  }
@@ -78,7 +76,8 @@ export function createTimingPhase(
78
76
  let totalNs = 0;
79
77
  let i = 0;
80
78
  let failedEarly = false;
81
- // One representative excerpt is enough for the aggregate warning.
79
+ // Only the first, since one representative excerpt is enough for the
80
+ // aggregate warning.
82
81
  let firstNoMatchOutput: string | undefined;
83
82
 
84
83
  function done(): boolean {
@@ -93,10 +92,10 @@ export function createTimingPhase(
93
92
  opts.prepare,
94
93
  { phase, index },
95
94
  {
96
- cwd: opts.cwd,
97
- env: opts.env,
98
- timeoutMs: opts.timeoutMs,
99
- signal: opts.signal,
95
+ ...(opts.cwd !== undefined && { cwd: opts.cwd }),
96
+ ...(opts.env !== undefined && { env: opts.env }),
97
+ ...(opts.timeoutMs !== undefined && { timeoutMs: opts.timeoutMs }),
98
+ ...(opts.signal !== undefined && { signal: opts.signal }),
100
99
  },
101
100
  );
102
101
  }
@@ -122,10 +121,12 @@ export function createTimingPhase(
122
121
  trials.push({
123
122
  i,
124
123
  wallNs: result.wallNs,
125
- exitCode,
126
- userNs: result.userNs,
127
- systemNs: result.systemNs,
128
- maxRssBytes: result.maxRssBytes,
124
+ ...(exitCode !== undefined && { exitCode }),
125
+ ...(result.userNs !== undefined && { userNs: result.userNs }),
126
+ ...(result.systemNs !== undefined && { systemNs: result.systemNs }),
127
+ ...(result.maxRssBytes !== undefined && {
128
+ maxRssBytes: result.maxRssBytes,
129
+ }),
129
130
  ...(result.reportedNs !== undefined && {
130
131
  reportedNs: result.reportedNs,
131
132
  }),
@@ -146,7 +147,7 @@ export function createTimingPhase(
146
147
  // reported-time series.
147
148
  const sampled = trials.filter((t) => !t.timedOut && !t.timeSourceNoMatch);
148
149
  const timingSamples = sampled.map((t) =>
149
- reported ? t.reportedNs! : t.wallNs,
150
+ reported ? (t.reportedNs ?? Number.NaN) : t.wallNs,
150
151
  );
151
152
 
152
153
  const warnings: Warning[] = [];
@@ -208,12 +209,11 @@ export async function runTimingPhase(
208
209
  return phase.result();
209
210
  }
210
211
 
211
- /**
212
- * True when some trial exited non-zero (outside `ignoreExitCodes`) or none
213
- * produced a sample. Not a regression: `ostia time` and `ostia ci` both
214
- * exit 2. A timed-out trial has no exit code, so it fails the run only
215
- * when no trial is left to sample (the `timeout` warning covers the
216
- * partial case). */
212
+ // True when some trial exited non-zero (outside `ignoreExitCodes`) or none
213
+ // produced a sample. Not a regression: `ostia time` and `ostia ci` both
214
+ // exit 2. A timed-out trial has no exit code, so it fails the run only
215
+ // when no trial is left to sample (the `timeout` warning covers the
216
+ // partial case).
217
217
  export function isHarnessFailure(
218
218
  measurement: Pick<Measurement, "trials" | "timing">,
219
219
  ignoreExitCodes: number[] = [],
package/src/profile.ts CHANGED
@@ -39,6 +39,7 @@ export interface ProfileResult<T> {
39
39
  document: ProfileDocument;
40
40
  }
41
41
 
42
+ /** Captures a CPU profile of `fn` in the current process. */
42
43
  export async function profile<T>(
43
44
  fn: () => T | Promise<T>,
44
45
  opts: ProfileOptions = {},
@@ -101,7 +102,7 @@ export async function profile<T>(
101
102
  configFingerprint: configFp,
102
103
  diagnosticWallNs: captured.diagnosticWallNs,
103
104
  cpu: captured.cpu,
104
- jit: captured.jit,
105
+ ...(captured.jit && { jit: captured.jit }),
105
106
  warnings,
106
107
  artifacts: [],
107
108
  }),
@@ -5,31 +5,38 @@ import type { Renderer, RenderResult, VizOptions } from "./types.ts";
5
5
 
6
6
  export const collapsedRenderer: Renderer<VizOptions> = {
7
7
  name: "collapsed",
8
- async render(
8
+ render(
9
9
  doc: ProfileDocument,
10
10
  options: VizOptions = {},
11
11
  ): Promise<RenderResult> {
12
- return renderCpuFiles(doc, options, "collapsed.txt", ({ cpu }) => {
13
- const { nodes, frames } = cpu;
14
- const tree = buildDenseTree(cpu);
12
+ return Promise.try(() =>
13
+ renderCpuFiles(doc, options, "collapsed.txt", ({ cpu }) => {
14
+ const { nodes, frames } = cpu;
15
+ const tree = buildDenseTree(cpu);
15
16
 
16
- const pathOf: string[] = new Array(tree.count);
17
- for (const i of tree.order) {
18
- const name = frameName(frames[nodes[i]!.frameIx]);
19
- const p = tree.parentIx[i]!;
20
- pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
21
- }
17
+ const pathOf = new Array<string>(tree.count);
18
+ for (const i of tree.order) {
19
+ const node = nodes[i];
20
+ if (node === undefined) continue;
21
+ const name = frameName(frames[node.frameIx]);
22
+ const p = tree.parentIx[i] ?? -1;
23
+ pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
24
+ }
22
25
 
23
- // Typed counts plus a first-seen list: this runs over every sample.
24
- const counts = new Float64Array(tree.count);
25
- const seen: number[] = [];
26
- for (const id of cpu.samples?.nodeIds ?? []) {
27
- const ix = tree.indexOf(id);
28
- if (ix === -1) continue;
29
- if (counts[ix]!++ === 0) seen.push(ix);
30
- }
31
- const lines = seen.map((ix) => `${pathOf[ix]} ${counts[ix]}`);
32
- return lines.length > 0 ? `${lines.join("\n")}\n` : "";
33
- });
26
+ // Typed counts plus a first-seen list, because this runs over every
27
+ // sample.
28
+ const counts = new Float64Array(tree.count);
29
+ const seen: number[] = [];
30
+ for (const id of cpu.samples?.nodeIds ?? []) {
31
+ const ix = tree.indexOf(id);
32
+ if (ix === -1) continue;
33
+ const count = counts[ix] ?? 0;
34
+ counts[ix] = count + 1;
35
+ if (count === 0) seen.push(ix);
36
+ }
37
+ const lines = seen.map((ix) => `${pathOf[ix]} ${counts[ix]}`);
38
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
39
+ }),
40
+ );
34
41
  },
35
42
  };
@@ -1,7 +1,7 @@
1
1
  import type { CpuEvidence, Measurement, ProfileDocument } from "../ir/types.ts";
2
2
  import type { RenderResult, VizOptions } from "./types.ts";
3
3
 
4
- export type CpuRun = Measurement & { cpu: CpuEvidence };
4
+ type CpuRun = Measurement & { cpu: CpuEvidence };
5
5
 
6
6
  function hasCpu(m: Measurement): m is CpuRun {
7
7
  return m.cpu !== undefined;
@@ -20,7 +20,6 @@ export function selectCpuRuns(
20
20
  );
21
21
  }
22
22
 
23
- /** One file per selected CPU run, named `<measurement id>.<ext>`. */
24
23
  export function renderCpuFiles(
25
24
  doc: ProfileDocument,
26
25
  options: VizOptions,
@@ -46,7 +45,7 @@ export function buildParentMap(cpu: CpuEvidence): Map<number, number> {
46
45
  export function findRootId(cpu: CpuEvidence): number | undefined {
47
46
  const tree = buildDenseTree(cpu);
48
47
  const rootIx = tree.roots[0];
49
- return rootIx === undefined ? undefined : cpu.nodes[rootIx]!.id;
48
+ return rootIx === undefined ? undefined : cpu.nodes[rootIx]?.id;
50
49
  }
51
50
 
52
51
  export function pathToRoot(
@@ -54,21 +53,23 @@ export function pathToRoot(
54
53
  parentOf: Map<number, number>,
55
54
  ): number[] {
56
55
  const path = [nodeId];
57
- let current = nodeId;
58
- while (parentOf.has(current)) {
59
- current = parentOf.get(current)!;
60
- path.push(current);
56
+ for (
57
+ let parent = parentOf.get(nodeId);
58
+ parent !== undefined;
59
+ parent = parentOf.get(parent)
60
+ ) {
61
+ path.push(parent);
61
62
  }
62
63
  return path.reverse();
63
64
  }
64
65
 
65
- export interface NodeTimes {
66
+ interface NodeTimes {
66
67
  selfUs: number;
67
68
  totalUs: number;
68
69
  samples: number;
69
70
  }
70
71
 
71
- export interface DenseTree {
72
+ interface DenseTree {
72
73
  count: number;
73
74
  indexOf: (id: number) => number;
74
75
  parentIx: Int32Array;
@@ -82,23 +83,23 @@ export function buildDenseTree(cpu: CpuEvidence): DenseTree {
82
83
  const indexOf = makeIndexer(cpu);
83
84
 
84
85
  const parentIx = new Int32Array(count).fill(-1);
85
- for (let i = 0; i < count; i++) {
86
- for (const childId of nodes[i]!.children) {
86
+ let ix = 0;
87
+ for (const node of nodes) {
88
+ for (const childId of node.children) {
87
89
  const c = indexOf(childId);
88
- if (c !== -1) parentIx[c] = i;
90
+ if (c !== -1) parentIx[c] = ix;
89
91
  }
92
+ ix++;
90
93
  }
91
94
 
92
95
  const roots: number[] = [];
93
96
  for (let i = 0; i < count; i++) if (parentIx[i] === -1) roots.push(i);
94
97
 
95
98
  const order: number[] = [];
96
- const stack: number[] = [];
97
- for (let r = roots.length - 1; r >= 0; r--) stack.push(roots[r]!);
98
- while (stack.length > 0) {
99
- const i = stack.pop()!;
99
+ const stack = roots.toReversed();
100
+ for (let i = stack.pop(); i !== undefined; i = stack.pop()) {
100
101
  order.push(i);
101
- for (const childId of nodes[i]!.children) {
102
+ for (const childId of nodes[i]?.children ?? []) {
102
103
  const c = indexOf(childId);
103
104
  if (c !== -1 && parentIx[c] === i) stack.push(c);
104
105
  }
@@ -113,8 +114,7 @@ function makeIndexer(cpu: CpuEvidence): (id: number) => number {
113
114
  let min = Infinity;
114
115
  let max = -Infinity;
115
116
  let integral = true;
116
- for (let i = 0; i < count; i++) {
117
- const id = nodes[i]!.id;
117
+ for (const { id } of nodes) {
118
118
  if (!Number.isInteger(id)) {
119
119
  integral = false;
120
120
  break;
@@ -125,18 +125,20 @@ function makeIndexer(cpu: CpuEvidence): (id: number) => number {
125
125
  if (integral && count > 0 && max - min < count * 4 + 64) {
126
126
  const span = max - min + 1;
127
127
  const table = new Int32Array(span).fill(-1);
128
- for (let i = 0; i < count; i++) table[nodes[i]!.id - min] = i;
128
+ let ix = 0;
129
+ for (const node of nodes) table[node.id - min] = ix++;
129
130
  return (id) => {
130
131
  const k = id - min;
131
- return k >= 0 && k < span ? table[k]! : -1;
132
+ return k >= 0 && k < span ? (table[k] ?? -1) : -1;
132
133
  };
133
134
  }
134
135
  const byId = new Map<number, number>();
135
- for (let i = 0; i < count; i++) byId.set(nodes[i]!.id, i);
136
+ let ix = 0;
137
+ for (const node of nodes) byId.set(node.id, ix++);
136
138
  return (id) => byId.get(id) ?? -1;
137
139
  }
138
140
 
139
- export interface DenseNodeTimes {
141
+ interface DenseNodeTimes {
140
142
  selfUs: Float64Array;
141
143
  totalUs: Float64Array;
142
144
  samples: Float64Array;
@@ -152,18 +154,22 @@ export function computeDenseNodeTimes(
152
154
  const nodeIds = cpu.samples?.nodeIds ?? [];
153
155
  const deltas = cpu.samples?.timeDeltasUs ?? [];
154
156
  for (let i = 0; i < nodeIds.length; i++) {
155
- const ix = indexOf(nodeIds[i]!);
157
+ const id = nodeIds[i];
158
+ if (id === undefined) continue;
159
+ const ix = indexOf(id);
156
160
  if (ix === -1) continue;
157
- selfUs[ix]! += deltas[i] ?? 0;
158
- samples[ix]! += 1;
161
+ selfUs[ix] = (selfUs[ix] ?? 0) + (deltas[i] ?? 0);
162
+ samples[ix] = (samples[ix] ?? 0) + 1;
159
163
  }
160
164
 
161
165
  const totalUs = new Float64Array(count);
162
166
  for (let k = order.length - 1; k >= 0; k--) {
163
- const i = order[k]!;
164
- totalUs[i]! += selfUs[i]!;
165
- const p = parentIx[i]!;
166
- if (p >= 0) totalUs[p]! += totalUs[i]!;
167
+ const i = order[k];
168
+ if (i === undefined) continue;
169
+ const total = (totalUs[i] ?? 0) + (selfUs[i] ?? 0);
170
+ totalUs[i] = total;
171
+ const p = parentIx[i] ?? -1;
172
+ if (p >= 0) totalUs[p] = (totalUs[p] ?? 0) + total;
167
173
  }
168
174
  return { selfUs, totalUs, samples };
169
175
  }
@@ -172,12 +178,14 @@ export function computeNodeTimes(cpu: CpuEvidence): Map<number, NodeTimes> {
172
178
  const tree = buildDenseTree(cpu);
173
179
  const { selfUs, totalUs, samples } = computeDenseNodeTimes(cpu, tree);
174
180
  const times = new Map<number, NodeTimes>();
175
- for (let i = 0; i < tree.count; i++) {
176
- times.set(cpu.nodes[i]!.id, {
177
- selfUs: selfUs[i]!,
178
- totalUs: totalUs[i]!,
179
- samples: samples[i]!,
181
+ let i = 0;
182
+ for (const node of cpu.nodes) {
183
+ times.set(node.id, {
184
+ selfUs: selfUs[i] ?? 0,
185
+ totalUs: totalUs[i] ?? 0,
186
+ samples: samples[i] ?? 0,
180
187
  });
188
+ i++;
181
189
  }
182
190
  return times;
183
191
  }
@@ -10,7 +10,6 @@ import type {
10
10
  } from "../ir/types.ts";
11
11
  import { percentile, sortedCopy } from "../stats/index.ts";
12
12
 
13
- /** `lo…hi` in one shared unit. */
14
13
  export function formatSpan(lo: number, hi: number, unit: DurationUnit): string {
15
14
  return `${formatDuration(lo, unit)}…${formatDuration(hi, unit)}`;
16
15
  }
@@ -23,17 +22,13 @@ export function formatUsAsMs(us: number): string {
23
22
  return (us / 1000).toFixed(2);
24
23
  }
25
24
 
26
- /**
27
- * `512B`, `2.00KiB`, `14.90MiB`: every byte count ostia prints is
28
- * 1024-based.
29
- */
25
+ // invariant: every byte count ostia prints is 1024-based.
30
26
  export function formatBytes(bytes: number): string {
31
27
  if (bytes < 1024) return `${bytes.toFixed(0)}B`;
32
28
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)}KiB`;
33
29
  return `${(bytes / (1024 * 1024)).toFixed(2)}MiB`;
34
30
  }
35
31
 
36
- /** An instruction count: `840`, `12.4K`, `3.02M`, `1.25G`. */
37
32
  export function formatInstructions(count: number): string {
38
33
  if (count < 1e3) return count.toFixed(0);
39
34
  const [divisor, suffix] =
@@ -46,11 +41,17 @@ export function frameName(frame: Frame | undefined): string {
46
41
  return frame?.name || "(anonymous)";
47
42
  }
48
43
 
49
- /**
50
- * The `limit` heaviest frames by self time (`cpu.totals` is pre-sorted),
51
- * with each one's share of all self time as a one-decimal percent string.
52
- * */
53
- export function topSelfFrames(cpu: CpuEvidence, limit: number) {
44
+ // `cpu.totals` is pre-sorted by self time, so the first `limit` are the
45
+ // heaviest.
46
+ export function topSelfFrames(
47
+ cpu: CpuEvidence,
48
+ limit: number,
49
+ ): {
50
+ frame: Frame | undefined;
51
+ selfUs: number;
52
+ totalUs: number;
53
+ pct: string;
54
+ }[] {
54
55
  const totalSelfUs = cpu.totals.reduce((s, t) => s + t.selfUs, 0) || 1;
55
56
  return cpu.totals.slice(0, limit).map((t) => ({
56
57
  frame: cpu.frames[t.frameIx],
@@ -60,17 +61,14 @@ export function topSelfFrames(cpu: CpuEvidence, limit: number) {
60
61
  }));
61
62
  }
62
63
 
63
- /** `1200 objects, 3.42MiB` */
64
64
  export function formatHeapSummary(heap: HeapEvidence): string {
65
65
  return `${heap.objectCount ?? "?"} objects, ${formatBytes(heap.heapSizeBytes ?? 0)}`;
66
66
  }
67
67
 
68
- /** `Apple M2 Pro · 12 cores · load 2.1 · noise floor 1.8%` */
69
68
  export function formatEnvironmentLine(env: Environment): string {
70
69
  return `${env.cpuModel} · ${env.cores} cores · load ${env.loadAvg1.toFixed(1)} · noise floor ${env.noise.floorPct.toFixed(1)}%`;
71
70
  }
72
71
 
73
- /** `abc1234 (main, dirty)` */
74
72
  export function formatGit(git: GitMetadata): string {
75
73
  return `${git.sha} (${git.branch}${git.dirty ? ", dirty" : ""})`;
76
74
  }
@@ -79,24 +77,17 @@ export function workloadLabel(w: Workload): string {
79
77
  return w.label ?? w.command?.join(" ") ?? w.entry?.task ?? w.id;
80
78
  }
81
79
 
82
- /**
83
- * The workload's label, or its raw id when the document has no such
84
- * workload.
85
- */
86
80
  export function labelOrId(w: Workload | undefined, id: string): string {
87
81
  return w ? workloadLabel(w) : id;
88
82
  }
89
83
 
90
- /** `1.00× (baseline)` / `1.00×` / `2.43× slower` / `1.95× faster` */
91
84
  export function formatRelative(relative: number, baseline: boolean): string {
92
85
  if (relative === 1) return baseline ? "1.00× (baseline)" : "1.00×";
93
86
  if (relative > 1) return `${relative.toFixed(2)}× slower`;
94
87
  return `${(1 / relative).toFixed(2)}× faster`;
95
88
  }
96
89
 
97
- /**
98
- * Escapes `|`, `<`, `>`, backticks and newlines so a name can't break a
99
- * GFM table row. */
90
+ // So a name can't break a GFM table row.
100
91
  export function escapeMdCell(s: string): string {
101
92
  return s
102
93
  .replace(/\|/g, "\\|")
@@ -106,9 +97,8 @@ export function escapeMdCell(s: string): string {
106
97
  .replace(/\r\n|\r|\n/g, "<br>");
107
98
  }
108
99
 
109
- /**
110
- * Median user/system CPU time per trial of a subprocess measurement;
111
- * undefined for in-process ones. */
100
+ // Median per trial; in-process measurements have no CPU times, so
101
+ // undefined.
112
102
  export function cpuTimes(
113
103
  run: Pick<Measurement, "trials">,
114
104
  ): { userNs: number; systemNs: number } | undefined {
@@ -134,7 +124,7 @@ export function formatCpuTimes(times: {
134
124
  return `${formatDuration(times.userNs)}/${formatDuration(times.systemNs)}`;
135
125
  }
136
126
 
137
- /** `+3.2%`, `-1.5%`; a delta that rounds to zero is `0.0%`, unsigned. */
127
+ // A delta that rounds to zero prints unsigned, never `-0.0%`.
138
128
  export function formatSignedPct(pct: number): string {
139
129
  const text = pct.toFixed(1);
140
130
  if (Number(text) === 0) return "0.0%";
@@ -3,16 +3,26 @@ import { cpuprofileRenderer } from "./cpuprofile.ts";
3
3
  import { jsonRenderer } from "./json.ts";
4
4
  import { jsonlRenderer } from "./jsonl.ts";
5
5
  import { markdownRenderer } from "./markdown.ts";
6
- import { mermaidRenderer } from "./mermaid.ts";
7
- import { minimalRenderer } from "./minimal.ts";
6
+ import { type MermaidOptions, mermaidRenderer } from "./mermaid.ts";
7
+ import { minimalRenderer, type MinimalRenderOptions } from "./minimal.ts";
8
8
  import { speedscopeRenderer } from "./speedscope.ts";
9
9
  import { terminalRenderer } from "./terminal.ts";
10
- import type { FormatName, Renderer } from "./types.ts";
10
+ import type { FormatName, Renderer, VizOptions } from "./types.ts";
11
11
 
12
12
  /** Each format's renderer, typed with its own options. `Renderer<never>` is
13
13
  * the top type, so `satisfies` checks every format is present without
14
14
  * widening the options. */
15
- export const renderers = {
15
+ export const renderers: {
16
+ table: Renderer;
17
+ json: Renderer;
18
+ markdown: Renderer;
19
+ jsonl: Renderer;
20
+ minimal: Renderer<MinimalRenderOptions>;
21
+ collapsed: Renderer<VizOptions>;
22
+ mermaid: Renderer<MermaidOptions>;
23
+ speedscope: Renderer<VizOptions>;
24
+ cpuprofile: Renderer<VizOptions>;
25
+ } = {
16
26
  table: terminalRenderer,
17
27
  json: jsonRenderer,
18
28
  markdown: markdownRenderer,
@@ -4,7 +4,7 @@ import type { Renderer, RenderResult } from "./types.ts";
4
4
 
5
5
  export const jsonRenderer: Renderer = {
6
6
  name: "json",
7
- async render(doc: ProfileDocument): Promise<RenderResult> {
8
- return { text: serializeDocument(doc) };
7
+ render(doc: ProfileDocument): Promise<RenderResult> {
8
+ return Promise.try(() => ({ text: serializeDocument(doc) }));
9
9
  },
10
10
  };
@@ -4,12 +4,16 @@ import type { Renderer, RenderResult } from "./types.ts";
4
4
 
5
5
  export const jsonlRenderer: Renderer = {
6
6
  name: "jsonl",
7
- async render(doc: ProfileDocument): Promise<RenderResult> {
8
- const { measurements, ...header } = doc;
9
- const lines = [
10
- canonicalJSON({ kind: "document", ...header }),
11
- ...measurements.map((r) => canonicalJSON({ kind: "measurement", ...r })),
12
- ];
13
- return { text: `${lines.join("\n")}\n` };
7
+ render(doc: ProfileDocument): Promise<RenderResult> {
8
+ return Promise.try(() => {
9
+ const { measurements, ...header } = doc;
10
+ const lines = [
11
+ canonicalJSON({ kind: "document", ...header }),
12
+ ...measurements.map((r) =>
13
+ canonicalJSON({ kind: "measurement", ...r }),
14
+ ),
15
+ ];
16
+ return { text: `${lines.join("\n")}\n` };
17
+ });
14
18
  },
15
19
  };