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,21 +9,20 @@ const DEFAULT_BATCH_SIZE = 100;
9
9
  // reach it.
10
10
  const DEFAULT_BUDGET_MS = 1000;
11
11
 
12
- export interface AllocCaptureResult {
12
+ interface AllocCaptureResult {
13
13
  memory: MemoryEvidence;
14
14
  /** The heap grows in blocks, so fewer calls mean a coarser `bytesPerOp`. */
15
15
  calls: number;
16
16
  diagnosticWallNs: number;
17
17
  }
18
18
 
19
- /**
20
- * Retained heap growth per call: heap size after a batch and a full GC,
21
- * minus before, over the calls made: up to `batchSize`, fewer (at least
22
- * one) once `budgetMs` has passed. Garbage is collected, so this is a leak
23
- * check and a garbage-heavy task reads near zero. Never feeds timing
24
- * stats. */
19
+ // Retained heap growth per call: heap size after a batch and a full GC,
20
+ // minus before, over the calls made: up to `batchSize`, fewer (at least
21
+ // one) once `budgetMs` has passed. Garbage is collected, so this is a leak
22
+ // check and a garbage-heavy task reads near zero. Never feeds timing
23
+ // stats.
25
24
  export async function measureAllocPerOp(
26
- fn: () => unknown | Promise<unknown>,
25
+ fn: () => unknown,
27
26
  batchSize: number = DEFAULT_BATCH_SIZE,
28
27
  budgetMs: number = DEFAULT_BUDGET_MS,
29
28
  ): Promise<AllocCaptureResult> {
@@ -3,14 +3,12 @@ import { cpuSampleCount } from "../ir/cpu.ts";
3
3
  import type { CpuEvidence, JitTierBreakdown, Warning } from "../ir/types.ts";
4
4
  import { isPromiseLike } from "./loop.ts";
5
5
 
6
- /**
7
- * JSC's 1000µs default gives a ~3ms task about three samples per call, too
8
- * few for a top-frame table to hold still between runs. */
6
+ // JSC's 1000µs default would give a ~3ms task about three samples per
7
+ // call, too few for a top-frame table to hold still between runs.
9
8
  export const DEFAULT_TASK_CPU_INTERVAL_US = 100;
10
- /**
11
- * The sampler manages well under one sample per interval (about 0.6 at
12
- * 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on the window.
13
- * */
9
+ // perf: the sampler manages well under one sample per interval (about 0.6
10
+ // at 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on the
11
+ // window.
14
12
  const TARGET_SAMPLES = 2000;
15
13
  const WINDOW_SLACK = 2;
16
14
  const MIN_WINDOW_MS = 200;
@@ -18,30 +16,28 @@ const MAX_WINDOW_MS = 10_000;
18
16
  const LOW_SAMPLES = TARGET_SAMPLES / 2;
19
17
  const JIT_COLD_THRESHOLD_PCT = 20;
20
18
 
21
- export interface TaskCpuCaptureOptions {
19
+ interface TaskCpuCaptureOptions {
22
20
  intervalUs?: number;
23
21
  }
24
22
 
25
- export interface TaskCpuCaptureResult {
23
+ interface TaskCpuCaptureResult {
26
24
  cpu: CpuEvidence;
27
25
  jit: JitTierBreakdown;
28
26
  diagnosticWallNs: number;
29
27
  warnings: Warning[];
30
28
  }
31
29
 
32
- /**
33
- * Capture window, ms: about `TARGET_SAMPLES` at `intervalUs`, clamped to
34
- * [200ms, 10s]. A task slower than the window still runs once, whole. */
30
+ // In ms. A task slower than the window still runs once, whole: the window
31
+ // never cuts a call short.
35
32
  export function cpuWindowMs(intervalUs: number): number {
36
33
  const ms = (TARGET_SAMPLES * WINDOW_SLACK * intervalUs) / 1000;
37
34
  return Math.min(MAX_WINDOW_MS, Math.max(MIN_WINDOW_MS, ms));
38
35
  }
39
36
 
40
- /**
41
- * Loops `fn` under the JSC sampling profiler for `cpuWindowMs`; one call
42
- * is usually gone before the first tick. Never feeds timing stats. */
37
+ // Loops `fn` under the JSC sampling profiler for `cpuWindowMs`; one call
38
+ // is usually gone before the first tick. Never feeds timing stats.
43
39
  export async function captureTaskCpuProfile(
44
- fn: () => unknown | Promise<unknown>,
40
+ fn: () => unknown,
45
41
  opts: TaskCpuCaptureOptions = {},
46
42
  ): Promise<TaskCpuCaptureResult> {
47
43
  const intervalUs = opts.intervalUs ?? DEFAULT_TASK_CPU_INTERVAL_US;
@@ -76,10 +72,6 @@ function lowCpuSampleWarning(cpu: CpuEvidence): Warning | undefined {
76
72
  };
77
73
  }
78
74
 
79
- /**
80
- * Warns when over `JIT_COLD_THRESHOLD_PCT`% of samples are still in
81
- * llint/baseline.
82
- */
83
75
  export function jitColdWarning(jit: JitTierBreakdown): Warning | undefined {
84
76
  const { llint, baseline, dfg, ftl } = jit.tiers;
85
77
  const total = llint + baseline + dfg + ftl;
@@ -5,10 +5,8 @@ import { measureNoiseFloor } from "./noise.ts";
5
5
 
6
6
  const LOAD_WARNING_FRACTION = 0.75;
7
7
 
8
- /**
9
- * Takes ~200ms (runs the noise-floor workload): call once per invocation,
10
- * not per workload.
11
- */
8
+ // perf: takes ~200ms (runs the noise-floor workload), so call it once per
9
+ // invocation, never per workload.
12
10
  export function captureEnvironment(): Environment {
13
11
  const [loadAvg1 = 0, loadAvg5 = 0] = os.loadavg();
14
12
  return {
@@ -20,10 +18,9 @@ export function captureEnvironment(): Environment {
20
18
  };
21
19
  }
22
20
 
23
- /**
24
- * Re-runs the reference loop at the end of a run and stamps how much
25
- * slower it ran than at the start on `env.noise.driftPct`: the machine's
26
- * drift over the run, which `compare` adds to its timing threshold. */
21
+ // Run at the end of a run, because `compare` adds the machine's drift
22
+ // over the run (how much slower the reference loop ran than at the start)
23
+ // to its timing threshold.
27
24
  export function stampDrift(env: Environment | undefined): void {
28
25
  if (!env) return;
29
26
  const start = env.noise.referenceMedianNs;
@@ -44,13 +44,14 @@ const BATCH_THRESHOLD_NS = 1000;
44
44
  // trial is sorted, serialized over IPC and parsed back, which costs
45
45
  // seconds at millions.
46
46
  const TRIALS_TARGET = 10_000;
47
- // Hard stop for a task that got faster than its calibration predicted.
47
+ // A hard stop, since a task that got faster than its calibration predicted
48
+ // would otherwise run far past `TRIALS_TARGET`.
48
49
  const MAX_TRIALS = 2 * TRIALS_TARGET;
49
50
  // Warmup doubles its batch until one spans this long.
50
51
  const WARMUP_CHUNK_NS = 1_000_000;
51
52
  const CALIBRATION_ROUNDS = 5;
52
53
 
53
- export interface InprocessTimingResult {
54
+ interface InprocessTimingResult {
54
55
  trials: Trial[];
55
56
  timing: TimingStats;
56
57
  /** Per trial, where the machine counts them. */
@@ -58,10 +59,9 @@ export interface InprocessTimingResult {
58
59
  warnings: Warning[];
59
60
  }
60
61
 
61
- /** Samples a task's per-trial cost earns regardless of budget: 3 at 1ms or
62
- * less, two more per decade of cost, capped at 10 from about 3s up. Only
63
- * expensive tasks ever hit it; the budget fills cheap ones with thousands.
64
- * */
62
+ // Samples a task's per-trial cost earns regardless of budget: 3 at 1ms or
63
+ // less, two more per decade of cost, capped at 10 from about 3s up. Only
64
+ // expensive tasks ever hit it; the budget fills cheap ones with thousands.
65
65
  export function rigorFloor(trialCostNs: number): number {
66
66
  const decadesAboveOneMs = Math.log10(Math.max(1, trialCostNs) / 1e6);
67
67
  const floor = Math.round(
@@ -70,8 +70,8 @@ export function rigorFloor(trialCostNs: number): number {
70
70
  return Math.min(RIGOR_FLOOR_CAP, Math.max(RIGOR_FLOOR_MIN, floor));
71
71
  }
72
72
 
73
- /** Default floor without `minSamples`: as many trials as fit in the budget
74
- * (capped at 20), never fewer than `rigorFloor`. */
73
+ // Default floor without `minSamples`: as many trials as fit in the budget
74
+ // (capped at 20), never fewer than `rigorFloor`.
75
75
  export function defaultSampleFloor(
76
76
  trialCostNs: number,
77
77
  timeBudgetNs: number,
@@ -81,14 +81,13 @@ export function defaultSampleFloor(
81
81
  }
82
82
 
83
83
  // Write-only on purpose: a store to module state is never provably dead.
84
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- see above
85
- let kept: unknown;
84
+ const kept: { value?: unknown } = {};
86
85
 
87
86
  /** Pins `value` against dead-code elimination for an intermediate inside a
88
87
  * task body. A task's own return value is already pinned by the timing
89
88
  * loop. */
90
89
  export function keep(value: unknown): void {
91
- kept = value;
90
+ kept.value = value;
92
91
  }
93
92
 
94
93
  function sizeBatch(singleCallNs: number, timeBudgetNs: number): number {
@@ -101,7 +100,7 @@ function sizeBatch(singleCallNs: number, timeBudgetNs: number): number {
101
100
 
102
101
  function medianOf(values: number[]): number {
103
102
  const sorted = [...values].sort((a, b) => a - b);
104
- return sorted[sorted.length >> 1]!;
103
+ return sorted[sorted.length >> 1] ?? 0;
105
104
  }
106
105
 
107
106
  export async function measureTask(
@@ -112,8 +111,8 @@ export async function measureTask(
112
111
  const warmupBudgetNs =
113
112
  timeBudgetNs * (opts.warmup ?? DEFAULT_WARMUP_FRACTION);
114
113
 
115
- // The first call picks the loop and is the cost estimate when warmup is
116
- // off.
114
+ // The first call picks the loop, and is the only cost estimate when
115
+ // warmup is off.
117
116
  const first = await probeFirstCall(fn);
118
117
  let singleCallNs = first.ns;
119
118
  const timeBatch = batchTimer(fn, first.isAsync);
@@ -146,7 +145,8 @@ export async function measureTask(
146
145
  const effectiveBudgetNs = opts.samples !== undefined ? 0 : timeBudgetNs;
147
146
  const maxTrials = opts.samples ?? Math.max(MAX_TRIALS, minSamples);
148
147
 
149
- // Read around each batch, outside the loop's own clock reads.
148
+ // Read around each batch, outside the loop's own clock reads, so reading
149
+ // the counter never adds to the measured time.
150
150
  const count = instructionCounter().read;
151
151
  const instructions: number[] = [];
152
152
  const trials: Trial[] = [];
@@ -1,24 +1,27 @@
1
1
  import { dlopen, FFIType, ptr, read } from "bun:ffi";
2
2
 
3
+ import { errorMessage } from "../errors.ts";
4
+
3
5
  /**
4
6
  * Reads how many instructions the calling thread has retired in user mode.
5
7
  * Only differences between two reads mean anything. */
6
8
  type InstructionReader = () => number;
7
9
 
8
- export type InstructionCounter =
10
+ type InstructionCounter =
9
11
  | { read: InstructionReader; unavailable?: undefined }
10
12
  /** Why this machine can't count instructions, for an error message. */
11
13
  | { read?: undefined; unavailable: string };
12
14
 
15
+ // One counter per process: each Linux open holds a perf event fd.
16
+ // eslint-disable-next-line no-restricted-syntax -- a lazy cache, opened once
13
17
  let counter: InstructionCounter | undefined;
14
18
 
15
- /**
16
- * The calling thread's retired-instruction counter: steadier than wall
17
- * time on a loaded machine, since another process taking the CPU doesn't
18
- * change what this thread executes. Per thread, user mode only, so neither
19
- * the kernel's work for a system call nor any other thread's (JIT
20
- * compiler, GC helpers, I/O pool) counts. Reads the hardware counter
21
- * through `thread_selfcounts` on macOS and `perf_event_open` on Linux. */
19
+ // The calling thread's retired-instruction counter: steadier than wall
20
+ // time on a loaded machine, since another process taking the CPU doesn't
21
+ // change what this thread executes. Per thread, user mode only, so neither
22
+ // the kernel's work for a system call nor any other thread's (JIT
23
+ // compiler, GC helpers, I/O pool) counts. Reads the hardware counter
24
+ // through `thread_selfcounts` on macOS and `perf_event_open` on Linux.
22
25
  export function instructionCounter(): InstructionCounter {
23
26
  counter ??= openCounter();
24
27
  return counter;
@@ -29,13 +32,14 @@ function openCounter(): InstructionCounter {
29
32
  if (process.platform === "darwin") return darwinCounter();
30
33
  if (process.platform === "linux") return linuxCounter();
31
34
  } catch (err) {
32
- return { unavailable: (err as Error).message };
35
+ return { unavailable: errorMessage(err) };
33
36
  }
34
37
  return { unavailable: `not supported on ${process.platform}` };
35
38
  }
36
39
 
37
- // thread_selfcounts(1, ...) fills { instructions, cycles } for the calling
38
- // thread: what `/usr/bin/time -l` totals over a process, read per thread.
40
+ // spec: thread_selfcounts(1, ...) fills { instructions, cycles } for the
41
+ // calling thread: what `/usr/bin/time -l` totals over a process, read per
42
+ // thread.
39
43
  function darwinCounter(): InstructionCounter {
40
44
  const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
41
45
  thread_selfcounts: {
@@ -67,11 +71,12 @@ const PERF_TYPE_HARDWARE = 0;
67
71
  const PERF_COUNT_HW_INSTRUCTIONS = 1;
68
72
  // perf_event_attr's first version, which every kernel since takes.
69
73
  const PERF_ATTR_SIZE_VER0 = 64;
70
- // exclude_kernel | exclude_hv: what `perf_event_paranoid` 2 still allows.
74
+ // spec: exclude_kernel | exclude_hv, because `perf_event_paranoid` 2 still
75
+ // allows that much.
71
76
  const PERF_USER_ONLY = (1n << 5n) | (1n << 6n);
72
77
 
73
- // An event opened with pid 0 and cpu -1 counts the calling thread, on any
74
- // CPU, from the moment it's opened.
78
+ // spec: an event opened with pid 0 and cpu -1 counts the calling thread,
79
+ // on any CPU, from the moment it's opened.
75
80
  function linuxCounter(): InstructionCounter {
76
81
  const nr = PERF_EVENT_OPEN[process.arch];
77
82
  if (nr === undefined) {
@@ -103,8 +108,9 @@ function linuxCounter(): InstructionCounter {
103
108
  attr[5] = PERF_USER_ONLY;
104
109
  const fd = Number(symbols.syscall(nr, ptr(attr), 0, -1, -1, 0));
105
110
  if (fd < 0) {
106
- const errno = read.i32(symbols.__errno_location()!);
107
- return { unavailable: perfError(errno) };
111
+ const errnoAt = symbols.__errno_location();
112
+ if (errnoAt === null) throw new Error("__errno_location returned null");
113
+ return { unavailable: perfError(read.i32(errnoAt)) };
108
114
  }
109
115
  const count = new BigUint64Array(1);
110
116
  const at = ptr(count);
@@ -1,32 +1,40 @@
1
- export type TaskBody = () => unknown | Promise<unknown>;
1
+ export type TaskBody = () => unknown;
2
2
 
3
3
  export function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
4
4
  return (
5
5
  value !== null &&
6
6
  typeof value === "object" &&
7
- typeof (value as PromiseLike<unknown>).then === "function"
7
+ "then" in value &&
8
+ typeof value.then === "function"
8
9
  );
9
10
  }
10
11
 
12
+ // What `Function` and AsyncFunction build at runtime: a callable whose
13
+ // signature only the source text knows.
14
+ function isCallable<T>(f: unknown): f is T {
15
+ return typeof f === "function";
16
+ }
17
+
11
18
  type Loop = (
12
19
  fn: TaskBody,
13
20
  sink: unknown[],
14
21
  n: number,
15
22
  ) => number | Promise<number>;
16
23
 
17
- const AsyncFunction = (async () => {}).constructor as FunctionConstructor;
24
+ const AsyncFunction: unknown = (async () => {}).constructor;
25
+ // eslint-disable-next-line no-restricted-syntax -- gives each compiled loop its own source; see batchTimer
18
26
  let loopSerial = 0;
19
27
  // Ring buffer every result is stored into: the JIT can't prove a stored
20
28
  // value unused, so it can't elide the call or its allocations.
21
29
  const SINK_SIZE = 256;
22
30
 
23
- /** Times `n` back-to-back calls of `fn`, returning total ns, through a loop
24
- * compiled for this task alone. JSC specializes compiled code per
25
- * function: a shared loop gets its `fn()` call site tuned for whichever
26
- * task ran first and measures every later task through a slower generic
27
- * call. The serial in the source keeps JSC's code cache from handing two
28
- * tasks the same compiled body. An async task gets an awaiting loop; a
29
- * sync one never pays a microtask per call. */
31
+ // Times `n` back-to-back calls of `fn`, returning total ns, through a loop
32
+ // compiled for this task alone. JSC specializes compiled code per
33
+ // function: a shared loop gets its `fn()` call site tuned for whichever
34
+ // task ran first and measures every later task through a slower generic
35
+ // call. The serial in the source keeps JSC's code cache from handing two
36
+ // tasks the same compiled body. An async task gets an awaiting loop; a
37
+ // sync one never pays a microtask per call.
30
38
  export function batchTimer(
31
39
  fn: TaskBody,
32
40
  isAsync: boolean,
@@ -35,17 +43,16 @@ export function batchTimer(
35
43
  const t0 = Bun.nanoseconds()
36
44
  for (let b = 0; b < n; b++) sink[b & ${SINK_SIZE - 1}] = ${isAsync ? "await " : ""}fn()
37
45
  return Bun.nanoseconds() - t0`;
38
- const loop = (isAsync ? AsyncFunction : Function)(
39
- "fn",
40
- "sink",
41
- "n",
42
- body,
43
- ) as Loop;
46
+ const make = isAsync ? AsyncFunction : Function;
47
+ const loop = isCallable<FunctionConstructor>(make)
48
+ ? make("fn", "sink", "n", body)
49
+ : undefined;
50
+ if (!isCallable<Loop>(loop))
51
+ throw new Error("ostia: can't compile a task loop");
44
52
  const sink: unknown[] = new Array(SINK_SIZE);
45
53
  return (n) => loop(fn, sink, n);
46
54
  }
47
55
 
48
- /** Calls `fn` once, timed, to learn whether it is async. */
49
56
  export async function probeFirstCall(
50
57
  fn: TaskBody,
51
58
  ): Promise<{ isAsync: boolean; result: unknown; ns: number }> {
@@ -6,8 +6,8 @@ const DEFAULT_BUDGET_MS = 200;
6
6
  // dominate.
7
7
  const HASHES_PER_TRIAL = 64;
8
8
 
9
- // Fixed, allocation-free workload: trial-to-trial variance is the
10
- // machine's noise.
9
+ // Fixed and allocation-free, so trial-to-trial variance is the machine's
10
+ // noise.
11
11
  const REFERENCE_BUFFER = (() => {
12
12
  const buf = new Uint8Array(4096);
13
13
  for (let i = 0; i < buf.length; i++) buf[i] = (i * 2654435761) & 0xff;
@@ -17,13 +17,12 @@ const REFERENCE_BUFFER = (() => {
17
17
  function hashBuffer(buf: Uint8Array, seed: number): number {
18
18
  let h = seed;
19
19
  for (let i = 0; i < buf.length; i++) {
20
- h ^= buf[i]!;
20
+ h ^= buf[i] ?? 0;
21
21
  h = Math.imul(h, 16777619);
22
22
  }
23
23
  return h >>> 0;
24
24
  }
25
25
 
26
- /** `mad / median` of `samples`, as a percent. */
27
26
  export function computeNoiseFloor(samples: number[]): NoiseFloor {
28
27
  const stats = computeTimingStats(samples);
29
28
  return {
@@ -33,10 +32,11 @@ export function computeNoiseFloor(samples: number[]): NoiseFloor {
33
32
  };
34
33
  }
35
34
 
36
- /**
37
- * Samples the reference hash loop for `budgetMs`; characterizes the
38
- * machine, not any workload, so run it once per document. */
39
- export function measureNoiseFloor(budgetMs = DEFAULT_BUDGET_MS): NoiseFloor {
35
+ // Samples the reference hash loop for `budgetMs`; characterizes the
36
+ // machine, not any workload, so run it once per document.
37
+ export function measureNoiseFloor(
38
+ budgetMs: number = DEFAULT_BUDGET_MS,
39
+ ): NoiseFloor {
40
40
  const budgetNs = budgetMs * 1e6;
41
41
  const trials: number[] = [];
42
42
  let sink = 0;
@@ -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);