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.
- package/index.d.ts +62 -35
- package/package.json +1 -1
- package/src/ab/ab-runner.ts +57 -44
- package/src/ab/index.ts +186 -112
- package/src/baseline/index.ts +3 -9
- package/src/bench/index.ts +177 -123
- package/src/bench/projects.ts +14 -10
- package/src/bench/registry.ts +68 -66
- package/src/bench/run-tasks.ts +26 -23
- package/src/bench/run.ts +2 -1
- package/src/bench/runner.ts +20 -5
- package/src/bench/support.ts +26 -26
- package/src/bench/sweep.ts +6 -4
- package/src/cache/fingerprint.ts +9 -6
- package/src/cache/store.ts +17 -5
- package/src/capture/bunflags.ts +12 -11
- package/src/capture/cpu-parse.ts +36 -24
- package/src/capture/cpu.ts +7 -4
- package/src/capture/frames.ts +7 -1
- package/src/capture/heap-parse.ts +30 -5
- package/src/capture/heap.ts +9 -5
- package/src/capture/inspector.ts +8 -7
- package/src/capture/jsc-parse.ts +8 -8
- package/src/capture/jsc.ts +4 -4
- package/src/ci/index.ts +64 -40
- package/src/cli/flags.ts +42 -43
- package/src/cli/output.ts +29 -35
- package/src/cli/run.ts +95 -95
- package/src/compare/index.ts +39 -32
- package/src/config/env.ts +13 -0
- package/src/config/index.ts +31 -23
- package/src/config/validate.ts +33 -27
- package/src/format.ts +5 -6
- package/src/glob.ts +9 -12
- package/src/index.ts +1 -3
- package/src/ir/cpu.ts +2 -2
- package/src/ir/defined.ts +12 -0
- package/src/ir/document.ts +93 -73
- package/src/ir/fp.ts +7 -10
- package/src/ir/git.ts +4 -3
- package/src/measure/alloc.ts +7 -8
- package/src/measure/cpu.ts +12 -20
- package/src/measure/environment.ts +5 -8
- package/src/measure/inprocess.ts +15 -15
- package/src/measure/instructions.ts +22 -16
- package/src/measure/loop.ts +24 -17
- package/src/measure/noise.ts +8 -8
- package/src/measure/paired.ts +39 -47
- package/src/measure/peak.ts +20 -21
- package/src/measure/timing.ts +23 -23
- package/src/profile.ts +2 -1
- package/src/renderers/collapsed.ts +28 -21
- package/src/renderers/cpu-tree.ts +43 -35
- package/src/renderers/format.ts +16 -26
- package/src/renderers/index.ts +14 -4
- package/src/renderers/json.ts +2 -2
- package/src/renderers/jsonl.ts +11 -7
- package/src/renderers/markdown.ts +54 -36
- package/src/renderers/mermaid.ts +43 -31
- package/src/renderers/minimal.ts +12 -12
- package/src/renderers/paired.ts +31 -37
- package/src/renderers/relative.ts +10 -14
- package/src/renderers/select.ts +17 -39
- package/src/renderers/speedscope.ts +52 -48
- package/src/renderers/terminal.ts +37 -33
- package/src/spawn/index.ts +38 -47
- package/src/stats/bootstrap.ts +56 -58
- package/src/stats/index.ts +16 -12
- package/src/stats/mannwhitney.ts +11 -10
- 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
|
-
|
|
11
|
+
render(
|
|
12
12
|
doc: ProfileDocument,
|
|
13
13
|
options: VizOptions = {},
|
|
14
14
|
): Promise<RenderResult> {
|
|
15
|
-
|
|
15
|
+
return Promise.try(() => {
|
|
16
|
+
const byWorkload = workloadsById(doc);
|
|
16
17
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
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
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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 (
|
|
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) =>
|
|
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
|
|
package/src/spawn/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
152
|
-
new Response(proc.stderr
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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 =
|
|
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
|
|
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
|
-
|
|
364
|
-
|
|
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
|
|
360
|
+
return commandArgv(hook);
|
|
371
361
|
}
|
|
372
362
|
|
|
373
|
-
|
|
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
|
-
|
|
379
|
+
interface SerializedTimeSource {
|
|
389
380
|
pattern: string;
|
|
390
381
|
group?: number;
|
|
391
382
|
unit?: TimeUnit;
|
package/src/stats/bootstrap.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { percentile } from "./index.ts";
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
17
|
+
interface BootstrapOptions {
|
|
18
18
|
iterations?: number;
|
|
19
19
|
seed?: number;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
|
|
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
|
-
|
|
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
|
-
|
|
51
|
+
interface Side {
|
|
54
52
|
readonly sorted: Float64Array;
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
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
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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 =
|
|
131
|
-
const candSide =
|
|
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 =
|
|
137
|
-
const c =
|
|
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
|