ostia 0.2.12 → 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.
- 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 +894 -677
- package/package.json +16 -14
- package/src/ab/ab-runner.ts +474 -0
- package/src/ab/index.ts +1086 -0
- package/src/baseline/index.ts +75 -0
- package/src/bench/index.ts +462 -0
- package/src/bench/projects.ts +39 -0
- package/src/bench/range.ts +27 -0
- package/src/bench/registry.ts +424 -0
- package/src/bench/run-tasks.ts +176 -0
- package/src/bench/run.ts +51 -0
- package/src/bench/runner.ts +147 -0
- package/src/bench/support.ts +161 -0
- package/src/bench/sweep.ts +39 -0
- package/src/cache/fingerprint.ts +59 -0
- package/src/cache/store.ts +28 -0
- package/src/capture/bunflags.ts +91 -0
- package/src/capture/cpu-parse.ts +119 -0
- package/src/capture/cpu.ts +44 -0
- package/src/capture/frames.ts +54 -0
- package/src/capture/heap-parse.ts +86 -0
- package/src/capture/heap.ts +32 -0
- package/src/capture/inspector.ts +46 -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 +416 -0
- package/src/cli/flags.ts +264 -0
- package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
- package/src/cli/main.ts +18 -0
- package/src/cli/output.ts +185 -0
- package/src/cli/run.ts +1110 -0
- package/src/compare/index.ts +617 -0
- package/src/config/index.ts +275 -0
- package/src/config/validate.ts +267 -0
- package/src/errors.ts +8 -0
- package/src/format.ts +36 -0
- package/src/glob.ts +48 -0
- package/src/index.ts +62 -0
- package/src/ir/cpu.ts +10 -0
- package/src/ir/document.ts +471 -0
- package/src/ir/fp.ts +31 -0
- package/src/ir/git.ts +36 -0
- package/src/ir/types.ts +615 -0
- package/src/measure/alloc.ts +57 -0
- package/src/measure/cpu.ts +99 -0
- package/src/measure/environment.ts +41 -0
- package/src/measure/inprocess.ts +191 -0
- package/src/measure/instructions.ts +133 -0
- package/src/measure/loop.ts +57 -0
- package/src/measure/noise.ts +55 -0
- package/src/measure/paired.ts +312 -0
- package/src/measure/peak.ts +202 -0
- package/src/measure/timing.ts +263 -0
- package/src/profile.ts +109 -0
- package/src/renderers/collapsed.ts +35 -0
- package/src/renderers/cpu-tree.ts +183 -0
- package/src/renderers/cpuprofile.ts +43 -0
- package/src/renderers/format.ts +142 -0
- package/src/renderers/index.ts +27 -0
- package/src/renderers/json.ts +10 -0
- package/src/renderers/jsonl.ts +15 -0
- package/src/renderers/markdown.ts +525 -0
- package/src/renderers/mermaid.ts +78 -0
- package/src/renderers/minimal.ts +602 -0
- package/src/renderers/paired.ts +229 -0
- package/src/renderers/relative.ts +64 -0
- package/src/renderers/select.ts +286 -0
- package/src/renderers/speedscope.ts +69 -0
- package/src/renderers/terminal.ts +466 -0
- package/src/renderers/types.ts +27 -0
- package/src/spawn/index.ts +396 -0
- package/src/stats/bootstrap.ts +153 -0
- package/src/stats/index.ts +140 -0
- package/src/stats/mannwhitney.ts +81 -0
- package/src/time.ts +325 -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,81 @@
|
|
|
1
|
+
import { sortedCopy } from "./index.ts";
|
|
2
|
+
|
|
3
|
+
export interface MannWhitneyResult {
|
|
4
|
+
/** U statistic for `a`. */
|
|
5
|
+
u: number;
|
|
6
|
+
z: number;
|
|
7
|
+
/** Two-sided, normal approximation, tie-corrected. */
|
|
8
|
+
pValue: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Abramowitz & Stegun 7.1.26: erf approximation, max error ~1.5e-7. */
|
|
12
|
+
function erf(x: number): number {
|
|
13
|
+
const sign = x < 0 ? -1 : 1;
|
|
14
|
+
const ax = Math.abs(x);
|
|
15
|
+
const a1 = 0.254829592;
|
|
16
|
+
const a2 = -0.284496736;
|
|
17
|
+
const a3 = 1.421413741;
|
|
18
|
+
const a4 = -1.453152027;
|
|
19
|
+
const a5 = 1.061405429;
|
|
20
|
+
const p = 0.3275911;
|
|
21
|
+
const t = 1 / (1 + p * ax);
|
|
22
|
+
const y =
|
|
23
|
+
1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-ax * ax);
|
|
24
|
+
return sign * y;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function normalCdf(z: number): number {
|
|
28
|
+
return 0.5 * (1 + erf(z / Math.SQRT2));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Mann-Whitney U test: whether `a` and `b` share a distribution, without
|
|
33
|
+
* the normality a t-test assumes (wall-clock samples are right-skewed).
|
|
34
|
+
* Ranks come from a merge walk over the two sorted sides. An empty side
|
|
35
|
+
* gives `pValue: 1`. */
|
|
36
|
+
export function mannWhitneyU(a: number[], b: number[]): MannWhitneyResult {
|
|
37
|
+
const n1 = a.length;
|
|
38
|
+
const n2 = b.length;
|
|
39
|
+
const n = n1 + n2;
|
|
40
|
+
// No evidence either way: the variance below is 0/0 for an empty side.
|
|
41
|
+
if (n1 === 0 || n2 === 0) return { u: 0, z: 0, pValue: 1 };
|
|
42
|
+
|
|
43
|
+
const sa = sortedCopy(a);
|
|
44
|
+
const sb = sortedCopy(b);
|
|
45
|
+
|
|
46
|
+
// One tie group (distinct value) at a time; each member gets the group's
|
|
47
|
+
// average rank.
|
|
48
|
+
let r1 = 0; // rank sum of `a`
|
|
49
|
+
let tieCorrection = 0;
|
|
50
|
+
let i = 0;
|
|
51
|
+
let j = 0;
|
|
52
|
+
let pos = 0; // 0-based rank position consumed so far
|
|
53
|
+
while (i < n1 || j < n2) {
|
|
54
|
+
const v = j >= n2 || (i < n1 && sa[i]! <= sb[j]!) ? sa[i]! : sb[j]!;
|
|
55
|
+
let ca = 0;
|
|
56
|
+
while (i < n1 && sa[i] === v) {
|
|
57
|
+
ca++;
|
|
58
|
+
i++;
|
|
59
|
+
}
|
|
60
|
+
let cb = 0;
|
|
61
|
+
while (j < n2 && sb[j] === v) {
|
|
62
|
+
cb++;
|
|
63
|
+
j++;
|
|
64
|
+
}
|
|
65
|
+
const t = ca + cb;
|
|
66
|
+
const avgRank = pos + (t + 1) / 2;
|
|
67
|
+
r1 += ca * avgRank;
|
|
68
|
+
if (t > 1) tieCorrection += t ** 3 - t;
|
|
69
|
+
pos += t;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const u1 = r1 - (n1 * (n1 + 1)) / 2;
|
|
73
|
+
const muU = (n1 * n2) / 2;
|
|
74
|
+
const sigmaU = Math.sqrt(
|
|
75
|
+
(n1 * n2 * (n + 1 - tieCorrection / (n * (n - 1)))) / 12,
|
|
76
|
+
);
|
|
77
|
+
const z = sigmaU === 0 ? 0 : (u1 - muU) / sigmaU;
|
|
78
|
+
const pValue = Math.min(1, Math.max(0, 2 * (1 - normalCdf(Math.abs(z)))));
|
|
79
|
+
|
|
80
|
+
return { u: u1, z, pValue };
|
|
81
|
+
}
|
package/src/time.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { runCpuCapture } from "./capture/cpu.ts";
|
|
2
|
+
import { runHeapCapture } from "./capture/heap.ts";
|
|
3
|
+
import { DEFAULT_OUT_DIR } from "./config/index.ts";
|
|
4
|
+
import {
|
|
5
|
+
configFingerprint,
|
|
6
|
+
createDocument,
|
|
7
|
+
type InstrumentedMeasurementInput,
|
|
8
|
+
makeArtifactRef,
|
|
9
|
+
makeInstrumentedMeasurement,
|
|
10
|
+
makeSubprocessWorkload,
|
|
11
|
+
makeTimingMeasurement,
|
|
12
|
+
} from "./ir/document.ts";
|
|
13
|
+
import type {
|
|
14
|
+
ArtifactRef,
|
|
15
|
+
Measurement,
|
|
16
|
+
ProfileDocument,
|
|
17
|
+
Warning,
|
|
18
|
+
Workload,
|
|
19
|
+
} from "./ir/types.ts";
|
|
20
|
+
import {
|
|
21
|
+
captureEnvironment,
|
|
22
|
+
noisyMachineWarning,
|
|
23
|
+
stampDrift,
|
|
24
|
+
} from "./measure/environment.ts";
|
|
25
|
+
import {
|
|
26
|
+
assertSamplingOptions,
|
|
27
|
+
createTimingPhase,
|
|
28
|
+
drainTimingPhase,
|
|
29
|
+
} from "./measure/timing.ts";
|
|
30
|
+
import {
|
|
31
|
+
type PrepareHook,
|
|
32
|
+
type PrepareRun,
|
|
33
|
+
runPrepare,
|
|
34
|
+
splitCommand,
|
|
35
|
+
type TimeSource,
|
|
36
|
+
} from "./spawn/index.ts";
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_CPU_INTERVAL_US = 1000;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* One command for `time()`: a string (whitespace-split, no shell), an argv
|
|
42
|
+
* array, or an object with per-command settings, which is how one command
|
|
43
|
+
* becomes several labeled workloads (e.g. warm vs cold `prepare`). */
|
|
44
|
+
export interface CommandSpec {
|
|
45
|
+
command: string | string[];
|
|
46
|
+
label?: string;
|
|
47
|
+
/** Overrides `TimeOptions.prepare` for this command. */
|
|
48
|
+
prepare?: PrepareHook;
|
|
49
|
+
/** Overrides `TimeOptions.timeSource` for this command. */
|
|
50
|
+
timeSource?: TimeSource;
|
|
51
|
+
/** Overrides `TimeOptions.timeoutMs` for this command. */
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
/** Overrides `TimeOptions.ignoreExitCodes` for this command. */
|
|
54
|
+
ignoreExitCodes?: number[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface TimeOptions {
|
|
58
|
+
commands: (string | string[] | CommandSpec)[];
|
|
59
|
+
/**
|
|
60
|
+
* Runs unmeasured before every trial (warmup and instrumented included),
|
|
61
|
+
* in `cwd`/`env`: a command spawned and awaited, or a function. */
|
|
62
|
+
prepare?: PrepareHook;
|
|
63
|
+
/**
|
|
64
|
+
* Take timing from a number in each command's own output (e.g. a build
|
|
65
|
+
* tool's `built in 342ms`) instead of its wall clock. */
|
|
66
|
+
timeSource?: TimeSource;
|
|
67
|
+
/** Exact trial count; when set, `budgetMs` is ignored. */
|
|
68
|
+
samples?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Wall-clock budget for the sampling loop, ms. Default: ~3s when neither
|
|
71
|
+
* `samples` nor `budgetMs` is given. */
|
|
72
|
+
budgetMs?: number;
|
|
73
|
+
/** Floor on trials when no exact `samples` is given. */
|
|
74
|
+
minSamples?: number;
|
|
75
|
+
warmup?: number;
|
|
76
|
+
/**
|
|
77
|
+
* Round-robin trials across commands instead of finishing each command
|
|
78
|
+
* first, so drift hits every command equally. Default: true with 2+
|
|
79
|
+
* commands. */
|
|
80
|
+
interleave?: boolean;
|
|
81
|
+
cwd?: string;
|
|
82
|
+
env?: Record<string, string>;
|
|
83
|
+
cpu?: boolean;
|
|
84
|
+
heap?: boolean;
|
|
85
|
+
cpuIntervalUs?: number;
|
|
86
|
+
outDir?: string;
|
|
87
|
+
/**
|
|
88
|
+
* Measure the machine's noise floor first (default true, ~200ms) and stamp
|
|
89
|
+
* it on the document as `environment`. */
|
|
90
|
+
noiseCheck?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* SIGKILLs a trial (or prepare hook) still running after this many ms. No
|
|
93
|
+
* default. A timed-out trial contributes no sample. */
|
|
94
|
+
timeoutMs?: number;
|
|
95
|
+
/**
|
|
96
|
+
* Abort kills in-flight trials, schedules no more, and resolves (never
|
|
97
|
+
* rejects) with the completed measurements plus an `aborted` warning on
|
|
98
|
+
* the last one. */
|
|
99
|
+
signal?: AbortSignal;
|
|
100
|
+
/**
|
|
101
|
+
* Exit codes to treat as success (hyperfine's `--ignore-failure`): the
|
|
102
|
+
* trial still contributes its sample and gets no `nonzero-exit` warning.
|
|
103
|
+
* */
|
|
104
|
+
ignoreExitCodes?: number[];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function abortedWarning(): Warning {
|
|
108
|
+
return {
|
|
109
|
+
code: "aborted",
|
|
110
|
+
message:
|
|
111
|
+
"Run was cancelled before it finished; this document holds whatever measurements had already completed.",
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
116
|
+
assertSamplingOptions("time", opts);
|
|
117
|
+
|
|
118
|
+
const cfgFp = configFingerprint({
|
|
119
|
+
samples: opts.samples ?? null,
|
|
120
|
+
budgetMs: opts.budgetMs ?? null,
|
|
121
|
+
minSamples: opts.minSamples ?? null,
|
|
122
|
+
warmup: opts.warmup ?? null,
|
|
123
|
+
cpu: opts.cpu ?? false,
|
|
124
|
+
heap: opts.heap ?? false,
|
|
125
|
+
cpuIntervalUs: opts.cpuIntervalUs ?? DEFAULT_CPU_INTERVAL_US,
|
|
126
|
+
});
|
|
127
|
+
const artifactDir = `${opts.outDir ?? DEFAULT_OUT_DIR}/artifacts`;
|
|
128
|
+
const environment =
|
|
129
|
+
opts.noiseCheck === false ? undefined : captureEnvironment();
|
|
130
|
+
const noiseWarning = environment
|
|
131
|
+
? noisyMachineWarning(environment)
|
|
132
|
+
: undefined;
|
|
133
|
+
|
|
134
|
+
const workloads: Workload[] = [];
|
|
135
|
+
const measurements: Measurement[] = [];
|
|
136
|
+
|
|
137
|
+
const entries = opts.commands.map((entry) => {
|
|
138
|
+
const spec: CommandSpec =
|
|
139
|
+
typeof entry === "string" || Array.isArray(entry)
|
|
140
|
+
? { command: entry }
|
|
141
|
+
: entry;
|
|
142
|
+
const argv = Array.isArray(spec.command)
|
|
143
|
+
? spec.command
|
|
144
|
+
: splitCommand(spec.command);
|
|
145
|
+
const prepare = spec.prepare ?? opts.prepare;
|
|
146
|
+
const timeSource = spec.timeSource ?? opts.timeSource;
|
|
147
|
+
const workload = makeSubprocessWorkload(
|
|
148
|
+
argv,
|
|
149
|
+
spec.label ?? (Array.isArray(spec.command) ? undefined : spec.command),
|
|
150
|
+
{ prepare, timeSource },
|
|
151
|
+
);
|
|
152
|
+
return {
|
|
153
|
+
argv,
|
|
154
|
+
workload,
|
|
155
|
+
prepare,
|
|
156
|
+
timeSource,
|
|
157
|
+
timeoutMs: spec.timeoutMs ?? opts.timeoutMs,
|
|
158
|
+
ignoreExitCodes: spec.ignoreExitCodes ?? opts.ignoreExitCodes,
|
|
159
|
+
};
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const interleave = (opts.interleave ?? true) && entries.length > 1;
|
|
163
|
+
|
|
164
|
+
const phases = entries.map((entry) =>
|
|
165
|
+
createTimingPhase({
|
|
166
|
+
argv: entry.argv,
|
|
167
|
+
cwd: opts.cwd,
|
|
168
|
+
env: opts.env,
|
|
169
|
+
samples: opts.samples,
|
|
170
|
+
budgetMs: opts.budgetMs,
|
|
171
|
+
minSamples: opts.minSamples,
|
|
172
|
+
warmup: opts.warmup,
|
|
173
|
+
prepare: entry.prepare,
|
|
174
|
+
timeSource: entry.timeSource,
|
|
175
|
+
timeoutMs: entry.timeoutMs,
|
|
176
|
+
ignoreExitCodes: entry.ignoreExitCodes,
|
|
177
|
+
signal: opts.signal,
|
|
178
|
+
}),
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
const record = async (i: number) => {
|
|
182
|
+
const { argv, workload, prepare } = entries[i]!;
|
|
183
|
+
workloads.push(workload);
|
|
184
|
+
const phaseResult = phases[i]!.result();
|
|
185
|
+
const timingMeasurement = makeTimingMeasurement({
|
|
186
|
+
workload,
|
|
187
|
+
configFingerprint: cfgFp,
|
|
188
|
+
trials: phaseResult.trials,
|
|
189
|
+
timing: phaseResult.timing,
|
|
190
|
+
warnings:
|
|
191
|
+
noiseWarning && measurements.length === 0
|
|
192
|
+
? [...phaseResult.warnings, noiseWarning]
|
|
193
|
+
: phaseResult.warnings,
|
|
194
|
+
interleaved: interleave ? true : undefined,
|
|
195
|
+
});
|
|
196
|
+
measurements.push(timingMeasurement);
|
|
197
|
+
// An instrumented capture is one more spawned run, so don't start it once
|
|
198
|
+
// cancelled.
|
|
199
|
+
if (!opts.signal?.aborted) {
|
|
200
|
+
measurements.push(
|
|
201
|
+
...(await captureInstrumentedPhases({
|
|
202
|
+
workload,
|
|
203
|
+
argv,
|
|
204
|
+
timingMeasurementId: timingMeasurement.id,
|
|
205
|
+
cfgFp,
|
|
206
|
+
opts,
|
|
207
|
+
artifactDir,
|
|
208
|
+
prepare,
|
|
209
|
+
})),
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
if (interleave) {
|
|
215
|
+
for (const phase of phases) await phase.warmup();
|
|
216
|
+
let stepped = true;
|
|
217
|
+
while (stepped) {
|
|
218
|
+
stepped = false;
|
|
219
|
+
for (const phase of phases) {
|
|
220
|
+
if (await phase.step()) stepped = true;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
for (let i = 0; i < entries.length; i++) await record(i);
|
|
224
|
+
} else {
|
|
225
|
+
for (let i = 0; i < entries.length; i++) {
|
|
226
|
+
await drainTimingPhase(phases[i]!);
|
|
227
|
+
await record(i);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (opts.signal?.aborted && measurements.length > 0) {
|
|
232
|
+
const last = measurements[measurements.length - 1]!;
|
|
233
|
+
last.warnings = [...last.warnings, abortedWarning()];
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
stampDrift(environment);
|
|
237
|
+
return createDocument(workloads, measurements, environment);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function captureInstrumentedPhases({
|
|
241
|
+
workload,
|
|
242
|
+
argv,
|
|
243
|
+
timingMeasurementId,
|
|
244
|
+
cfgFp,
|
|
245
|
+
opts,
|
|
246
|
+
artifactDir,
|
|
247
|
+
prepare,
|
|
248
|
+
}: {
|
|
249
|
+
workload: Workload;
|
|
250
|
+
argv: string[];
|
|
251
|
+
timingMeasurementId: string;
|
|
252
|
+
cfgFp: string;
|
|
253
|
+
opts: TimeOptions;
|
|
254
|
+
artifactDir: string;
|
|
255
|
+
prepare?: PrepareHook;
|
|
256
|
+
}): Promise<Measurement[]> {
|
|
257
|
+
const extra: Measurement[] = [];
|
|
258
|
+
// A prepare hook (cold cache, fresh fixture) applies to an instrumented
|
|
259
|
+
// run like a timing trial.
|
|
260
|
+
const prepareFor = async (phase: PrepareRun["phase"]) => {
|
|
261
|
+
if (prepare)
|
|
262
|
+
await runPrepare(
|
|
263
|
+
prepare,
|
|
264
|
+
{ phase, index: 0 },
|
|
265
|
+
{ cwd: opts.cwd, env: opts.env },
|
|
266
|
+
);
|
|
267
|
+
};
|
|
268
|
+
const captureOpts = (suffix: string) => ({
|
|
269
|
+
argv,
|
|
270
|
+
cwd: opts.cwd,
|
|
271
|
+
env: opts.env,
|
|
272
|
+
artifactDir,
|
|
273
|
+
fileName: `${timingMeasurementId}-${suffix}`,
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
if (opts.cpu) {
|
|
277
|
+
await prepareFor("cpu");
|
|
278
|
+
const capture = await runCpuCapture({
|
|
279
|
+
...captureOpts("cpu.cpuprofile"),
|
|
280
|
+
intervalUs: opts.cpuIntervalUs ?? DEFAULT_CPU_INTERVAL_US,
|
|
281
|
+
});
|
|
282
|
+
extra.push(
|
|
283
|
+
await instrumentedMeasurement({
|
|
284
|
+
workload,
|
|
285
|
+
phase: "cpu",
|
|
286
|
+
configFingerprint: cfgFp,
|
|
287
|
+
artifactKind: "cpuprofile",
|
|
288
|
+
...capture,
|
|
289
|
+
}),
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (opts.heap) {
|
|
294
|
+
await prepareFor("heap");
|
|
295
|
+
const capture = await runHeapCapture(captureOpts("heap.heapsnapshot"));
|
|
296
|
+
extra.push(
|
|
297
|
+
await instrumentedMeasurement({
|
|
298
|
+
workload,
|
|
299
|
+
phase: "heap",
|
|
300
|
+
configFingerprint: cfgFp,
|
|
301
|
+
artifactKind: "heapsnapshot",
|
|
302
|
+
...capture,
|
|
303
|
+
}),
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
return extra;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function instrumentedMeasurement({
|
|
311
|
+
artifactPath,
|
|
312
|
+
artifactKind,
|
|
313
|
+
...input
|
|
314
|
+
}: Omit<InstrumentedMeasurementInput, "artifacts"> & {
|
|
315
|
+
artifactPath?: string;
|
|
316
|
+
artifactKind: ArtifactRef["kind"];
|
|
317
|
+
}): Promise<Measurement> {
|
|
318
|
+
const measurement = makeInstrumentedMeasurement({ ...input, artifacts: [] });
|
|
319
|
+
if (artifactPath) {
|
|
320
|
+
measurement.artifacts = [
|
|
321
|
+
await makeArtifactRef(measurement.id, artifactKind, artifactPath),
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
return measurement;
|
|
325
|
+
}
|
package/src/version.ts
ADDED
package/ab-runner.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
// @bun
|
|
3
|
-
import{d,v,s,tn,i,p,x,pe,B,fe,_,He,Ge,ge,Ve,h,an,U,he,W}from"./chunk-1g1x9zz2.js";import{J,z,se}from"./chunk-ct2xsezd.js";import{y,ce,fn,ue}from"./chunk-23g2rwrn.js";function I(e,u=_(e)){return`${u}\x00${v(e.params??null)}`}function C(e){return[_(e),...He(e)].map((u)=>I(e,u))}async function G(e){return fe(),await import(e),[...B()]}var X=5;function P(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
4
|
-
`).slice(0,X).join(`
|
|
5
|
-
`)}async function M(e,u,c){if(process.stderr.write(`ab runner: ${u}
|
|
6
|
-
`),await Bun.write(`${e}.error`,u),c)await Bun.write(`${e}.side`,c);return 2}async function Y(e,u,c,w){let t={base:e,cand:u},m=new Map,f=(a,g)=>{if(!m.has(a))m.set(a,g)},k=new Set;for(let a of w)try{await t[a].opts?.before?.(),k.add(a)}catch(g){f(a,g)}let R,l;if(k.size===2)try{R=await fn(e.fn,u.fn,{rounds:c,candFirst:w[0]==="cand"})}catch(a){if(a instanceof ce)f(a.side,a.cause);else l={err:a}}if(m.size===1){let a=m.has("base")?"cand":"base";if(k.has(a))try{await t[a].fn()}catch(g){f(a,g)}}for(let a of w.toReversed()){if(!k.has(a))continue;try{await t[a].opts?.after?.()}catch(g){f(a,g)}}if(l)throw l.err;let o=m.get("base"),A=m.get("cand");if(m.size===2)return{threw:{side:"both",message:`base: ${P(o)}
|
|
7
|
-
candidate: ${P(A)}`}};if(m.has("base"))return{threw:{side:"base",message:P(o)}};if(m.has("cand"))return{threw:{side:"cand",message:P(A)}};return{result:R}}async function Z(e,u,c,w,t){let{workloadId:m,side:f}=w,k=w.peakMem?await z():void 0;await import("./index.js");let R=J(),l;try{for(let o of t)await import(o);l=(await G(e)).find((o)=>W(u,o).id===m)}catch(o){return M(c,`the ${y(f)} side failed to load ${e}: ${P(o)}`,f)}if(!l)return M(c,`no task with workload id ${m} in ${e}.`);try{let o={};if(await h(l,"before"),await l.opts?.before?.(),k)o.peak=await se(l.fn,R,k);if(w.alloc){await he(l.fn);let{memory:A,calls:a}=await he(l.fn);o.alloc={bytesPerOp:A.bytesPerOp,calls:a}}return await l.opts?.after?.(),await h(l,"after"),await Bun.write(c,JSON.stringify(o)),0}catch(o){return M(c,`${_(l)} threw on the ${y(f)} side while measuring memory: ${P(o)}`,f)}}async function ee(){let[e,u,c,w]=process.argv.slice(2);if(!e||u===void 0||!c||!w)return process.stderr.write(`ab runner: usage: ab-runner.ts <candSuite> <baseSuite|''> <outputPath> <optsJson>
|
|
8
|
-
`),2;let t=JSON.parse(w);if(t.memoryFor)return Z(t.memoryFor.side==="base"?u:e,e,c,t.memoryFor,t.preload??[]);let m=t.metric==="instructions"&&x().unavailable;if(m)return M(c,`can't count instructions: ${m}`);for(let r of t.preload??[])await import(r);let f=t.candFirst?["cand","base"]:["base","cand"],k=[],R=[];for(let r of f){let n=r==="base"?u:e;if(!n)continue;try{let b=await G(n);if(r==="base")k=b;else R=b}catch(b){return M(c,`the ${y(r)} side failed to load ${n}: ${P(b)}`,r)}}if(R.length===0)return M(c,`${e} registered no tasks (no task() calls found).${pe}`,"cand");let l;try{l=U(R,t.filter,e,!t.workloadIds)}catch(r){return M(c,r.message)}let o=t.workloadIds&&new Set(t.workloadIds),A=new Map(k.map((r)=>[I(r),r])),a=new Set(R.flatMap(C)),g=[],O=[],E=[];for(let r of l){let n=W(e,r);if(o&&!o.has(n.id))continue;if(g.push(n),r.skipped)continue;let b=C(r).map((T)=>A.get(T)).find((T)=>T!==void 0);if(b&&!b.skipped)O.push({workload:n,base:b,cand:r});else E.push(n.id)}let K=[];if(!o&&!R.some((r)=>r.only))for(let r of an(k,t.filter)){if(r.skipped||a.has(I(r)))continue;let n=W(e,r);g.push(n),K.push(n.id)}let q=Ve(O.map((r)=>r.cand));if(t.planPath){let r={memory:O.map((n)=>({workloadId:n.workload.id,alloc:Ge(n.cand,t.alloc??!1),peakMem:ge(n.cand,t.peakMem??!1)})).filter((n)=>n.alloc||n.peakMem)};await Bun.write(t.planPath,JSON.stringify(r))}let D=i({rounds:t.rounds,thresholdPct:t.thresholdPct,metric:t.metric}),N=[];for(let r=0;r<O.length;r++){let{workload:n,base:b,cand:T}=O[r],{enter:Q,leave:V}=q(r);if(t.progress)process.send?.({task:r+1,tasks:O.length,label:_(T)});let L={base:b,cand:T};for(let S of f)await h(L[S],"before",Q);let F=await Y(b,T,t.rounds,f);if("threw"in F)N.push(tn({workload:n,configFingerprint:D,threw:F.threw,diagnosticWallNs:0,warnings:[]}));else{let{result:S}=F,j=d(S.candSamples);if(S.batch>1)j.batch=S.batch;N.push(tn({workload:n,configFingerprint:D,timing:j,diagnosticWallNs:S.diagnosticWallNs,warnings:[],paired:ue(S,t.thresholdPct,t.metric)}))}for(let S of f.toReversed())await h(L[S],"after",V)}let H=s(g,N);return H.unmatched={baseOnly:K,candOnly:E},await p(H,c),0}ee().then((e)=>process.exit(e));
|
package/chunk-05jfst35.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{T,m,xe,hn,Me,X,S,e,d,l,t,Re,v,n,s,de,bn,j,k,wn,i,Q,a,Te,C,Se,ee,ve,g,w,H,F,Ce,$e,Ie,G,c,o,Ae,yn,ne,Oe,r,P,Ee,Ne,D,f,sn,le,Fe,I,De,Be,x,We,Le,je,B,kn,U,te,Je,ze,be}from"./chunk-1g1x9zz2.js";import{y,O,ue,E,gn}from"./chunk-23g2rwrn.js";import{appendFileSync as Ui,existsSync as Un,lstatSync as _i,mkdirSync as ji,readdirSync as Qt,realpathSync as Jt,renameSync as Li,statSync as Vi,symlinkSync as Hi,unlinkSync as Gi,utimesSync as zi,writeFileSync as Ki}from"fs";import{mkdir as Ji}from"fs/promises";import{relative as kr,sep as Yi}from"path";import{relative as oi}from"path";function bt(p,h,N,W=[]){let _=W.map((z)=>z.suites.map((V)=>new Bun.Glob(V)));return p.map((z)=>{let V=oi(h,P(h,z)),re=_.findIndex((pe)=>pe.some((me)=>me.match(V))),J=re<0?void 0:W[re];return{preload:(J?.preload??N.preload??[]).map((pe)=>P(h,pe)),bunFlags:J?.bunFlags??N.bunFlags??[]}})}function si(p){let h=p>>>0;return()=>{h=h+1831565813|0;let N=Math.imul(h^h>>>15,1|h);return N=N+Math.imul(N^N>>>7,61|N)^N,((N^N>>>14)>>>0)/4294967296}}var yt=2000,ai=2000;function sr(p,h,N){if(p.length<=N)return p;let W=[...p];for(let _=0;_<N;_++){let z=_+Math.floor(h()*(W.length-_)),V=W[_];W[_]=W[z],W[z]=V}return W.slice(0,N)}class jt{sorted;rankOf;counts;n;constructor(p){let h=p.length,N=new Uint32Array(h);for(let W=0;W<h;W++)N[W]=W;N.sort((W,_)=>p[W]-p[_]),this.sorted=new Float64Array(h),this.rankOf=new Uint32Array(h);for(let W=0;W<h;W++)this.sorted[W]=p[N[W]],this.rankOf[N[W]]=W;this.n=h,this.counts=new Uint32Array(h)}resampleMedian(p){let{n:h,counts:N,sorted:W,rankOf:_}=this;N.fill(0);for(let pe=0;pe<h;pe++)N[_[Math.floor(p()*h)]]++;let z=h+1>>1,V=h%2===0?z+1:z,re=0,J=-1;for(let pe=0;pe<h;pe++){if(re+=N[pe],J<0&&re>=z)J=pe;if(re>=V)return J===pe?W[pe]:(W[J]+W[pe])/2}return W[h-1]}}function mi(p,h){let N=new Float64Array(p.length+h.length+1);return N.set(p),N[p.length]=Number.NaN,N.set(h,p.length+1),Bun.hash.crc32(N)}function ar(p,h,N={}){if(p.length===0||h.length===0)throw RangeError("bootstrapMedianDiffCi: both sides need samples");let W=N.seed??mi(p,h),_=si(W),z=N.iterations??ai,V=p.length>yt||h.length>yt,re=new jt(sr(p,_,yt)),J=new jt(sr(h,_,yt)),pe=t(re.sorted,0.5),me=new Float64Array(z);for(let se=0;se<z;se++){let ce=re.resampleMedian(_),Ue=J.resampleMedian(_)-ce;me[se]=pe===0?Ue===0?0:Ue*(1/0):Ue/pe*100}return me.sort(),{ci95:[t(me,0.025),t(me,0.975)],seed:W,data:{subsampled:V,iterations:z}}}function ui(p){let h=p<0?-1:1,N=Math.abs(p),W=0.254829592,_=-0.284496736,z=1.421413741,V=-1.453152027,re=1.061405429,J=0.3275911,pe=1/(1+0.3275911*N),me=1-((((1.061405429*pe+-1.453152027)*pe+1.421413741)*pe+-0.284496736)*pe+0.254829592)*pe*Math.exp(-N*N);return h*me}function ci(p){return 0.5*(1+ui(p/Math.SQRT2))}function mr(p,h){let N=p.length,W=h.length,_=N+W;if(N===0||W===0)return{u:0,z:0,pValue:1};let z=l(p),V=l(h),re=0,J=0,pe=0,me=0,se=0;while(pe<N||me<W){let _e=me>=W||pe<N&&z[pe]<=V[me]?z[pe]:V[me],fe=0;while(pe<N&&z[pe]===_e)fe++,pe++;let He=0;while(me<W&&V[me]===_e)He++,me++;let Ye=fe+He,qe=se+(Ye+1)/2;if(re+=fe*qe,Ye>1)J+=Ye**3-Ye;se+=Ye}let ce=re-N*(N+1)/2,he=N*W/2,Ue=Math.sqrt(N*W*(_+1-J/(_*(_-1)))/12),ge=Ue===0?0:(ce-he)/Ue,Ve=Math.min(1,Math.max(0,2*(1-ci(Math.abs(ge)))));return{u:ce,z:ge,pValue:Ve}}var M={timingPct:5,frameSelfPct:10,heapTypePct:10,minFrameSelfUs:1000,alpha:0.01,bootstrapIterations:2000},Lt=5;function dt(p,h){if(p===0)return h===0?0:1/0;return(h-p)/p*100}function ur(p){let h=new Map;for(let N of p.measurements){let W=`${N.workloadId}\x00${N.phase}`;if(!h.has(W))h.set(W,N)}return(N,W)=>h.get(`${N}\x00${W}`)}function cr(p){let h=new Map;for(let N of p.measurements){let W=N.memory;if(!W||N.phase!=="timing"&&N.phase!=="memstats")continue;let _=h.get(N.workloadId)??{};if(N.phase==="timing")_.heapUsedBefore=W.heapUsedBeforeBytes,_.heapUsedAfter=W.heapUsedAfterBytes,_.maxRss=W.maxRssBytes;else if(W.kind==="peak")_.peak=W.peakBytes;else _.retained=W.bytesPerOp;h.set(N.workloadId,_)}return(N)=>h.get(N)??{}}function dr(p){let{referenceMedianNs:h,driftPct:N}=p.noise;return h*(1+(N??0)/200)}function di(p,h){if(!p.environment||!h.environment)return;let N=dr(p.environment),W=N>0?(dr(h.environment)/N-1)*100:0;return Math.max(Math.abs(p.environment.noise.driftPct??0),Math.abs(h.environment.noise.driftPct??0),Math.abs(W))}function li(p,h,N){let W=new Map(p.workloads.map((V)=>[V.id,V])),_=new Map(h.workloads.map((V)=>[V.id,V])),z=di(p,h);return{base:ur(p),cand:ur(h),baseMemory:cr(p),candMemory:cr(h),baseWorkloads:W,candWorkloads:_,baseIdFor:(V)=>{if(W.has(V))return V;return _.get(V)?.formerIds?.find((re)=>W.has(re))},environmentMismatch:pi(p,h),driftPct:z,effectiveTimingPct:Math.max(N.timingPct,p.environment?.noise.floorPct??0,h.environment?.noise.floorPct??0)+(z??0)}}function pi(p,h){let N=[["platform.os",p.platform.os,h.platform.os],["platform.arch",p.platform.arch,h.platform.arch],["bunVersion",p.bunVersion,h.bunVersion]];if(p.environment&&h.environment)N.push(["cpuModel",p.environment.cpuModel,h.environment.cpuModel],["cores",p.environment.cores,h.environment.cores]);let W=N.filter(([,_,z])=>_!==z).map(([_,z,V])=>({field:_,base:z,cand:V}));if(W.length===0)return;return{code:"environment-mismatch",message:`Base and candidate were measured on different environments (${W.map((_)=>_.field).join(", ")}); a timing delta may reflect that instead of the code change.`,data:{fields:W}}}function fi(p){let h=[];for(let W of p){if(!W.timing)continue;let _=1+W.timing.medianDeltaPct/100;if(Number.isFinite(_)&&_>0)h.push(Math.log(_))}if(h.length===0)return null;let N=h.reduce((W,_)=>W+_,0)/h.length;return(Math.exp(N)-1)*100}function Xe(p,h,N=M){let W=li(p,h,N),_=()=>{let z=new Set,V=[];for(let re of h.workloads){let J=W.baseIdFor(re.id);if(J===void 0)V.push(re);else z.add(J)}return{baseOnly:p.workloads.filter((re)=>!z.has(re.id)),candOnly:V}};return{effectiveTimingPct:W.effectiveTimingPct,driftPct:W.driftPct,compare:(z)=>Pi(W,z,N),unmatched:_,compared(z){let V=new Set(z.map(([me])=>me)),re=h.workloads.filter((me)=>!V.has(me.id)),{baseOnly:J}=_(),pe=(me,se)=>({workloadId:me.id,task:c(me),...me.entry?.group!==void 0&&{group:me.entry.group},verdict:se});return[...z.map(([me,se])=>hi(W,me,se)),...re.map((me)=>pe(me,"missing-base")),...J.map((me)=>pe(me,"missing-cand"))]}}}var gi=["heapUsedBefore","heapUsedAfter","retained","peak","maxRss"];function hi(p,h,N){let W=p.baseIdFor(h)??h,_=p.candWorkloads.get(h),z=p.baseWorkloads.get(W),V={workloadId:h,task:_?c(_):h,..._?.entry?.group!==void 0&&{group:_.entry.group},verdict:N.timing?.verdict??"unchanged",comparisonId:N.id,pass:N.verdict==="pass"};if(W!==h)V.renamedFrom={workloadId:W,task:z?c(z):W};let re=p.base(W,"timing")?.timing,J=p.cand(h,"timing")?.timing;if(N.timing&&re&&J){let{medianDeltaPct:ce,ci95:he,pValue:Ue}=N.timing;V.timing={unit:"ns",baseMedian:re.median,candMedian:J.median,baseSamples:re.samples.length,candSamples:J.samples.length,medianDeltaPct:ce,...he&&{ci95:he},...Ue!==void 0&&{pValue:Ue},thresholdPct:N.thresholds.effectiveTimingPct}}let pe=p.baseMemory(W),me=p.candMemory(h),se=[];for(let ce of gi){let he=pe[ce],Ue=me[ce];if(he===void 0||Ue===void 0)continue;se.push({reading:ce,baseBytes:he,candBytes:Ue,deltaPct:dt(he,Ue)})}if(se.length>0)V.memory=se;return V}function Qe(p,h,N){let W=0,_=0,z=0;for(let V of p){if(!V.timing)continue;if(V.timing.verdict==="regressed")W++;else if(V.timing.verdict==="improved")_++;else z++}return{matched:p.length,regressed:W,improved:_,unchanged:z,geomeanPct:fi(p),effectiveTimingPct:h,...N!==void 0&&{driftPct:N},verdict:p.some((V)=>V.verdict==="fail")?"fail":"pass"}}function we(p,h,N=M){let W=Xe(p,h,N),_=[];for(let V of h.workloads){let re=W.compare(V.id);if(re)_.push([V.id,re])}let z=_.map(([,V])=>V);return{comparisons:z,unmatched:W.unmatched(),compared:W.compared(_),summary:Qe(z,W.effectiveTimingPct,W.driftPct)}}function bi(p,h,N,W){let _=p.samples,z=h.samples,V=dt(p.median,h.median),re=dt(p.mean,h.mean),J=(se,ce)=>{if(se>N)return"regressed";if(ce<-N)return"improved";return"unchanged"};if(_.length<Lt||z.length<Lt)return{timing:{medianDeltaPct:V,meanDeltaPct:re,verdict:J(V,V)},warning:{code:"thin-comparison",message:`Only ${_.length} baseline / ${z.length} candidate sample(s); falling back to a point-estimate threshold instead of a bootstrap CI and Mann-Whitney test (needs ${Lt}+ per side).`,data:{baseSamples:_.length,candSamples:z.length}}};let pe=ar(_,z,{iterations:W.bootstrapIterations}),me=mr(_,z);return{timing:{medianDeltaPct:V,meanDeltaPct:re,ci95:pe.ci95,pValue:me.pValue,seed:pe.seed,verdict:me.pValue<W.alpha?J(pe.ci95[0],pe.ci95[1]):"unchanged"}}}function yi(p,h,N){let W=(se)=>new Map(se.totals.map((ce)=>[se.frames[ce.frameIx].key,ce.selfUs])),_=(se)=>new Map(se.frames.map((ce)=>[ce.key,ce.name])),z=W(p),V=W(h),re=_(p),J=_(h),pe=[...new Set([...z.keys(),...V.keys()])].map((se)=>{let ce=z.get(se)??0,he=V.get(se)??0;return{frameKey:se,name:J.get(se)??re.get(se)??se,baseSelfUs:ce,candSelfUs:he,deltaPct:dt(ce,he)}}).sort((se,ce)=>Math.abs(ce.deltaPct)-Math.abs(se.deltaPct)),me=pe.some((se)=>(se.baseSelfUs>=N.minFrameSelfUs||se.candSelfUs>=N.minFrameSelfUs)&&se.deltaPct>N.frameSelfPct);return{frames:pe,failed:me}}function wi(p,h,N){let W=new Map(p.typeCounts.map((V)=>[V.type,V])),_=new Map(h.typeCounts.map((V)=>[V.type,V])),z=[...new Set([...W.keys(),..._.keys()])].map((V)=>{let re=W.get(V),J=_.get(V);return{type:V,baseCount:re?.count??0,candCount:J?.count??0,baseBytes:re?.retainedBytes,candBytes:J?.retainedBytes,deltaPct:dt(re?.count??0,J?.count??0)}}).sort((V,re)=>Math.abs(re.deltaPct)-Math.abs(V.deltaPct));return{heapTypes:z,failed:z.some((V)=>V.deltaPct>N.heapTypePct)}}function Pi(p,h,N){let{effectiveTimingPct:W}=p,_=p.baseIdFor(h);if(_===void 0)return;let z=p.base(_,"timing"),V=p.cand(h,"timing"),re=p.base(_,"cpu"),J=p.cand(h,"cpu"),pe=p.base(_,"heap"),me=p.cand(h,"heap"),se=p.candWorkloads.get(h),ce=z?.id??re?.id??pe?.id,he=V?.id??J?.id??me?.id??se?.id;if(!ce||!he)return;let Ue=!1,ge=[];if(p.environmentMismatch)ge.push(p.environmentMismatch);let Ve;if(z?.timing&&se?.skipped&&!V?.timing)Ve={medianDeltaPct:0,meanDeltaPct:0,verdict:"unchanged"},ge.push({code:"skipped",message:"Candidate has no timing measurement for this workload (task.skip()); treated as unchanged.",data:{workloadId:h}});else if(z?.timing&&V?.timing){let He=bi(z.timing,V.timing,W,N);if(Ve=He.timing,He.warning)ge.push(He.warning);if(Ve.verdict==="regressed")Ue=!0}let _e;if(re?.cpu&&J?.cpu){let He=yi(re.cpu,J.cpu,N);_e=He.frames,Ue||=He.failed}let fe;if(pe?.heap&&me?.heap){let He=wi(pe.heap,me.heap,N);fe=He.heapTypes,Ue||=He.failed}return{id:n("cmp",ce,he),baselineMeasurementId:ce,candidateMeasurementId:he,timing:Ve,...ge.length>0&&{warnings:ge},frames:_e,heapTypes:fe,thresholds:{...N,effectiveTimingPct:W},verdict:Ue?"fail":"pass"}}class u extends Error{}var lr=(p)=>typeof p==="object"&&p!==null&&!Array.isArray(p),pt=(p)=>(h)=>typeof h==="number"&&Number.isInteger(h)&&h>=p,_n=(p)=>(h)=>typeof h==="number"&&Number.isFinite(h)&&h>=p,Ln=(p)=>typeof p==="string",ki=(p)=>typeof p==="boolean",qn=(p)=>Array.isArray(p)&&p.every(Ln),Ht=(...p)=>(h)=>p.includes(h),an=(p,h)=>({ok:p,expects:h}),Wn=an(pt(1),"a positive integer"),Mi=an(pt(0),"a non-negative integer"),Vt=an(Ln,"a string"),jn=an(ki,"a boolean"),Qn=an(qn,"an array of strings"),Ri={timingPct:an(_n(0),"a non-negative number"),frameSelfPct:an(_n(0),"a non-negative number"),heapTypePct:an(_n(0),"a non-negative number"),minFrameSelfUs:an(_n(0),"a non-negative number"),alpha:an((p)=>_n(0)(p)&&p<=1,"a number in [0, 1]"),bootstrapIterations:Wn},Ti={suites:an((p)=>qn(p)&&p.length>0,"a non-empty array of glob strings"),preload:Qn,bunFlags:Qn},xi={suites:Qn,projects:an(Array.isArray,"an array of project objects"),preload:Qn,bunFlags:Qn,jobs:an((p)=>pt(1)(p)||p==="auto",'a positive integer or "auto"'),budgetMs:an(_n(0),"a non-negative number"),samples:Wn,minSamples:Wn,gc:jn,cpu:jn,cpuIntervalUs:Wn,alloc:jn,peakMem:jn,filter:Vt,isolate:jn,outDir:Vt,timeoutMs:Wn},Si={setup:an((p)=>Ln(p)||qn(p),"a command string or an array of them"),keepTrees:Wn,metric:an(Ht("time","instructions"),'"time" or "instructions"'),alloc:jn,peakMem:jn,memThresholdPct:an(_n(0),"a non-negative number")},$i=["inputs","prepare","timeSource","ignoreExitCodes"],Ci={label:Vt,command:an((p)=>qn(p)&&p.length>0,"a non-empty array of strings (argv, no shell)"),suites:an((p)=>qn(p)&&p.length>0,"a non-empty array of glob strings"),inputs:Qn,prepare:an((p)=>Ln(p)||qn(p)||typeof p==="function","a command string, an argv array, or (ostia.config.ts) a function"),timeSource:an((p)=>lr(p)&&(Ln(p.pattern)||p.pattern instanceof RegExp)&&(p.group===void 0||pt(0)(p.group))&&(p.unit===void 0||Ht("ns","us","ms","s")(p.unit)),'an object { pattern, group?, unit? } with a regex source string (or RegExp) pattern, an integer group, and unit "ns" | "us" | "ms" | "s"'),timeoutMs:Wn,ignoreExitCodes:an((p)=>Array.isArray(p)&&p.every((h)=>pt(0)(h)&&h<=255),"an array of exit codes 0-255")},vi={samples:Wn,budgetMs:an(_n(0),"a non-negative number"),minSamples:Wn,warmup:Mi,outDir:an((p)=>Ln(p)&&p!=="","a non-empty string"),baselineDir:an((p)=>Ln(p)&&p!=="","a non-empty string"),baseline:an((p)=>Ln(p)&&p!=="","a non-empty string"),onMissingBaseline:an(Ht("warn","fail"),'"warn" or "fail"'),noiseCheck:jn},Gt=(p)=>typeof p==="function"?"a function":p instanceof RegExp?String(p):JSON.stringify(p)??String(p);function Yn(p,h,N,W,_){let z=N===""?"":`${N}.`;for(let[V,re]of Object.entries(p)){if(re===void 0)continue;let J=Object.hasOwn(h,V)?h[V]:void 0;if(!J){if(!V.startsWith("$"))_(`${W}: unknown key "${z}${V}" is ignored.`)}else if(!J.ok(re))throw new u(`${W}: "${z}${V}" must be ${J.expects}, got ${Gt(re)}.`)}}function lt(p,h,N){if(!lr(p))throw new u(`${N}: "${h}" must be an object, got ${Gt(p)}.`);return p}function Ii(p,h,N,W){let _=`workloads[${h}]`,z=lt(p,_,N),V=(J)=>z[J]!==void 0;if(V("command")===V("suites"))throw new u(`${N}: "${_}" needs exactly one of "command" or "suites".`);if(Yn(z,Ci,_,N,W),V("suites")){for(let J of $i)if(V(J))W(`${N}: "${_}.${J}" applies to command workloads only; ignored on a suites workload.`)}let re=z.timeSource?.pattern;if(typeof re==="string")try{new RegExp(re)}catch(J){throw new u(`${N}: "${_}.timeSource.pattern" is not a valid regex: ${J.message}`)}}function pr(p,h,N){let{thresholds:W,workloads:_,bench:z,ab:V,...re}=p;if(Yn(re,vi,"",h,N),W!==void 0)Yn(lt(W,"thresholds",h),Ri,"thresholds",h,N);if(z!==void 0){let J=lt(z,"bench",h);Yn(J,xi,"bench",h,N),J.projects?.forEach((pe,me)=>{let se=`bench.projects[${me}]`,ce=lt(pe,se,h);if(ce.suites===void 0)throw new u(`${h}: "${se}" needs "suites".`);Yn(ce,Ti,se,h,N)})}if(V!==void 0)Yn(lt(V,"ab",h),Si,"ab",h,N);if(_!==void 0){if(!Array.isArray(_))throw new u(`${h}: "workloads" must be an array, got ${Gt(_)}.`);_.forEach((J,pe)=>{Ii(J,pe,h,N)})}}var Vn="node_modules/.cache/ostia",Oi=".ostia/baselines",Di={warmup:3,outDir:Vn,baselineDir:Oi,baseline:"main",thresholds:M,workloads:[]},Ni={runs:"samples"},oe=["ostia.config.ts","ostia.config.json"],gr=(p)=>console.warn(`ostia: ${p}`);function fr(p){return Object.fromEntries(Object.entries(p).filter(([,h])=>h!==void 0))}function Ei(p,h){if(typeof p!=="object"||p===null||Array.isArray(p))throw new u(`${h}: expected an object.`);for(let[W,_]of Object.entries(Ni))if(W in p)throw new u(`${h}: "${W}" was renamed to "${_}".`);pr(p,h,gr);let N=fr(p);return{...Di,...N,thresholds:{...M,...N.thresholds&&fr(N.thresholds)}}}async function Ai(p){let h=p.startsWith("/")?p:`${process.cwd()}/${p}`,N=Bun.file(h);if(!await N.exists())return;try{if(!p.endsWith(".ts"))return await N.json();let W=(await import(h)).default;if(W===void 0)throw Error('no default export; use "export default defineConfig({ ... })"');return W}catch(W){throw new u(`${p}: ${T(W)}`)}}async function hr(){let p=[];for(let h of oe)if(await Bun.file(h).exists())p.push(h);return p}async function dn(p){let h=p;if(h===void 0){let W=await hr();if(W.length>1)gr(`${W.join(" and ")} both exist; using ${W[0]} and ignoring the rest.`);h=W[0]}if(h===void 0)return;let N=await Ai(h);return N===void 0?void 0:Ei(N,h)}function A(p,h){return`${p.baselineDir}/${h??p.baseline}.json`}async function en(){return(await hr())[0]}var Fi=10,Bi=3000,Wi=3;function br(p,h){return p!==void 0&&p!==0&&!h.has(p)}function zt(p){if(Kn("time",p),p.timeSource)xe(p.timeSource);let h=p.warmup??Wi,N=p.samples,W=p.minSamples??Fi,_=N!==void 0?0:(p.budgetMs??Bi)*1e6,z=p.timeSource!==void 0,V=p.ignoreExitCodes??[],re=new Set(V),J=[],pe=0,me=0,se=!1,ce;function he(){if(se)return!0;if(N!==void 0)return me>=N;return me>=W&&pe>=_}async function Ue(ge,Ve){if(p.prepare)await Me(p.prepare,{phase:ge,index:Ve},{cwd:p.cwd,env:p.env,timeoutMs:p.timeoutMs,signal:p.signal});return hn(p)}return{async warmup(){for(let ge=0;ge<h;ge++){if(p.signal?.aborted)return;await Ue("warmup",ge)}},async step(){if(he()||p.signal?.aborted)return!1;let ge=await Ue("timing",me);if(p.signal?.aborted)return!1;if(ge.timeSourceNoMatch)ce??=ge.timeSourceMissOutput;let Ve=ge.exitCode??void 0;if(J.push({i:me,wallNs:ge.wallNs,exitCode:Ve,userNs:ge.userNs,systemNs:ge.systemNs,maxRssBytes:ge.maxRssBytes,...ge.reportedNs!==void 0&&{reportedNs:ge.reportedNs},...ge.timedOut&&{timedOut:!0},...ge.timeSourceNoMatch&&{timeSourceNoMatch:!0}}),pe+=ge.wallNs,me++,br(Ve,re))se=!0;return!0},done:he,result(){let ge=J.filter((qe)=>!qe.timedOut&&!qe.timeSourceNoMatch),Ve=ge.map((qe)=>z?qe.reportedNs:qe.wallNs),_e=[],fe=J.filter((qe)=>qe.timedOut).length;if(fe>0)_e.push({code:"timeout",message:`${fe} of ${J.length} trial(s) timed out after ${p.timeoutMs}ms.`,data:{timeoutMs:p.timeoutMs,trials:fe}});let He=J.filter((qe)=>qe.timeSourceNoMatch).length;if(He>0&&p.timeSource){let{pattern:qe}=p.timeSource;_e.push({code:"time-source-no-match",message:`${He} of ${J.length} trial(s) didn't match the timeSource pattern.`,data:{pattern:typeof qe==="string"?qe:qe.source,trials:He,...ce!==void 0&&{output:ce}}})}if(Ve.length===0)return{trials:J,warnings:_e};let Ye=d(Ve);return _e.push(...Re(Ye,ge.map((qe)=>qe.exitCode),z?"reported":"subprocess",V)),{trials:J,timing:Ye,warnings:_e}}}}async function Kt(p){await p.warmup();while(await p.step());}async function ln(p){let h=zt(p);return await Kt(h),h.result()}function ye(p,h=[]){if(!p.timing)return!0;let N=new Set(h);return p.trials.some((W)=>br(W.exitCode,N))}function Kn(p,h){for(let[N,W]of Object.entries({samples:h.samples,minSamples:h.minSamples}))if(W!==void 0&&(!Number.isFinite(W)||W<1))throw RangeError(`${p}: ${N} must be >= 1, got ${W}`);if(h.budgetMs!==void 0&&!Number.isFinite(h.budgetMs))throw RangeError(`${p}: budgetMs must be finite, got ${h.budgetMs}`);if(h.warmup!==void 0&&(!Number.isFinite(h.warmup)||h.warmup<0))throw RangeError(`${p}: warmup must be >= 0, got ${h.warmup}`);if(h.timeoutMs!==void 0&&(!Number.isFinite(h.timeoutMs)||h.timeoutMs<=0))throw RangeError(`${p}: timeoutMs must be > 0, got ${h.timeoutMs}`)}class L extends m{}class K extends Error{side;constructor(p,h){super(p);this.side=h}}class q extends Error{}var qi=new URL("./ab-runner.ts",import.meta.url).pathname,Dn={keepTrees:5,base:"HEAD",rounds:15,metric:"time",thresholdPct:10,geomeanThresholdPct:1.5,memThresholdPct:10,confirm:2},yr=1048576,Qi=16384;function Yt(p,h){let N=Bun.spawnSync(["git",...p],{cwd:h,stdout:"pipe",stderr:"ignore"});return N.success?N.stdout.toString().trim():void 0}var qt=`
|
|
3
|
-
;globalThis.__ostia_ab_base__;
|
|
4
|
-
`,Xi="**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}";async function Zi(p){for await(let h of new Bun.Glob(Xi).scan({cwd:p,dot:!0,absolute:!0})){if(/\.d\.[mc]?ts$/.test(h)||!_i(h).isFile())continue;Ui(h,qt)}}function eo(p,h,N){let W=h.slice(0,12);if(N.length===0)return`${p}/${W}`;return`${p}/${W}-${n("ab-setup",N).slice(-8)}`}function Mr(p){return`${p}/.ostia/ab`}function no(p){if(Un(`${p}/.gitignore`))return;ji(p,{recursive:!0}),Ki(`${p}/.gitignore`,`*
|
|
5
|
-
`)}var to=20,ro=65536,io=1000;function wr(p){let h=p.getReader(),N=new TextDecoder,W="",_=(async()=>{try{for(;;){let z=await h.read();if(z.done)return;W=(W+N.decode(z.value,{stream:!0})).slice(-ro)}}catch{}})();return{done:_,stop:async()=>(await h.cancel().catch(()=>{}),await _,W)}}async function oo(p,h,N,W){let _=Bun.spawn(["sh","-c",p],{cwd:h,env:N,stdout:"pipe",stderr:"pipe",stdin:"ignore",detached:!0}),z=()=>{try{process.kill(-_.pid,"SIGKILL")}catch{}},V=!1,re=W.timeoutMs===void 0?void 0:setTimeout(()=>{V=!0,z()},W.timeoutMs);if(W.signal?.addEventListener("abort",z),W.signal?.aborted)z();let J=wr(_.stdout),pe=wr(_.stderr),me;try{let se=await _.exited;z(),await Promise.race([Promise.all([J.done,pe.done]),new Promise((Ue)=>{me=setTimeout(Ue,io)})]);let[ce,he]=await Promise.all([J.stop(),pe.stop()]);return{exitCode:se,timedOut:V,output:he.trim()||ce.trim()}}finally{clearTimeout(re),clearTimeout(me),W.signal?.removeEventListener("abort",z)}}async function so(p,h,N){let W=Jt(N.toplevel),_=Jt(N.cwd),z=kr(W,_),V=z&&Un(`${p}/${z}`)?`${p}/${z}`:p,re=[];for(let[J,pe]of[[`${W}/node_modules`,`${p}/node_modules`],[`${_}/node_modules`,`${V}/node_modules`]]){if(!Un(J)||Un(pe))continue;Hi(J,pe),re.push(pe)}try{for(let J of N.commands){N.onProgress?.({phase:"setup",command:J});let{exitCode:pe,timedOut:me,output:se}=await oo(J,V,{...process.env,OSTIA_AB_SHA:h,OSTIA_AB_CANDIDATE_DIR:_},N);if(N.signal?.aborted)return!1;if(pe===0&&!me)continue;let ce=se.split(`
|
|
6
|
-
`).slice(-to).join(`
|
|
7
|
-
`),he=me?`timed out after ${N.timeoutMs}ms`:`exited ${pe}`;throw new q(`Base setup ${he}: ${J}${ce?`
|
|
8
|
-
${ce}`:""}`)}return!0}finally{for(let J of re)Gi(J)}}async function ao(p,h,N){if(Un(h))return!0;let W=`${h}.tmp-${process.pid}-${crypto.randomUUID().slice(0,8)}`;await f(W),await Ji(W,{recursive:!0});let _=Bun.spawn(["git","archive","--format=tar",p],{cwd:N.cwd,stdout:"pipe",stderr:"pipe"}),z=Bun.spawn(["tar","-x","-C",W],{stdin:_.stdout,stderr:"pipe"}),[V,re]=await Promise.all([_.exited,z.exited]);if(V!==0||re!==0){let J=await new Response(V!==0?_.stderr:z.stderr).text();throw await f(W),Error(`Could not extract ${p}: ${J.trim()}`)}try{if(!await so(W,p,N))return await f(W),!1}catch(J){throw await f(W),J}await Zi(W);try{Li(W,h)}catch{await f(W)}return!0}var mo=3600000;function uo(p){try{return process.kill(p,0),!0}catch(h){return h.code==="EPERM"}}function co(p){let h=new Date;try{zi(p,h,h)}catch{}}async function lo(p,h){if(!Un(p))return 0;let N=Date.now(),W=[],_=[];for(let z of Qt(p)){if(z===".gitignore")continue;let V=`${p}/${z}`,re=/\.tmp-(\d+)(?:-\w+)?$/.exec(z);if(re){if(!uo(Number(re[1])))W.push(V);continue}try{_.push({path:V,mtimeMs:Vi(V).mtimeMs})}catch{}}_.sort((z,V)=>V.mtimeMs-z.mtimeMs);for(let z of _.slice(h))if(N-z.mtimeMs>mo)W.push(z.path);for(let z of W)await f(z);return W.length}var po=/^[0-9a-f]{40}(?:-[0-9a-f]{8})?(?:\.tmp-\d+(?:-\w+)?)?$/;async function Rr(p){if(!Un(p))return 0;let h=Qt(p),N=h.filter((W)=>po.test(W));for(let W of N)await f(`${p}/${W}`);if(N.length===h.length)await f(p);return N.length}async function pn(p={}){let h=p.cwd??process.cwd(),N=await Rr(`${P(h,p.outDir??Vn)}/ab`),W=Yt(["rev-parse","--show-toplevel"],h),_=W===void 0?void 0:Mr(W);if(_&&Un(_))N+=Qt(_).filter((z)=>z!==".gitignore").length,await f(_);return N}function fo(p,h,N,W){let _=p.paired,z=[...N.base,...N.cand],V=(re,J)=>{let pe=gn(D(N.base.map(re)),D(N.cand.map(re)),W,J);if(!E(_))pe.verdict="unchanged";return pe};if(h.alloc){let re=Math.min(...z.map((J)=>J.alloc.calls));_.retained=V((J)=>J.alloc.bytesPerOp,Qi/re)}if(h.peakMem){let re=z.map((me)=>me.peak),J=Fe(re),pe=Math.max(...re.map((me)=>me.slackBytes));if(_.peak=V((me)=>me.peak.peakBytes,J?Math.max(yr,pe):yr),J)p.warnings.push(J)}}function go(p,h,N,W=Dn.metric){let _=new Map(h.measurements.map((V)=>[V.workloadId,V])),z=p.measurements.map((V)=>{let re=_.get(V.workloadId);if(!re)return V;if(V.threw&&re.threw&&V.threw.side!==re.threw.side)return{...V,threw:{side:"both",message:`${V.threw.message}
|
|
9
|
-
${re.threw.message}`}};if(V.threw)return V;if(re.threw)return re;let J=V.paired,pe=re.paired;if(!J||!pe||!V.timing||!re.timing)return V;let me=d([...V.timing.samples,...re.timing.samples]);if(J.batch>1)me.batch=J.batch;return{...V,timing:me,diagnosticWallNs:(V.diagnosticWallNs??0)+(re.diagnosticWallNs??0),paired:ue({rounds:J.rounds+pe.rounds,batch:J.batch,baseSamples:[...J.baseSamples,...pe.baseSamples],ratios:[...J.ratios,...pe.ratios],...J.instructions&&pe.instructions&&{instructions:{baseSamples:[...J.instructions.baseSamples,...pe.instructions.baseSamples],candSamples:[...J.instructions.candSamples,...pe.instructions.candSamples]}},sameOutput:J.sameOutput&&pe.sameOutput},N,W)}});return{...p,measurements:z}}function ho(p,h){let[N,...W]=[p,...p.repeats??[]].map((_)=>O(_,h)?.medianRatio);if(N===void 0)return;return D([N,...W.filter((_)=>_!==void 0)])}function Pr(p,h){let N=p.filter((fe)=>!fe.threw).map((fe)=>fe.paired).filter((fe)=>fe!==void 0),W=(fe)=>N.filter((He)=>He.verdict===fe).length,_=h.metric??Dn.metric,z=N.filter(E),V=z.map((fe)=>ho(fe,_)).filter((fe)=>fe!==void 0),re=V.reduce((fe,He)=>fe+Math.log(He),0),J=V.length>0?(Math.exp(re/V.length)-1)*100:null,pe=W("regressed"),me=W("improved"),se=p.filter((fe)=>fe.threw),ce=se.some((fe)=>fe.threw?.side==="cand"),{memThresholdPct:he,...Ue}=h,ge=N.filter((fe)=>fe.retained||fe.peak).map((fe)=>[fe.retained?.verdict,fe.peak?.verdict]),Ve=ge.filter((fe)=>fe.includes("regressed")),_e=ge.length>0&&{thresholdPct:he??Dn.memThresholdPct,regressed:Ve.length,improved:ge.filter((fe)=>fe.includes("improved")&&!fe.includes("regressed")).length};return{...Ue,metric:_,matched:N.length,regressed:pe,improved:me,unchanged:N.length-pe-me,unconfirmed:N.filter((fe)=>fe.confirmed===!1).length,outputDiffers:N.filter((fe)=>!fe.sameOutput).length,notComparable:N.length-z.length,threw:se.length,..._e&&{memory:_e},geomeanPct:J,verdict:pe>0||ce||Ve.length>0||J!==null&&J>h.geomeanThresholdPct?"fail":"pass"}}async function ke(p){let h=p.base??Dn.base,N=p.rounds??Dn.rounds,W=p.metric??Dn.metric,_=p.thresholdPct??Dn.thresholdPct,z=p.geomeanThresholdPct??Dn.geomeanThresholdPct,V=p.memThresholdPct??Dn.memThresholdPct,re=p.confirm??Dn.confirm,J=p.keepTrees??Dn.keepTrees;if(!Number.isInteger(J)||J<1)throw RangeError(`ab: keepTrees must be an integer >= 1, got ${J}`);if(!Number.isInteger(N)||N<3)throw RangeError(`ab: rounds must be an integer >= 3, got ${N}`);if(!Number.isInteger(re)||re<0)throw RangeError(`ab: confirm must be an integer >= 0, got ${re}`);if(W!=="time"&&W!=="instructions")throw RangeError(`ab: metric must be "time" or "instructions", got ${JSON.stringify(W)}`);let pe=W==="instructions"&&x().unavailable;if(pe)throw new m(`ab: can't judge by instructions on this machine: ${pe}.`);for(let[Ge,on]of Object.entries({thresholdPct:_,geomeanThresholdPct:z,memThresholdPct:V}))if(!Number.isFinite(on)||on<0)throw RangeError(`ab: ${Ge} must be >= 0, got ${on}`);Kn("ab",{timeoutMs:p.timeoutMs});let me=p.cwd??process.cwd(),se=P(me,p.outDir??Vn),ce=Ne(se,"ab"),he=p.suites.map((Ge)=>P(me,Ge));for(let[Ge,on]of he.entries())Ee(p.suites[Ge],on);let Ue=Yt(["rev-parse","--show-toplevel"],me);if(Ue===void 0)throw new L(`${me} is not inside a git repository.`);let ge=Yt(["rev-parse","--verify","--quiet",`${h}^{commit}`],me);if(ge===void 0)throw new L(`"${h}" is not a commit in ${Ue}.`);let Ve=typeof p.baseSetup==="string"?[p.baseSetup]:p.baseSetup??[],_e=Mr(Ue);no(_e);let fe=eo(_e,ge,Ve),He=await ao(ge,fe,{commands:Ve,toplevel:Ue,cwd:me,timeoutMs:p.timeoutMs,signal:p.signal,onProgress:p.onProgress}),Ye={base:{ref:h,sha:ge},rounds:N,metric:W,thresholdPct:_,geomeanThresholdPct:z,memThresholdPct:V};if(!He){let Ge=s([],[]);return Ge.unmatched={baseOnly:[],candOnly:[]},Ge.ab=Pr([],Ye),Ge}let{environment:qe,noiseWarning:Ke}=I(p.noiseCheck),Ze=he.map((Ge,on)=>{let cn=kr(Ue,Jt(Ge));if(cn===".."||cn.startsWith(`..${Yi}`))throw new m(`${p.suites[on]} is outside ${Ue}.`);return Un(`${fe}/${cn}`)?`${fe}/${cn}`:""}),mn=await Promise.all(he.map(async(Ge,on)=>{if(!Ze[on])return!1;let cn=await Bun.file(Ze[on]).text(),vn=await Bun.file(Ge).text();return(cn.endsWith(qt)?cn.slice(0,-qt.length):cn)!==vn})),Nn=bt(p.suites,me,p,p.projects),En=p.onProgress,An=0,$n=async(Ge,on={},cn)=>{co(fe);let vn=`${ce}/${n("ab-run",he[Ge],An++)}.json`,mt={filter:p.filter,rounds:N,thresholdPct:_,metric:W,preload:Nn[Ge].preload,progress:En!==void 0&&!on.workloadIds&&!on.memoryFor,...on},ut;try{ut=await Be(["bun",...Nn[Ge].bunFlags,qi,he[Ge],Ze[Ge],vn,JSON.stringify(mt)],{cwd:me,label:"A/B suite",name:p.suites[Ge],timeoutMs:p.timeoutMs,signal:p.signal,env:cn,errorFile:`${vn}.error`,...mt.progress&&{ipc:(Gn)=>En?.({phase:"measure",suite:Ge+1,suites:he.length,file:p.suites[Ge],pass:on.candFirst?2:1,passes:2,...Gn})}})}catch(Gn){let ct=Bun.file(`${vn}.side`);if(!await ct.exists())throw Gn;throw new K(Gn.message,await ct.text())}return ut?vn:void 0},Fn=async(Ge,on={})=>{let cn=await $n(Ge,{...on,rounds:Math.ceil(N/2)});if(!cn)return;let vn=await $n(Ge,{...on,planPath:void 0,rounds:Math.floor(N/2),candFirst:!0});if(!vn)return;return go(await a(cn),await a(vn),_,W)};try{let Ge=[],on=[],cn=new Map,vn=[],mt=[],ut=[];for(let rn=0;rn<he.length;rn++){let un=`${ce}/${n("ab-plan",he[rn])}.json`,In=await Fn(rn,{alloc:p.alloc,peakMem:p.peakMem,planPath:un});if(!In)break;let Bn=await Bun.file(un).json();for(let Sn of Bn.memory)ut.push({...Sn,suite:rn});Ge.push(...In.workloads),on.push(...In.measurements);for(let Sn of In.measurements){if(cn.set(Sn.workloadId,rn),!mn[rn]||!Sn.paired)continue;if(Sn.paired.suiteChanged=!0,!E(Sn.paired))Sn.paired.verdict="unchanged";Sn.warnings.push({code:"suite-changed",message:E(Sn.paired)?"The suite file differs from the base's copy, so each side may run a different benchmark.":"The suite file differs from the base's copy and so does the output: each side likely ran a different benchmark. Left out of the verdict, geomean and memory verdict."})}vn.push(...In.unmatched?.baseOnly??[]),mt.push(...In.unmatched?.candOnly??[])}let Gn=on.filter((rn)=>rn.paired?.flagged&&re>0&&E(rn.paired)),ct=new Map(Ge.map((rn)=>[rn.id,rn.entry?.task??rn.id])),ti=0;for(let rn of Gn){let un=rn.paired,In=un.flagged;un.repeats=[];for(let Bn=0;Bn<re&&!p.signal?.aborted;Bn++){En?.({phase:"confirm",repeat:++ti,repeats:Gn.length*re,label:ct.get(rn.workloadId)??rn.workloadId});let Jn=(await Fn(cn.get(rn.workloadId),{workloadIds:[rn.workloadId]}))?.measurements[0];if(Jn?.threw){rn.threw={...Jn.threw,repeat:Bn+1};break}let On=Jn?.paired;if(!On)break;let zn=On.instructions;un.repeats.push({medianRatio:On.medianRatio,ratioP25:On.ratioP25,ratioP75:On.ratioP75,...zn&&{instructions:{medianRatio:zn.medianRatio,ratioP25:zn.ratioP25,ratioP75:zn.ratioP75}},...On.flagged&&{flagged:On.flagged}})}un.confirmed=!rn.threw&&un.repeats.length===re&&un.repeats.every((Bn)=>Bn.flagged===In),un.verdict=un.confirmed?In:"unchanged"}let ir=new Map(on.map((rn)=>[rn.workloadId,rn])),or=ut.filter(({workloadId:rn})=>{let un=ir.get(rn);return un?.paired&&!un.threw}),ri=or.length*le*2,ii=0;for(let rn of or){let{workloadId:un,suite:In,peakMem:Bn}=rn,Sn={base:[],cand:[]};for(let Jn=0;Jn<le&&!p.signal?.aborted;Jn++)for(let On of["base","cand"]){if(p.signal?.aborted)break;En?.({phase:"memory",run:++ii,runs:ri,side:On,label:ct.get(un)??un});let zn=await $n(In,{memoryFor:{...rn,side:On}},Bn?{OSTIA_PEAK_MEM:"1"}:void 0);if(zn)Sn[On].push(await Bun.file(zn).json())}if(Sn.base.length===0||Sn.cand.length===0)continue;fo(ir.get(un),rn,Sn,V)}De(on,Ke,p.signal?.aborted?"Run was cancelled before it finished; this document holds whatever suites had already completed.":void 0);let _t=s(Ge,on,qe);return _t.unmatched={baseOnly:vn,candOnly:mt},_t.ab=Pr(on,{...Ye,newSuites:p.suites.filter((rn,un)=>!Ze[un])}),await lo(_e,J),await Rr(`${se}/ab`),_t}finally{await f(ce)}}import{resolve as bo}from"path";var yo=["node_modules",".git"],Tr=".ostia/ab",xr=/[*?[\]{}!]|[@+]\(/;function wo(p,h){let N=p.split("/"),W=N.findIndex((z)=>xr.test(z)),_=W<0?N.length:W;return[N.slice(_),h.split("/").slice(_)]}async function Y(p,h){let N=new Set;for(let W of p){if(!xr.test(W)){if(await Bun.file(bo(h,W)).exists())N.add(W);continue}for await(let _ of new Bun.Glob(W).scan({cwd:h,dot:!0})){let[z,V]=wo(W,_),re=V.some((pe)=>yo.includes(pe)&&!z.includes(pe)),J=`/${_}/`.includes(`/${Tr}/`)&&!W.includes(Tr);if(!re&&!J)N.add(_)}}return[...N].sort()}var Po=new URL("./runner.ts",import.meta.url).pathname;function nn(){return Math.max(1,navigator.hardwareConcurrency||1)}async function ie(p,h,N=process.cwd()){let W=[...h?.suites??[],...h?.projects?.flatMap((z)=>z.suites)??[]];return{suites:p.suites.length>0?p.suites:W.length>0?await Y(W,N):[],budgetMs:p.budgetMs??h?.budgetMs,samples:p.samples??h?.samples,minSamples:p.minSamples??h?.minSamples,jobs:p.jobs??(h?.jobs==="auto"?nn():h?.jobs),gc:p.gc??h?.gc??!1,cpu:p.cpu??h?.cpu??!1,cpuIntervalUs:p.cpuIntervalUs??h?.cpuIntervalUs,alloc:p.alloc??h?.alloc??!1,peakMem:p.peakMem??h?.peakMem??!1,filter:p.filter??h?.filter,isolate:p.isolate??h?.isolate??!1,preload:p.preload.length>0?p.preload:h?.preload??[],bunFlags:p.bunFlags.length>0?p.bunFlags:h?.bunFlags??[],projects:h?.projects?.map((z)=>({...z,...p.preload.length>0&&{preload:void 0},...p.bunFlags.length>0&&{bunFlags:void 0}})),outDir:p.outDir??h?.outDir,noiseCheck:p.noiseCheck,timeoutMs:p.timeoutMs??h?.timeoutMs,cwd:N}}function ko(p,h){if(!h?.length)return[];let N=D(h.map((_)=>_.peakBytes)),W=Fe(h);return[k({workload:p,phase:"memstats",configFingerprint:i({peakMem:!0}),diagnosticWallNs:D(h.map((_)=>_.wallNs)),memory:{origin:"resourceUsage",kind:"peak",peakBytes:N},warnings:W?[W]:[],artifacts:[]})]}async function Z(p){Kn("bench",p);let h=p.jobs??1;if(!Number.isInteger(h)||h<1)throw RangeError(`bench: jobs must be an integer >= 1, got ${h}`);let N=p.cwd??process.cwd(),W=Ne(P(N,p.outDir??Vn),"bench"),_=p.suites.map((se)=>P(N,se));for(let[se,ce]of _.entries())Ee(p.suites[se],ce);let z=bt(_,N,p,p.projects),{environment:V,noiseWarning:re}=I(p.noiseCheck),J={budgetMs:p.budgetMs,samples:p.samples,minSamples:p.minSamples,gc:p.gc,cpu:p.cpu,cpuIntervalUs:p.cpuIntervalUs,alloc:p.alloc,peakMem:p.peakMem,noiseCheck:!1},pe=(se,ce,...he)=>`${W}/${n(se,_[ce],...he)}.json`,me=async(se,ce)=>{let he=new Set,Ue=0,ge,Ve=async()=>{while(ge===void 0&&!p.signal?.aborted&&Ue<se.length){let _e=se[Ue++];try{if(!await Be(["bun",...z[_e.suiteIndex].bunFlags,Po,_[_e.suiteIndex],_e.outPath,JSON.stringify(_e.runnerOpts)],{label:"Bench suite",name:p.suites[_e.suiteIndex],cwd:N,env:ce,timeoutMs:p.timeoutMs,signal:p.signal,inFlight:he}))return}catch(fe){ge??=fe instanceof Error?fe:Error(String(fe));for(let He of he)He.kill()}}};if(await Promise.all(Array.from({length:Math.min(h,se.length)},Ve)),ge)throw ge};try{let se=_.map((Ke,Ze)=>({planPath:pe("bench-plan",Ze),outPath:pe("bench-primary",Ze)}));await me(se.map((Ke,Ze)=>({suiteIndex:Ze,outPath:Ke.outPath,runnerOpts:{...J,filter:p.filter,isolate:p.isolate,preload:z[Ze].preload,planPath:Ke.planPath}})));let ce=await Promise.all(se.map(async(Ke)=>await Bun.file(Ke.planPath).exists()?(await Bun.file(Ke.planPath).json()).tasks:[])),he=await Promise.all(se.map((Ke)=>sn(Ke.outPath))),Ue=ce.flatMap((Ke,Ze)=>Ke.filter((mn)=>mn.isolate).map((mn)=>({task:mn,suiteIndex:Ze}))),ge=Ue.map((Ke,Ze)=>pe("bench-item",Ke.suiteIndex,Ze));await me(Ue.map((Ke,Ze)=>({suiteIndex:Ke.suiteIndex,outPath:ge[Ze],runnerOpts:{...J,workloadIds:[Ke.task.workloadId],preload:z[Ke.suiteIndex].preload,markIsolated:!0}})));let Ve=new Map;await Promise.all(Ue.map(async(Ke,Ze)=>{let mn=await sn(ge[Ze]);if(mn)Ve.set(Ke.task,mn)}));let _e=ce.flatMap((Ke,Ze)=>Ke.filter((mn)=>mn.peakMem).flatMap((mn)=>Array.from({length:le},()=>({workloadId:mn.workloadId,suiteIndex:Ze})))),fe=_e.map((Ke,Ze)=>pe("bench-peak",Ke.suiteIndex,Ze));await me(_e.map((Ke,Ze)=>({suiteIndex:Ke.suiteIndex,outPath:fe[Ze],runnerOpts:{filter:p.filter,preload:z[Ke.suiteIndex].preload,peakMemFor:Ke.workloadId}})),{OSTIA_PEAK_MEM:"1"});let He=new Map;for(let Ke=0;Ke<_e.length;Ke++){let Ze=Bun.file(fe[Ke]);if(!await Ze.exists())continue;let mn=_e[Ke].workloadId,Nn=He.get(mn)??[];Nn.push(await Ze.json()),He.set(mn,Nn)}let Ye=[],qe=[];return ce.forEach((Ke,Ze)=>{let mn=he[Ze];if(!mn)return;let Nn=Map.groupBy(mn.measurements,(An)=>An.workloadId),En=0;for(let An of Ke){let $n,Fn;if(An.isolate){let Ge=Ve.get(An);if(!Ge)continue;$n=Ge.workloads[0],Fn=Ge.measurements.filter((on)=>on.workloadId===$n.id)}else $n=mn.workloads[En++],Fn=Nn.get($n.id)??[];Ye.push($n),qe.push(...Fn,...ko($n,He.get($n.id)))}}),De(qe,re,p.signal?.aborted?"Run was cancelled before it finished; this document holds whatever suites/tasks had already completed.":void 0),C(V),s(Ye,qe,V)}finally{await f(W)}}function Pn(p,h,N=8){if(N<=1)throw RangeError(`range: multiplier must be > 1, got ${N}`);if(p<=0)throw RangeError(`range: start must be > 0, got ${p}`);let W=[];for(let _=p;_<=h;_*=N)W.push(_);if(!W.includes(h))W.push(h);return W}function Sr(p){return p.cpu!==void 0}function Xt(p,h){if(h){let N=p.measurements.find((W)=>W.id===h);return N&&Sr(N)?[N]:[]}return p.measurements.filter((N)=>N.phase==="cpu"&&Sr(N))}function Xn(p,h,N,W){return{files:Xt(p,h.measurementId).map((_)=>({path:`${_.id}.${N}`,content:W(_)}))}}function Zn(p){let h=p.nodes,N=h.length,W=Mo(p),_=new Int32Array(N).fill(-1);for(let J=0;J<N;J++)for(let pe of h[J].children){let me=W(pe);if(me!==-1)_[me]=J}let z=[];for(let J=0;J<N;J++)if(_[J]===-1)z.push(J);let V=[],re=[];for(let J=z.length-1;J>=0;J--)re.push(z[J]);while(re.length>0){let J=re.pop();V.push(J);for(let pe of h[J].children){let me=W(pe);if(me!==-1&&_[me]===J)re.push(me)}}return{count:N,indexOf:W,parentIx:_,roots:z,order:V}}function Mo(p){let h=p.nodes,N=h.length,W=1/0,_=-1/0,z=!0;for(let re=0;re<N;re++){let J=h[re].id;if(!Number.isInteger(J)){z=!1;break}if(J<W)W=J;if(J>_)_=J}if(z&&N>0&&_-W<N*4+64){let re=_-W+1,J=new Int32Array(re).fill(-1);for(let pe=0;pe<N;pe++)J[h[pe].id-W]=pe;return(pe)=>{let me=pe-W;return me>=0&&me<re?J[me]:-1}}let V=new Map;for(let re=0;re<N;re++)V.set(h[re].id,re);return(re)=>V.get(re)??-1}function $r(p,h){let{count:N,indexOf:W,parentIx:_,order:z}=h,V=new Float64Array(N),re=new Float64Array(N),J=p.samples?.nodeIds??[],pe=p.samples?.timeDeltasUs??[];for(let se=0;se<J.length;se++){let ce=W(J[se]);if(ce===-1)continue;V[ce]+=pe[se]??0,re[ce]+=1}let me=new Float64Array(N);for(let se=z.length-1;se>=0;se--){let ce=z[se];me[ce]+=V[ce];let he=_[ce];if(he>=0)me[he]+=me[ce]}return{selfUs:V,totalUs:me,samples:re}}var Cr={name:"collapsed",async render(p,h={}){return Xn(p,h,"collapsed.txt",({cpu:N})=>{let{nodes:W,frames:_}=N,z=Zn(N),V=Array(z.count);for(let me of z.order){let se=F(_[W[me].frameIx]),ce=z.parentIx[me];V[me]=ce===-1?se:`${V[ce]};${se}`}let re=new Float64Array(z.count),J=[];for(let me of N.samples?.nodeIds??[]){let se=z.indexOf(me);if(se===-1)continue;if(re[se]++===0)J.push(se)}let pe=J.map((me)=>`${V[me]} ${re[me]}`);return pe.length>0?`${pe.join(`
|
|
10
|
-
`)}
|
|
11
|
-
`:""})}};var vr={name:"cpuprofile",async render(p,h={}){let N=[],W=[];for(let _ of Xt(p,h.measurementId)){let{origin:z}=_.cpu;if(z!=="cpu-prof"&&z!=="inspector"){W.push(`${_.id} (origin ${z} has no .cpuprofile artifact to pass through)`);continue}let V=_.artifacts.find((J)=>J.kind==="cpuprofile");if(!V){W.push(`${_.id} (no cpuprofile artifact recorded on this run)`);continue}let re=Bun.file(V.path);if(!await re.exists()){W.push(`${_.id} (artifact missing on disk: ${V.path})`);continue}N.push({path:`${_.id}.cpuprofile`,content:await re.text()})}if(N.length===0&&W.length>0)return{text:`No .cpuprofile artifacts available:
|
|
12
|
-
${W.map((_)=>` - ${_}`).join(`
|
|
13
|
-
`)}
|
|
14
|
-
`};return{files:N}}};var Ir={name:"json",async render(p){return{text:Q(p)}}};var Or={name:"jsonl",async render(p){let{measurements:h,...N}=p;return{text:`${[v({kind:"document",...N}),...h.map((_)=>v({kind:"measurement",..._}))].join(`
|
|
15
|
-
`)}
|
|
16
|
-
`}}};var Dr=0.5;function Cn(p){return new Map(p.workloads.map((h)=>[h.id,h]))}function et(p){return p.measurements.filter((h)=>h.phase==="timing"&&h.timing!==void 0)}function nt(p){return p.measurements.filter((h)=>h.phase==="timing"&&h.timing===void 0)}function tt(p,h){let N=new Set(h.map((W)=>W.workloadId));return p.workloads.filter((W)=>W.skipped&&!N.has(W.id))}function wt(p){for(let h of p.comparisons??[]){let N=h.warnings?.find((W)=>W.code==="environment-mismatch");if(N)return N}return}function Pt(p){return(p.warnings??[]).filter((h)=>h.code!=="environment-mismatch")}function Ro(p){let h=Cn(p),N=new Map(p.measurements.map((W)=>[W.id,W]));return(W)=>{let _=N.get(W.candidateMeasurementId),z=_?.workloadId??W.candidateMeasurementId;return{run:_,workloadId:z,workload:h.get(z)}}}function kt(p,h){return(p.frames??[]).slice(0,h).filter((N)=>Math.abs(N.deltaPct)>=Dr)}function Mt(p,h){return(p.heapTypes??[]).slice(0,h).filter((N)=>Math.abs(N.deltaPct)>=Dr)}function rt(p){let h=new Map;for(let N of p.measurements){if(N.phase!=="memstats"||!N.memory)continue;let W=h.get(N.workloadId)??{warnings:[]};if(N.memory.bytesPerOp!==void 0)W.retained=N.memory.bytesPerOp;if(N.memory.peakBytes!==void 0)W.peak=N.memory.peakBytes;W.warnings.push(...N.warnings),h.set(N.workloadId,W)}return h}function ft(p,h){let N=h.get(p.workloadId)?.warnings;return N?.length?[...p.warnings,...N]:p.warnings}function Rt(p){return[{header:"Retained/op",read:(N)=>N.retained},{header:"Peak mem",read:(N)=>N.peak}].filter((N)=>{for(let W of p.values())if(N.read(W)!==void 0)return!0;return!1}).map((N)=>({header:N.header,cell:(W)=>{let _=p.get(W),z=_&&N.read(_);return z===void 0?void 0:w(z)}}))}function it(p){if(!p.compared&&!p.comparisons?.length&&!p.unmatched)return[];let h=new Map((p.comparisons??[]).map((W)=>[W.id,W]));return(p.compared??To(p)).map((W)=>({row:W,cmp:W.comparisonId===void 0?void 0:h.get(W.comparisonId)}))}function To(p){let h=Ro(p),N=Cn(p),W=(_,z)=>{let V=N.get(_);return{workloadId:_,task:o(V,_),...V?.entry?.group!==void 0&&{group:V.entry.group},verdict:z}};return[...(p.comparisons??[]).map((_)=>{let{run:z,workload:V,workloadId:re}=h(_),J={workloadId:re,task:V?c(V):re,...V?.entry?.group!==void 0&&{group:V.entry.group},verdict:_.timing?.verdict??"unchanged",comparisonId:_.id,pass:_.verdict==="pass"};if(_.timing&&z?.timing){let{medianDeltaPct:pe,ci95:me,pValue:se}=_.timing;J.timing={unit:"ns",baseMedian:z.timing.median/(1+pe/100),candMedian:z.timing.median,candSamples:z.timing.samples.length,medianDeltaPct:pe,...me&&{ci95:me},...se!==void 0&&{pValue:se},thresholdPct:_.thresholds.effectiveTimingPct}}return J}),...(p.unmatched?.candOnly??[]).map((_)=>W(_,"missing-base")),...(p.unmatched?.baseOnly??[]).map((_)=>W(_,"missing-cand"))]}var xo=10,So={heapUsedBefore:"heap used before",heapUsedAfter:"heap used after",retained:"retained/op",peak:"peak",maxRss:"max RSS"};function Tt(p,h="\u2192"){return(p.memory??[]).filter((N)=>!(Math.abs(N.deltaPct)<xo)).map((N)=>`${So[N.reading]} ${w(N.baseBytes)} ${h} ${w(N.candBytes)} (${Number.isFinite(N.deltaPct)?r(N.deltaPct):"new"})`)}function xt(p){let h=p.comparisonSummary,N=p.comparisons?.[0]?.thresholds.timingPct;if(!h||N===void 0)return;if(!(h.effectiveTimingPct>N))return;let W=h.driftPct!==void 0&&h.driftPct>0?` and drift (${h.driftPct.toFixed(1)}%); \`ostia ab\` alternates base and candidate in one process, so drift can't favor either`:"";return`Timing threshold ${N.toFixed(1)}%, widened to ${h.effectiveTimingPct.toFixed(1)}% by machine noise${W}`}function St(p){return p==="missing-base"?"candidate only (new, or renamed without `aliases`)":"base only (removed, or renamed without `aliases`)"}function Nr(p){return p.phase==="paired"&&p.threw!==void 0}function Er(p){return p.phase==="paired"&&p.threw===void 0&&p.timing!==void 0&&p.paired!==void 0}function ot(p){return p.measurements.filter(Er)}function $t(p){return p.measurements.filter(Nr)}function Ar(p){let h=[];for(let N of p.measurements)if(Nr(N))h.push({kind:"threw",run:N});else if(Er(N))h.push({kind:"timed",run:N});return h}function Ct(p){return`${y(p.side)} threw${p.repeat?` (repeat ${p.repeat})`:""}`}function gt(p){return r((p-1)*100)}function $o(p,h){if(!E(p))return"not comparable";if(!p.flagged)return"";let N=p.repeats?.length?` (repeats: ${p.repeats.map((W)=>gt(O(W,h)?.medianRatio??Number.NaN)).join(", ")})`:"";if(p.confirmed===void 0)return`${p.flagged}${N}`;return`${p.confirmed?`${p.flagged}, confirmed`:`${p.flagged}? unconfirmed`}${N}`}function vt(p){if(!p.newSuites?.length)return;return`New suite${p.newSuites.length>1?"s":""}, not at ${p.base.ref}: ${p.newSuites.join(", ")}`}function It(p,h){let N=p.paired,W=N.instructions,_=O(N,h),z=O(N,h==="time"?"instructions":"time"),V="-",re="-";if(h==="time"){let J=S(Math.min(N.baseMedianNs,p.timing.median));V=e(N.baseMedianNs,J),re=e(p.timing.median,J)}else if(W)V=H(W.baseMedian),re=H(W.candMedian);return{base:V,candidate:re,change:_?gt(_.medianRatio):"",spread:_?`${gt(_.ratioP25)}\u2026${gt(_.ratioP75)}`:"",also:z?gt(z.medianRatio):"",verdict:$o(N,h)}}function Ot(p,h){if(h==="instructions")return"Time";return p.measurements.some((N)=>N.paired?.instructions)?"Instr":void 0}function Dt(p){return ot(p).flatMap((h)=>{let N=[],{retained:W,peak:_}=h.paired;if(W)N.push({run:h,reading:"retained/op",change:W});if(_)N.push({run:h,reading:"peak",change:_});return N})}function Co(p){let h=Math.round(p.baseBytes),N=Math.round(p.candBytes)-h;if(N===0)return"0B";let W=`${N>0?"+":"-"}${w(Math.abs(N))}`;if(h===0||p.baseBytes<p.floorBytes)return W;return`${W} (${r(N/h*100)})`}function Nt({reading:p,change:h}){return{reading:p,base:w(h.baseBytes),candidate:w(h.candBytes),change:Co(h),verdict:h.verdict==="unchanged"?"":h.verdict}}function Et(p){let h=p.metric==="instructions"?" \xB7 by instructions/call":"",N=p.memory?` \xB7 memory threshold ${p.memory.thresholdPct}%`:"";return`working tree vs ${p.base.ref} (${p.base.sha.slice(0,7)}) \xB7 ${p.rounds} rounds${h} \xB7 threshold ${p.thresholdPct}% \xB7 geomean threshold ${p.geomeanThresholdPct}%${N}`}function At(p){let h=p.geomeanPct===null?"Geomean -":`Geomean ${r(p.geomeanPct)} (threshold ${p.geomeanThresholdPct}%)`,N=[p.unconfirmed>0&&`${p.unconfirmed} unconfirmed`,p.notComparable>0&&`${p.notComparable} not comparable`,p.threw>0&&`${p.threw} threw`].filter(Boolean),W=N.length>0?` (${N.join(", ")})`:"",_=p.memory?` \xB7 memory: ${p.memory.regressed} regressed, ${p.memory.improved} improved`:"";return`${h} \xB7 ${p.regressed} regressed, ${p.improved} improved, ${p.unchanged} unchanged of ${p.matched}${W}${_} \xB7 ${p.verdict}`}function Ft(p){let h=Cn(p),N=(W)=>o(h.get(W),W);return{outputDiffers:ot(p).filter((W)=>!W.paired.sameOutput).map((W)=>N(W.workloadId)),baseOnly:(p.unmatched?.baseOnly??[]).map(N),candOnly:(p.unmatched?.candOnly??[]).map(N)}}function Hn(p){if(!p?.entry)return;if(p.entry.group!==void 0)return p.entry.group;let h=p.entry.task,N=h.lastIndexOf("/");return N===-1?void 0:h.slice(0,N)}function Fr(p,h){return h!==void 0&&p.startsWith(`${h}/`)?p.slice(h.length+1):p}function st(p){if(p.length<2)return;let h=Math.min(...p.map((_)=>_.run.timing.median)),N=new Map;for(let _ of p){let z=Hn(_.workload);if(z===void 0)continue;let V=N.get(z);if(V)V.push(_);else N.set(z,[_])}let W=new Map;for(let _ of p){let z=Hn(_.workload),V=h;if(z!==void 0){let re=N.get(z),J=re.find((pe)=>pe.workload?.baseline);V=J?J.run.timing.median:Math.min(...re.map((pe)=>pe.run.timing.median))}W.set(_,_.run.timing.median/V)}return W}var Br=10,Wr=10,fn=(p)=>yn(String(p));function at(p,h){return[`| ${p.join(" | ")} |`,`|${p.map(()=>"---").join("|")}|`,...h.map((N)=>`| ${N.join(" | ")} |`)]}function vo(p){if(!p?.params)return"";return` (${Object.entries(p.params).map(([N,W])=>`${N}=${W}`).join(", ")})`}function ht(p,h){return fn(o(p,h)+vo(p))}function Zt(p){return`${p.message} (\`${p.code}\`)`}function Ur(p,h){return h.map((N)=>`- **${p}**: ${Zt(N)}`)}function Io(p){let h;for(let N of p){let W=N?.params?Object.keys(N.params):void 0;if(W?.length!==2)return;if(h===void 0)h=W;else if(W.some((_,z)=>_!==h[z]))return}return h}var _r={name:"markdown",async render(p){let h=Cn(p),N=p.git?` \xB7 ${G(p.git)}`:"",W=wt(p);return{text:["# Profile Report","",`Bun ${p.bunVersion} \xB7 ostia ${p.toolVersion} \xB7 ${p.platform.os}/${p.platform.arch} \xB7 ${p.createdAt}${N}`,"",...p.environment?[Ie(p.environment),""]:[],...W?[`> \u26A0 ${W.message}`,""]:[],...p.ab?Oo(p,p.ab,h):[],...Do(p,h),...No(p,h),...Fo(p)].join(`
|
|
17
|
-
`)}}};function Oo(p,h,N){let W=ot(p),_=["## A/B","",Et(h),""];if(W.length>0){let me=Ot(p,h.metric);_.push(...at(["Task","Base","Candidate","Change","p25\u2026p75",...me?[me]:[],"Verdict"],W.map((se)=>{let ce=It(se,h.metric),he=[ht(N.get(se.workloadId),se.workloadId),ce.base,ce.candidate,ce.change,ce.spread];if(me)he.push(ce.also);return he.push(ce.verdict?`**${fn(ce.verdict)}**`:""),he})),"")}let z=Dt(p);if(z.length>0)_.push(...at(["Task","Memory","Base","Candidate","Change","Verdict"],z.map((me)=>{let se=Nt(me);return[ht(N.get(me.run.workloadId),me.run.workloadId),se.reading,se.base,se.candidate,se.change,se.verdict?`**${se.verdict}**`:""]})),"");let V=$t(p);if(V.length>0){_.push(`Threw (${V.length}):`,"");for(let me of V){let se=me.threw.message.split(`
|
|
18
|
-
`)[0].replaceAll("`","'");_.push(`- **${ht(N.get(me.workloadId),me.workloadId)}**: ${Ct(me.threw)}: \`${se}\``)}_.push("")}let re=Ft(p),J=(me,se)=>se.length>0?`${me}: ${se.map(fn).join(", ")}`:void 0;for(let me of[J("Output differs from the base",re.outputDiffers),vt(h),J("Base only",re.baseOnly),J("Candidate only",re.candOnly)])if(me)_.push(me,"");let pe=W.flatMap((me)=>Ur(o(N.get(me.workloadId),me.workloadId),me.warnings));if(pe.length>0)_.push(...pe,"");return _.push(`**${At(h)}**`,""),_}function Do(p,h){let N=et(p),W=nt(p),_=rt(p),z=[...tt(p,N).map((ce)=>({id:ce.id,workload:ce,status:"skipped"})),...W.map((ce)=>({id:ce.workloadId,workload:h.get(ce.workloadId),status:"no samples"}))];if(N.length===0&&z.length===0)return[];let V=["## Timing",""],re=N.map((ce)=>({run:ce,workload:h.get(ce.workloadId)})),J=new Map,pe=[];for(let ce of re){let he=Hn(ce.workload);if(he===void 0)pe.push(ce);else if(J.has(he))J.get(he).push(ce);else J.set(he,[ce])}let me=[];for(let[ce,he]of J){let Ue=Io(he.map((ge)=>ge.workload));if(Ue)me.push({group:ce,keys:Ue,rows:he});else pe.push(...he)}if(pe.length>0||z.length>0){let ce=st(re),he=[],Ue=new Map(pe.map((ge)=>[ge,ne(ge.run)]));if([...Ue.values()].some(Boolean))he.push({header:"User/Sys",cell:(ge)=>{let Ve=Ue.get(ge);return Ve?Oe(Ve):"-"}});if(pe.some((ge)=>ge.run.instructions))he.push({header:"Instr/call",cell:(ge)=>ge.run.instructions?H(ge.run.instructions.median):"-"});for(let ge of Rt(_))he.push({header:ge.header,cell:(Ve)=>ge.cell(Ve.run.workloadId)??"-"});if(ce)he.push({header:"Relative",cell:(ge)=>Ae(ce.get(ge),!!ge.workload?.baseline)});V.push(...at(["Task","Median","Spread (p75\u2026p99)","Mean \xB1 SD","Range","MAD",...he.map((ge)=>ge.header)],[...pe.map((ge)=>{let Ve=ge.run.timing,_e=S(Ve.median);return[ht(ge.workload,ge.run.workloadId),e(Ve.median,_e),ee(Ve.p75,Ve.p99,_e),`${e(Ve.mean,_e)} \xB1 ${e(Ve.stddev,_e)}`,ee(Ve.min,Ve.max,_e),e(Ve.mad,_e),...he.map((fe)=>fe.cell(ge))]}),...z.map(({id:ge,workload:Ve,status:_e})=>[ht(Ve,ge),`- ${_e}`,"-","-","-","-",...he.map(()=>"-")])]),"")}for(let{group:ce,keys:[he,Ue],rows:ge}of me){let Ve=[],_e=[],fe=new Map;for(let{run:He,workload:Ye}of ge){let qe=Ye.params[he],Ke=Ye.params[Ue];if(!Ve.includes(qe))Ve.push(qe);if(!_e.includes(Ke))_e.push(Ke);fe.set(`${qe} ${Ke}`,He.timing.median)}V.push(`### ${fn(ce)} (${fn(he)} \xD7 ${fn(Ue)})`,"",...at([`${fn(he)} \\ ${fn(Ue)}`,..._e.map(fn)],Ve.map((He)=>[fn(He),..._e.map((Ye)=>{let qe=fe.get(`${He} ${Ye}`);return qe===void 0?"-":e(qe)})])),"")}let se=[...N,...W].flatMap((ce)=>Ur(o(h.get(ce.workloadId),ce.workloadId),ft(ce,_)));if(se.length>0)V.push("### Warnings","",...se,"");return V}function No(p,h){let N=[];for(let W of p.measurements){if(W.phase!=="cpu"&&W.phase!=="heap")continue;let _=o(h.get(W.workloadId),W.workloadId);N.push(W.phase==="cpu"?`## CPU capture - ${_}`:`## Heap snapshot - ${_}`,"",`instrumented, diagnostic wall ${ve(W.diagnosticWallNs??0)}ms`,"",...W.phase==="cpu"?Eo(W):Ao(W));let z=[...W.artifacts.map((V)=>`- artifact: \`${V.path}\``),...W.warnings.map((V)=>`- ! ${Zt(V)}`)];if(z.length>0)N.push(...z,"")}return N}function Eo(p){let{cpu:h}=p;if(!h)return[];let N=[`origin: \`${h.origin}\`, interval: ${h.samplingIntervalUs}\xB5s, samples: ${te(h)}`,"",...at(["Self %","Self (ms)","Total (ms)","Frame"],Ce(h,Br).map((W)=>[`${W.pct}%`,g(W.selfUs),g(W.totalUs),fn(F(W.frame))])),""];if(p.jit){let W=p.jit.tiers;N.push(`JIT tiers: LLInt ${W.llint} \xB7 Baseline ${W.baseline} \xB7 DFG ${W.dfg} \xB7 FTL ${W.ftl}`,"")}return N}function Ao(p){let{heap:h}=p;if(!h)return[];return[$e(h),"",...at(["Count","Type"],h.typeCounts.slice(0,Wr).map((N)=>[String(N.count),fn(N.type)])),""]}function Fo(p){let h=it(p);if(h.length===0)return[];let N=["## Comparisons",""],W=xt(p);if(W)N.push(`${W}.`,"");let _=[];for(let{row:z,cmp:V}of h){if(z.verdict==="missing-base"||z.verdict==="missing-cand"){_.push(`- \`${fn(z.task)}\`: ${St(z.verdict)}`);continue}if(N.push(`### ${z.pass===!1?"\u2717":"\u2713"} ${z.task}`,""),z.renamedFrom)N.push(`- renamed from \`${fn(z.renamedFrom.task)}\``);if(z.timing){let{baseMedian:J,candMedian:pe,medianDeltaPct:me,ci95:se,pValue:ce}=z.timing,he=V?.thresholds.alpha,Ue=z.verdict==="unchanged"&&ce!==void 0&&he!==void 0&&ce>=he?"~":"",ge=S(Math.max(J,pe)),Ve=[`n=${z.timing.candSamples}`];if(se)Ve.push(`95% CI [${r(se[0])}, ${r(se[1])}]`);if(ce!==void 0)Ve.push(`p=${ce.toFixed(4)}`);Ve.push(`threshold ${z.timing.thresholdPct.toFixed(1)}%`),N.push(`- timing: ${e(J,ge)} \u2192 ${e(pe,ge)}, ${Ue}${r(me)} median, ${Ve.join(", ")} (**${z.verdict}**)`)}let re=Tt(z);if(re.length>0)N.push(`- memory: ${re.join(", ")}`);if(V){for(let J of kt(V,Br))N.push(`- frame \`${fn(J.name)}\`: ${r(J.deltaPct)} self-time (${g(J.baseSelfUs)}ms \u2192 ${g(J.candSelfUs)}ms)`);for(let J of Mt(V,Wr))N.push(`- heap \`${fn(J.type)}\`: ${r(J.deltaPct)} count (${J.baseCount} \u2192 ${J.candCount})`);for(let J of Pt(V))N.push(`- ! ${Zt(J)}`)}N.push("")}if(_.length>0)N.push("### Not compared","",..._,"");return N}var Bo=15;function Wo(p,h,N){return`${p.replace(/"/g,"'")} (self ${g(h)}ms, total ${g(N)}ms)`}function Uo(p,h,N,W){let _=[];if(W<=0)return _;for(let z=0;z<h;z++){if(z===N)continue;let V=p[z];if(_.length===W&&V<=p[_[W-1]])continue;let re=_.length;while(re>0&&p[_[re-1]]<V)re--;if(_.splice(re,0,z),_.length>W)_.pop()}return _}var jr={name:"mermaid",async render(p,h={}){let N=h.topN??Bo;return Xn(p,h,"mermaid.md",({cpu:W})=>{let{nodes:_,frames:z}=W,V=Zn(W),{selfUs:re,totalUs:J}=$r(W,V),{parentIx:pe}=V,me=V.roots[0]??-1,se=new Set(me!==-1?[me]:[]);for(let Ue of Uo(re,V.count,me,N)){let ge=[];for(let Ve=Ue;Ve!==-1;Ve=pe[Ve])ge.push(Ve);for(let Ve=ge.length-1;Ve>=0;Ve--)se.add(ge[Ve])}let ce=(Ue)=>`n${_[Ue].id}`,he=["graph TD"];for(let Ue of se){let ge=F(z[_[Ue].frameIx]);he.push(` ${ce(Ue)}["${Wo(ge,re[Ue],J[Ue])}"]`)}for(let Ue of se){let ge=pe[Ue];if(ge!==-1&&se.has(ge))he.push(` ${ce(ge)} --> ${ce(Ue)}`)}return`${he.join(`
|
|
19
|
-
`)}
|
|
20
|
-
`})}};var R=2;function tn(p){return Number.isFinite(p)?Number(p.toPrecision(6)):p}function Lr(p){return{base:Math.round(p.baseBytes),cand:Math.round(p.candBytes),verdict:p.verdict,floor:Math.round(p.floorBytes)}}function er(p){return p.map((h)=>h.data?{code:h.code,data:h.data}:{code:h.code})}function nr(p,h){if(h?.entry?.group!==void 0)p.group=h.entry.group;if(h?.description!==void 0)p.description=h.description;if(h?.groupDescription!==void 0)p.groupDescription=h.groupDescription;if(h?.params!==void 0)p.params=h.params}function Hr(p,h){if(!p?.timing)return;let N={...h?.timing&&{baseMedian:tn(h.timing.baseMedian)},medianPct:tn(p.timing.medianDeltaPct),meanPct:tn(p.timing.meanDeltaPct),verdict:p.timing.verdict,pass:p.verdict==="pass",effectiveTimingPct:tn(p.thresholds.effectiveTimingPct),matched:!0};if(p.timing.ci95)N.ci95=[tn(p.timing.ci95[0]),tn(p.timing.ci95[1])];if(p.timing.pValue!==void 0)N.pValue=tn(p.timing.pValue);if(h?.renamedFrom)N.renamedFrom=h.renamedFrom.task;return N}function Vr(p,h,N,W,_,z,V){let re={event:"run",protocolVersion:R,schemaVersion:p.schemaVersion,workloadId:h.id,task:o(h,h.id),...N,batch:1,warnings:er(W)};if(nr(re,h),V!==void 0)re.noiseFloorPct=tn(V);let J=Hr(_,z);if(J)re.delta=J;return re}function _o(p){let h=Cn(p),N=p.environment?.noise.floorPct,W=(_e)=>({run:_e,workload:h.get(_e.workloadId)}),_=et(p).map(W),z=st(_),V=[..._,...ot(p).map(W)],re=new Map((p.comparisons??[]).map((_e)=>[_e.candidateMeasurementId,_e])),J=new Map(it(p).map(({row:_e})=>[_e.comparisonId,_e])),pe=(_e)=>_e&&J.get(_e.id),me=rt(p),se=new Map;for(let _e of p.measurements){if(_e.phase!=="cpu"||_e.warnings.length===0)continue;let fe=se.get(_e.workloadId)??[];se.set(_e.workloadId,[...fe,..._e.warnings])}let ce=(_e,fe)=>[..._e.warnings,...se.get(_e.workloadId)??[],...me.get(_e.workloadId)?.warnings??[],...fe?.warnings??[]],he=tt(p,V.map((_e)=>_e.run)).map((_e)=>Vr(p,_e,{skipped:!0},re.get(_e.id)?.warnings??[],re.get(_e.id),pe(re.get(_e.id)),N)),Ue=nt(p).flatMap((_e)=>{let fe=h.get(_e.workloadId);if(!fe)return[];let He=re.get(_e.id);return Vr(p,fe,{samples:0},ce(_e,He),He,pe(He),N)}),ge=V.map((_e)=>{let{run:fe,workload:He}=_e,Ye=fe.timing,qe=re.get(fe.id),Ke={event:"run",protocolVersion:R,schemaVersion:p.schemaVersion,workloadId:fe.workloadId,task:o(He,fe.workloadId),unit:"ns",samples:Ye.samples.length,batch:Ye.batch??1,mean:tn(Ye.mean),median:tn(Ye.median),stddev:tn(Ye.stddev),stddevPct:tn(Ye.mean===0?0:Ye.stddev/Ye.mean*100),min:tn(Ye.min),max:tn(Ye.max),warnings:er(ce(fe,qe))};Ke.p75=tn(Ye.p75),Ke.p99=tn(Ye.p99),Ke.mad=tn(Ye.mad);let Ze=ne(fe);if(Ze)Ke.userNs=tn(Ze.userNs),Ke.systemNs=tn(Ze.systemNs);let mn=me.get(fe.workloadId),Nn=mn?.retained??fe.paired?.retained?.candBytes;if(Nn!==void 0)Ke.retainedBytesPerOp=Math.round(Nn);let En=mn?.peak??fe.paired?.peak?.candBytes;if(En!==void 0)Ke.peakBytes=Math.round(En);let An=fe.instructions?.median??fe.paired?.instructions?.candMedian;if(An!==void 0)Ke.instructions=Math.round(An);nr(Ke,He);let $n=z?.get(_e);if($n!==void 0)Ke.relative=tn($n);if(He?.baseline)Ke.baseline=!0;if(N!==void 0)Ke.noiseFloorPct=tn(N);let Fn=Hr(qe,pe(qe));if(Fn)Ke.delta=Fn;let Ge=fe.paired;if(Ge)Ke.paired={baseMedian:tn(Ge.baseMedianNs),medianRatio:tn(Ge.medianRatio),ratioP25:tn(Ge.ratioP25),ratioP75:tn(Ge.ratioP75),rounds:Ge.rounds,verdict:Ge.verdict,...Ge.flagged&&{flagged:Ge.flagged},...Ge.confirmed!==void 0&&{confirmed:Ge.confirmed},...Ge.repeats&&{repeats:Ge.repeats.map((on)=>tn(O(on,p.ab?.metric??"time")?.medianRatio??Number.NaN))},...Ge.instructions&&{instructions:{baseMedian:Math.round(Ge.instructions.baseMedian),medianRatio:tn(Ge.instructions.medianRatio),ratioP25:tn(Ge.instructions.ratioP25),ratioP75:tn(Ge.instructions.ratioP75)}},sameOutput:Ge.sameOutput,...Ge.suiteChanged&&{suiteChanged:!0},...Ge.retained&&{retained:Lr(Ge.retained)},...Ge.peak&&{peak:Lr(Ge.peak)}};return Ke}),Ve=$t(p).map((_e)=>{let fe=h.get(_e.workloadId),He={event:"run",protocolVersion:R,schemaVersion:p.schemaVersion,workloadId:_e.workloadId,task:o(fe,_e.workloadId),batch:1,warnings:er(_e.warnings)};if(nr(He,fe),N!==void 0)He.noiseFloorPct=tn(N);return He.threw=_e.threw,He});return[...ge,...Ue,...Ve,...he]}function jo(p){if(!p.unmatched)return[];let h=(N,W)=>({event:"unmatched",protocolVersion:R,workloadId:N.id,task:o(N,N.id),side:W});return[...p.unmatched.baseOnly.map((N)=>h(N,"base")),...p.unmatched.candOnly.map((N)=>h(N,"cand"))]}function Lo(p){return p===0?"pass":p===1?"fail":"error"}function Vo(p,h){let N=h.command==="ab"&&p.ab?{...p.ab,effectiveTimingPct:p.ab.thresholdPct}:p.comparisonSummary,W=(h.unmatched?.baseOnly.length??0)+(h.unmatched?.candOnly.length??0),_={event:"summary",protocolVersion:R,command:h.command,matched:N?.matched??0,regressed:N?.regressed??0,improved:N?.improved??0,unchanged:N?.unchanged??0,unmatched:W,geomeanPct:N?.geomeanPct!==void 0?N.geomeanPct:null,effectiveTimingPct:tn(N?.effectiveTimingPct??0),verdict:Lo(h.exitCode),exitCode:h.exitCode};if(h.command==="ci"){if(_.cached=h.cached??0,_.executed=h.executed??0,_.failed=h.failed??0,_.missingBaseline=h.missingBaseline??0,h.baseline)_.baseline=h.baseline}if(h.command==="ab"&&p.ab){if(_.base=p.ab.base,_.metric=p.ab.metric,_.geomeanThresholdPct=p.ab.geomeanThresholdPct,_.unconfirmed=p.ab.unconfirmed,_.outputDiffers=p.ab.outputDiffers,p.ab.notComparable!==void 0)_.notComparable=p.ab.notComparable;if(p.ab.threw!==void 0)_.threw=p.ab.threw;if(p.ab.newSuites?.length)_.newSuites=p.ab.newSuites;if(p.ab.memory)_.memory=p.ab.memory}if(p.comparisonSummary?.driftPct!==void 0&&h.command!=="ab")_.driftPct=tn(p.comparisonSummary.driftPct);if(p.environment)_.noiseFloorPct=tn(p.environment.noise.floorPct);if(h.baseGit||h.candGit)_.git={...h.baseGit&&{base:h.baseGit},...h.candGit&&{cand:h.candGit}};if(h.exportedTo)_.exportedTo=h.exportedTo;return _}var Gr={name:"minimal",async render(p,h={}){let N=[..._o(p)];if(h.protocol)N.push(...jo(h.protocol)),N.push(Vo(p,h.protocol));let W=N.map((_)=>JSON.stringify(_));return{text:W.length>0?`${W.join(`
|
|
21
|
-
`)}
|
|
22
|
-
`:""}}};var Ho="https://www.speedscope.app/file-format-schema.json",zr={name:"speedscope",async render(p,h={}){let N=Cn(p);return Xn(p,h,"speedscope.json",(W)=>{let{cpu:_}=W,{nodes:z}=_,V=Zn(_),re=_.samples?.nodeIds??[],J=_.samples?.timeDeltasUs??[],pe=Array(V.count);for(let Ue of V.order){let ge=V.parentIx[Ue],Ve=z[Ue].frameIx;pe[Ue]=ge===-1?[Ve]:[...pe[ge],Ve]}let me=re.map((Ue)=>{let ge=V.indexOf(Ue);return ge===-1?[]:pe[ge]}),se=N.get(W.workloadId),ce=se?.label??se?.command?.join(" ")??se?.entry?.task??"profile",he={$schema:Ho,exporter:"ostia",name:ce,activeProfileIndex:0,shared:{frames:_.frames.map((Ue)=>({name:F(Ue),file:Ue.url,line:Ue.line!==void 0?Ue.line+1:void 0}))},profiles:[{type:"sampled",name:ce,unit:"microseconds",startValue:0,endValue:J.reduce((Ue,ge)=>Ue+ge,0),samples:me,weights:J}]};return`${JSON.stringify(he,null,2)}
|
|
23
|
-
`})}};var Kr=5,Jr=5,Go=10;function rr(p,h){let N=(J)=>J.group!==void 0?" ":"",W=(J)=>Fr(J.label,J.group),_=4;for(let J of h)_=Math.max(_,N(J).length+W(J).length);let z=`${"Task".padEnd(_)} ${p.map((J)=>J.header.padEnd(J.width)).join(" ")}`,V=[z,"-".repeat(z.length)],re;for(let J of h){if(J.group!==void 0&&J.group!==re)V.push(`${J.group}:`);re=J.group;let pe=N(J),me=(pe+W(J)).padEnd(_),se=J.data;if(V.push(se===void 0?`${me} - ${J.status}`:`${me} ${p.map((ce)=>ce.cell(se).padEnd(ce.width)).join(" ")}`),J.warnings.length>0)V.push(`${pe} ! ${J.warnings.map((ce)=>ce.code).join(", ")}`)}return V}function Yr(p){let h=p.flatMap((N)=>N.warnings.map((W)=>` ${N.label}: ${W.message}`));return h.length>0?["","Warnings:",...h]:[]}function tr(p){return{text:`${p.map((h)=>h.trimEnd()).join(`
|
|
24
|
-
`)}
|
|
25
|
-
`}}var qr={name:"table",async render(p){let h=p.environment?[Ie(p.environment),""]:[];if(p.ab)return tr(Ko(p,p.ab,h));let N=et(p),W=nt(p),_=Jo(p);if(N.length===0&&W.length===0&&tt(p,N).length===0)return _.length>0?tr([...h,..._]):{text:`(no timing runs)
|
|
26
|
-
`};let z=[...h,...zo(p,N,W)],V=Yo(p);if(V.length>0)z.push("",...V);if(_.length>0)z.push("",..._);return tr(z)}};function zo(p,h,N){let W=rt(p),_=new Map(h.map((ce)=>[ce.workloadId,ce])),z=new Map(N.map((ce)=>[ce.workloadId,ce])),V=[],re=[];for(let ce of p.workloads){let he=_.get(ce.id),Ue=c(ce),ge=Hn(ce);if(he){let Ve={run:he,workload:ce};re.push(Ve),V.push({label:Ue,group:ge,data:Ve,warnings:ft(he,W)})}else if(z.has(ce.id)){let Ve=ft(z.get(ce.id),W);V.push({label:Ue,group:ge,status:"no samples",warnings:Ve})}else if(ce.skipped)V.push({label:Ue,group:ge,status:"skipped",warnings:[]})}let J=({run:ce})=>S(ce.timing.median),pe=new Map(re.map((ce)=>[ce,ne(ce.run)])),me=st(re),se=[{header:"Median",width:10,cell:(ce)=>e(ce.run.timing.median,J(ce))},{header:"Spread",width:18,cell:(ce)=>ee(ce.run.timing.p75,ce.run.timing.p99,J(ce))},{header:"Range",width:18,cell:(ce)=>ee(ce.run.timing.min,ce.run.timing.max,J(ce))}];if([...pe.values()].some(Boolean))se.push({header:"User/Sys",width:18,cell:(ce)=>{let he=pe.get(ce);return he?Oe(he):""}});if(re.some((ce)=>ce.run.instructions))se.push({header:"Instr/call",width:10,cell:(ce)=>ce.run.instructions?H(ce.run.instructions.median):""});for(let ce of Rt(W))se.push({header:ce.header,width:Math.max(ce.header.length,Go),cell:(he)=>ce.cell(he.run.workloadId)??""});if(me)se.push({header:"Relative",width:8,cell:(ce)=>Ae(me.get(ce),!!ce.workload?.baseline)});return[...rr(se,V),...Yr(V)]}function Ko(p,h,N){let W=Cn(p),_=[...N,`A/B: ${Et(h)}`,""],z=[],V=Ar(p).map(({kind:me,run:se})=>{let ce=W.get(se.workloadId),he=o(ce,se.workloadId),Ue;if(me==="threw"){let ge=Ct(se.threw);z.push({label:he,verdict:ge,message:se.threw.message}),Ue={base:"-",candidate:"-",change:"",spread:"",also:"",verdict:ge}}else Ue=It(se,h.metric);return{label:he,group:Hn(ce),data:Ue,warnings:se.warnings}});if(V.length>0){let me=Ot(p,h.metric);_.push(...rr([{header:"Base",width:10,cell:(se)=>se.base},{header:"Candidate",width:10,cell:(se)=>se.candidate},{header:"Change",width:9,cell:(se)=>se.change},{header:"p25\u2026p75",width:18,cell:(se)=>se.spread},...me?[{header:me,width:8,cell:(se)=>se.also}]:[],{header:"Verdict",width:7,cell:(se)=>se.verdict}],V))}let re=Dt(p);if(re.length>0)_.push("","Memory:",...rr([{header:"Reading",width:11,cell:(me)=>me.reading},{header:"Base",width:10,cell:(me)=>me.base},{header:"Candidate",width:10,cell:(me)=>me.candidate},{header:"Change",width:18,cell:(me)=>me.change},{header:"Verdict",width:7,cell:(me)=>me.verdict}],re.map((me)=>{let se=W.get(me.run.workloadId);return{label:o(se,me.run.workloadId),group:Hn(se),data:Nt(me),warnings:[]}})));let J=Ft(p);if(z.length>0){_.push("",`Threw (${z.length}):`);for(let me of z){let[se,...ce]=me.message.split(`
|
|
27
|
-
`);_.push(` ${me.label}: ${me.verdict}: ${se}`);for(let he of ce)_.push(` ${he}`)}}if(J.outputDiffers.length>0)_.push("",`Output differs from the base (${J.outputDiffers.length}):`,...J.outputDiffers.map((me)=>` ${me}`));let pe=vt(h);if(pe)_.push("",pe);if(J.baseOnly.length>0||J.candOnly.length>0){if(_.push("","Unmatched:"),J.baseOnly.length>0)_.push(` base only: ${J.baseOnly.join(", ")}`);if(J.candOnly.length>0)_.push(` candidate only: ${J.candOnly.join(", ")}`)}return _.push(...Yr(V),"",At(h)),_}function Jo(p){let h=it(p);if(h.length===0)return[];let N=[],W=wt(p);if(W)N.push(`\u26A0 ${W.message}`,"");let _=xt(p);if(_)N.push(_,"");let z=[],V=[];for(let{row:re,cmp:J}of h){if(re.verdict==="missing-base"||re.verdict==="missing-cand"){V.push(` ${re.task}: ${St(re.verdict)}`);continue}if(N.push(`${re.pass===!1?"\u2717":"\u2713"} ${re.task}`),re.renamedFrom)N.push(` renamed from ${re.renamedFrom.task}`);if(re.timing){let{baseMedian:se,candMedian:ce,medianDeltaPct:he,ci95:Ue,pValue:ge}=re.timing,Ve=S(Math.max(se,ce)),_e=`${e(se,Ve)} -> ${e(ce,Ve)}`;if(Ue&&ge!==void 0){let fe=ge<0.001?"p<0.001":`p=${ge.toFixed(3)}`;N.push(` timing: ${_e}, ${r(he)} median, 95% CI [${r(Ue[0])}, ${r(Ue[1])}], ${fe} (${re.verdict})`)}else N.push(` timing: ${_e}, ${r(he)} median (${re.verdict})`)}let pe=Tt(re,"->");if(pe.length>0)N.push(` memory: ${pe.join(", ")}`);if(!J)continue;for(let se of kt(J,Kr))N.push(` frame ${se.name}: ${r(se.deltaPct)} self-time (${g(se.baseSelfUs)}ms -> ${g(se.candSelfUs)}ms)`);for(let se of Mt(J,Jr))N.push(` heap ${se.type}: ${r(se.deltaPct)} count (${se.baseCount} -> ${se.candCount})`);let me=Pt(J);if(me.length>0){N.push(` ! ${me.map((se)=>se.code).join(", ")}`);for(let se of me)z.push(` ${re.task}: ${se.message}`)}}if(V.length>0)N.push("","Not compared:",...V);if(z.length>0)N.push("","Comparison warnings:",...z);return N}function Yo(p){let h=Cn(p),N=[];for(let W of p.measurements){if(W.phase!=="cpu"&&W.phase!=="heap")continue;let _=h.get(W.workloadId),z=o(_,W.workloadId);if(W.phase==="cpu")if(W.cpu){N.push(`CPU capture - ${z} (instrumented, ${W.cpu.samplingIntervalUs}\xB5s interval, ${te(W.cpu)} samples, diagnostic wall ${ve(W.diagnosticWallNs??0)}ms)`);for(let V of Ce(W.cpu,Kr))N.push(` ${V.pct.padStart(5)}% ${g(V.selfUs).padStart(8)}ms self ${V.frame?.name??"?"}`)}else N.push(`CPU capture - ${z} (instrumented, no evidence captured)`);else if(W.heap){N.push(`Heap snapshot - ${z} (instrumented, ${$e(W.heap)})`);for(let V of W.heap.typeCounts.slice(0,Jr))N.push(` ${String(V.count).padStart(6)} ${V.type}`)}else N.push(`Heap snapshot - ${z} (instrumented, no evidence captured)`);for(let V of W.artifacts)N.push(` artifact: ${V.path}`);for(let V of W.warnings)N.push(` ! ${V.message}`)}return N}var b={table:qr,json:Ir,markdown:_r,jsonl:Or,minimal:Gr,collapsed:Cr,mermaid:jr,speedscope:zr,cpuprofile:vr};async function xn(p={}){let h=B();if(h.length===0)throw Error("run(): no tasks registered - call group()/task() before run() in the same file.");let N=Bun.main,W;try{W=U(h,p.filter,N)}catch(z){throw Error(`run(): ${z.message}`)}let _=await be(N,W,p);if(!p.quiet){let z=p.format??"table",{text:V}=await b[z].render(_,{});if(V)process.stdout.write(V)}return _}function Mn(p,h){let N=Object.keys(p),W=(_,z)=>{if(_===N.length){kn(z,()=>h(z));return}let V=N[_];for(let re of p[V])W(_+1,{...z,[V]:re})};W(0,{})}function qo(p){return p.startsWith("file://")?p.slice(7):p}function Bt(p,h,N){let W=p.nodes,_=W.length,{frames:z,intern:V}=We(),re=new Map,J=Array(_);for(let fe=0;fe<_;fe++){let He=W[fe],Ye=He.callFrame,qe=V(Ye.functionName,qo(Ye.url)||void 0,Ye.lineNumber>=0?Ye.lineNumber:void 0,Ye.columnNumber>=0?Ye.columnNumber:void 0);J[fe]={id:He.id,frameIx:qe,children:He.children??[]},re.set(He.id,fe)}let pe=new Float64Array(_),me=new Float64Array(_),{samples:se,timeDeltas:ce}=p;for(let fe=0;fe<se.length;fe++){let He=re.get(se[fe]);if(He===void 0)continue;pe[He]+=ce[fe]??0,me[He]+=1}let he=new Int32Array(_).fill(-1);for(let fe=0;fe<_;fe++){let He=W[fe].children;if(!He)continue;for(let Ye of He){let qe=re.get(Ye);if(qe!==void 0)he[qe]=fe}}let Ue=[],ge=[];for(let fe=_-1;fe>=0;fe--)if(he[fe]===-1)ge.push(fe);while(ge.length>0){let fe=ge.pop();Ue.push(fe);let He=W[fe].children;if(!He)continue;for(let Ye of He){let qe=re.get(Ye);if(qe!==void 0&&he[qe]===fe)ge.push(qe)}}let Ve=new Float64Array(_);for(let fe=Ue.length-1;fe>=0;fe--){let He=Ue[fe];Ve[He]+=pe[He];let Ye=he[He];if(Ye>=0)Ve[Ye]+=Ve[He]}let _e=new Map;for(let fe=0;fe<_;fe++)Le(_e,J[fe].frameIx,pe[fe],Ve[fe],me[fe]);return{origin:h,samplingIntervalUs:N,frames:z,nodes:J,totals:je(_e),samples:{nodeIds:p.samples,timeDeltasUs:p.timeDeltas}}}async function Qr(p,h={}){let N=h.intervalUs??Je,{Session:W}=await import("inspector/promises"),_=new W;_.connect();try{await _.post("Profiler.enable"),await _.post("Profiler.setSamplingInterval",{interval:N});let z=Bun.nanoseconds();await _.post("Profiler.start");let V=await p(),{profile:re}=await _.post("Profiler.stop"),J=Bun.nanoseconds()-z,pe=Bt(re,"inspector",N);return{result:V,cpu:pe,diagnosticWallNs:J}}finally{_.disconnect()}}function Qo(p){return p.replace(/[\s"']/g,"\\$&")}function Xo(p,h,N){let W=p[0];if(W&&/(^|[\\/])bun(\.exe)?$/.test(W))return{argv:[W,...h,...p.slice(1)],env:N};let _={...process.env,...N},z=h.map(Qo).join(" ");return{argv:p,env:{..._,BUN_OPTIONS:_.BUN_OPTIONS?`${_.BUN_OPTIONS} ${z}`:z}}}async function Wt(p,h,N){let W=`${p.artifactDir}/${p.fileName}`,{argv:_,env:z}=Xo(p.argv,h,p.env),V=Bun.nanoseconds(),J=await Bun.spawn(_,{cwd:p.cwd,env:z,stdout:"ignore",stderr:"ignore",stdin:"ignore"}).exited,pe=Bun.nanoseconds()-V,me=Bun.file(W);if(!await me.exists())return{diagnosticWallNs:pe,exitCode:J,warnings:[{code:"artifact-missing",message:`Expected ${N.what} at ${W} after exit ${J}, found nothing. The workload's argv[0] must be a \`bun\` binary for ${N.kind} capture.`,data:{artifactPath:W,argv:p.argv}}]};return{diagnosticWallNs:pe,exitCode:J,artifactPath:W,raw:await me.json(),warnings:[]}}async function Xr(p){let{raw:h,...N}=await Wt(p,["--cpu-prof","--cpu-prof-dir",p.artifactDir,"--cpu-prof-name",p.fileName,"--cpu-prof-interval",String(p.intervalUs)],{what:"a .cpuprofile",kind:"CPU"});if(!h)return N;if(h.samples.length===0)N.warnings.push({code:"empty-profile",message:"CPU capture produced zero samples."});return{...N,cpu:Bt(h,"cpu-prof",p.intervalUs)}}function Zr(p){let{node_fields:N,node_types:W}=p.snapshot.meta,_=N.indexOf("type"),z=N.indexOf("self_size"),V=N.length,re=W[0];if(_===-1||z===-1||!Array.isArray(re))return{origin:"heap-prof",typeCounts:[],objectCount:p.snapshot.node_count};let J=re.length,pe=Array(J),me=new Map,se=[],ce=(fe)=>{let He={type:fe,count:0,bytes:0};return se.push(He),He},he=0,Ue=p.nodes,ge=Ue.length;for(let fe=0;fe<ge;fe+=V){let He=Ue[fe+_],Ye=Ue[fe+z]??0;he+=Ye;let qe;if(He>=0&&He<J)qe=pe[He]??=ce(re[He]);else if(qe=me.get(He),qe===void 0)qe=ce(`unknown(${He})`),me.set(He,qe);qe.count++,qe.bytes+=Ye}se.sort((fe,He)=>He.count-fe.count);let Ve=se.slice(0,20).map(({type:fe,count:He,bytes:Ye})=>({type:fe,count:He,retainedBytes:Ye})),_e=se.slice(20);if(_e.length>0)Ve.push({type:"other",count:_e.reduce((fe,He)=>fe+He.count,0),retainedBytes:_e.reduce((fe,He)=>fe+He.bytes,0)});return{origin:"heap-prof",heapSizeBytes:he,objectCount:p.snapshot.node_count,typeCounts:Ve}}async function ei(p){let{raw:h,...N}=await Wt(p,["--heap-prof","--heap-prof-dir",p.artifactDir,"--heap-prof-name",p.fileName],{what:"a heap snapshot",kind:"heap"});return h?{...N,heap:Zr(h)}:N}var Ut=1000;function ae(){return{code:"aborted",message:"Run was cancelled before it finished; this document holds whatever measurements had already completed."}}async function Pe(p){Kn("time",p);let h=i({samples:p.samples??null,budgetMs:p.budgetMs??null,minSamples:p.minSamples??null,warmup:p.warmup??null,cpu:p.cpu??!1,heap:p.heap??!1,cpuIntervalUs:p.cpuIntervalUs??Ut}),N=`${p.outDir??Vn}/artifacts`,W=p.noiseCheck===!1?void 0:Te(),_=W?Se(W):void 0,z=[],V=[],re=p.commands.map((se)=>{let ce=typeof se==="string"||Array.isArray(se)?{command:se}:se,he=Array.isArray(ce.command)?ce.command:X(ce.command),Ue=ce.prepare??p.prepare,ge=ce.timeSource??p.timeSource,Ve=de(he,ce.label??(Array.isArray(ce.command)?void 0:ce.command),{prepare:Ue,timeSource:ge});return{argv:he,workload:Ve,prepare:Ue,timeSource:ge,timeoutMs:ce.timeoutMs??p.timeoutMs,ignoreExitCodes:ce.ignoreExitCodes??p.ignoreExitCodes}}),J=(p.interleave??!0)&&re.length>1,pe=re.map((se)=>zt({argv:se.argv,cwd:p.cwd,env:p.env,samples:p.samples,budgetMs:p.budgetMs,minSamples:p.minSamples,warmup:p.warmup,prepare:se.prepare,timeSource:se.timeSource,timeoutMs:se.timeoutMs,ignoreExitCodes:se.ignoreExitCodes,signal:p.signal})),me=async(se)=>{let{argv:ce,workload:he,prepare:Ue}=re[se];z.push(he);let ge=pe[se].result(),Ve=j({workload:he,configFingerprint:h,trials:ge.trials,timing:ge.timing,warnings:_&&V.length===0?[...ge.warnings,_]:ge.warnings,interleaved:J?!0:void 0});if(V.push(Ve),!p.signal?.aborted)V.push(...await Zo({workload:he,argv:ce,timingMeasurementId:Ve.id,cfgFp:h,opts:p,artifactDir:N,prepare:Ue}))};if(J){for(let ce of pe)await ce.warmup();let se=!0;while(se){se=!1;for(let ce of pe)if(await ce.step())se=!0}for(let ce=0;ce<re.length;ce++)await me(ce)}else for(let se=0;se<re.length;se++)await Kt(pe[se]),await me(se);if(p.signal?.aborted&&V.length>0){let se=V[V.length-1];se.warnings=[...se.warnings,ae()]}return C(W),s(z,V,W)}async function Zo({workload:p,argv:h,timingMeasurementId:N,cfgFp:W,opts:_,artifactDir:z,prepare:V}){let re=[],J=async(me)=>{if(V)await Me(V,{phase:me,index:0},{cwd:_.cwd,env:_.env})},pe=(me)=>({argv:h,cwd:_.cwd,env:_.env,artifactDir:z,fileName:`${N}-${me}`});if(_.cpu){await J("cpu");let me=await Xr({...pe("cpu.cpuprofile"),intervalUs:_.cpuIntervalUs??Ut});re.push(await ni({workload:p,phase:"cpu",configFingerprint:W,artifactKind:"cpuprofile",...me}))}if(_.heap){await J("heap");let me=await ei(pe("heap.heapsnapshot"));re.push(await ni({workload:p,phase:"heap",configFingerprint:W,artifactKind:"heapsnapshot",...me}))}return re}async function ni({artifactPath:p,artifactKind:h,...N}){let W=k({...N,artifacts:[]});if(p)W.artifacts=[await wn(W.id,h,p)];return W}async function Rn(p,h={}){if(h.name!==void 0&&(typeof h.name!=="string"||!h.name))throw TypeError("profile(): name must be a non-empty string");let N=bn(p,h.name),W=h.cpuIntervalUs??Ut,_=i({intervalUs:W,origin:h.origin??"inspector"}),z=(J,pe)=>({result:J,measurement:pe,document:s([N],[pe])});if(h.signal?.aborted){let J=Bun.nanoseconds(),pe=await p();return z(pe,k({workload:N,phase:"cpu",configFingerprint:_,diagnosticWallNs:Bun.nanoseconds()-J,warnings:[ae()],artifacts:[]}))}let V=h.origin==="jsc"?await ze(p,{intervalUs:W}):{...await Qr(p,{intervalUs:W}),jit:void 0},re=V.cpu.samples?.nodeIds.length===0?[{code:"empty-profile",message:"In-process capture produced zero samples."}]:[];return z(V.result,k({workload:N,phase:"cpu",configFingerprint:_,diagnosticWallNs:V.diagnosticWallNs,cpu:V.cpu,jit:V.jit,warnings:re,artifacts:[]}))}function Tn(p){return p}
|
|
28
|
-
export{M,Xe,Qe,we,u,oe,dn,A,en,ln,ye,L,K,q,pn,ke,Y,nn,ie,Z,ae,Pe,Pn,R,b,xn,Mn,Rn,Tn};
|