ostia 0.3.0 → 0.4.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 (71) hide show
  1. package/index.d.ts +127 -99
  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 +70 -68
  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 +7 -5
  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 +19 -4
  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/ir/types.ts +3 -3
  42. package/src/measure/alloc.ts +7 -8
  43. package/src/measure/cpu.ts +12 -20
  44. package/src/measure/environment.ts +5 -8
  45. package/src/measure/inprocess.ts +15 -15
  46. package/src/measure/instructions.ts +22 -16
  47. package/src/measure/loop.ts +24 -17
  48. package/src/measure/noise.ts +8 -8
  49. package/src/measure/paired.ts +39 -47
  50. package/src/measure/peak.ts +20 -21
  51. package/src/measure/timing.ts +23 -23
  52. package/src/profile.ts +2 -1
  53. package/src/renderers/collapsed.ts +28 -21
  54. package/src/renderers/cpu-tree.ts +43 -35
  55. package/src/renderers/format.ts +16 -26
  56. package/src/renderers/index.ts +14 -4
  57. package/src/renderers/json.ts +2 -2
  58. package/src/renderers/jsonl.ts +11 -7
  59. package/src/renderers/markdown.ts +54 -36
  60. package/src/renderers/mermaid.ts +43 -31
  61. package/src/renderers/minimal.ts +15 -15
  62. package/src/renderers/paired.ts +31 -37
  63. package/src/renderers/relative.ts +10 -14
  64. package/src/renderers/select.ts +17 -39
  65. package/src/renderers/speedscope.ts +52 -48
  66. package/src/renderers/terminal.ts +37 -33
  67. package/src/spawn/index.ts +38 -47
  68. package/src/stats/bootstrap.ts +56 -58
  69. package/src/stats/index.ts +16 -12
  70. package/src/stats/mannwhitney.ts +11 -10
  71. package/src/time.ts +51 -39
@@ -10,7 +10,6 @@ import { batchTimer, probeFirstCall, type TaskBody } from "./loop.ts";
10
10
 
11
11
  export type Side = "base" | "cand";
12
12
 
13
- /** `"candidate"` for `"cand"`, for messages; other sides as they are. */
14
13
  export function sideLabel(side: Side | "both"): string {
15
14
  return side === "cand" ? "candidate" : side;
16
15
  }
@@ -19,17 +18,13 @@ export function sideLabel(side: Side | "both"): string {
19
18
  * What `measurePaired` throws when one side's task throws, naming the
20
19
  * side; the task's own error is `cause`. */
21
20
  export class PairedSideError extends Error {
22
- constructor(
23
- readonly side: Side,
24
- cause: unknown,
25
- ) {
21
+ readonly side: Side;
22
+ constructor(side: Side, cause: unknown) {
26
23
  super(cause instanceof Error ? cause.message : String(cause), { cause });
24
+ this.side = side;
27
25
  }
28
26
  }
29
27
 
30
- /**
31
- * Runs `fn`, rethrowing anything it throws as a `PairedSideError` for
32
- * `side`. */
33
28
  async function onSide<T>(
34
29
  side: "base" | "cand",
35
30
  fn: () => T | Promise<T>,
@@ -41,7 +36,7 @@ async function onSide<T>(
41
36
  }
42
37
  }
43
38
 
44
- export interface PairedTimingOptions {
39
+ interface PairedTimingOptions {
45
40
  /** Rounds of one base batch and one candidate batch (default: 15). */
46
41
  rounds?: number;
47
42
  /**
@@ -54,7 +49,7 @@ export interface PairedTimingOptions {
54
49
  candFirst?: boolean;
55
50
  }
56
51
 
57
- export interface PairedTimingResult {
52
+ interface PairedTimingResult {
58
53
  rounds: number;
59
54
  /** Calls per side per round. */
60
55
  batch: number;
@@ -77,7 +72,7 @@ interface InstructionSamples {
77
72
  candSamples: number[];
78
73
  }
79
74
 
80
- export interface RatioStats {
75
+ interface RatioStats {
81
76
  medianRatio: number;
82
77
  ratioP25: number;
83
78
  ratioP75: number;
@@ -85,17 +80,16 @@ export interface RatioStats {
85
80
  }
86
81
 
87
82
  const DEFAULT_ROUNDS = 15;
88
- // Long enough that timer resolution vanishes, short enough that the
83
+ // Long enough that timer resolution can't matter, short enough that the
89
84
  // machine barely changes between a round's two halves.
90
85
  const ROUND_BATCH_NS = 10_000_000;
91
86
  // Warmup doubles each side's batch until it spans this long.
92
87
  const WARMUP_CHUNK_NS = 1_000_000;
93
88
  const WARM_ROUNDS = 3;
94
89
 
95
- /**
96
- * Whether two first-call results are deep-equal. A result too deeply
97
- * nested to compare (a 10,000-level chain overflows the stack) counts as
98
- * equal: the check is informational and must not take the run down. */
90
+ // Whether two first-call results are deep-equal. A result too deeply
91
+ // nested to compare (a 10,000-level chain overflows the stack) counts as
92
+ // equal: the check is informational and must not take the run down.
99
93
  function sameResult(a: unknown, b: unknown): boolean {
100
94
  try {
101
95
  return Bun.deepEquals(a, b);
@@ -105,13 +99,12 @@ function sameResult(a: unknown, b: unknown): boolean {
105
99
  }
106
100
  }
107
101
 
108
- /**
109
- * Times `base` and `cand` against each other in one process: after warmup,
110
- * `rounds` rounds of one ~10ms batch per side, alternating which goes
111
- * first. Drift (load, thermal throttling) hits both halves of a round
112
- * alike and cancels in that round's ratio, which a baseline measured
113
- * minutes earlier can't do. A throw from either side rejects with a
114
- * `PairedSideError` naming it. */
102
+ // Times `base` and `cand` against each other in one process: after warmup,
103
+ // `rounds` rounds of one ~10ms batch per side, alternating which goes
104
+ // first. Drift (load, thermal throttling) hits both halves of a round
105
+ // alike and cancels in that round's ratio, which a baseline measured
106
+ // minutes earlier can't do. A throw from either side rejects with a
107
+ // `PairedSideError` naming it.
115
108
  export async function measurePaired(
116
109
  base: TaskBody,
117
110
  cand: TaskBody,
@@ -125,10 +118,17 @@ export async function measurePaired(
125
118
  const order: Side[] = opts.candFirst ? ["cand", "base"] : ["base", "cand"];
126
119
  const reversed = order.toReversed();
127
120
  const fns = { base, cand };
128
- const probes = {} as Record<Side, Awaited<ReturnType<typeof probeFirstCall>>>;
121
+ const probed: Partial<
122
+ Record<Side, Awaited<ReturnType<typeof probeFirstCall>>>
123
+ > = {};
129
124
  for (const name of order) {
130
- probes[name] = await onSide(name, () => probeFirstCall(fns[name]));
125
+ probed[name] = await onSide(name, () => probeFirstCall(fns[name]));
131
126
  }
127
+ const { base: baseProbe, cand: candProbe } = probed;
128
+ // invariant: `order` holds both sides.
129
+ if (!baseProbe || !candProbe)
130
+ throw new Error("measurePaired: a side wasn't probed");
131
+ const probes = { base: baseProbe, cand: candProbe };
132
132
  const sameOutput = sameResult(probes.base.result, probes.cand.result);
133
133
 
134
134
  const side = (name: Side) => {
@@ -158,7 +158,8 @@ export async function measurePaired(
158
158
  for (const name of order) await timers[name](batch);
159
159
  }
160
160
 
161
- // Read around each batch, outside the loop's own clock reads.
161
+ // Read around each batch, outside the loop's own clock reads, so reading
162
+ // the counter never adds to the measured time.
162
163
  const count = instructionCounter().read;
163
164
  const instructions: InstructionSamples = { baseSamples: [], candSamples: [] };
164
165
  const baseSamples: number[] = [];
@@ -200,9 +201,7 @@ function median(values: number[]): number {
200
201
 
201
202
  type RatioQuartiles = Omit<RatioStats, "flagged">;
202
203
 
203
- /**
204
- * `metric`'s ratios of a paired task or one of its repeats; undefined when
205
- * its instructions weren't counted. */
204
+ // Undefined only when `metric` is instructions and they weren't counted.
206
205
  export function metricRatios(
207
206
  r: RatioQuartiles & { instructions?: RatioQuartiles },
208
207
  metric: AbSummary["metric"],
@@ -210,9 +209,6 @@ export function metricRatios(
210
209
  return metric === "instructions" ? r.instructions : r;
211
210
  }
212
211
 
213
- /**
214
- * A paired task's evidence from its rounds (one process's, or several
215
- * pooled), `flagged` by `metric`'s ratios. */
216
212
  export function pairedEvidence(
217
213
  input: Pick<
218
214
  PairedTimingResult,
@@ -231,7 +227,9 @@ export function pairedEvidence(
231
227
  let instructionFlag: RatioStats["flagged"];
232
228
  if (input.instructions) {
233
229
  const { baseSamples, candSamples } = input.instructions;
234
- const ratios = candSamples.map((c, i) => c / Math.max(1, baseSamples[i]!));
230
+ const ratios = candSamples.map(
231
+ (c, i) => c / Math.max(1, baseSamples[i] ?? Number.NaN),
232
+ );
235
233
  const { flagged, ...stats } = ratioStats(ratios, thresholdPct);
236
234
  instructionFlag = flagged;
237
235
  instructions = {
@@ -258,10 +256,9 @@ export function pairedEvidence(
258
256
  };
259
257
  }
260
258
 
261
- /**
262
- * False when the suite file changed and the two sides' outputs differ:
263
- * the sides then likely ran different benchmarks, and their time ratio
264
- * says nothing about the code under test. */
259
+ // False when the suite file changed and the two sides' outputs differ,
260
+ // because the sides then likely ran different benchmarks, and their time
261
+ // ratio says nothing about the code under test.
265
262
  export function comparable(p: {
266
263
  suiteChanged?: true;
267
264
  sameOutput: boolean;
@@ -269,10 +266,6 @@ export function comparable(p: {
269
266
  return !(p.suiteChanged && !p.sameOutput);
270
267
  }
271
268
 
272
- /**
273
- * `regressed` when the candidate exceeds the base by more than
274
- * `thresholdPct` of the base and more than `floorBytes`; `improved` is the
275
- * mirror. */
276
269
  export function memoryChange(
277
270
  baseBytes: number,
278
271
  candBytes: number,
@@ -290,12 +283,11 @@ export function memoryChange(
290
283
  };
291
284
  }
292
285
 
293
- /**
294
- * `regressed` when the median ratio is above `1 + thresholdPct/100` and
295
- * the 25th percentile is above 1 (slower in at least three quarters of
296
- * rounds); `improved` is the mirror. The quartile condition keeps a few
297
- * wild rounds from flagging a workload whose typical round shows no
298
- * change. */
286
+ // `regressed` when the median ratio is above `1 + thresholdPct/100` and
287
+ // the 25th percentile is above 1 (slower in at least three quarters of
288
+ // rounds); `improved` is the mirror. The quartile condition is there so a
289
+ // few wild rounds can't flag a workload whose typical round shows no
290
+ // change.
299
291
  export function ratioStats(ratios: number[], thresholdPct: number): RatioStats {
300
292
  const sorted = sortedCopy(ratios);
301
293
  const medianRatio = percentile(sorted, 0.5);
@@ -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
  }