ostia 0.2.12 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +50 -358
- package/docs/agent-protocol.md +210 -0
- package/docs/cli.md +1196 -0
- package/docs/config.md +233 -0
- package/docs/document-schema.md +224 -0
- package/docs/library.md +421 -0
- package/docs/preload-recipes.md +169 -0
- package/docs/statistics.md +218 -0
- package/index.d.ts +923 -679
- package/package.json +16 -14
- package/src/ab/ab-runner.ts +487 -0
- package/src/ab/index.ts +1160 -0
- package/src/baseline/index.ts +69 -0
- package/src/bench/index.ts +516 -0
- package/src/bench/projects.ts +43 -0
- package/src/bench/range.ts +27 -0
- package/src/bench/registry.ts +426 -0
- package/src/bench/run-tasks.ts +179 -0
- package/src/bench/run.ts +52 -0
- package/src/bench/runner.ts +162 -0
- package/src/bench/support.ts +161 -0
- package/src/bench/sweep.ts +41 -0
- package/src/cache/fingerprint.ts +62 -0
- package/src/cache/store.ts +40 -0
- package/src/capture/bunflags.ts +92 -0
- package/src/capture/cpu-parse.ts +131 -0
- package/src/capture/cpu.ts +47 -0
- package/src/capture/frames.ts +60 -0
- package/src/capture/heap-parse.ts +111 -0
- package/src/capture/heap.ts +36 -0
- package/src/capture/inspector.ts +47 -0
- package/src/capture/jsc-parse.ts +167 -0
- package/src/capture/jsc.ts +35 -0
- package/src/capture/sampling.ts +5 -0
- package/src/ci/index.ts +440 -0
- package/src/cli/flags.ts +263 -0
- package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
- package/src/cli/main.ts +18 -0
- package/src/cli/output.ts +179 -0
- package/src/cli/run.ts +1110 -0
- package/src/compare/index.ts +624 -0
- package/src/config/env.ts +13 -0
- package/src/config/index.ts +283 -0
- package/src/config/validate.ts +273 -0
- package/src/errors.ts +8 -0
- package/src/format.ts +35 -0
- package/src/glob.ts +45 -0
- package/src/index.ts +60 -0
- package/src/ir/cpu.ts +10 -0
- package/src/ir/defined.ts +12 -0
- package/src/ir/document.ts +491 -0
- package/src/ir/fp.ts +28 -0
- package/src/ir/git.ts +37 -0
- package/src/ir/types.ts +615 -0
- package/src/measure/alloc.ts +56 -0
- package/src/measure/cpu.ts +91 -0
- package/src/measure/environment.ts +38 -0
- package/src/measure/inprocess.ts +191 -0
- package/src/measure/instructions.ts +139 -0
- package/src/measure/loop.ts +64 -0
- package/src/measure/noise.ts +55 -0
- package/src/measure/paired.ts +304 -0
- package/src/measure/peak.ts +201 -0
- package/src/measure/timing.ts +263 -0
- package/src/profile.ts +110 -0
- package/src/renderers/collapsed.ts +42 -0
- package/src/renderers/cpu-tree.ts +191 -0
- package/src/renderers/cpuprofile.ts +43 -0
- package/src/renderers/format.ts +132 -0
- package/src/renderers/index.ts +37 -0
- package/src/renderers/json.ts +10 -0
- package/src/renderers/jsonl.ts +19 -0
- package/src/renderers/markdown.ts +543 -0
- package/src/renderers/mermaid.ts +90 -0
- package/src/renderers/minimal.ts +602 -0
- package/src/renderers/paired.ts +223 -0
- package/src/renderers/relative.ts +60 -0
- package/src/renderers/select.ts +264 -0
- package/src/renderers/speedscope.ts +73 -0
- package/src/renderers/terminal.ts +470 -0
- package/src/renderers/types.ts +27 -0
- package/src/spawn/index.ts +387 -0
- package/src/stats/bootstrap.ts +151 -0
- package/src/stats/index.ts +144 -0
- package/src/stats/mannwhitney.ts +82 -0
- package/src/time.ts +337 -0
- package/src/version.ts +3 -0
- package/ab-runner.ts +0 -8
- package/chunk-05jfst35.js +0 -28
- package/chunk-1g1x9zz2.js +0 -15
- package/chunk-23g2rwrn.js +0 -3
- package/chunk-468h5412.js +0 -25
- package/chunk-4esjfc2m.js +0 -2
- package/chunk-ct2xsezd.js +0 -14
- package/cli.js +0 -3
- package/index.js +0 -2
- package/runner.ts +0 -7
package/src/ab/index.ts
ADDED
|
@@ -0,0 +1,1160 @@
|
|
|
1
|
+
import {
|
|
2
|
+
appendFileSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
lstatSync,
|
|
5
|
+
mkdirSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
realpathSync,
|
|
8
|
+
renameSync,
|
|
9
|
+
statSync,
|
|
10
|
+
symlinkSync,
|
|
11
|
+
unlinkSync,
|
|
12
|
+
utimesSync,
|
|
13
|
+
writeFileSync,
|
|
14
|
+
} from "node:fs";
|
|
15
|
+
import { mkdir } from "node:fs/promises";
|
|
16
|
+
import { relative, sep } from "node:path";
|
|
17
|
+
|
|
18
|
+
import { resolveSuiteLaunches } from "../bench/projects.ts";
|
|
19
|
+
import {
|
|
20
|
+
absolutePath,
|
|
21
|
+
assertSuiteExists,
|
|
22
|
+
captureRunEnvironment,
|
|
23
|
+
median,
|
|
24
|
+
PEAK_MEM_PROCESSES,
|
|
25
|
+
peakHiddenWarning,
|
|
26
|
+
removeDir,
|
|
27
|
+
runRunnerProcess,
|
|
28
|
+
stampRunWarnings,
|
|
29
|
+
uniqueTmpDir,
|
|
30
|
+
} from "../bench/support.ts";
|
|
31
|
+
import { nowMs, processEnv } from "../config/env.ts";
|
|
32
|
+
import { type BenchProject, DEFAULT_OUT_DIR } from "../config/index.ts";
|
|
33
|
+
import { errorMessage, OstiaUsageError } from "../errors.ts";
|
|
34
|
+
import { definedFields } from "../ir/defined.ts";
|
|
35
|
+
import { createDocument, loadDocument } from "../ir/document.ts";
|
|
36
|
+
import { fp } from "../ir/fp.ts";
|
|
37
|
+
import type {
|
|
38
|
+
AbSummary,
|
|
39
|
+
Measurement,
|
|
40
|
+
PairedEvidence,
|
|
41
|
+
ProfileDocument,
|
|
42
|
+
Workload,
|
|
43
|
+
} from "../ir/types.ts";
|
|
44
|
+
import { instructionCounter } from "../measure/instructions.ts";
|
|
45
|
+
import {
|
|
46
|
+
comparable,
|
|
47
|
+
memoryChange,
|
|
48
|
+
metricRatios,
|
|
49
|
+
pairedEvidence,
|
|
50
|
+
type Side,
|
|
51
|
+
} from "../measure/paired.ts";
|
|
52
|
+
import { assertSamplingOptions } from "../measure/timing.ts";
|
|
53
|
+
import { computeTimingStats } from "../stats/index.ts";
|
|
54
|
+
import type {
|
|
55
|
+
AbMemoryResult,
|
|
56
|
+
AbMemoryTask,
|
|
57
|
+
AbRunnerOpts,
|
|
58
|
+
AbRunnerPlan,
|
|
59
|
+
AbRunnerProgress,
|
|
60
|
+
} from "./ab-runner.ts";
|
|
61
|
+
|
|
62
|
+
/** What `ab()` is doing, for `onProgress`. Counts start at 1. */
|
|
63
|
+
export type AbProgress =
|
|
64
|
+
| { phase: "setup"; command: string }
|
|
65
|
+
| {
|
|
66
|
+
phase: "measure";
|
|
67
|
+
suite: number;
|
|
68
|
+
suites: number;
|
|
69
|
+
file: string;
|
|
70
|
+
/** Each suite runs twice, once with each side first. */
|
|
71
|
+
pass: number;
|
|
72
|
+
passes: number;
|
|
73
|
+
task: number;
|
|
74
|
+
tasks: number;
|
|
75
|
+
label: string;
|
|
76
|
+
}
|
|
77
|
+
| { phase: "confirm"; repeat: number; repeats: number; label: string }
|
|
78
|
+
| { phase: "memory"; run: number; runs: number; side: Side; label: string };
|
|
79
|
+
|
|
80
|
+
export interface AbOptions {
|
|
81
|
+
suites: string[];
|
|
82
|
+
/** Git ref whose committed tree is the base side (default: `"HEAD"`); the
|
|
83
|
+
* candidate is the working tree, uncommitted changes included. */
|
|
84
|
+
base?: string;
|
|
85
|
+
/** Rounds per workload, each one base batch and one candidate batch of
|
|
86
|
+
* about 10ms (default: 15). */
|
|
87
|
+
rounds?: number;
|
|
88
|
+
/** What to judge each round by: the candidate/base time ratio
|
|
89
|
+
* (`"time"`, the default), or the ratio of instructions each side retired
|
|
90
|
+
* per call (`"instructions"`), which a loaded machine barely moves, so a
|
|
91
|
+
* lower `thresholdPct` holds. Instructions are recorded either way where
|
|
92
|
+
* the machine counts them (see `PairedEvidence.instructions`); asking to
|
|
93
|
+
* judge by them where it can't throws an `OstiaUsageError`. */
|
|
94
|
+
metric?: "time" | "instructions";
|
|
95
|
+
/** Flag a workload whose median candidate/base ratio moves past this many
|
|
96
|
+
* percent (default: 10). */
|
|
97
|
+
thresholdPct?: number;
|
|
98
|
+
/** Fail when the geometric mean of all workloads' ratios is slower than
|
|
99
|
+
* this many percent (default: 1.5): a broad slowdown too small to flag any
|
|
100
|
+
* one workload. */
|
|
101
|
+
geomeanThresholdPct?: number;
|
|
102
|
+
/** Fresh-process repeats of each flagged workload, which only counts when
|
|
103
|
+
* every repeat flags it the same way (default: 2; 0 trusts the first). */
|
|
104
|
+
confirm?: number;
|
|
105
|
+
filter?: string;
|
|
106
|
+
preload?: string[];
|
|
107
|
+
bunFlags?: string[];
|
|
108
|
+
/** Per-suite `preload` / `bunFlags`; see `BenchOptions.projects`. */
|
|
109
|
+
projects?: BenchProject[];
|
|
110
|
+
outDir?: string;
|
|
111
|
+
cwd?: string;
|
|
112
|
+
noiseCheck?: boolean;
|
|
113
|
+
/** Also compare each side's retained heap per call (see
|
|
114
|
+
* `bench({ alloc })`) and how far its first call raises RSS (see
|
|
115
|
+
* `bench({ peakMem })`), each the median of 3 fresh processes per side.
|
|
116
|
+
* Task/group options override these. */
|
|
117
|
+
alloc?: boolean;
|
|
118
|
+
peakMem?: boolean;
|
|
119
|
+
/** Flag a memory reading that moves past this many percent of the base's
|
|
120
|
+
* and past its noise floor (default: 10). A memory regression fails the
|
|
121
|
+
* run. */
|
|
122
|
+
memThresholdPct?: number;
|
|
123
|
+
/** Shell commands run once, in order, in a freshly extracted base tree
|
|
124
|
+
* before it's used: to build what the suites import but git doesn't hold
|
|
125
|
+
* (generated or gitignored files). Each runs with its cwd at the tree's
|
|
126
|
+
* counterpart of `cwd`, the project's `node_modules` linked in, and
|
|
127
|
+
* `OSTIA_AB_SHA` / `OSTIA_AB_CANDIDATE_DIR` (the working tree's `cwd`) in
|
|
128
|
+
* its environment. The tree is cached per commit and command list. */
|
|
129
|
+
baseSetup?: string | string[];
|
|
130
|
+
/** Base trees to keep under `.ostia/ab`, counting this run's: after a
|
|
131
|
+
* run, older ones go, least recently used first, unless one was used in
|
|
132
|
+
* the last hour (another run may still need it). Default: 5. */
|
|
133
|
+
keepTrees?: number;
|
|
134
|
+
/** SIGKILLs a runner process (one suite file or repeat), or a `baseSetup`
|
|
135
|
+
* command, after this many ms. */
|
|
136
|
+
timeoutMs?: number;
|
|
137
|
+
/** Aborting kills the running process and resolves with the suites that
|
|
138
|
+
* had finished, plus an `aborted` warning; unrun repeats leave their
|
|
139
|
+
* workloads unconfirmed. */
|
|
140
|
+
signal?: AbortSignal;
|
|
141
|
+
/** Called as each setup command, task, confirmation repeat and memory
|
|
142
|
+
* process starts. */
|
|
143
|
+
onProgress?: (progress: AbProgress) => void;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `ab()` can't run: not in a git repository, or `base` isn't a commit. */
|
|
147
|
+
export class AbBaseError extends OstiaUsageError {}
|
|
148
|
+
|
|
149
|
+
/** One side's suite failed outside any task: on import, with no tasks, or
|
|
150
|
+
* while a task's memory was measured. */
|
|
151
|
+
export class AbSuiteError extends Error {
|
|
152
|
+
readonly side: Side;
|
|
153
|
+
constructor(message: string, side: Side) {
|
|
154
|
+
super(message);
|
|
155
|
+
this.side = side;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** A `baseSetup` command exited non-zero or timed out. The message names
|
|
160
|
+
* the command and ends with the tail of its output. */
|
|
161
|
+
export class AbSetupError extends Error {}
|
|
162
|
+
|
|
163
|
+
const RUNNER_PATH = new URL("./ab-runner.ts", import.meta.url).pathname;
|
|
164
|
+
|
|
165
|
+
const DEFAULT_METRIC: AbSummary["metric"] = "time";
|
|
166
|
+
|
|
167
|
+
const DEFAULTS = {
|
|
168
|
+
keepTrees: 5,
|
|
169
|
+
base: "HEAD",
|
|
170
|
+
rounds: 15,
|
|
171
|
+
metric: DEFAULT_METRIC,
|
|
172
|
+
thresholdPct: 10,
|
|
173
|
+
geomeanThresholdPct: 1.5,
|
|
174
|
+
memThresholdPct: 10,
|
|
175
|
+
confirm: 2,
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// RSS moves by pages and allocator chunks, and fresh processes differ by
|
|
179
|
+
// a few hundred KiB on small readings. A peak change smaller than this
|
|
180
|
+
// isn't counted.
|
|
181
|
+
const PEAK_NOISE_BYTES = 1024 * 1024;
|
|
182
|
+
// The JSC heap grows in blocks, so a batch that keeps nothing can still
|
|
183
|
+
// read a block or two of growth. A retained change smaller than this over
|
|
184
|
+
// the batch isn't counted.
|
|
185
|
+
const RETAINED_NOISE_BYTES = 16 * 1024;
|
|
186
|
+
|
|
187
|
+
function git(args: string[], cwd: string): string | undefined {
|
|
188
|
+
const proc = Bun.spawnSync(["git", ...args], {
|
|
189
|
+
cwd,
|
|
190
|
+
stdout: "pipe",
|
|
191
|
+
stderr: "ignore",
|
|
192
|
+
});
|
|
193
|
+
return proc.success ? proc.stdout.toString().trim() : undefined;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Appended to every base-tree script so no file is byte-identical to its
|
|
197
|
+
// working-tree copy: JSC's code cache shares compiled code between
|
|
198
|
+
// identical sources, and whichever copy was imported (and warmed) first
|
|
199
|
+
// ran 5-15% faster in A/A runs. A statement, not a comment: Bun's
|
|
200
|
+
// transpiler strips comments and inert expressions.
|
|
201
|
+
const BASE_SALT = "\n;globalThis.__ostia_ab_base__;\n";
|
|
202
|
+
const SCRIPT_GLOB = "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}";
|
|
203
|
+
|
|
204
|
+
async function saltScripts(dir: string): Promise<void> {
|
|
205
|
+
for await (const file of new Bun.Glob(SCRIPT_GLOB).scan({
|
|
206
|
+
cwd: dir,
|
|
207
|
+
dot: true,
|
|
208
|
+
absolute: true,
|
|
209
|
+
})) {
|
|
210
|
+
// A committed symlink can point outside the tree.
|
|
211
|
+
if (/\.d\.[mc]?ts$/.test(file) || !lstatSync(file).isFile()) continue;
|
|
212
|
+
appendFileSync(file, BASE_SALT);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
interface TreeSetup {
|
|
217
|
+
commands: string[];
|
|
218
|
+
/** The project root and the directory `ab()` runs from, in the working
|
|
219
|
+
* tree. */
|
|
220
|
+
toplevel: string;
|
|
221
|
+
cwd: string;
|
|
222
|
+
timeoutMs?: number | undefined;
|
|
223
|
+
signal?: AbortSignal | undefined;
|
|
224
|
+
onProgress?: ((progress: AbProgress) => void) | undefined;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Where the base tree for `sha` lives: `<sha>`, or with setup commands,
|
|
228
|
+
// `<sha>-<hash of the commands>`, so changing them builds a new tree. The
|
|
229
|
+
// sha is shortened: code that works on absolute paths costs more on the
|
|
230
|
+
// longer ones, so every character the base tree adds reads as a slowdown.
|
|
231
|
+
function treeDir(abDir: string, sha: string, commands: string[]): string {
|
|
232
|
+
const short = sha.slice(0, 12);
|
|
233
|
+
if (commands.length === 0) return `${abDir}/${short}`;
|
|
234
|
+
return `${abDir}/${short}-${fp("ab-setup", commands).slice(-8)}`;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Where the base trees of the project at `toplevel` live: inside it, so
|
|
238
|
+
// a bare import walks up to the project's own `node_modules` by its real
|
|
239
|
+
// path, but not under `node_modules`, which code under test (bundler
|
|
240
|
+
// plugins, resolvers, globbers) often skips or treats differently.
|
|
241
|
+
export function abTreesDir(toplevel: string): string {
|
|
242
|
+
return `${toplevel}/.ostia/ab`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function ignoreTrees(abDir: string): void {
|
|
246
|
+
if (existsSync(`${abDir}/.gitignore`)) return;
|
|
247
|
+
mkdirSync(abDir, { recursive: true });
|
|
248
|
+
writeFileSync(`${abDir}/.gitignore`, "*\n");
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const SETUP_OUTPUT_LINES = 20;
|
|
252
|
+
// A failed command shows only the tail of its output, so no more is kept.
|
|
253
|
+
const SETUP_OUTPUT_BYTES = 64 * 1024;
|
|
254
|
+
// How long a command's output may stay open once its process group is
|
|
255
|
+
// killed. Only a descendant that left the group can hold it open longer.
|
|
256
|
+
const SETUP_DRAIN_MS = 1000;
|
|
257
|
+
|
|
258
|
+
function readTail(stream: ReadableStream<Uint8Array>): {
|
|
259
|
+
done: Promise<void>;
|
|
260
|
+
stop: () => Promise<string>;
|
|
261
|
+
} {
|
|
262
|
+
const reader = stream.getReader();
|
|
263
|
+
const decoder = new TextDecoder();
|
|
264
|
+
let text = "";
|
|
265
|
+
const done = (async () => {
|
|
266
|
+
try {
|
|
267
|
+
for (;;) {
|
|
268
|
+
const chunk = await reader.read();
|
|
269
|
+
if (chunk.done) return;
|
|
270
|
+
text = (text + decoder.decode(chunk.value, { stream: true })).slice(
|
|
271
|
+
-SETUP_OUTPUT_BYTES,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
} catch {
|
|
275
|
+
// Cancelled by `stop()`.
|
|
276
|
+
}
|
|
277
|
+
})();
|
|
278
|
+
return {
|
|
279
|
+
done,
|
|
280
|
+
stop: async () => {
|
|
281
|
+
await reader.cancel().catch(() => {});
|
|
282
|
+
await done;
|
|
283
|
+
return text;
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Runs one setup command in its own process group. A timeout, a cancel,
|
|
289
|
+
// or the command's own exit kills the whole group, so no child it started
|
|
290
|
+
// can hold the output pipes open or write into the tree later.
|
|
291
|
+
async function runSetupCommand(
|
|
292
|
+
command: string,
|
|
293
|
+
dir: string,
|
|
294
|
+
env: Record<string, string | undefined>,
|
|
295
|
+
setup: TreeSetup,
|
|
296
|
+
): Promise<{ exitCode: number; timedOut: boolean; output: string }> {
|
|
297
|
+
const proc = Bun.spawn(["sh", "-c", command], {
|
|
298
|
+
cwd: dir,
|
|
299
|
+
env,
|
|
300
|
+
stdout: "pipe",
|
|
301
|
+
stderr: "pipe",
|
|
302
|
+
stdin: "ignore",
|
|
303
|
+
detached: true,
|
|
304
|
+
});
|
|
305
|
+
const killGroup = () => {
|
|
306
|
+
try {
|
|
307
|
+
process.kill(-proc.pid, "SIGKILL");
|
|
308
|
+
} catch {
|
|
309
|
+
// The whole group has exited already.
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
let timedOut = false;
|
|
313
|
+
const timer =
|
|
314
|
+
setup.timeoutMs === undefined
|
|
315
|
+
? undefined
|
|
316
|
+
: setTimeout(() => {
|
|
317
|
+
timedOut = true;
|
|
318
|
+
killGroup();
|
|
319
|
+
}, setup.timeoutMs);
|
|
320
|
+
setup.signal?.addEventListener("abort", killGroup);
|
|
321
|
+
if (setup.signal?.aborted) killGroup();
|
|
322
|
+
const stdout = readTail(proc.stdout);
|
|
323
|
+
const stderr = readTail(proc.stderr);
|
|
324
|
+
let drainTimer: ReturnType<typeof setTimeout> | undefined;
|
|
325
|
+
try {
|
|
326
|
+
const exitCode = await proc.exited;
|
|
327
|
+
killGroup();
|
|
328
|
+
await Promise.race([
|
|
329
|
+
Promise.all([stdout.done, stderr.done]),
|
|
330
|
+
new Promise((resolve) => {
|
|
331
|
+
drainTimer = setTimeout(resolve, SETUP_DRAIN_MS);
|
|
332
|
+
}),
|
|
333
|
+
]);
|
|
334
|
+
const [out, err] = await Promise.all([stdout.stop(), stderr.stop()]);
|
|
335
|
+
return { exitCode, timedOut, output: err.trim() || out.trim() };
|
|
336
|
+
} finally {
|
|
337
|
+
clearTimeout(timer);
|
|
338
|
+
clearTimeout(drainTimer);
|
|
339
|
+
setup.signal?.removeEventListener("abort", killGroup);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Runs `setup.commands` in the extracted tree at `tree`. Build scripts
|
|
344
|
+
// often read `./node_modules/...` by relative path, which walking up to
|
|
345
|
+
// the project's `node_modules` doesn't satisfy, so the project's is linked
|
|
346
|
+
// into the tree while they run and unlinked before the salt pass. Returns
|
|
347
|
+
// false when `signal` aborted a command.
|
|
348
|
+
async function runSetup(
|
|
349
|
+
tree: string,
|
|
350
|
+
sha: string,
|
|
351
|
+
setup: TreeSetup,
|
|
352
|
+
): Promise<boolean> {
|
|
353
|
+
const toplevel = realpathSync(setup.toplevel);
|
|
354
|
+
const cwd = realpathSync(setup.cwd);
|
|
355
|
+
const sub = relative(toplevel, cwd);
|
|
356
|
+
const dir = sub && existsSync(`${tree}/${sub}`) ? `${tree}/${sub}` : tree;
|
|
357
|
+
const links: string[] = [];
|
|
358
|
+
for (const [from, to] of [
|
|
359
|
+
[`${toplevel}/node_modules`, `${tree}/node_modules`],
|
|
360
|
+
[`${cwd}/node_modules`, `${dir}/node_modules`],
|
|
361
|
+
] as const) {
|
|
362
|
+
if (!existsSync(from) || existsSync(to)) continue;
|
|
363
|
+
symlinkSync(from, to);
|
|
364
|
+
links.push(to);
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
for (const command of setup.commands) {
|
|
368
|
+
setup.onProgress?.({ phase: "setup", command });
|
|
369
|
+
const { exitCode, timedOut, output } = await runSetupCommand(
|
|
370
|
+
command,
|
|
371
|
+
dir,
|
|
372
|
+
{ ...processEnv(), OSTIA_AB_SHA: sha, OSTIA_AB_CANDIDATE_DIR: cwd },
|
|
373
|
+
setup,
|
|
374
|
+
);
|
|
375
|
+
if (setup.signal?.aborted) return false;
|
|
376
|
+
if (exitCode === 0 && !timedOut) continue;
|
|
377
|
+
const excerpt = output.split("\n").slice(-SETUP_OUTPUT_LINES).join("\n");
|
|
378
|
+
const why = timedOut
|
|
379
|
+
? `timed out after ${setup.timeoutMs}ms`
|
|
380
|
+
: `exited ${exitCode}`;
|
|
381
|
+
throw new AbSetupError(
|
|
382
|
+
`Base setup ${why}: ${command}${excerpt ? `\n${excerpt}` : ""}`,
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
return true;
|
|
386
|
+
} finally {
|
|
387
|
+
for (const link of links) unlinkSync(link);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// The committed tree at `sha`, extracted once under `dir` and reused by
|
|
392
|
+
// every later run against the same commit (and setup commands), with each
|
|
393
|
+
// script salted (see `BASE_SALT`). Extracted and set up in a temp
|
|
394
|
+
// directory and renamed into place, so a directory at `dir` is always
|
|
395
|
+
// complete; a failed or cancelled setup leaves nothing behind. Returns
|
|
396
|
+
// false when `setup.signal` aborted a setup command.
|
|
397
|
+
async function extractTree(
|
|
398
|
+
sha: string,
|
|
399
|
+
dir: string,
|
|
400
|
+
setup: TreeSetup,
|
|
401
|
+
): Promise<boolean> {
|
|
402
|
+
if (existsSync(dir)) return true;
|
|
403
|
+
const tmp = `${dir}.tmp-${process.pid}-${crypto.randomUUID().slice(0, 8)}`;
|
|
404
|
+
await removeDir(tmp);
|
|
405
|
+
await mkdir(tmp, { recursive: true });
|
|
406
|
+
const archive = Bun.spawn(["git", "archive", "--format=tar", sha], {
|
|
407
|
+
cwd: setup.cwd,
|
|
408
|
+
stdout: "pipe",
|
|
409
|
+
stderr: "pipe",
|
|
410
|
+
});
|
|
411
|
+
const tar = Bun.spawn(["tar", "-x", "-C", tmp], {
|
|
412
|
+
stdin: archive.stdout,
|
|
413
|
+
stderr: "pipe",
|
|
414
|
+
});
|
|
415
|
+
const [archiveCode, tarCode] = await Promise.all([
|
|
416
|
+
archive.exited,
|
|
417
|
+
tar.exited,
|
|
418
|
+
]);
|
|
419
|
+
if (archiveCode !== 0 || tarCode !== 0) {
|
|
420
|
+
const stderr = await new Response(
|
|
421
|
+
archiveCode !== 0 ? archive.stderr : tar.stderr,
|
|
422
|
+
).text();
|
|
423
|
+
await removeDir(tmp);
|
|
424
|
+
throw new Error(`Could not extract ${sha}: ${stderr.trim()}`);
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
if (!(await runSetup(tmp, sha, setup))) {
|
|
428
|
+
await removeDir(tmp);
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
} catch (err) {
|
|
432
|
+
await removeDir(tmp);
|
|
433
|
+
throw err;
|
|
434
|
+
}
|
|
435
|
+
await saltScripts(tmp);
|
|
436
|
+
try {
|
|
437
|
+
renameSync(tmp, dir);
|
|
438
|
+
} catch {
|
|
439
|
+
// Another run extracted the same commit first.
|
|
440
|
+
await removeDir(tmp);
|
|
441
|
+
}
|
|
442
|
+
return true;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Never pruned within this long of its last use, since the tree may
|
|
446
|
+
// belong to a run still going.
|
|
447
|
+
const PRUNE_GRACE_MS = 60 * 60 * 1000;
|
|
448
|
+
|
|
449
|
+
function pidAlive(pid: number): boolean {
|
|
450
|
+
try {
|
|
451
|
+
process.kill(pid, 0);
|
|
452
|
+
return true;
|
|
453
|
+
} catch (err) {
|
|
454
|
+
return err instanceof Error && "code" in err && err.code === "EPERM";
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Sets the modification time because pruning goes by it: unlike access
|
|
459
|
+
// time, every filesystem keeps it.
|
|
460
|
+
function touchTree(dir: string): void {
|
|
461
|
+
const now = new Date();
|
|
462
|
+
try {
|
|
463
|
+
utimesSync(dir, now, now);
|
|
464
|
+
} catch {
|
|
465
|
+
// Gone already: nothing to keep fresh.
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function pruneAbTrees(abDir: string, keep: number): Promise<number> {
|
|
470
|
+
if (!existsSync(abDir)) return 0;
|
|
471
|
+
const now = nowMs();
|
|
472
|
+
const doomed: string[] = [];
|
|
473
|
+
const trees: { path: string; mtimeMs: number }[] = [];
|
|
474
|
+
for (const name of readdirSync(abDir)) {
|
|
475
|
+
if (name === ".gitignore") continue;
|
|
476
|
+
const path = `${abDir}/${name}`;
|
|
477
|
+
const tmp = /\.tmp-(\d+)(?:-\w+)?$/.exec(name);
|
|
478
|
+
if (tmp) {
|
|
479
|
+
if (!pidAlive(Number(tmp[1]))) doomed.push(path);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
try {
|
|
483
|
+
trees.push({ path, mtimeMs: statSync(path).mtimeMs });
|
|
484
|
+
} catch {
|
|
485
|
+
// Removed by another run in the meantime.
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
trees.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
489
|
+
for (const tree of trees.slice(keep)) {
|
|
490
|
+
if (now - tree.mtimeMs > PRUNE_GRACE_MS) doomed.push(tree.path);
|
|
491
|
+
}
|
|
492
|
+
for (const path of doomed) await removeDir(path);
|
|
493
|
+
return doomed.length;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// compat: base trees were cached under `<outDir>/ab` before they moved
|
|
497
|
+
// out of node_modules; this matches their names (`<sha>`, `<sha>-<hash>`,
|
|
498
|
+
// or a temp directory for one).
|
|
499
|
+
const LEGACY_TREE = /^[0-9a-f]{40}(?:-[0-9a-f]{8})?(?:\.tmp-\d+(?:-\w+)?)?$/;
|
|
500
|
+
|
|
501
|
+
// Removes the base trees left under `dir` by earlier versions, and `dir`
|
|
502
|
+
// once nothing else is in it. Returns how many it removed.
|
|
503
|
+
async function removeLegacyTrees(dir: string): Promise<number> {
|
|
504
|
+
if (!existsSync(dir)) return 0;
|
|
505
|
+
const names = readdirSync(dir);
|
|
506
|
+
const trees = names.filter((name) => LEGACY_TREE.test(name));
|
|
507
|
+
for (const name of trees) await removeDir(`${dir}/${name}`);
|
|
508
|
+
if (trees.length === names.length) await removeDir(dir);
|
|
509
|
+
return trees.length;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// compat: also removes the trees left under `<outDir>/ab`, where they were
|
|
513
|
+
// cached before.
|
|
514
|
+
export async function cleanAbTrees(
|
|
515
|
+
opts: { outDir?: string; cwd?: string } = {},
|
|
516
|
+
): Promise<number> {
|
|
517
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
518
|
+
let count = await removeLegacyTrees(
|
|
519
|
+
`${absolutePath(cwd, opts.outDir ?? DEFAULT_OUT_DIR)}/ab`,
|
|
520
|
+
);
|
|
521
|
+
const toplevel = git(["rev-parse", "--show-toplevel"], cwd);
|
|
522
|
+
const dir = toplevel === undefined ? undefined : abTreesDir(toplevel);
|
|
523
|
+
if (dir && existsSync(dir)) {
|
|
524
|
+
count += readdirSync(dir).filter((name) => name !== ".gitignore").length;
|
|
525
|
+
await removeDir(dir);
|
|
526
|
+
}
|
|
527
|
+
return count;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// invariant: a memory process asked for a reading always writes it, so a
|
|
531
|
+
// missing one is a bug, not a result.
|
|
532
|
+
function reading<T>(value: T | undefined, what: string): T {
|
|
533
|
+
if (value === undefined) {
|
|
534
|
+
throw new Error(`ab: a memory process wrote no ${what} reading`);
|
|
535
|
+
}
|
|
536
|
+
return value;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const isRecord = (v: unknown): v is Record<string, unknown> =>
|
|
540
|
+
typeof v === "object" && v !== null && !Array.isArray(v);
|
|
541
|
+
|
|
542
|
+
function isMemoryResult(v: unknown): v is AbMemoryResult {
|
|
543
|
+
if (!isRecord(v)) return false;
|
|
544
|
+
const { peak, alloc } = v;
|
|
545
|
+
return (
|
|
546
|
+
(peak === undefined ||
|
|
547
|
+
(isRecord(peak) &&
|
|
548
|
+
typeof peak.peakBytes === "number" &&
|
|
549
|
+
typeof peak.slackBytes === "number" &&
|
|
550
|
+
typeof peak.wallNs === "number")) &&
|
|
551
|
+
(alloc === undefined ||
|
|
552
|
+
(isRecord(alloc) &&
|
|
553
|
+
typeof alloc.bytesPerOp === "number" &&
|
|
554
|
+
typeof alloc.calls === "number"))
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function isRunnerPlan(v: unknown): v is AbRunnerPlan {
|
|
559
|
+
return (
|
|
560
|
+
isRecord(v) &&
|
|
561
|
+
Array.isArray(v.memory) &&
|
|
562
|
+
v.memory.every(
|
|
563
|
+
(m) =>
|
|
564
|
+
isRecord(m) &&
|
|
565
|
+
typeof m.workloadId === "string" &&
|
|
566
|
+
typeof m.alloc === "boolean" &&
|
|
567
|
+
typeof m.peakMem === "boolean",
|
|
568
|
+
)
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function isSide(v: string): v is Side {
|
|
573
|
+
return v === "base" || v === "cand";
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function judgeMemory(
|
|
577
|
+
m: Measurement,
|
|
578
|
+
p: PairedEvidence,
|
|
579
|
+
task: AbMemoryTask,
|
|
580
|
+
readings: Record<Side, AbMemoryResult[]>,
|
|
581
|
+
thresholdPct: number,
|
|
582
|
+
): void {
|
|
583
|
+
const all = [...readings.base, ...readings.cand];
|
|
584
|
+
const judge = (read: (r: AbMemoryResult) => number, floorBytes: number) => {
|
|
585
|
+
const change = memoryChange(
|
|
586
|
+
median(readings.base.map(read)),
|
|
587
|
+
median(readings.cand.map(read)),
|
|
588
|
+
thresholdPct,
|
|
589
|
+
floorBytes,
|
|
590
|
+
);
|
|
591
|
+
if (!comparable(p)) change.verdict = "unchanged";
|
|
592
|
+
return change;
|
|
593
|
+
};
|
|
594
|
+
if (task.alloc) {
|
|
595
|
+
const calls = Math.min(...all.map((r) => reading(r.alloc, "alloc").calls));
|
|
596
|
+
p.retained = judge(
|
|
597
|
+
(r) => reading(r.alloc, "alloc").bytesPerOp,
|
|
598
|
+
RETAINED_NOISE_BYTES / calls,
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
if (task.peakMem) {
|
|
602
|
+
const peaks = all.map((r) => reading(r.peak, "peak"));
|
|
603
|
+
// Memory freed before the call can hide up to `slackBytes` of its peak,
|
|
604
|
+
// so a warned reading's noise floor rises to the slack.
|
|
605
|
+
const warning = peakHiddenWarning(peaks);
|
|
606
|
+
const slack = Math.max(...peaks.map((r) => r.slackBytes));
|
|
607
|
+
p.peak = judge(
|
|
608
|
+
(r) => reading(r.peak, "peak").peakBytes,
|
|
609
|
+
warning ? Math.max(PEAK_NOISE_BYTES, slack) : PEAK_NOISE_BYTES,
|
|
610
|
+
);
|
|
611
|
+
if (warning) m.warnings.push(warning);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Pools a suite's base-first run `a` with its candidate-first run `b`. The
|
|
616
|
+
// side that goes first in a process can run several percent faster, the
|
|
617
|
+
// same way every time, so one order alone reads as a change on identical
|
|
618
|
+
// code; pooled, the bias pulls both ways and cancels. A throw in either
|
|
619
|
+
// run counts.
|
|
620
|
+
export function poolOrders(
|
|
621
|
+
a: ProfileDocument,
|
|
622
|
+
b: ProfileDocument,
|
|
623
|
+
thresholdPct: number,
|
|
624
|
+
metric: AbSummary["metric"] = DEFAULTS.metric,
|
|
625
|
+
): ProfileDocument {
|
|
626
|
+
const second = new Map(b.measurements.map((m) => [m.workloadId, m]));
|
|
627
|
+
const pooled = a.measurements.map((m): Measurement => {
|
|
628
|
+
const other = second.get(m.workloadId);
|
|
629
|
+
if (!other) return m;
|
|
630
|
+
if (m.threw && other.threw && m.threw.side !== other.threw.side) {
|
|
631
|
+
return {
|
|
632
|
+
...m,
|
|
633
|
+
threw: {
|
|
634
|
+
side: "both",
|
|
635
|
+
message: `${m.threw.message}\n${other.threw.message}`,
|
|
636
|
+
},
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
if (m.threw) return m;
|
|
640
|
+
if (other.threw) return other;
|
|
641
|
+
const p = m.paired;
|
|
642
|
+
const q = other.paired;
|
|
643
|
+
if (!p || !q || !m.timing || !other.timing) return m;
|
|
644
|
+
const timing = computeTimingStats([
|
|
645
|
+
...m.timing.samples,
|
|
646
|
+
...other.timing.samples,
|
|
647
|
+
]);
|
|
648
|
+
if (p.batch > 1) timing.batch = p.batch;
|
|
649
|
+
return {
|
|
650
|
+
...m,
|
|
651
|
+
timing,
|
|
652
|
+
diagnosticWallNs:
|
|
653
|
+
(m.diagnosticWallNs ?? 0) + (other.diagnosticWallNs ?? 0),
|
|
654
|
+
paired: pairedEvidence(
|
|
655
|
+
{
|
|
656
|
+
rounds: p.rounds + q.rounds,
|
|
657
|
+
batch: p.batch,
|
|
658
|
+
baseSamples: [...p.baseSamples, ...q.baseSamples],
|
|
659
|
+
ratios: [...p.ratios, ...q.ratios],
|
|
660
|
+
...(p.instructions &&
|
|
661
|
+
q.instructions && {
|
|
662
|
+
instructions: {
|
|
663
|
+
baseSamples: [
|
|
664
|
+
...p.instructions.baseSamples,
|
|
665
|
+
...q.instructions.baseSamples,
|
|
666
|
+
],
|
|
667
|
+
candSamples: [
|
|
668
|
+
...p.instructions.candSamples,
|
|
669
|
+
...q.instructions.candSamples,
|
|
670
|
+
],
|
|
671
|
+
},
|
|
672
|
+
}),
|
|
673
|
+
sameOutput: p.sameOutput && q.sameOutput,
|
|
674
|
+
},
|
|
675
|
+
thresholdPct,
|
|
676
|
+
metric,
|
|
677
|
+
),
|
|
678
|
+
};
|
|
679
|
+
});
|
|
680
|
+
return { ...a, measurements: pooled };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// `metric`'s median ratio over the main run and any fresh-process repeats,
|
|
684
|
+
// so one process's JIT luck moves the geomean less; undefined when the
|
|
685
|
+
// task has no `metric` reading.
|
|
686
|
+
function ratioEstimate(
|
|
687
|
+
p: PairedEvidence,
|
|
688
|
+
metric: AbSummary["metric"],
|
|
689
|
+
): number | undefined {
|
|
690
|
+
const [main, ...repeats] = [p, ...(p.repeats ?? [])].map(
|
|
691
|
+
(r) => metricRatios(r, metric)?.medianRatio,
|
|
692
|
+
);
|
|
693
|
+
if (main === undefined) return undefined;
|
|
694
|
+
return median([main, ...repeats.filter((r) => r !== undefined)]);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
export function summarizePaired(
|
|
698
|
+
measurements: Measurement[],
|
|
699
|
+
settings: {
|
|
700
|
+
base: AbSummary["base"];
|
|
701
|
+
newSuites?: string[];
|
|
702
|
+
rounds: number;
|
|
703
|
+
metric?: AbSummary["metric"];
|
|
704
|
+
thresholdPct: number;
|
|
705
|
+
geomeanThresholdPct: number;
|
|
706
|
+
memThresholdPct?: number;
|
|
707
|
+
},
|
|
708
|
+
): AbSummary {
|
|
709
|
+
// A task that threw, even in a confirmation repeat, isn't judged on time.
|
|
710
|
+
const paired = measurements
|
|
711
|
+
.filter((m) => !m.threw)
|
|
712
|
+
.map((m) => m.paired)
|
|
713
|
+
.filter((p): p is PairedEvidence => p !== undefined);
|
|
714
|
+
const count = (verdict: PairedEvidence["verdict"]) =>
|
|
715
|
+
paired.filter((p) => p.verdict === verdict).length;
|
|
716
|
+
const metric = settings.metric ?? DEFAULTS.metric;
|
|
717
|
+
const judged = paired.filter(comparable);
|
|
718
|
+
const estimates = judged
|
|
719
|
+
.map((p) => ratioEstimate(p, metric))
|
|
720
|
+
.filter((r) => r !== undefined);
|
|
721
|
+
const logSum = estimates.reduce((sum, r) => sum + Math.log(r), 0);
|
|
722
|
+
const geomeanPct =
|
|
723
|
+
estimates.length > 0
|
|
724
|
+
? (Math.exp(logSum / estimates.length) - 1) * 100
|
|
725
|
+
: null;
|
|
726
|
+
const regressed = count("regressed");
|
|
727
|
+
const improved = count("improved");
|
|
728
|
+
const threw = measurements.filter((m) => m.threw);
|
|
729
|
+
const candThrew = threw.some((m) => m.threw?.side === "cand");
|
|
730
|
+
const { memThresholdPct, ...rest } = settings;
|
|
731
|
+
// One verdict pair per task, so a task counts once even when both its
|
|
732
|
+
// readings regressed.
|
|
733
|
+
const memVerdicts = paired
|
|
734
|
+
.filter((p) => p.retained || p.peak)
|
|
735
|
+
.map((p) => [p.retained?.verdict, p.peak?.verdict]);
|
|
736
|
+
const memRegressed = memVerdicts.filter((v) => v.includes("regressed"));
|
|
737
|
+
const memory = memVerdicts.length > 0 && {
|
|
738
|
+
thresholdPct: memThresholdPct ?? DEFAULTS.memThresholdPct,
|
|
739
|
+
regressed: memRegressed.length,
|
|
740
|
+
improved: memVerdicts.filter(
|
|
741
|
+
(v) => v.includes("improved") && !v.includes("regressed"),
|
|
742
|
+
).length,
|
|
743
|
+
};
|
|
744
|
+
return {
|
|
745
|
+
...rest,
|
|
746
|
+
metric,
|
|
747
|
+
matched: paired.length,
|
|
748
|
+
regressed,
|
|
749
|
+
improved,
|
|
750
|
+
unchanged: paired.length - regressed - improved,
|
|
751
|
+
unconfirmed: paired.filter((p) => p.confirmed === false).length,
|
|
752
|
+
outputDiffers: paired.filter((p) => !p.sameOutput).length,
|
|
753
|
+
notComparable: paired.length - judged.length,
|
|
754
|
+
threw: threw.length,
|
|
755
|
+
...(memory && { memory }),
|
|
756
|
+
geomeanPct,
|
|
757
|
+
verdict:
|
|
758
|
+
regressed > 0 ||
|
|
759
|
+
candThrew ||
|
|
760
|
+
memRegressed.length > 0 ||
|
|
761
|
+
(geomeanPct !== null && geomeanPct > settings.geomeanThresholdPct)
|
|
762
|
+
? "fail"
|
|
763
|
+
: "pass",
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Paired A/B timing of suite files against a git ref: every task runs on
|
|
768
|
+
* the ref's committed tree (base) and the working tree (candidate) in one
|
|
769
|
+
* process, alternating short batches, and is judged on the per-round time
|
|
770
|
+
* ratio. Drift between two runs minutes apart cancels within a round. What
|
|
771
|
+
* pairing can't cancel is how the JIT compiled each side in that process,
|
|
772
|
+
* so every flagged workload is re-measured in `confirm` fresh processes
|
|
773
|
+
* and only counts when they all agree. */
|
|
774
|
+
export async function ab(opts: AbOptions): Promise<ProfileDocument> {
|
|
775
|
+
const ref = opts.base ?? DEFAULTS.base;
|
|
776
|
+
const rounds = opts.rounds ?? DEFAULTS.rounds;
|
|
777
|
+
const metric = opts.metric ?? DEFAULTS.metric;
|
|
778
|
+
const thresholdPct = opts.thresholdPct ?? DEFAULTS.thresholdPct;
|
|
779
|
+
const geomeanThresholdPct =
|
|
780
|
+
opts.geomeanThresholdPct ?? DEFAULTS.geomeanThresholdPct;
|
|
781
|
+
const memThresholdPct = opts.memThresholdPct ?? DEFAULTS.memThresholdPct;
|
|
782
|
+
const confirm = opts.confirm ?? DEFAULTS.confirm;
|
|
783
|
+
const keepTrees = opts.keepTrees ?? DEFAULTS.keepTrees;
|
|
784
|
+
if (!Number.isInteger(keepTrees) || keepTrees < 1) {
|
|
785
|
+
throw new RangeError(
|
|
786
|
+
`ab: keepTrees must be an integer >= 1, got ${keepTrees}`,
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
if (!Number.isInteger(rounds) || rounds < 3) {
|
|
790
|
+
throw new RangeError(`ab: rounds must be an integer >= 3, got ${rounds}`);
|
|
791
|
+
}
|
|
792
|
+
if (!Number.isInteger(confirm) || confirm < 0) {
|
|
793
|
+
throw new RangeError(`ab: confirm must be an integer >= 0, got ${confirm}`);
|
|
794
|
+
}
|
|
795
|
+
if (metric !== "time" && metric !== "instructions") {
|
|
796
|
+
throw new RangeError(
|
|
797
|
+
`ab: metric must be "time" or "instructions", got ${JSON.stringify(metric)}`,
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
const uncounted =
|
|
801
|
+
metric === "instructions" && instructionCounter().unavailable;
|
|
802
|
+
if (uncounted) {
|
|
803
|
+
throw new OstiaUsageError(
|
|
804
|
+
`ab: can't judge by instructions on this machine: ${uncounted}.`,
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
for (const [key, value] of Object.entries({
|
|
808
|
+
thresholdPct,
|
|
809
|
+
geomeanThresholdPct,
|
|
810
|
+
memThresholdPct,
|
|
811
|
+
})) {
|
|
812
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
813
|
+
throw new RangeError(`ab: ${key} must be >= 0, got ${value}`);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
assertSamplingOptions("ab", definedFields({ timeoutMs: opts.timeoutMs }));
|
|
817
|
+
|
|
818
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
819
|
+
const absOutDir = absolutePath(cwd, opts.outDir ?? DEFAULT_OUT_DIR);
|
|
820
|
+
const tmpDir = uniqueTmpDir(absOutDir, "ab");
|
|
821
|
+
|
|
822
|
+
// Same path join as `bench()`, so workload ids match `ostia bench`'s.
|
|
823
|
+
const candSuites = opts.suites.map((file) => absolutePath(cwd, file));
|
|
824
|
+
for (const file of opts.suites) {
|
|
825
|
+
assertSuiteExists(file, absolutePath(cwd, file));
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const toplevel = git(["rev-parse", "--show-toplevel"], cwd);
|
|
829
|
+
if (toplevel === undefined) {
|
|
830
|
+
throw new AbBaseError(`${cwd} is not inside a git repository.`);
|
|
831
|
+
}
|
|
832
|
+
const sha = git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd);
|
|
833
|
+
if (sha === undefined) {
|
|
834
|
+
throw new AbBaseError(`"${ref}" is not a commit in ${toplevel}.`);
|
|
835
|
+
}
|
|
836
|
+
const setup =
|
|
837
|
+
typeof opts.baseSetup === "string"
|
|
838
|
+
? [opts.baseSetup]
|
|
839
|
+
: (opts.baseSetup ?? []);
|
|
840
|
+
const treesDir = abTreesDir(toplevel);
|
|
841
|
+
ignoreTrees(treesDir);
|
|
842
|
+
const checkout = treeDir(treesDir, sha, setup);
|
|
843
|
+
const extracted = await extractTree(sha, checkout, {
|
|
844
|
+
commands: setup,
|
|
845
|
+
toplevel,
|
|
846
|
+
cwd,
|
|
847
|
+
timeoutMs: opts.timeoutMs,
|
|
848
|
+
signal: opts.signal,
|
|
849
|
+
onProgress: opts.onProgress,
|
|
850
|
+
});
|
|
851
|
+
const settings = {
|
|
852
|
+
base: { ref, sha },
|
|
853
|
+
rounds,
|
|
854
|
+
metric,
|
|
855
|
+
thresholdPct,
|
|
856
|
+
geomeanThresholdPct,
|
|
857
|
+
memThresholdPct,
|
|
858
|
+
};
|
|
859
|
+
if (!extracted) {
|
|
860
|
+
const doc = createDocument([], []);
|
|
861
|
+
doc.unmatched = { baseOnly: [], candOnly: [] };
|
|
862
|
+
doc.ab = summarizePaired([], settings);
|
|
863
|
+
return doc;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
const { environment, noiseWarning } = captureRunEnvironment(opts.noiseCheck);
|
|
867
|
+
|
|
868
|
+
// "" when the file doesn't exist at the base ref: all its tasks are new.
|
|
869
|
+
const baseSuites = candSuites.map((suite, i) => {
|
|
870
|
+
const inRepo = relative(toplevel, realpathSync(suite));
|
|
871
|
+
if (inRepo === ".." || inRepo.startsWith(`..${sep}`)) {
|
|
872
|
+
throw new OstiaUsageError(`${opts.suites[i]} is outside ${toplevel}.`);
|
|
873
|
+
}
|
|
874
|
+
return existsSync(`${checkout}/${inRepo}`) ? `${checkout}/${inRepo}` : "";
|
|
875
|
+
});
|
|
876
|
+
// A suite whose text changed may time something else on each side (a
|
|
877
|
+
// fixed fixture, a new input), so its tasks are marked. The base copy
|
|
878
|
+
// carries the salt; nothing else differs in an unchanged file.
|
|
879
|
+
const suiteChanged = await Promise.all(
|
|
880
|
+
candSuites.map(async (suite, s) => {
|
|
881
|
+
if (!baseSuites[s]) return false;
|
|
882
|
+
const base = await Bun.file(baseSuites[s]).text();
|
|
883
|
+
const cand = await Bun.file(suite).text();
|
|
884
|
+
return (
|
|
885
|
+
(base.endsWith(BASE_SALT) ? base.slice(0, -BASE_SALT.length) : base) !==
|
|
886
|
+
cand
|
|
887
|
+
);
|
|
888
|
+
}),
|
|
889
|
+
);
|
|
890
|
+
const launches = resolveSuiteLaunches(opts.suites, cwd, opts, opts.projects);
|
|
891
|
+
|
|
892
|
+
const onProgress = opts.onProgress;
|
|
893
|
+
let spawned = 0;
|
|
894
|
+
// Resolves undefined only when cancelled.
|
|
895
|
+
const runRunner = async (
|
|
896
|
+
s: number,
|
|
897
|
+
extra: Partial<AbRunnerOpts> = {},
|
|
898
|
+
env?: Record<string, string>,
|
|
899
|
+
): Promise<string | undefined> => {
|
|
900
|
+
const candSuite = candSuites[s];
|
|
901
|
+
const baseSuite = baseSuites[s];
|
|
902
|
+
const launch = launches[s];
|
|
903
|
+
const file = opts.suites[s];
|
|
904
|
+
// invariant: `s` indexes every per-suite array.
|
|
905
|
+
if (
|
|
906
|
+
candSuite === undefined ||
|
|
907
|
+
baseSuite === undefined ||
|
|
908
|
+
launch === undefined ||
|
|
909
|
+
file === undefined
|
|
910
|
+
) {
|
|
911
|
+
throw new Error(`ab: no suite ${s}`);
|
|
912
|
+
}
|
|
913
|
+
touchTree(checkout);
|
|
914
|
+
const outPath = `${tmpDir}/${fp("ab-run", candSuite, spawned++)}.json`;
|
|
915
|
+
const runnerOpts: AbRunnerOpts = {
|
|
916
|
+
...definedFields({ filter: opts.filter }),
|
|
917
|
+
rounds,
|
|
918
|
+
thresholdPct,
|
|
919
|
+
metric,
|
|
920
|
+
preload: launch.preload,
|
|
921
|
+
// Per task only on the first pass; repeats report themselves.
|
|
922
|
+
progress:
|
|
923
|
+
onProgress !== undefined && !extra.workloadIds && !extra.memoryFor,
|
|
924
|
+
...extra,
|
|
925
|
+
};
|
|
926
|
+
let ran: boolean;
|
|
927
|
+
try {
|
|
928
|
+
ran = await runRunnerProcess(
|
|
929
|
+
[
|
|
930
|
+
"bun",
|
|
931
|
+
...launch.bunFlags,
|
|
932
|
+
RUNNER_PATH,
|
|
933
|
+
candSuite,
|
|
934
|
+
baseSuite,
|
|
935
|
+
outPath,
|
|
936
|
+
JSON.stringify(runnerOpts),
|
|
937
|
+
],
|
|
938
|
+
{
|
|
939
|
+
cwd,
|
|
940
|
+
label: "A/B suite",
|
|
941
|
+
name: file,
|
|
942
|
+
...definedFields({
|
|
943
|
+
timeoutMs: opts.timeoutMs,
|
|
944
|
+
signal: opts.signal,
|
|
945
|
+
env,
|
|
946
|
+
}),
|
|
947
|
+
// The runner names the side that failed to load, when that's why.
|
|
948
|
+
errorFile: `${outPath}.error`,
|
|
949
|
+
...(runnerOpts.progress && {
|
|
950
|
+
ipc: (message: AbRunnerProgress) =>
|
|
951
|
+
onProgress?.({
|
|
952
|
+
phase: "measure",
|
|
953
|
+
suite: s + 1,
|
|
954
|
+
suites: candSuites.length,
|
|
955
|
+
file,
|
|
956
|
+
pass: extra.candFirst ? 2 : 1,
|
|
957
|
+
passes: 2,
|
|
958
|
+
...message,
|
|
959
|
+
}),
|
|
960
|
+
}),
|
|
961
|
+
},
|
|
962
|
+
);
|
|
963
|
+
} catch (err) {
|
|
964
|
+
const sideFile = Bun.file(`${outPath}.side`);
|
|
965
|
+
if (!(await sideFile.exists())) throw err;
|
|
966
|
+
const side = await sideFile.text();
|
|
967
|
+
if (!isSide(side)) throw err;
|
|
968
|
+
throw new AbSuiteError(errorMessage(err), side);
|
|
969
|
+
}
|
|
970
|
+
return ran ? outPath : undefined;
|
|
971
|
+
};
|
|
972
|
+
// Each order gets half the rounds, so the pooled run costs what one order
|
|
973
|
+
// alone would. Undefined only when cancelled.
|
|
974
|
+
const runSuite = async (
|
|
975
|
+
s: number,
|
|
976
|
+
extra: Partial<AbRunnerOpts> = {},
|
|
977
|
+
): Promise<ProfileDocument | undefined> => {
|
|
978
|
+
const first = await runRunner(s, {
|
|
979
|
+
...extra,
|
|
980
|
+
rounds: Math.ceil(rounds / 2),
|
|
981
|
+
});
|
|
982
|
+
if (!first) return undefined;
|
|
983
|
+
// Only the first pass writes the plan, so the second drops `planPath`.
|
|
984
|
+
const { planPath: _planPath, ...secondExtra } = extra;
|
|
985
|
+
const second = await runRunner(s, {
|
|
986
|
+
...secondExtra,
|
|
987
|
+
rounds: Math.floor(rounds / 2),
|
|
988
|
+
candFirst: true,
|
|
989
|
+
});
|
|
990
|
+
if (!second) return undefined;
|
|
991
|
+
return poolOrders(
|
|
992
|
+
await loadDocument(first),
|
|
993
|
+
await loadDocument(second),
|
|
994
|
+
thresholdPct,
|
|
995
|
+
metric,
|
|
996
|
+
);
|
|
997
|
+
};
|
|
998
|
+
|
|
999
|
+
try {
|
|
1000
|
+
const workloads: Workload[] = [];
|
|
1001
|
+
const measurements: Measurement[] = [];
|
|
1002
|
+
const suiteOf = new Map<string, number>();
|
|
1003
|
+
const baseOnly: string[] = [];
|
|
1004
|
+
const candOnly: string[] = [];
|
|
1005
|
+
const wantsMemory: (AbMemoryTask & { suite: number })[] = [];
|
|
1006
|
+
for (const [s, candSuite] of candSuites.entries()) {
|
|
1007
|
+
const planPath = `${tmpDir}/${fp("ab-plan", candSuite)}.json`;
|
|
1008
|
+
const doc = await runSuite(s, {
|
|
1009
|
+
...definedFields({ alloc: opts.alloc, peakMem: opts.peakMem }),
|
|
1010
|
+
planPath,
|
|
1011
|
+
});
|
|
1012
|
+
if (!doc) break;
|
|
1013
|
+
const plan: unknown = await Bun.file(planPath).json();
|
|
1014
|
+
if (!isRunnerPlan(plan)) {
|
|
1015
|
+
throw new Error(`ab: ${planPath} isn't a runner plan`);
|
|
1016
|
+
}
|
|
1017
|
+
for (const m of plan.memory) wantsMemory.push({ ...m, suite: s });
|
|
1018
|
+
workloads.push(...doc.workloads);
|
|
1019
|
+
measurements.push(...doc.measurements);
|
|
1020
|
+
for (const m of doc.measurements) {
|
|
1021
|
+
suiteOf.set(m.workloadId, s);
|
|
1022
|
+
if (!suiteChanged[s] || !m.paired) continue;
|
|
1023
|
+
m.paired.suiteChanged = true;
|
|
1024
|
+
if (!comparable(m.paired)) m.paired.verdict = "unchanged";
|
|
1025
|
+
m.warnings.push({
|
|
1026
|
+
code: "suite-changed",
|
|
1027
|
+
message: comparable(m.paired)
|
|
1028
|
+
? "The suite file differs from the base's copy, so each side may run a different benchmark."
|
|
1029
|
+
: "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.",
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
baseOnly.push(...(doc.unmatched?.baseOnly ?? []));
|
|
1033
|
+
candOnly.push(...(doc.unmatched?.candOnly ?? []));
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const toConfirm = measurements.flatMap((m) => {
|
|
1037
|
+
const p = m.paired;
|
|
1038
|
+
return p?.flagged && confirm > 0 && comparable(p)
|
|
1039
|
+
? [{ m, p, flagged: p.flagged }]
|
|
1040
|
+
: [];
|
|
1041
|
+
});
|
|
1042
|
+
const labelOf = new Map(
|
|
1043
|
+
workloads.map((w) => [w.id, w.entry?.task ?? w.id]),
|
|
1044
|
+
);
|
|
1045
|
+
let started = 0;
|
|
1046
|
+
for (const { m, p, flagged } of toConfirm) {
|
|
1047
|
+
const s = suiteOf.get(m.workloadId);
|
|
1048
|
+
// invariant: every measurement's suite was recorded above.
|
|
1049
|
+
if (s === undefined) throw new Error(`ab: no suite for ${m.workloadId}`);
|
|
1050
|
+
p.repeats = [];
|
|
1051
|
+
for (let r = 0; r < confirm && !opts.signal?.aborted; r++) {
|
|
1052
|
+
onProgress?.({
|
|
1053
|
+
phase: "confirm",
|
|
1054
|
+
repeat: ++started,
|
|
1055
|
+
repeats: toConfirm.length * confirm,
|
|
1056
|
+
label: labelOf.get(m.workloadId) ?? m.workloadId,
|
|
1057
|
+
});
|
|
1058
|
+
const doc = await runSuite(s, {
|
|
1059
|
+
workloadIds: [m.workloadId],
|
|
1060
|
+
});
|
|
1061
|
+
const run = doc?.measurements[0];
|
|
1062
|
+
// A throw in a repeat counts like one in the first process; the
|
|
1063
|
+
// first process's timing stays for the record.
|
|
1064
|
+
if (run?.threw) {
|
|
1065
|
+
m.threw = { ...run.threw, repeat: r + 1 };
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
const repeat = run?.paired;
|
|
1069
|
+
if (!repeat) break;
|
|
1070
|
+
const i = repeat.instructions;
|
|
1071
|
+
p.repeats.push({
|
|
1072
|
+
medianRatio: repeat.medianRatio,
|
|
1073
|
+
ratioP25: repeat.ratioP25,
|
|
1074
|
+
ratioP75: repeat.ratioP75,
|
|
1075
|
+
...(i && {
|
|
1076
|
+
instructions: {
|
|
1077
|
+
medianRatio: i.medianRatio,
|
|
1078
|
+
ratioP25: i.ratioP25,
|
|
1079
|
+
ratioP75: i.ratioP75,
|
|
1080
|
+
},
|
|
1081
|
+
}),
|
|
1082
|
+
...(repeat.flagged && { flagged: repeat.flagged }),
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
p.confirmed =
|
|
1086
|
+
!m.threw &&
|
|
1087
|
+
p.repeats.length === confirm &&
|
|
1088
|
+
p.repeats.every((r) => r.flagged === flagged);
|
|
1089
|
+
p.verdict = p.confirmed ? flagged : "unchanged";
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// Memory, for tasks that timed without throwing: each side in its own
|
|
1093
|
+
// fresh processes, alternating sides.
|
|
1094
|
+
const byWorkload = new Map(measurements.map((m) => [m.workloadId, m]));
|
|
1095
|
+
const memoryTasks = wantsMemory.filter(({ workloadId }) => {
|
|
1096
|
+
const m = byWorkload.get(workloadId);
|
|
1097
|
+
return m?.paired && !m.threw;
|
|
1098
|
+
});
|
|
1099
|
+
const memoryRuns = memoryTasks.length * PEAK_MEM_PROCESSES * 2;
|
|
1100
|
+
let memoryRun = 0;
|
|
1101
|
+
const readMemory = async (task: (typeof memoryTasks)[number]) => {
|
|
1102
|
+
const { workloadId, suite, peakMem } = task;
|
|
1103
|
+
const readings: Record<Side, AbMemoryResult[]> = { base: [], cand: [] };
|
|
1104
|
+
for (let r = 0; r < PEAK_MEM_PROCESSES; r++) {
|
|
1105
|
+
for (const side of ["base", "cand"] as const) {
|
|
1106
|
+
if (opts.signal?.aborted) return readings;
|
|
1107
|
+
onProgress?.({
|
|
1108
|
+
phase: "memory",
|
|
1109
|
+
run: ++memoryRun,
|
|
1110
|
+
runs: memoryRuns,
|
|
1111
|
+
side,
|
|
1112
|
+
label: labelOf.get(workloadId) ?? workloadId,
|
|
1113
|
+
});
|
|
1114
|
+
const outPath = await runRunner(
|
|
1115
|
+
suite,
|
|
1116
|
+
{ memoryFor: { ...task, side } },
|
|
1117
|
+
// Lets a suite skip heavy module-scope work that would peak
|
|
1118
|
+
// before the measured call does.
|
|
1119
|
+
peakMem ? { OSTIA_PEAK_MEM: "1" } : undefined,
|
|
1120
|
+
);
|
|
1121
|
+
if (!outPath) continue;
|
|
1122
|
+
const result: unknown = await Bun.file(outPath).json();
|
|
1123
|
+
if (!isMemoryResult(result)) {
|
|
1124
|
+
throw new Error(`ab: ${outPath} isn't a memory reading`);
|
|
1125
|
+
}
|
|
1126
|
+
readings[side].push(result);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
return readings;
|
|
1130
|
+
};
|
|
1131
|
+
for (const task of memoryTasks) {
|
|
1132
|
+
const readings = await readMemory(task);
|
|
1133
|
+
if (readings.base.length === 0 || readings.cand.length === 0) continue;
|
|
1134
|
+
const m = byWorkload.get(task.workloadId);
|
|
1135
|
+
// invariant: memoryTasks holds only tasks with a paired measurement.
|
|
1136
|
+
if (!m?.paired) continue;
|
|
1137
|
+
judgeMemory(m, m.paired, task, readings, memThresholdPct);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
stampRunWarnings(
|
|
1141
|
+
measurements,
|
|
1142
|
+
noiseWarning,
|
|
1143
|
+
opts.signal?.aborted
|
|
1144
|
+
? "Run was cancelled before it finished; this document holds whatever suites had already completed."
|
|
1145
|
+
: undefined,
|
|
1146
|
+
);
|
|
1147
|
+
|
|
1148
|
+
const doc = createDocument(workloads, measurements, environment);
|
|
1149
|
+
doc.unmatched = { baseOnly, candOnly };
|
|
1150
|
+
doc.ab = summarizePaired(measurements, {
|
|
1151
|
+
...settings,
|
|
1152
|
+
newSuites: opts.suites.filter((_, s) => !baseSuites[s]),
|
|
1153
|
+
});
|
|
1154
|
+
await pruneAbTrees(treesDir, keepTrees);
|
|
1155
|
+
await removeLegacyTrees(`${absOutDir}/ab`);
|
|
1156
|
+
return doc;
|
|
1157
|
+
} finally {
|
|
1158
|
+
await removeDir(tmpDir);
|
|
1159
|
+
}
|
|
1160
|
+
}
|