ostia 0.2.11 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -353
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +942 -642
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-scvezzm9.js → src/cli/help.ts} +31 -15
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-5m601yfv.js +0 -15
  89. package/chunk-82vs1rw1.js +0 -2
  90. package/chunk-dvqggjkn.js +0 -14
  91. package/chunk-fc36fd0b.js +0 -3
  92. package/chunk-pdv5zb3w.js +0 -27
  93. package/chunk-r6hwb84z.js +0 -25
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,396 @@
1
+ export interface TrialResult {
2
+ wallNs: number;
3
+ /** `null` when the trial timed out: its exit code carries no information. */
4
+ exitCode: number | null;
5
+ userNs?: number;
6
+ systemNs?: number;
7
+ maxRssBytes?: number;
8
+ /** Parsed from the command's output via `timeSource`, in ns. */
9
+ reportedNs?: number;
10
+ /**
11
+ * `timeoutMs` elapsed and the process was SIGKILLed; contributes no
12
+ * sample.
13
+ */
14
+ timedOut?: true;
15
+ /**
16
+ * `timeSource` was set but its pattern missed this trial's output;
17
+ * contributes no sample (no `wallNs` fallback). */
18
+ timeSourceNoMatch?: true;
19
+ /**
20
+ * Up to 2 KiB of output, set with `timeSourceNoMatch`. Not persisted on
21
+ * `Trial`; the timing phase folds one into the aggregate warning. */
22
+ timeSourceMissOutput?: string;
23
+ }
24
+
25
+ /**
26
+ * `index` counts from 0 within each phase, so "first run" logic checks
27
+ * `phase === "warmup" && index === 0` (or `phase === "timing"` when warmup
28
+ * is 0). */
29
+ export interface PrepareRun {
30
+ phase: "warmup" | "timing" | "cpu" | "heap";
31
+ index: number;
32
+ }
33
+
34
+ /** Return value ignored; a returned promise is awaited. */
35
+ export type PrepareFn = (run: PrepareRun) => unknown;
36
+
37
+ /**
38
+ * Runs unmeasured before every trial of a command, in its `cwd`/`env`
39
+ * (hyperfine's `--prepare`): a shell-less command (string,
40
+ * whitespace-split, or argv array) that must exit 0 or the run aborts, or
41
+ * a function. */
42
+ export type PrepareHook = string | string[] | PrepareFn;
43
+
44
+ export type TimeUnit = "ns" | "us" | "ms" | "s";
45
+
46
+ /**
47
+ * Take a command's timing from a number in its own stdout/stderr instead
48
+ * of the wall clock (e.g. a build tool's `built in 342ms` line). `pattern`
49
+ * is matched against stdout, then stderr; `group` (default 1) holds the
50
+ * number; `unit` defaults to "ms". A trial that doesn't match contributes
51
+ * no sample (`time-source-no-match` warning); if every trial misses, the
52
+ * workload has no timing stats. A `RegExp` pattern must not carry the `g`,
53
+ * `y`, or `d` flag: it is reused across trials, and `lastIndex` would make
54
+ * it alternate match/no-match. */
55
+ export interface TimeSource {
56
+ pattern: string | RegExp;
57
+ group?: number;
58
+ unit?: TimeUnit;
59
+ }
60
+
61
+ /**
62
+ * A pattern miss (a per-trial drop), unlike a matched-but-malformed
63
+ * capture, which is a configuration error and throws a plain `Error`. */
64
+ class TimeSourceNoMatchError extends Error {}
65
+
66
+ const compiledPatterns = new WeakMap<TimeSource, RegExp>();
67
+
68
+ /**
69
+ * A string pattern is compiled once per `TimeSource` object, not per
70
+ * trial.
71
+ */
72
+ function compiledPattern(source: TimeSource): RegExp {
73
+ if (typeof source.pattern !== "string") return source.pattern;
74
+ let re = compiledPatterns.get(source);
75
+ if (!re) {
76
+ re = new RegExp(source.pattern);
77
+ compiledPatterns.set(source, re);
78
+ }
79
+ return re;
80
+ }
81
+
82
+ /** Called once per workload so a bad pattern fails before any trial runs. */
83
+ export function assertReusableTimeSource(source: TimeSource): void {
84
+ const re = compiledPattern(source);
85
+ if (/[gyd]/.test(re.flags)) {
86
+ throw new RangeError("timeSource pattern must not use the g, y or d flag");
87
+ }
88
+ }
89
+
90
+ export interface SpawnTrialOptions {
91
+ argv: string[];
92
+ cwd?: string;
93
+ env?: Record<string, string>;
94
+ timeSource?: TimeSource;
95
+ /**
96
+ * SIGKILLs the trial after this many ms; it resolves (never rejects) with
97
+ * `exitCode: null, timedOut: true`. Unset never times out. */
98
+ timeoutMs?: number;
99
+ /**
100
+ * Aborting SIGKILLs the process. Unlike `timeoutMs`, the caller discards
101
+ * the trial rather than recording `timedOut`. */
102
+ signal?: AbortSignal;
103
+ }
104
+
105
+ const UNIT_NS: Record<TimeUnit, number> = {
106
+ ns: 1,
107
+ us: 1e3,
108
+ ms: 1e6,
109
+ s: 1e9,
110
+ };
111
+
112
+ /**
113
+ * `timeoutMs` and the caller's `signal` folded into spawn options that
114
+ * SIGKILL on either; `timedOut()` tells the two apart afterwards. */
115
+ export function killSwitch(
116
+ timeoutMs: number | undefined,
117
+ signal: AbortSignal | undefined,
118
+ ): {
119
+ spawn: { signal?: AbortSignal; killSignal?: "SIGKILL" };
120
+ timedOut: () => boolean;
121
+ } {
122
+ const timeout =
123
+ timeoutMs !== undefined ? AbortSignal.timeout(timeoutMs) : undefined;
124
+ const combined =
125
+ timeout && signal
126
+ ? AbortSignal.any([timeout, signal])
127
+ : (timeout ?? signal);
128
+ return {
129
+ spawn: combined ? { signal: combined, killSignal: "SIGKILL" } : {},
130
+ timedOut: () => timeout?.aborted ?? false,
131
+ };
132
+ }
133
+
134
+ export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
135
+ const capture = opts.timeSource !== undefined;
136
+ const start = Bun.nanoseconds();
137
+
138
+ const kill = killSwitch(opts.timeoutMs, opts.signal);
139
+ const proc = Bun.spawn(opts.argv, {
140
+ cwd: opts.cwd,
141
+ env: opts.env,
142
+ stdout: capture ? "pipe" : "ignore",
143
+ stderr: capture ? "pipe" : "ignore",
144
+ stdin: "ignore",
145
+ ...kill.spawn,
146
+ });
147
+ // Drain concurrently with exit: a full pipe would block the command and
148
+ // inflate the wall time.
149
+ const output = capture
150
+ ? Promise.all([
151
+ new Response(proc.stdout as ReadableStream).text(),
152
+ new Response(proc.stderr as ReadableStream).text(),
153
+ ])
154
+ : undefined;
155
+ const exitCode = await proc.exited;
156
+ const end = Bun.nanoseconds();
157
+ const usage = proc.resourceUsage?.();
158
+ const timedOut = kill.timedOut();
159
+
160
+ const result: TrialResult = {
161
+ wallNs: end - start,
162
+ 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,
166
+ ...(timedOut && { timedOut: true as const }),
167
+ };
168
+ if (output) {
169
+ const [stdout, stderr] = await output;
170
+ // A killed process's output is partial: nothing to parse.
171
+ if (opts.timeSource && !timedOut) {
172
+ try {
173
+ result.reportedNs = parseReportedTime(
174
+ opts.timeSource,
175
+ stdout,
176
+ stderr,
177
+ opts.argv,
178
+ );
179
+ } catch (err) {
180
+ // A miss drops this trial's sample; a malformed capture would hit
181
+ // every trial identically, so that still throws.
182
+ if (!(err instanceof TimeSourceNoMatchError)) throw err;
183
+ result.timeSourceNoMatch = true;
184
+ result.timeSourceMissOutput = excerptForNoMatch(stdout, stderr);
185
+ }
186
+ }
187
+ }
188
+ return result;
189
+ }
190
+
191
+ export function parseReportedTime(
192
+ source: TimeSource,
193
+ stdout: string,
194
+ stderr: string,
195
+ argv: string[] = [],
196
+ ): number {
197
+ const re = compiledPattern(source);
198
+ const group = source.group ?? 1;
199
+ const match = re.exec(stdout) ?? re.exec(stderr);
200
+ const label = argv.length > 0 ? ` for "${argv.join(" ")}"` : "";
201
+ if (!match) {
202
+ throw new TimeSourceNoMatchError(
203
+ `timeSource pattern ${re} did not match the output${label}. Output was:\n${excerpt(stdout, stderr)}`,
204
+ );
205
+ }
206
+ const raw = match[group];
207
+ if (raw === undefined) {
208
+ throw new Error(
209
+ `timeSource pattern ${re} matched${label} but has no capture group ${group} (matched text: "${match[0]}").`,
210
+ );
211
+ }
212
+ const value = Number(raw);
213
+ if (!Number.isFinite(value)) {
214
+ throw new Error(
215
+ `timeSource pattern ${re} group ${group} captured "${raw}"${label}, which is not a number.`,
216
+ );
217
+ }
218
+ return value * UNIT_NS[source.unit ?? "ms"];
219
+ }
220
+
221
+ function excerpt(stdout: string, stderr: string): string {
222
+ const LIMIT = 800;
223
+ const clip = (s: string) =>
224
+ s.length > LIMIT ? `${s.slice(0, LIMIT)}…(${s.length - LIMIT} more)` : s;
225
+ const parts: string[] = [];
226
+ if (stdout.trim()) parts.push(`--- stdout ---\n${clip(stdout.trimEnd())}`);
227
+ if (stderr.trim()) parts.push(`--- stderr ---\n${clip(stderr.trimEnd())}`);
228
+ return parts.length > 0 ? parts.join("\n") : "(empty)";
229
+ }
230
+
231
+ const NO_MATCH_OUTPUT_LIMIT_BYTES = 2048;
232
+
233
+ /**
234
+ * `excerpt` capped at 2 KiB total, for a `time-source-no-match` warning's
235
+ * `data`.
236
+ */
237
+ function excerptForNoMatch(stdout: string, stderr: string): string {
238
+ const full = excerpt(stdout, stderr);
239
+ if (Buffer.byteLength(full, "utf8") <= NO_MATCH_OUTPUT_LIMIT_BYTES) {
240
+ return full;
241
+ }
242
+ let sliced = full.slice(0, NO_MATCH_OUTPUT_LIMIT_BYTES);
243
+ while (Buffer.byteLength(sliced, "utf8") > NO_MATCH_OUTPUT_LIMIT_BYTES) {
244
+ sliced = sliced.slice(0, -1);
245
+ }
246
+ return `${sliced}…`;
247
+ }
248
+
249
+ const OUTPUT_CAP_BYTES = 1024 * 1024;
250
+
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. */
257
+ export async function readBoundedText(
258
+ stream: ReadableStream<Uint8Array>,
259
+ capBytes: number = OUTPUT_CAP_BYTES,
260
+ ): Promise<string> {
261
+ const halfBytes = Math.floor(capBytes / 2);
262
+ const reader = stream.getReader();
263
+ const headChunks: Uint8Array[] = [];
264
+ let headBytes = 0;
265
+ const tailChunks: Uint8Array[] = [];
266
+ let tailBytes = 0;
267
+ let totalBytes = 0;
268
+
269
+ try {
270
+ for (;;) {
271
+ const { done, value } = await reader.read();
272
+ if (done) break;
273
+ if (!value || value.byteLength === 0) continue;
274
+ totalBytes += value.byteLength;
275
+
276
+ let chunk = value;
277
+ if (headBytes < halfBytes) {
278
+ const room = halfBytes - headBytes;
279
+ if (chunk.byteLength <= room) {
280
+ headChunks.push(chunk);
281
+ headBytes += chunk.byteLength;
282
+ continue;
283
+ }
284
+ headChunks.push(chunk.subarray(0, room));
285
+ headBytes += room;
286
+ chunk = chunk.subarray(room);
287
+ }
288
+ tailChunks.push(chunk);
289
+ tailBytes += chunk.byteLength;
290
+ // Keep only the last `halfBytes`.
291
+ while (tailBytes > halfBytes && tailChunks.length > 0) {
292
+ const first = tailChunks[0]!;
293
+ const excess = tailBytes - halfBytes;
294
+ if (first.byteLength <= excess) {
295
+ tailChunks.shift();
296
+ tailBytes -= first.byteLength;
297
+ } else {
298
+ tailChunks[0] = first.subarray(excess);
299
+ tailBytes -= excess;
300
+ }
301
+ }
302
+ }
303
+ } finally {
304
+ reader.releaseLock();
305
+ }
306
+
307
+ const decoder = new TextDecoder();
308
+ const head = decoder.decode(Buffer.concat(headChunks));
309
+ if (totalBytes <= headBytes + tailBytes) return head;
310
+ const tail = decoder.decode(Buffer.concat(tailChunks));
311
+ const elidedBytes = totalBytes - headBytes - tailBytes;
312
+ return `${head}\n…(${elidedBytes} bytes elided)…\n${tail}`;
313
+ }
314
+
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. */
320
+ export async function runPrepare(
321
+ hook: PrepareHook,
322
+ run: PrepareRun,
323
+ opts: {
324
+ cwd?: string;
325
+ env?: Record<string, string>;
326
+ timeoutMs?: number;
327
+ signal?: AbortSignal;
328
+ },
329
+ ): Promise<void> {
330
+ if (typeof hook === "function") {
331
+ await hook(run);
332
+ return;
333
+ }
334
+ const argv = prepareArgv(hook)!;
335
+ const kill = killSwitch(opts.timeoutMs, opts.signal);
336
+ const proc = Bun.spawn(argv, {
337
+ cwd: opts.cwd,
338
+ env: opts.env,
339
+ stdout: "ignore",
340
+ stderr: "pipe",
341
+ stdin: "ignore",
342
+ ...kill.spawn,
343
+ });
344
+ // Drain even if nothing reads it, so a chatty hook can't block on a full
345
+ // pipe; `.catch` avoids an unhandled rejection.
346
+ const stderrText = readBoundedText(proc.stderr as ReadableStream).catch(
347
+ () => "",
348
+ );
349
+ const exitCode = await proc.exited;
350
+ const timedOut = kill.timedOut();
351
+ if (!timedOut && opts.signal?.aborted) return;
352
+ if (!timedOut && exitCode === 0) return;
353
+ const how = timedOut
354
+ ? `timed out after ${opts.timeoutMs}ms`
355
+ : `exited with code ${exitCode}`;
356
+ const stderr = (await stderrText).trim();
357
+ throw new Error(
358
+ `prepare command "${argv.join(" ")}" ${how} before ${run.phase} trial ${run.index}.${stderr ? `\n${stderr}` : ""}`,
359
+ );
360
+ }
361
+
362
+ /**
363
+ * The command form's argv, for the document; a function isn't
364
+ * serializable.
365
+ */
366
+ export function prepareArgv(
367
+ hook: PrepareHook | undefined,
368
+ ): string[] | undefined {
369
+ if (hook === undefined || typeof hook === "function") return undefined;
370
+ return Array.isArray(hook) ? hook : splitCommand(hook);
371
+ }
372
+
373
+ /** A `RegExp` pattern becomes its source string (flags dropped). */
374
+ export function timeSourceSpec(
375
+ source: TimeSource | undefined,
376
+ ): SerializedTimeSource | undefined {
377
+ if (source === undefined) return undefined;
378
+ return {
379
+ pattern:
380
+ typeof source.pattern === "string"
381
+ ? source.pattern
382
+ : source.pattern.source,
383
+ ...(source.group !== undefined && { group: source.group }),
384
+ ...(source.unit !== undefined && { unit: source.unit }),
385
+ };
386
+ }
387
+
388
+ export interface SerializedTimeSource {
389
+ pattern: string;
390
+ group?: number;
391
+ unit?: TimeUnit;
392
+ }
393
+
394
+ export function splitCommand(command: string): string[] {
395
+ return command.trim().split(/\s+/).filter(Boolean);
396
+ }
@@ -0,0 +1,153 @@
1
+ import { percentile } from "./index.ts";
2
+
3
+ /** Seeded PRNG, deterministic across platforms (32-bit integer math only). */
4
+ export function mulberry32(seed: number): () => number {
5
+ let a = seed >>> 0;
6
+ return () => {
7
+ a = (a + 0x6d2b79f5) | 0;
8
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
9
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
10
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
11
+ };
12
+ }
13
+
14
+ const MAX_SAMPLES_PER_SIDE = 2000;
15
+ const DEFAULT_ITERATIONS = 2000;
16
+
17
+ export interface BootstrapOptions {
18
+ iterations?: number;
19
+ seed?: number;
20
+ }
21
+
22
+ export interface BootstrapResult {
23
+ /** 95% CI on the difference of medians, percent of the baseline median. */
24
+ ci95: [number, number];
25
+ seed: number;
26
+ data: {
27
+ /** Either side was randomly cut to `MAX_SAMPLES_PER_SIDE` samples. */
28
+ subsampled: boolean;
29
+ iterations: number;
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Partial Fisher-Yates; returns `samples` itself when already within
35
+ * `max`.
36
+ */
37
+ function subsample(
38
+ samples: number[],
39
+ rng: () => number,
40
+ max: number,
41
+ ): number[] {
42
+ if (samples.length <= max) return samples;
43
+ const pool = [...samples];
44
+ for (let i = 0; i < max; i++) {
45
+ const j = i + Math.floor(rng() * (pool.length - i));
46
+ const tmp = pool[i]!;
47
+ pool[i] = pool[j]!;
48
+ pool[j] = tmp;
49
+ }
50
+ return pool.slice(0, max);
51
+ }
52
+
53
+ class Side {
54
+ 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. */
58
+ readonly rankOf: Uint32Array;
59
+ readonly counts: Uint32Array;
60
+ 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);
74
+ }
75
+
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
+ }
94
+ }
95
+ return sorted[n - 1]!;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Hash of both arrays, so identical input always gets the same CI and
101
+ * verdict.
102
+ */
103
+ function seedFromSamples(base: number[], cand: number[]): number {
104
+ const all = new Float64Array(base.length + cand.length + 1);
105
+ all.set(base);
106
+ all[base.length] = Number.NaN; // keeps [a, b] | [c] apart from [a] | [b, c]
107
+ all.set(cand, base.length + 1);
108
+ return Bun.hash.crc32(all);
109
+ }
110
+
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. */
116
+ export function bootstrapMedianDiffCi(
117
+ base: number[],
118
+ cand: number[],
119
+ opts: BootstrapOptions = {},
120
+ ): BootstrapResult {
121
+ if (base.length === 0 || cand.length === 0) {
122
+ throw new RangeError("bootstrapMedianDiffCi: both sides need samples");
123
+ }
124
+ const seed = opts.seed ?? seedFromSamples(base, cand);
125
+ const rng = mulberry32(seed);
126
+ const iterations = opts.iterations ?? DEFAULT_ITERATIONS;
127
+
128
+ const subsampled =
129
+ 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));
132
+ const baseMedian = percentile(baseSide.sorted, 0.5);
133
+
134
+ const deltas = new Float64Array(iterations);
135
+ for (let i = 0; i < iterations; i++) {
136
+ const b = baseSide.resampleMedian(rng);
137
+ const c = candSide.resampleMedian(rng);
138
+ const diff = c - b;
139
+ deltas[i] =
140
+ baseMedian === 0
141
+ ? diff === 0
142
+ ? 0
143
+ : diff * Infinity
144
+ : (diff / baseMedian) * 100;
145
+ }
146
+ deltas.sort();
147
+
148
+ return {
149
+ ci95: [percentile(deltas, 0.025), percentile(deltas, 0.975)],
150
+ seed,
151
+ data: { subsampled, iterations },
152
+ };
153
+ }
@@ -0,0 +1,140 @@
1
+ import { formatDuration } from "../format.ts";
2
+ import type { TimingStats, Warning } from "../ir/types.ts";
3
+
4
+ export function computeTimingStats(samples: number[]): TimingStats {
5
+ if (samples.length === 0) {
6
+ throw new Error("computeTimingStats: samples must be non-empty");
7
+ }
8
+ const n = samples.length;
9
+ const sorted = sortedCopy(samples);
10
+ let total = 0;
11
+ for (let i = 0; i < n; i++) total += samples[i]!;
12
+ const mean = total / n;
13
+ const median = percentile(sorted, 0.5);
14
+ let squaredDeviation = 0;
15
+ for (let i = 0; i < n; i++) {
16
+ const d = samples[i]! - mean;
17
+ squaredDeviation += d * d;
18
+ }
19
+ const stddev = Math.sqrt(squaredDeviation / n);
20
+ const min = sorted[0]!;
21
+ const max = sorted[n - 1]!;
22
+
23
+ const q1 = percentile(sorted, 0.25);
24
+ const q3 = percentile(sorted, 0.75);
25
+ const iqr = q3 - q1;
26
+ const mildLow = q1 - 1.5 * iqr;
27
+ const mildHigh = q3 + 1.5 * iqr;
28
+ const severeLow = q1 - 3 * iqr;
29
+ const severeHigh = q3 + 3 * iqr;
30
+
31
+ let mild = 0;
32
+ let severe = 0;
33
+ for (let i = 0; i < n; i++) {
34
+ const s = samples[i]!;
35
+ if (s < severeLow || s > severeHigh) severe++;
36
+ else if (s < mildLow || s > mildHigh) mild++;
37
+ }
38
+
39
+ const p99 = percentile(sorted, 0.99);
40
+ const deviations = new Float64Array(n);
41
+ for (let i = 0; i < n; i++) deviations[i] = Math.abs(samples[i]! - median);
42
+ deviations.sort();
43
+ const mad = percentile(deviations, 0.5);
44
+
45
+ return {
46
+ unit: "ns",
47
+ samples,
48
+ mean,
49
+ median,
50
+ stddev,
51
+ min,
52
+ max,
53
+ outliers: { mild, severe },
54
+ p25: q1,
55
+ p75: q3,
56
+ p99,
57
+ mad,
58
+ };
59
+ }
60
+
61
+ export function sortedCopy(samples: number[]): Float64Array {
62
+ const sorted = new Float64Array(samples.length);
63
+ sorted.set(samples);
64
+ sorted.sort();
65
+ return sorted;
66
+ }
67
+
68
+ export function percentile(sorted: Float64Array, p: number): number {
69
+ const n = sorted.length;
70
+ if (n === 1) return sorted[0]!;
71
+ const idx = p * (n - 1);
72
+ const lo = Math.floor(idx);
73
+ const hi = Math.ceil(idx);
74
+ if (lo === hi) return sorted[lo]!;
75
+ const frac = idx - lo;
76
+ return sorted[lo]! * (1 - frac) + sorted[hi]! * frac;
77
+ }
78
+
79
+ const FAST_COMMAND_NS = 5_000_000;
80
+
81
+ /**
82
+ * `reported`: samples are the command's own printed times (`timeSource`),
83
+ * so the spawn-overhead heuristic doesn't apply. */
84
+ export type TimingMode = "subprocess" | "inprocess" | "reported";
85
+
86
+ export function timingWarnings(
87
+ stats: TimingStats,
88
+ exitCodes: (number | undefined)[],
89
+ mode: TimingMode = "subprocess",
90
+ ignoreExitCodes: number[] = [],
91
+ ): Warning[] {
92
+ const warnings: Warning[] = [];
93
+
94
+ const first = stats.samples[0];
95
+ if (first !== undefined) {
96
+ const iqr = stats.p75 - stats.p25;
97
+ // The IQR fence alone flags a first sample a few percent slow when the
98
+ // spread is tight.
99
+ if (first > stats.median + 3 * iqr && first > 2 * stats.median && iqr > 0) {
100
+ warnings.push({
101
+ code: "slow-first-run",
102
+ message: `First run took ${formatDuration(first)}, much slower than the median ${formatDuration(stats.median)}. Consider more warmup.`,
103
+ data: { firstNs: first, medianNs: stats.median },
104
+ });
105
+ }
106
+ }
107
+
108
+ // In-process samples always have a long right tail (GC, tier-up) that the
109
+ // median is robust to; with a handful of subprocess trials one outlier
110
+ // matters.
111
+ if (mode !== "inprocess" && stats.outliers.mild + stats.outliers.severe > 0) {
112
+ warnings.push({
113
+ code: "outliers-detected",
114
+ message: `${stats.outliers.mild + stats.outliers.severe} outlier(s) detected (${stats.outliers.severe} severe, ${stats.outliers.mild} mild).`,
115
+ data: stats.outliers,
116
+ });
117
+ }
118
+
119
+ if (mode === "subprocess" && stats.median < FAST_COMMAND_NS) {
120
+ warnings.push({
121
+ code: "fast-command",
122
+ message: `Median run time (${(stats.median / 1e6).toFixed(3)}ms) is very fast; results may be dominated by spawn overhead.`,
123
+ data: { medianNs: stats.median },
124
+ });
125
+ }
126
+
127
+ const ignoreSet = new Set(ignoreExitCodes);
128
+ const nonZero = exitCodes.filter(
129
+ (c) => c !== undefined && c !== 0 && !ignoreSet.has(c),
130
+ );
131
+ if (nonZero.length > 0) {
132
+ warnings.push({
133
+ code: "nonzero-exit",
134
+ message: `${nonZero.length} of ${exitCodes.length} trial(s) exited non-zero.`,
135
+ data: { exitCodes: nonZero },
136
+ });
137
+ }
138
+
139
+ return warnings;
140
+ }