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
@@ -8,62 +8,66 @@ const SCHEMA_URL = "https://www.speedscope.app/file-format-schema.json";
8
8
 
9
9
  export const speedscopeRenderer: Renderer<VizOptions> = {
10
10
  name: "speedscope",
11
- async render(
11
+ render(
12
12
  doc: ProfileDocument,
13
13
  options: VizOptions = {},
14
14
  ): Promise<RenderResult> {
15
- const byWorkload = workloadsById(doc);
15
+ return Promise.try(() => {
16
+ const byWorkload = workloadsById(doc);
16
17
 
17
- return renderCpuFiles(doc, options, "speedscope.json", (run) => {
18
- const { cpu } = run;
19
- const { nodes } = cpu;
20
- const tree = buildDenseTree(cpu);
21
- const nodeIds = cpu.samples?.nodeIds ?? [];
22
- const weights = cpu.samples?.timeDeltasUs ?? [];
18
+ return renderCpuFiles(doc, options, "speedscope.json", (run) => {
19
+ const { cpu } = run;
20
+ const { nodes } = cpu;
21
+ const tree = buildDenseTree(cpu);
22
+ const nodeIds = cpu.samples?.nodeIds ?? [];
23
+ const weights = cpu.samples?.timeDeltasUs ?? [];
23
24
 
24
- const stackOf: number[][] = new Array(tree.count);
25
- for (const i of tree.order) {
26
- const p = tree.parentIx[i]!;
27
- const frameIx = nodes[i]!.frameIx;
28
- stackOf[i] = p === -1 ? [frameIx] : [...stackOf[p]!, frameIx];
29
- }
25
+ const stackOf = new Array<number[]>(tree.count);
26
+ for (const i of tree.order) {
27
+ const node = nodes[i];
28
+ if (node === undefined) continue;
29
+ const p = tree.parentIx[i] ?? -1;
30
+ stackOf[i] =
31
+ p === -1 ? [node.frameIx] : [...(stackOf[p] ?? []), node.frameIx];
32
+ }
30
33
 
31
- const samples = nodeIds.map((id) => {
32
- const ix = tree.indexOf(id);
33
- return ix === -1 ? [] : stackOf[ix]!;
34
- });
35
- const workload = byWorkload.get(run.workloadId);
36
- const name =
37
- workload?.label ??
38
- workload?.command?.join(" ") ??
39
- workload?.entry?.task ??
40
- "profile";
34
+ const samples = nodeIds.map((id) => {
35
+ const ix = tree.indexOf(id);
36
+ return (ix === -1 ? undefined : stackOf[ix]) ?? [];
37
+ });
38
+ const workload = byWorkload.get(run.workloadId);
39
+ const name =
40
+ workload?.label ??
41
+ workload?.command?.join(" ") ??
42
+ workload?.entry?.task ??
43
+ "profile";
41
44
 
42
- const document = {
43
- $schema: SCHEMA_URL,
44
- exporter: "ostia",
45
- name,
46
- activeProfileIndex: 0,
47
- shared: {
48
- frames: cpu.frames.map((f) => ({
49
- name: frameName(f),
50
- file: f.url,
51
- line: f.line !== undefined ? f.line + 1 : undefined,
52
- })),
53
- },
54
- profiles: [
55
- {
56
- type: "sampled",
57
- name,
58
- unit: "microseconds",
59
- startValue: 0,
60
- endValue: weights.reduce((sum, w) => sum + w, 0),
61
- samples,
62
- weights,
45
+ const document = {
46
+ $schema: SCHEMA_URL,
47
+ exporter: "ostia",
48
+ name,
49
+ activeProfileIndex: 0,
50
+ shared: {
51
+ frames: cpu.frames.map((f) => ({
52
+ name: frameName(f),
53
+ file: f.url,
54
+ line: f.line !== undefined ? f.line + 1 : undefined,
55
+ })),
63
56
  },
64
- ],
65
- };
66
- return `${JSON.stringify(document, null, 2)}\n`;
57
+ profiles: [
58
+ {
59
+ type: "sampled",
60
+ name,
61
+ unit: "microseconds",
62
+ startValue: 0,
63
+ endValue: weights.reduce((sum, w) => sum + w, 0),
64
+ samples,
65
+ weights,
66
+ },
67
+ ],
68
+ };
69
+ return `${JSON.stringify(document, null, 2)}\n`;
70
+ });
67
71
  });
68
72
  },
69
73
  };
@@ -70,7 +70,7 @@ interface Column<R> {
70
70
 
71
71
  interface TableRow<R> {
72
72
  label: string;
73
- group?: string;
73
+ group?: string | undefined;
74
74
  /** Absent when there is nothing to tabulate; `status` says why. */
75
75
  data?: R;
76
76
  /** The row's text when `data` is absent: `skipped` or `no samples`. */
@@ -80,7 +80,6 @@ interface TableRow<R> {
80
80
 
81
81
  function textTable<R>(columns: Column<R>[], rows: TableRow<R>[]): string[] {
82
82
  const indentOf = (row: TableRow<R>) => (row.group !== undefined ? " " : "");
83
- // Under its group's header, a row shows the task name alone.
84
83
  const shown = (row: TableRow<R>) => labelInGroup(row.label, row.group);
85
84
  let labelWidth = 4;
86
85
  for (const r of rows) {
@@ -122,32 +121,34 @@ function finish(lines: string[]): RenderResult {
122
121
 
123
122
  export const terminalRenderer: Renderer = {
124
123
  name: "table",
125
- async render(doc: ProfileDocument): Promise<RenderResult> {
126
- const env = doc.environment
127
- ? [formatEnvironmentLine(doc.environment), ""]
128
- : [];
129
-
130
- // Only `ab()` writes paired measurements, and it always stamps `ab`.
131
- if (doc.ab) return finish(renderPaired(doc, doc.ab, env));
132
-
133
- const runs = timingRuns(doc);
134
- const empty = noSampleRuns(doc);
135
- const comparisons = renderComparisons(doc);
136
- if (
137
- runs.length === 0 &&
138
- empty.length === 0 &&
139
- skippedWorkloads(doc, runs).length === 0
140
- ) {
141
- return comparisons.length > 0
142
- ? finish([...env, ...comparisons])
143
- : { text: "(no timing runs)\n" };
144
- }
124
+ render(doc: ProfileDocument): Promise<RenderResult> {
125
+ return Promise.try(() => {
126
+ const env = doc.environment
127
+ ? [formatEnvironmentLine(doc.environment), ""]
128
+ : [];
129
+
130
+ // Only `ab()` writes paired measurements, and it always stamps `ab`.
131
+ if (doc.ab) return finish(renderPaired(doc, doc.ab, env));
132
+
133
+ const runs = timingRuns(doc);
134
+ const empty = noSampleRuns(doc);
135
+ const comparisons = renderComparisons(doc);
136
+ if (
137
+ runs.length === 0 &&
138
+ empty.length === 0 &&
139
+ skippedWorkloads(doc, runs).length === 0
140
+ ) {
141
+ return comparisons.length > 0
142
+ ? finish([...env, ...comparisons])
143
+ : { text: "(no timing runs)\n" };
144
+ }
145
145
 
146
- const lines = [...env, ...renderTiming(doc, runs, empty)];
147
- const instrumented = renderInstrumentedRuns(doc);
148
- if (instrumented.length > 0) lines.push("", ...instrumented);
149
- if (comparisons.length > 0) lines.push("", ...comparisons);
150
- return finish(lines);
146
+ const lines = [...env, ...renderTiming(doc, runs, empty)];
147
+ const instrumented = renderInstrumentedRuns(doc);
148
+ if (instrumented.length > 0) lines.push("", ...instrumented);
149
+ if (comparisons.length > 0) lines.push("", ...comparisons);
150
+ return finish(lines);
151
+ });
151
152
  },
152
153
  };
153
154
 
@@ -167,15 +168,13 @@ function renderTiming(
167
168
  const run = runByWorkloadId.get(workload.id);
168
169
  const label = workloadLabel(workload);
169
170
  const group = groupOf(workload);
171
+ const noSample = noSampleByWorkloadId.get(workload.id);
170
172
  if (run) {
171
173
  const data = { run, workload };
172
174
  measured.push(data);
173
175
  rows.push({ label, group, data, warnings: runWarnings(run, memory) });
174
- } else if (noSampleByWorkloadId.has(workload.id)) {
175
- const warnings = runWarnings(
176
- noSampleByWorkloadId.get(workload.id)!,
177
- memory,
178
- );
176
+ } else if (noSample) {
177
+ const warnings = runWarnings(noSample, memory);
179
178
  rows.push({ label, group, status: "no samples", warnings });
180
179
  } else if (workload.skipped) {
181
180
  rows.push({ label, group, status: "skipped", warnings: [] });
@@ -238,7 +237,12 @@ function renderTiming(
238
237
  columns.push({
239
238
  header: "Relative",
240
239
  width: 8,
241
- cell: (row) => formatRelative(ratios.get(row)!, !!row.workload?.baseline),
240
+ cell: (row) => {
241
+ const ratio = ratios.get(row);
242
+ return ratio === undefined
243
+ ? ""
244
+ : formatRelative(ratio, !!row.workload?.baseline);
245
+ },
242
246
  });
243
247
  }
244
248
 
@@ -1,4 +1,4 @@
1
- export interface TrialResult {
1
+ interface TrialResult {
2
2
  wallNs: number;
3
3
  /** `null` when the trial timed out: its exit code carries no information. */
4
4
  exitCode: number | null;
@@ -65,10 +65,6 @@ class TimeSourceNoMatchError extends Error {}
65
65
 
66
66
  const compiledPatterns = new WeakMap<TimeSource, RegExp>();
67
67
 
68
- /**
69
- * A string pattern is compiled once per `TimeSource` object, not per
70
- * trial.
71
- */
72
68
  function compiledPattern(source: TimeSource): RegExp {
73
69
  if (typeof source.pattern !== "string") return source.pattern;
74
70
  let re = compiledPatterns.get(source);
@@ -79,7 +75,7 @@ function compiledPattern(source: TimeSource): RegExp {
79
75
  return re;
80
76
  }
81
77
 
82
- /** Called once per workload so a bad pattern fails before any trial runs. */
78
+ // Called once per workload so a bad pattern fails before any trial runs.
83
79
  export function assertReusableTimeSource(source: TimeSource): void {
84
80
  const re = compiledPattern(source);
85
81
  if (/[gyd]/.test(re.flags)) {
@@ -109,9 +105,8 @@ const UNIT_NS: Record<TimeUnit, number> = {
109
105
  s: 1e9,
110
106
  };
111
107
 
112
- /**
113
- * `timeoutMs` and the caller's `signal` folded into spawn options that
114
- * SIGKILL on either; `timedOut()` tells the two apart afterwards. */
108
+ // One kill for a timeout and an abort alike, since the spawn options
109
+ // SIGKILL on either; `timedOut()` tells the two apart afterwards.
115
110
  export function killSwitch(
116
111
  timeoutMs: number | undefined,
117
112
  signal: AbortSignal | undefined,
@@ -137,8 +132,8 @@ export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
137
132
 
138
133
  const kill = killSwitch(opts.timeoutMs, opts.signal);
139
134
  const proc = Bun.spawn(opts.argv, {
140
- cwd: opts.cwd,
141
- env: opts.env,
135
+ ...(opts.cwd !== undefined && { cwd: opts.cwd }),
136
+ ...(opts.env !== undefined && { env: opts.env }),
142
137
  stdout: capture ? "pipe" : "ignore",
143
138
  stderr: capture ? "pipe" : "ignore",
144
139
  stdin: "ignore",
@@ -148,8 +143,8 @@ export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
148
143
  // inflate the wall time.
149
144
  const output = capture
150
145
  ? Promise.all([
151
- new Response(proc.stdout as ReadableStream).text(),
152
- new Response(proc.stderr as ReadableStream).text(),
146
+ new Response(proc.stdout).text(),
147
+ new Response(proc.stderr).text(),
153
148
  ])
154
149
  : undefined;
155
150
  const exitCode = await proc.exited;
@@ -160,9 +155,11 @@ export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
160
155
  const result: TrialResult = {
161
156
  wallNs: end - start,
162
157
  exitCode: timedOut ? null : exitCode,
163
- userNs: usage ? Number(usage.cpuTime.user) * 1000 : undefined,
164
- systemNs: usage ? Number(usage.cpuTime.system) * 1000 : undefined,
165
- maxRssBytes: usage?.maxRSS,
158
+ ...(usage && {
159
+ userNs: Number(usage.cpuTime.user) * 1000,
160
+ systemNs: Number(usage.cpuTime.system) * 1000,
161
+ maxRssBytes: usage.maxRSS,
162
+ }),
166
163
  ...(timedOut && { timedOut: true as const }),
167
164
  };
168
165
  if (output) {
@@ -230,10 +227,6 @@ function excerpt(stdout: string, stderr: string): string {
230
227
 
231
228
  const NO_MATCH_OUTPUT_LIMIT_BYTES = 2048;
232
229
 
233
- /**
234
- * `excerpt` capped at 2 KiB total, for a `time-source-no-match` warning's
235
- * `data`.
236
- */
237
230
  function excerptForNoMatch(stdout: string, stderr: string): string {
238
231
  const full = excerpt(stdout, stderr);
239
232
  if (Buffer.byteLength(full, "utf8") <= NO_MATCH_OUTPUT_LIMIT_BYTES) {
@@ -248,12 +241,10 @@ function excerptForNoMatch(stdout: string, stderr: string): string {
248
241
 
249
242
  const OUTPUT_CAP_BYTES = 1024 * 1024;
250
243
 
251
- /**
252
- * Reads a stream into a string capped at `capBytes`: the first and last
253
- * half joined by an elision marker, dropping the middle as it arrives so
254
- * memory stays bounded. For debug output (a misbehaving `prepare` hook's
255
- * stderr), not `timeSource` capture, which stays unbounded because a
256
- * summary line may be anywhere in the output. */
244
+ // The first and last half joined by an elision marker, dropping the middle
245
+ // as it arrives so memory stays bounded. For debug output (a misbehaving
246
+ // `prepare` hook's stderr), not `timeSource` capture, which stays
247
+ // unbounded because a summary line may be anywhere in the output.
257
248
  export async function readBoundedText(
258
249
  stream: ReadableStream<Uint8Array>,
259
250
  capBytes: number = OUTPUT_CAP_BYTES,
@@ -287,9 +278,9 @@ export async function readBoundedText(
287
278
  }
288
279
  tailChunks.push(chunk);
289
280
  tailBytes += chunk.byteLength;
290
- // Keep only the last `halfBytes`.
291
- while (tailBytes > halfBytes && tailChunks.length > 0) {
292
- const first = tailChunks[0]!;
281
+ while (tailBytes > halfBytes) {
282
+ const first = tailChunks[0];
283
+ if (first === undefined) break;
293
284
  const excess = tailBytes - halfBytes;
294
285
  if (first.byteLength <= excess) {
295
286
  tailChunks.shift();
@@ -312,11 +303,10 @@ export async function readBoundedText(
312
303
  return `${head}\n…(${elidedBytes} bytes elided)…\n${tail}`;
313
304
  }
314
305
 
315
- /**
316
- * Runs a `prepare` hook ahead of one trial. Command forms must exit 0.
317
- * `timeoutMs` SIGKILLs a hung command and aborts the run; `signal` kills
318
- * it silently, since cancellation isn't a failure. stderr is captured (1
319
- * MiB bounded) and folded into the thrown error rather than streamed. */
306
+ // Command forms must exit 0. `timeoutMs` SIGKILLs a hung command and
307
+ // aborts the run; `signal` kills it silently, since cancellation isn't a
308
+ // failure. stderr is captured (1 MiB bounded) and folded into the thrown
309
+ // error rather than streamed.
320
310
  export async function runPrepare(
321
311
  hook: PrepareHook,
322
312
  run: PrepareRun,
@@ -331,11 +321,11 @@ export async function runPrepare(
331
321
  await hook(run);
332
322
  return;
333
323
  }
334
- const argv = prepareArgv(hook)!;
324
+ const argv = commandArgv(hook);
335
325
  const kill = killSwitch(opts.timeoutMs, opts.signal);
336
326
  const proc = Bun.spawn(argv, {
337
- cwd: opts.cwd,
338
- env: opts.env,
327
+ ...(opts.cwd !== undefined && { cwd: opts.cwd }),
328
+ ...(opts.env !== undefined && { env: opts.env }),
339
329
  stdout: "ignore",
340
330
  stderr: "pipe",
341
331
  stdin: "ignore",
@@ -343,9 +333,7 @@ export async function runPrepare(
343
333
  });
344
334
  // Drain even if nothing reads it, so a chatty hook can't block on a full
345
335
  // pipe; `.catch` avoids an unhandled rejection.
346
- const stderrText = readBoundedText(proc.stderr as ReadableStream).catch(
347
- () => "",
348
- );
336
+ const stderrText = readBoundedText(proc.stderr).catch(() => "");
349
337
  const exitCode = await proc.exited;
350
338
  const timedOut = kill.timedOut();
351
339
  if (!timedOut && opts.signal?.aborted) return;
@@ -359,18 +347,21 @@ export async function runPrepare(
359
347
  );
360
348
  }
361
349
 
362
- /**
363
- * The command form's argv, for the document; a function isn't
364
- * serializable.
365
- */
350
+ function commandArgv(hook: string | string[]): string[] {
351
+ return Array.isArray(hook) ? hook : splitCommand(hook);
352
+ }
353
+
354
+ // The command form's argv, for the document; a function isn't
355
+ // serializable.
366
356
  export function prepareArgv(
367
357
  hook: PrepareHook | undefined,
368
358
  ): string[] | undefined {
369
359
  if (hook === undefined || typeof hook === "function") return undefined;
370
- return Array.isArray(hook) ? hook : splitCommand(hook);
360
+ return commandArgv(hook);
371
361
  }
372
362
 
373
- /** A `RegExp` pattern becomes its source string (flags dropped). */
363
+ // A `RegExp` pattern is stored as its source alone: the document is JSON,
364
+ // so flags are dropped.
374
365
  export function timeSourceSpec(
375
366
  source: TimeSource | undefined,
376
367
  ): SerializedTimeSource | undefined {
@@ -385,7 +376,7 @@ export function timeSourceSpec(
385
376
  };
386
377
  }
387
378
 
388
- export interface SerializedTimeSource {
379
+ interface SerializedTimeSource {
389
380
  pattern: string;
390
381
  group?: number;
391
382
  unit?: TimeUnit;
@@ -1,6 +1,6 @@
1
1
  import { percentile } from "./index.ts";
2
2
 
3
- /** Seeded PRNG, deterministic across platforms (32-bit integer math only). */
3
+ // Seeded PRNG, deterministic across platforms (32-bit integer math only).
4
4
  export function mulberry32(seed: number): () => number {
5
5
  let a = seed >>> 0;
6
6
  return () => {
@@ -14,12 +14,12 @@ export function mulberry32(seed: number): () => number {
14
14
  const MAX_SAMPLES_PER_SIDE = 2000;
15
15
  const DEFAULT_ITERATIONS = 2000;
16
16
 
17
- export interface BootstrapOptions {
17
+ interface BootstrapOptions {
18
18
  iterations?: number;
19
19
  seed?: number;
20
20
  }
21
21
 
22
- export interface BootstrapResult {
22
+ interface BootstrapResult {
23
23
  /** 95% CI on the difference of medians, percent of the baseline median. */
24
24
  ci95: [number, number];
25
25
  seed: number;
@@ -30,10 +30,8 @@ export interface BootstrapResult {
30
30
  };
31
31
  }
32
32
 
33
- /**
34
- * Partial Fisher-Yates; returns `samples` itself when already within
35
- * `max`.
36
- */
33
+ // Partial Fisher-Yates: only the first `max` positions are shuffled, since
34
+ // only they are kept.
37
35
  function subsample(
38
36
  samples: number[],
39
37
  rng: () => number,
@@ -43,63 +41,64 @@ function subsample(
43
41
  const pool = [...samples];
44
42
  for (let i = 0; i < max; i++) {
45
43
  const j = i + Math.floor(rng() * (pool.length - i));
46
- const tmp = pool[i]!;
47
- pool[i] = pool[j]!;
44
+ const tmp = pool[i] ?? 0;
45
+ pool[i] = pool[j] ?? 0;
48
46
  pool[j] = tmp;
49
47
  }
50
48
  return pool.slice(0, max);
51
49
  }
52
50
 
53
- class Side {
51
+ interface Side {
54
52
  readonly sorted: Float64Array;
55
- /**
56
- * Sorted position of each original sample, so results for a given seed
57
- * match a naive `samples[floor(rng() * n)]` resample bit for bit. */
53
+ // Sorted position of each original sample, so results for a given seed
54
+ // match a naive `samples[floor(rng() * n)]` resample bit for bit.
58
55
  readonly rankOf: Uint32Array;
59
56
  readonly counts: Uint32Array;
60
57
  readonly n: number;
61
- constructor(samples: number[]) {
62
- const n = samples.length;
63
- const order = new Uint32Array(n);
64
- for (let i = 0; i < n; i++) order[i] = i;
65
- order.sort((x, y) => samples[x]! - samples[y]!);
66
- this.sorted = new Float64Array(n);
67
- this.rankOf = new Uint32Array(n);
68
- for (let k = 0; k < n; k++) {
69
- this.sorted[k] = samples[order[k]!]!;
70
- this.rankOf[order[k]!] = k;
71
- }
72
- this.n = n;
73
- this.counts = new Uint32Array(n);
58
+ }
59
+
60
+ function side(samples: number[]): Side {
61
+ const n = samples.length;
62
+ const order = new Uint32Array(n);
63
+ for (let i = 0; i < n; i++) order[i] = i;
64
+ order.sort((x, y) => (samples[x] ?? 0) - (samples[y] ?? 0));
65
+ const sorted = new Float64Array(n);
66
+ const rankOf = new Uint32Array(n);
67
+ for (let k = 0; k < n; k++) {
68
+ const at = order[k] ?? 0;
69
+ sorted[k] = samples[at] ?? 0;
70
+ rankOf[at] = k;
74
71
  }
72
+ return { sorted, rankOf, counts: new Uint32Array(n), n };
73
+ }
75
74
 
76
- /**
77
- * Median of a with-replacement resample, found with one O(n) walk over an
78
- * index histogram instead of sorting `n` values per round. */
79
- resampleMedian(rng: () => number): number {
80
- const { n, counts, sorted, rankOf } = this;
81
- counts.fill(0);
82
- for (let i = 0; i < n; i++) counts[rankOf[Math.floor(rng() * n)]!]!++;
83
- // 1-based middle order statistic(s) of the draws.
84
- const loRank = (n + 1) >> 1;
85
- const hiRank = n % 2 === 0 ? loRank + 1 : loRank;
86
- let seen = 0;
87
- let lo = -1;
88
- for (let k = 0; k < n; k++) {
89
- seen += counts[k]!;
90
- if (lo < 0 && seen >= loRank) lo = k;
91
- if (seen >= hiRank) {
92
- return lo === k ? sorted[k]! : (sorted[lo]! + sorted[k]!) / 2;
93
- }
75
+ // Median of a with-replacement resample, found with one O(n) walk over an
76
+ // index histogram instead of sorting `n` values per round.
77
+ function resampleMedian(s: Side, rng: () => number): number {
78
+ const { n, counts, sorted, rankOf } = s;
79
+ counts.fill(0);
80
+ for (let i = 0; i < n; i++) {
81
+ const rank = rankOf[Math.floor(rng() * n)] ?? 0;
82
+ counts[rank] = (counts[rank] ?? 0) + 1;
83
+ }
84
+ // Ranks are 1-based because `seen` counts draws, not indices.
85
+ const loRank = (n + 1) >> 1;
86
+ const hiRank = n % 2 === 0 ? loRank + 1 : loRank;
87
+ let seen = 0;
88
+ let lo = -1;
89
+ for (let k = 0; k < n; k++) {
90
+ seen += counts[k] ?? 0;
91
+ if (lo < 0 && seen >= loRank) lo = k;
92
+ if (seen >= hiRank) {
93
+ const hi = sorted[k] ?? 0;
94
+ return lo === k ? hi : ((sorted[lo] ?? 0) + hi) / 2;
94
95
  }
95
- return sorted[n - 1]!;
96
96
  }
97
+ return sorted[n - 1] ?? 0;
97
98
  }
98
99
 
99
- /**
100
- * Hash of both arrays, so identical input always gets the same CI and
101
- * verdict.
102
- */
100
+ // Hash of both arrays, so identical input always gets the same CI and
101
+ // verdict.
103
102
  function seedFromSamples(base: number[], cand: number[]): number {
104
103
  const all = new Float64Array(base.length + cand.length + 1);
105
104
  all.set(base);
@@ -108,11 +107,10 @@ function seedFromSamples(base: number[], cand: number[]): number {
108
107
  return Bun.hash.crc32(all);
109
108
  }
110
109
 
111
- /**
112
- * Bootstrap 95% CI on the difference of medians, in percent of `base`'s
113
- * observed median. Each side is capped at `MAX_SAMPLES_PER_SIDE` samples
114
- * so a many-thousand-sample task doesn't take seconds. Throws when a side
115
- * is empty. */
110
+ // Bootstrap 95% CI on the difference of medians, in percent of `base`'s
111
+ // observed median. Each side is capped at `MAX_SAMPLES_PER_SIDE` samples
112
+ // so a many-thousand-sample task doesn't take seconds. Throws when a side
113
+ // is empty.
116
114
  export function bootstrapMedianDiffCi(
117
115
  base: number[],
118
116
  cand: number[],
@@ -127,14 +125,14 @@ export function bootstrapMedianDiffCi(
127
125
 
128
126
  const subsampled =
129
127
  base.length > MAX_SAMPLES_PER_SIDE || cand.length > MAX_SAMPLES_PER_SIDE;
130
- const baseSide = new Side(subsample(base, rng, MAX_SAMPLES_PER_SIDE));
131
- const candSide = new Side(subsample(cand, rng, MAX_SAMPLES_PER_SIDE));
128
+ const baseSide = side(subsample(base, rng, MAX_SAMPLES_PER_SIDE));
129
+ const candSide = side(subsample(cand, rng, MAX_SAMPLES_PER_SIDE));
132
130
  const baseMedian = percentile(baseSide.sorted, 0.5);
133
131
 
134
132
  const deltas = new Float64Array(iterations);
135
133
  for (let i = 0; i < iterations; i++) {
136
- const b = baseSide.resampleMedian(rng);
137
- const c = candSide.resampleMedian(rng);
134
+ const b = resampleMedian(baseSide, rng);
135
+ const c = resampleMedian(candSide, rng);
138
136
  const diff = c - b;
139
137
  deltas[i] =
140
138
  baseMedian === 0