ostia 0.2.12 → 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/LICENSE +21 -0
- package/README.md +50 -358
- package/docs/agent-protocol.md +210 -0
- package/docs/cli.md +1196 -0
- package/docs/config.md +233 -0
- package/docs/document-schema.md +224 -0
- package/docs/library.md +421 -0
- package/docs/preload-recipes.md +169 -0
- package/docs/statistics.md +218 -0
- package/index.d.ts +923 -679
- package/package.json +16 -14
- package/src/ab/ab-runner.ts +487 -0
- package/src/ab/index.ts +1160 -0
- package/src/baseline/index.ts +69 -0
- package/src/bench/index.ts +516 -0
- package/src/bench/projects.ts +43 -0
- package/src/bench/range.ts +27 -0
- package/src/bench/registry.ts +426 -0
- package/src/bench/run-tasks.ts +179 -0
- package/src/bench/run.ts +52 -0
- package/src/bench/runner.ts +162 -0
- package/src/bench/support.ts +161 -0
- package/src/bench/sweep.ts +41 -0
- package/src/cache/fingerprint.ts +62 -0
- package/src/cache/store.ts +40 -0
- package/src/capture/bunflags.ts +92 -0
- package/src/capture/cpu-parse.ts +131 -0
- package/src/capture/cpu.ts +47 -0
- package/src/capture/frames.ts +60 -0
- package/src/capture/heap-parse.ts +111 -0
- package/src/capture/heap.ts +36 -0
- package/src/capture/inspector.ts +47 -0
- package/src/capture/jsc-parse.ts +167 -0
- package/src/capture/jsc.ts +35 -0
- package/src/capture/sampling.ts +5 -0
- package/src/ci/index.ts +440 -0
- package/src/cli/flags.ts +263 -0
- package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
- package/src/cli/main.ts +18 -0
- package/src/cli/output.ts +179 -0
- package/src/cli/run.ts +1110 -0
- package/src/compare/index.ts +624 -0
- package/src/config/env.ts +13 -0
- package/src/config/index.ts +283 -0
- package/src/config/validate.ts +273 -0
- package/src/errors.ts +8 -0
- package/src/format.ts +35 -0
- package/src/glob.ts +45 -0
- package/src/index.ts +60 -0
- package/src/ir/cpu.ts +10 -0
- package/src/ir/defined.ts +12 -0
- package/src/ir/document.ts +491 -0
- package/src/ir/fp.ts +28 -0
- package/src/ir/git.ts +37 -0
- package/src/ir/types.ts +615 -0
- package/src/measure/alloc.ts +56 -0
- package/src/measure/cpu.ts +91 -0
- package/src/measure/environment.ts +38 -0
- package/src/measure/inprocess.ts +191 -0
- package/src/measure/instructions.ts +139 -0
- package/src/measure/loop.ts +64 -0
- package/src/measure/noise.ts +55 -0
- package/src/measure/paired.ts +304 -0
- package/src/measure/peak.ts +201 -0
- package/src/measure/timing.ts +263 -0
- package/src/profile.ts +110 -0
- package/src/renderers/collapsed.ts +42 -0
- package/src/renderers/cpu-tree.ts +191 -0
- package/src/renderers/cpuprofile.ts +43 -0
- package/src/renderers/format.ts +132 -0
- package/src/renderers/index.ts +37 -0
- package/src/renderers/json.ts +10 -0
- package/src/renderers/jsonl.ts +19 -0
- package/src/renderers/markdown.ts +543 -0
- package/src/renderers/mermaid.ts +90 -0
- package/src/renderers/minimal.ts +602 -0
- package/src/renderers/paired.ts +223 -0
- package/src/renderers/relative.ts +60 -0
- package/src/renderers/select.ts +264 -0
- package/src/renderers/speedscope.ts +73 -0
- package/src/renderers/terminal.ts +470 -0
- package/src/renderers/types.ts +27 -0
- package/src/spawn/index.ts +387 -0
- package/src/stats/bootstrap.ts +151 -0
- package/src/stats/index.ts +144 -0
- package/src/stats/mannwhitney.ts +82 -0
- package/src/time.ts +337 -0
- package/src/version.ts +3 -0
- package/ab-runner.ts +0 -8
- package/chunk-05jfst35.js +0 -28
- package/chunk-1g1x9zz2.js +0 -15
- package/chunk-23g2rwrn.js +0 -3
- package/chunk-468h5412.js +0 -25
- package/chunk-4esjfc2m.js +0 -2
- package/chunk-ct2xsezd.js +0 -14
- package/cli.js +0 -3
- package/index.js +0 -2
- package/runner.ts +0 -7
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
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
|
+
function compiledPattern(source: TimeSource): RegExp {
|
|
69
|
+
if (typeof source.pattern !== "string") return source.pattern;
|
|
70
|
+
let re = compiledPatterns.get(source);
|
|
71
|
+
if (!re) {
|
|
72
|
+
re = new RegExp(source.pattern);
|
|
73
|
+
compiledPatterns.set(source, re);
|
|
74
|
+
}
|
|
75
|
+
return re;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Called once per workload so a bad pattern fails before any trial runs.
|
|
79
|
+
export function assertReusableTimeSource(source: TimeSource): void {
|
|
80
|
+
const re = compiledPattern(source);
|
|
81
|
+
if (/[gyd]/.test(re.flags)) {
|
|
82
|
+
throw new RangeError("timeSource pattern must not use the g, y or d flag");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface SpawnTrialOptions {
|
|
87
|
+
argv: string[];
|
|
88
|
+
cwd?: string;
|
|
89
|
+
env?: Record<string, string>;
|
|
90
|
+
timeSource?: TimeSource;
|
|
91
|
+
/**
|
|
92
|
+
* SIGKILLs the trial after this many ms; it resolves (never rejects) with
|
|
93
|
+
* `exitCode: null, timedOut: true`. Unset never times out. */
|
|
94
|
+
timeoutMs?: number;
|
|
95
|
+
/**
|
|
96
|
+
* Aborting SIGKILLs the process. Unlike `timeoutMs`, the caller discards
|
|
97
|
+
* the trial rather than recording `timedOut`. */
|
|
98
|
+
signal?: AbortSignal;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const UNIT_NS: Record<TimeUnit, number> = {
|
|
102
|
+
ns: 1,
|
|
103
|
+
us: 1e3,
|
|
104
|
+
ms: 1e6,
|
|
105
|
+
s: 1e9,
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// One kill for a timeout and an abort alike, since the spawn options
|
|
109
|
+
// SIGKILL on either; `timedOut()` tells the two apart afterwards.
|
|
110
|
+
export function killSwitch(
|
|
111
|
+
timeoutMs: number | undefined,
|
|
112
|
+
signal: AbortSignal | undefined,
|
|
113
|
+
): {
|
|
114
|
+
spawn: { signal?: AbortSignal; killSignal?: "SIGKILL" };
|
|
115
|
+
timedOut: () => boolean;
|
|
116
|
+
} {
|
|
117
|
+
const timeout =
|
|
118
|
+
timeoutMs !== undefined ? AbortSignal.timeout(timeoutMs) : undefined;
|
|
119
|
+
const combined =
|
|
120
|
+
timeout && signal
|
|
121
|
+
? AbortSignal.any([timeout, signal])
|
|
122
|
+
: (timeout ?? signal);
|
|
123
|
+
return {
|
|
124
|
+
spawn: combined ? { signal: combined, killSignal: "SIGKILL" } : {},
|
|
125
|
+
timedOut: () => timeout?.aborted ?? false,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
|
|
130
|
+
const capture = opts.timeSource !== undefined;
|
|
131
|
+
const start = Bun.nanoseconds();
|
|
132
|
+
|
|
133
|
+
const kill = killSwitch(opts.timeoutMs, opts.signal);
|
|
134
|
+
const proc = Bun.spawn(opts.argv, {
|
|
135
|
+
...(opts.cwd !== undefined && { cwd: opts.cwd }),
|
|
136
|
+
...(opts.env !== undefined && { env: opts.env }),
|
|
137
|
+
stdout: capture ? "pipe" : "ignore",
|
|
138
|
+
stderr: capture ? "pipe" : "ignore",
|
|
139
|
+
stdin: "ignore",
|
|
140
|
+
...kill.spawn,
|
|
141
|
+
});
|
|
142
|
+
// Drain concurrently with exit: a full pipe would block the command and
|
|
143
|
+
// inflate the wall time.
|
|
144
|
+
const output = capture
|
|
145
|
+
? Promise.all([
|
|
146
|
+
new Response(proc.stdout).text(),
|
|
147
|
+
new Response(proc.stderr).text(),
|
|
148
|
+
])
|
|
149
|
+
: undefined;
|
|
150
|
+
const exitCode = await proc.exited;
|
|
151
|
+
const end = Bun.nanoseconds();
|
|
152
|
+
const usage = proc.resourceUsage?.();
|
|
153
|
+
const timedOut = kill.timedOut();
|
|
154
|
+
|
|
155
|
+
const result: TrialResult = {
|
|
156
|
+
wallNs: end - start,
|
|
157
|
+
exitCode: timedOut ? null : exitCode,
|
|
158
|
+
...(usage && {
|
|
159
|
+
userNs: Number(usage.cpuTime.user) * 1000,
|
|
160
|
+
systemNs: Number(usage.cpuTime.system) * 1000,
|
|
161
|
+
maxRssBytes: usage.maxRSS,
|
|
162
|
+
}),
|
|
163
|
+
...(timedOut && { timedOut: true as const }),
|
|
164
|
+
};
|
|
165
|
+
if (output) {
|
|
166
|
+
const [stdout, stderr] = await output;
|
|
167
|
+
// A killed process's output is partial: nothing to parse.
|
|
168
|
+
if (opts.timeSource && !timedOut) {
|
|
169
|
+
try {
|
|
170
|
+
result.reportedNs = parseReportedTime(
|
|
171
|
+
opts.timeSource,
|
|
172
|
+
stdout,
|
|
173
|
+
stderr,
|
|
174
|
+
opts.argv,
|
|
175
|
+
);
|
|
176
|
+
} catch (err) {
|
|
177
|
+
// A miss drops this trial's sample; a malformed capture would hit
|
|
178
|
+
// every trial identically, so that still throws.
|
|
179
|
+
if (!(err instanceof TimeSourceNoMatchError)) throw err;
|
|
180
|
+
result.timeSourceNoMatch = true;
|
|
181
|
+
result.timeSourceMissOutput = excerptForNoMatch(stdout, stderr);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function parseReportedTime(
|
|
189
|
+
source: TimeSource,
|
|
190
|
+
stdout: string,
|
|
191
|
+
stderr: string,
|
|
192
|
+
argv: string[] = [],
|
|
193
|
+
): number {
|
|
194
|
+
const re = compiledPattern(source);
|
|
195
|
+
const group = source.group ?? 1;
|
|
196
|
+
const match = re.exec(stdout) ?? re.exec(stderr);
|
|
197
|
+
const label = argv.length > 0 ? ` for "${argv.join(" ")}"` : "";
|
|
198
|
+
if (!match) {
|
|
199
|
+
throw new TimeSourceNoMatchError(
|
|
200
|
+
`timeSource pattern ${re} did not match the output${label}. Output was:\n${excerpt(stdout, stderr)}`,
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
const raw = match[group];
|
|
204
|
+
if (raw === undefined) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`timeSource pattern ${re} matched${label} but has no capture group ${group} (matched text: "${match[0]}").`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
const value = Number(raw);
|
|
210
|
+
if (!Number.isFinite(value)) {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`timeSource pattern ${re} group ${group} captured "${raw}"${label}, which is not a number.`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return value * UNIT_NS[source.unit ?? "ms"];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function excerpt(stdout: string, stderr: string): string {
|
|
219
|
+
const LIMIT = 800;
|
|
220
|
+
const clip = (s: string) =>
|
|
221
|
+
s.length > LIMIT ? `${s.slice(0, LIMIT)}…(${s.length - LIMIT} more)` : s;
|
|
222
|
+
const parts: string[] = [];
|
|
223
|
+
if (stdout.trim()) parts.push(`--- stdout ---\n${clip(stdout.trimEnd())}`);
|
|
224
|
+
if (stderr.trim()) parts.push(`--- stderr ---\n${clip(stderr.trimEnd())}`);
|
|
225
|
+
return parts.length > 0 ? parts.join("\n") : "(empty)";
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const NO_MATCH_OUTPUT_LIMIT_BYTES = 2048;
|
|
229
|
+
|
|
230
|
+
function excerptForNoMatch(stdout: string, stderr: string): string {
|
|
231
|
+
const full = excerpt(stdout, stderr);
|
|
232
|
+
if (Buffer.byteLength(full, "utf8") <= NO_MATCH_OUTPUT_LIMIT_BYTES) {
|
|
233
|
+
return full;
|
|
234
|
+
}
|
|
235
|
+
let sliced = full.slice(0, NO_MATCH_OUTPUT_LIMIT_BYTES);
|
|
236
|
+
while (Buffer.byteLength(sliced, "utf8") > NO_MATCH_OUTPUT_LIMIT_BYTES) {
|
|
237
|
+
sliced = sliced.slice(0, -1);
|
|
238
|
+
}
|
|
239
|
+
return `${sliced}…`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const OUTPUT_CAP_BYTES = 1024 * 1024;
|
|
243
|
+
|
|
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.
|
|
248
|
+
export async function readBoundedText(
|
|
249
|
+
stream: ReadableStream<Uint8Array>,
|
|
250
|
+
capBytes: number = OUTPUT_CAP_BYTES,
|
|
251
|
+
): Promise<string> {
|
|
252
|
+
const halfBytes = Math.floor(capBytes / 2);
|
|
253
|
+
const reader = stream.getReader();
|
|
254
|
+
const headChunks: Uint8Array[] = [];
|
|
255
|
+
let headBytes = 0;
|
|
256
|
+
const tailChunks: Uint8Array[] = [];
|
|
257
|
+
let tailBytes = 0;
|
|
258
|
+
let totalBytes = 0;
|
|
259
|
+
|
|
260
|
+
try {
|
|
261
|
+
for (;;) {
|
|
262
|
+
const { done, value } = await reader.read();
|
|
263
|
+
if (done) break;
|
|
264
|
+
if (!value || value.byteLength === 0) continue;
|
|
265
|
+
totalBytes += value.byteLength;
|
|
266
|
+
|
|
267
|
+
let chunk = value;
|
|
268
|
+
if (headBytes < halfBytes) {
|
|
269
|
+
const room = halfBytes - headBytes;
|
|
270
|
+
if (chunk.byteLength <= room) {
|
|
271
|
+
headChunks.push(chunk);
|
|
272
|
+
headBytes += chunk.byteLength;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
headChunks.push(chunk.subarray(0, room));
|
|
276
|
+
headBytes += room;
|
|
277
|
+
chunk = chunk.subarray(room);
|
|
278
|
+
}
|
|
279
|
+
tailChunks.push(chunk);
|
|
280
|
+
tailBytes += chunk.byteLength;
|
|
281
|
+
while (tailBytes > halfBytes) {
|
|
282
|
+
const first = tailChunks[0];
|
|
283
|
+
if (first === undefined) break;
|
|
284
|
+
const excess = tailBytes - halfBytes;
|
|
285
|
+
if (first.byteLength <= excess) {
|
|
286
|
+
tailChunks.shift();
|
|
287
|
+
tailBytes -= first.byteLength;
|
|
288
|
+
} else {
|
|
289
|
+
tailChunks[0] = first.subarray(excess);
|
|
290
|
+
tailBytes -= excess;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
} finally {
|
|
295
|
+
reader.releaseLock();
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const decoder = new TextDecoder();
|
|
299
|
+
const head = decoder.decode(Buffer.concat(headChunks));
|
|
300
|
+
if (totalBytes <= headBytes + tailBytes) return head;
|
|
301
|
+
const tail = decoder.decode(Buffer.concat(tailChunks));
|
|
302
|
+
const elidedBytes = totalBytes - headBytes - tailBytes;
|
|
303
|
+
return `${head}\n…(${elidedBytes} bytes elided)…\n${tail}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
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.
|
|
310
|
+
export async function runPrepare(
|
|
311
|
+
hook: PrepareHook,
|
|
312
|
+
run: PrepareRun,
|
|
313
|
+
opts: {
|
|
314
|
+
cwd?: string;
|
|
315
|
+
env?: Record<string, string>;
|
|
316
|
+
timeoutMs?: number;
|
|
317
|
+
signal?: AbortSignal;
|
|
318
|
+
},
|
|
319
|
+
): Promise<void> {
|
|
320
|
+
if (typeof hook === "function") {
|
|
321
|
+
await hook(run);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const argv = commandArgv(hook);
|
|
325
|
+
const kill = killSwitch(opts.timeoutMs, opts.signal);
|
|
326
|
+
const proc = Bun.spawn(argv, {
|
|
327
|
+
...(opts.cwd !== undefined && { cwd: opts.cwd }),
|
|
328
|
+
...(opts.env !== undefined && { env: opts.env }),
|
|
329
|
+
stdout: "ignore",
|
|
330
|
+
stderr: "pipe",
|
|
331
|
+
stdin: "ignore",
|
|
332
|
+
...kill.spawn,
|
|
333
|
+
});
|
|
334
|
+
// Drain even if nothing reads it, so a chatty hook can't block on a full
|
|
335
|
+
// pipe; `.catch` avoids an unhandled rejection.
|
|
336
|
+
const stderrText = readBoundedText(proc.stderr).catch(() => "");
|
|
337
|
+
const exitCode = await proc.exited;
|
|
338
|
+
const timedOut = kill.timedOut();
|
|
339
|
+
if (!timedOut && opts.signal?.aborted) return;
|
|
340
|
+
if (!timedOut && exitCode === 0) return;
|
|
341
|
+
const how = timedOut
|
|
342
|
+
? `timed out after ${opts.timeoutMs}ms`
|
|
343
|
+
: `exited with code ${exitCode}`;
|
|
344
|
+
const stderr = (await stderrText).trim();
|
|
345
|
+
throw new Error(
|
|
346
|
+
`prepare command "${argv.join(" ")}" ${how} before ${run.phase} trial ${run.index}.${stderr ? `\n${stderr}` : ""}`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
|
|
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.
|
|
356
|
+
export function prepareArgv(
|
|
357
|
+
hook: PrepareHook | undefined,
|
|
358
|
+
): string[] | undefined {
|
|
359
|
+
if (hook === undefined || typeof hook === "function") return undefined;
|
|
360
|
+
return commandArgv(hook);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// A `RegExp` pattern is stored as its source alone: the document is JSON,
|
|
364
|
+
// so flags are dropped.
|
|
365
|
+
export function timeSourceSpec(
|
|
366
|
+
source: TimeSource | undefined,
|
|
367
|
+
): SerializedTimeSource | undefined {
|
|
368
|
+
if (source === undefined) return undefined;
|
|
369
|
+
return {
|
|
370
|
+
pattern:
|
|
371
|
+
typeof source.pattern === "string"
|
|
372
|
+
? source.pattern
|
|
373
|
+
: source.pattern.source,
|
|
374
|
+
...(source.group !== undefined && { group: source.group }),
|
|
375
|
+
...(source.unit !== undefined && { unit: source.unit }),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
interface SerializedTimeSource {
|
|
380
|
+
pattern: string;
|
|
381
|
+
group?: number;
|
|
382
|
+
unit?: TimeUnit;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export function splitCommand(command: string): string[] {
|
|
386
|
+
return command.trim().split(/\s+/).filter(Boolean);
|
|
387
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
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
|
+
interface BootstrapOptions {
|
|
18
|
+
iterations?: number;
|
|
19
|
+
seed?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
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
|
+
// Partial Fisher-Yates: only the first `max` positions are shuffled, since
|
|
34
|
+
// only they are kept.
|
|
35
|
+
function subsample(
|
|
36
|
+
samples: number[],
|
|
37
|
+
rng: () => number,
|
|
38
|
+
max: number,
|
|
39
|
+
): number[] {
|
|
40
|
+
if (samples.length <= max) return samples;
|
|
41
|
+
const pool = [...samples];
|
|
42
|
+
for (let i = 0; i < max; i++) {
|
|
43
|
+
const j = i + Math.floor(rng() * (pool.length - i));
|
|
44
|
+
const tmp = pool[i] ?? 0;
|
|
45
|
+
pool[i] = pool[j] ?? 0;
|
|
46
|
+
pool[j] = tmp;
|
|
47
|
+
}
|
|
48
|
+
return pool.slice(0, max);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface Side {
|
|
52
|
+
readonly sorted: Float64Array;
|
|
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.
|
|
55
|
+
readonly rankOf: Uint32Array;
|
|
56
|
+
readonly counts: Uint32Array;
|
|
57
|
+
readonly n: number;
|
|
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;
|
|
71
|
+
}
|
|
72
|
+
return { sorted, rankOf, counts: new Uint32Array(n), n };
|
|
73
|
+
}
|
|
74
|
+
|
|
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;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return sorted[n - 1] ?? 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Hash of both arrays, so identical input always gets the same CI and
|
|
101
|
+
// verdict.
|
|
102
|
+
function seedFromSamples(base: number[], cand: number[]): number {
|
|
103
|
+
const all = new Float64Array(base.length + cand.length + 1);
|
|
104
|
+
all.set(base);
|
|
105
|
+
all[base.length] = Number.NaN; // keeps [a, b] | [c] apart from [a] | [b, c]
|
|
106
|
+
all.set(cand, base.length + 1);
|
|
107
|
+
return Bun.hash.crc32(all);
|
|
108
|
+
}
|
|
109
|
+
|
|
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.
|
|
114
|
+
export function bootstrapMedianDiffCi(
|
|
115
|
+
base: number[],
|
|
116
|
+
cand: number[],
|
|
117
|
+
opts: BootstrapOptions = {},
|
|
118
|
+
): BootstrapResult {
|
|
119
|
+
if (base.length === 0 || cand.length === 0) {
|
|
120
|
+
throw new RangeError("bootstrapMedianDiffCi: both sides need samples");
|
|
121
|
+
}
|
|
122
|
+
const seed = opts.seed ?? seedFromSamples(base, cand);
|
|
123
|
+
const rng = mulberry32(seed);
|
|
124
|
+
const iterations = opts.iterations ?? DEFAULT_ITERATIONS;
|
|
125
|
+
|
|
126
|
+
const subsampled =
|
|
127
|
+
base.length > MAX_SAMPLES_PER_SIDE || cand.length > 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));
|
|
130
|
+
const baseMedian = percentile(baseSide.sorted, 0.5);
|
|
131
|
+
|
|
132
|
+
const deltas = new Float64Array(iterations);
|
|
133
|
+
for (let i = 0; i < iterations; i++) {
|
|
134
|
+
const b = resampleMedian(baseSide, rng);
|
|
135
|
+
const c = resampleMedian(candSide, rng);
|
|
136
|
+
const diff = c - b;
|
|
137
|
+
deltas[i] =
|
|
138
|
+
baseMedian === 0
|
|
139
|
+
? diff === 0
|
|
140
|
+
? 0
|
|
141
|
+
: diff * Infinity
|
|
142
|
+
: (diff / baseMedian) * 100;
|
|
143
|
+
}
|
|
144
|
+
deltas.sort();
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
ci95: [percentile(deltas, 0.025), percentile(deltas, 0.975)],
|
|
148
|
+
seed,
|
|
149
|
+
data: { subsampled, iterations },
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
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 (const s of samples) total += s;
|
|
12
|
+
const mean = total / n;
|
|
13
|
+
const median = percentile(sorted, 0.5);
|
|
14
|
+
let squaredDeviation = 0;
|
|
15
|
+
for (const s of samples) {
|
|
16
|
+
const d = s - mean;
|
|
17
|
+
squaredDeviation += d * d;
|
|
18
|
+
}
|
|
19
|
+
const stddev = Math.sqrt(squaredDeviation / n);
|
|
20
|
+
const min = sorted[0] ?? 0;
|
|
21
|
+
const max = sorted[n - 1] ?? 0;
|
|
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 (const s of samples) {
|
|
34
|
+
if (s < severeLow || s > severeHigh) severe++;
|
|
35
|
+
else if (s < mildLow || s > mildHigh) mild++;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const p99 = percentile(sorted, 0.99);
|
|
39
|
+
const deviations = new Float64Array(n);
|
|
40
|
+
for (let i = 0; i < n; i++) {
|
|
41
|
+
deviations[i] = Math.abs((samples[i] ?? 0) - median);
|
|
42
|
+
}
|
|
43
|
+
deviations.sort();
|
|
44
|
+
const mad = percentile(deviations, 0.5);
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
unit: "ns",
|
|
48
|
+
samples,
|
|
49
|
+
mean,
|
|
50
|
+
median,
|
|
51
|
+
stddev,
|
|
52
|
+
min,
|
|
53
|
+
max,
|
|
54
|
+
outliers: { mild, severe },
|
|
55
|
+
p25: q1,
|
|
56
|
+
p75: q3,
|
|
57
|
+
p99,
|
|
58
|
+
mad,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function sortedCopy(samples: number[]): Float64Array {
|
|
63
|
+
const sorted = new Float64Array(samples.length);
|
|
64
|
+
sorted.set(samples);
|
|
65
|
+
sorted.sort();
|
|
66
|
+
return sorted;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// An empty array gives NaN, never a throw, as the interpolation does.
|
|
70
|
+
export function percentile(sorted: Float64Array, p: number): number {
|
|
71
|
+
const n = sorted.length;
|
|
72
|
+
if (n === 1) return sorted[0] ?? Number.NaN;
|
|
73
|
+
const idx = p * (n - 1);
|
|
74
|
+
const lo = Math.floor(idx);
|
|
75
|
+
const hi = Math.ceil(idx);
|
|
76
|
+
if (lo === hi) return sorted[lo] ?? Number.NaN;
|
|
77
|
+
const frac = idx - lo;
|
|
78
|
+
return (
|
|
79
|
+
(sorted[lo] ?? Number.NaN) * (1 - frac) + (sorted[hi] ?? Number.NaN) * frac
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const FAST_COMMAND_NS = 5_000_000;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `reported`: samples are the command's own printed times (`timeSource`),
|
|
87
|
+
* so the spawn-overhead heuristic doesn't apply. */
|
|
88
|
+
type TimingMode = "subprocess" | "inprocess" | "reported";
|
|
89
|
+
|
|
90
|
+
export function timingWarnings(
|
|
91
|
+
stats: TimingStats,
|
|
92
|
+
exitCodes: (number | undefined)[],
|
|
93
|
+
mode: TimingMode = "subprocess",
|
|
94
|
+
ignoreExitCodes: number[] = [],
|
|
95
|
+
): Warning[] {
|
|
96
|
+
const warnings: Warning[] = [];
|
|
97
|
+
|
|
98
|
+
const first = stats.samples[0];
|
|
99
|
+
if (first !== undefined) {
|
|
100
|
+
const iqr = stats.p75 - stats.p25;
|
|
101
|
+
// The IQR fence alone flags a first sample a few percent slow when the
|
|
102
|
+
// spread is tight.
|
|
103
|
+
if (first > stats.median + 3 * iqr && first > 2 * stats.median && iqr > 0) {
|
|
104
|
+
warnings.push({
|
|
105
|
+
code: "slow-first-run",
|
|
106
|
+
message: `First run took ${formatDuration(first)}, much slower than the median ${formatDuration(stats.median)}. Consider more warmup.`,
|
|
107
|
+
data: { firstNs: first, medianNs: stats.median },
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// In-process samples always have a long right tail (GC, tier-up) that the
|
|
113
|
+
// median is robust to; with a handful of subprocess trials one outlier
|
|
114
|
+
// matters.
|
|
115
|
+
if (mode !== "inprocess" && stats.outliers.mild + stats.outliers.severe > 0) {
|
|
116
|
+
warnings.push({
|
|
117
|
+
code: "outliers-detected",
|
|
118
|
+
message: `${stats.outliers.mild + stats.outliers.severe} outlier(s) detected (${stats.outliers.severe} severe, ${stats.outliers.mild} mild).`,
|
|
119
|
+
data: stats.outliers,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (mode === "subprocess" && stats.median < FAST_COMMAND_NS) {
|
|
124
|
+
warnings.push({
|
|
125
|
+
code: "fast-command",
|
|
126
|
+
message: `Median run time (${(stats.median / 1e6).toFixed(3)}ms) is very fast; results may be dominated by spawn overhead.`,
|
|
127
|
+
data: { medianNs: stats.median },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const ignoreSet = new Set(ignoreExitCodes);
|
|
132
|
+
const nonZero = exitCodes.filter(
|
|
133
|
+
(c) => c !== undefined && c !== 0 && !ignoreSet.has(c),
|
|
134
|
+
);
|
|
135
|
+
if (nonZero.length > 0) {
|
|
136
|
+
warnings.push({
|
|
137
|
+
code: "nonzero-exit",
|
|
138
|
+
message: `${nonZero.length} of ${exitCodes.length} trial(s) exited non-zero.`,
|
|
139
|
+
data: { exitCodes: nonZero },
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return warnings;
|
|
144
|
+
}
|