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