Skip to content

Commit 9bd3d5a

Browse files
committed
feat(vitest): run analysis benchmarks in their own process
With Vitest 5, simulation and memory runs now reuse the walltime fork flow: workers queue each benchmark instead of measuring it, and the main process runs one fresh `vitest bench` per benchmark once the run is over. The fork is restricted to the benchmark's file and measures only that benchmark. `CODSPEED_WALLTIME_FORKS` and the `forks` options do not apply: analysis measures a benchmark once. Vitest 3/4 still don't fork. Closes COD-4156
1 parent 6633f24 commit 9bd3d5a

4 files changed

Lines changed: 72 additions & 12 deletions

File tree

‎packages/vitest-plugin/src/__tests__/isolation.test.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { spawn } from "child_process";
22
import { once } from "events";
33
import {
4+
existsSync,
45
mkdtempSync,
56
readdirSync,
67
readFileSync,
@@ -44,6 +45,7 @@ interface FixtureOptions {
4445
pluginForks?: number;
4546
firstForks?: number;
4647
failing?: boolean;
48+
mode?: "walltime" | "simulation";
4749
}
4850

4951
async function runFixture(options: FixtureOptions = {}) {
@@ -53,7 +55,7 @@ async function runFixture(options: FixtureOptions = {}) {
5355
const env: NodeJS.ProcessEnv = {
5456
...process.env,
5557
CODSPEED_ENV: "true",
56-
CODSPEED_RUNNER_MODE: "walltime",
58+
CODSPEED_RUNNER_MODE: options.mode ?? "walltime",
5759
CODSPEED_PROFILE_FOLDER: profileFolder,
5860
ISOLATION_LOG_FILE: logFile,
5961
[PROCESS_ISOLATION_ENV]: options.isolation,
@@ -85,7 +87,9 @@ async function runFixture(options: FixtureOptions = {}) {
8587

8688
const roundsByName = new Map<string, number>();
8789
const resultsDir = join(profileFolder, "results");
88-
for (const file of status === 0 ? readdirSync(resultsDir) : []) {
90+
// Only walltime runs write results: the instruments hold analysis ones.
91+
const hasResults = status === 0 && existsSync(resultsDir);
92+
for (const file of hasResults ? readdirSync(resultsDir) : []) {
8993
const data = JSON.parse(readFileSync(join(resultsDir, file), "utf8"));
9094
for (const benchmark of data.benchmarks) {
9195
roundsByName.set(benchmark.name, benchmark.stats.rounds);
@@ -147,3 +151,20 @@ describe("walltime forks", () => {
147151
RUN_TIMEOUT_MS,
148152
);
149153
});
154+
155+
describe("simulation isolation", () => {
156+
it(
157+
"runs every benchmark in its own process",
158+
async () => {
159+
const run = await runFixture({ mode: "simulation", forksEnv: 2 });
160+
161+
expect(run.status, run.stderr).toBe(0);
162+
const pids = ["first", "second", "third"].map((name) => {
163+
expect(run.pidsByName.get(name)?.size).toBe(1);
164+
return [...run.pidsByName.get(name)!][0];
165+
});
166+
expect(new Set(pids).size).toBe(pids.length);
167+
},
168+
RUN_TIMEOUT_MS,
169+
);
170+
});

‎packages/vitest-plugin/src/v5/forkReporter.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
getInstrumentMode,
23
resolveWalltimeForks,
34
runForks,
45
samplesToResult,
@@ -15,7 +16,8 @@ import { withForkContext } from "./forkContext";
1516

1617
/**
1718
* Measures the benchmarks the workers queued (see `provider.ts`) in fresh
18-
* processes and reports their pooled rounds. Runs in the main process once the
19+
* processes and reports their pooled walltime rounds; analysis forks report to
20+
* the instruments themselves. Runs in the main process once the
1921
* run is over: every file has torn down, so resources its hooks held (ports,
2022
* databases, ...) are free for the forks. The global setup is still up (it
2123
* tears down on close), so the forks skip it and inherit what it provided.
@@ -40,6 +42,11 @@ async function measureInForks(
4042
for (const module of modules) {
4143
for (const test of module.children.allTests()) {
4244
for (const queued of forkedBenchmarks(test.meta())) {
45+
if (getInstrumentMode() !== "walltime") {
46+
// Analysis measures a benchmark once, so it needs only one fork.
47+
await runForks(queued.uri, 1);
48+
continue;
49+
}
4350
const forks = resolveWalltimeForks(queued.forks ?? options.forks);
4451
const samples = await runForks(queued.uri, forks);
4552
const benchmark = tinybenchTaskToBenchmark(

‎packages/vitest-plugin/src/v5/provider.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
analysisIsolation,
23
getGitDir,
34
getInstrumentMode,
45
InstrumentHooks,
@@ -152,21 +153,42 @@ const provider: BenchmarkProvider = {
152153
if (isWalltime) {
153154
return runWalltime(registrations, options, getUri, test);
154155
}
155-
return runAnalysis(registrations, getUri);
156+
return runAnalysis(registrations, getUri, test);
156157
},
157158
};
158159

159160
async function runAnalysis(
160161
registrations: BenchRegistrationInput[],
161162
getUri: (name: string) => string,
163+
test: BenchmarkGroup["test"],
162164
): Promise<BenchResult[]> {
165+
const mode = analysisIsolation();
166+
if (mode.kind === "Forks") {
167+
queueForkedBenchmarks(
168+
test.meta,
169+
registrations.map(({ name }) => ({
170+
uri: getUri(name),
171+
name,
172+
forks: undefined,
173+
options: {},
174+
})),
175+
);
176+
return registrations.map(({ name }) => analysisResult(name));
177+
}
178+
163179
const label = InstrumentHooks.isInstrumented() ? "Measured" : "Checked";
164180
const results: BenchResult[] = [];
165181
for (const { name, fn, fnOpts } of registrations) {
166182
const uri = getUri(name);
183+
results.push(analysisResult(name));
184+
// A fork measures only its benchmark; Vitest still gets every result.
185+
if (mode.kind === "Fork" && mode.uri !== uri) continue;
167186
await runAnalysisTask(fn, fnOpts, uri);
168187
console.log(`[CodSpeed] ${label} ${uri}`);
169-
results.push(analysisResult(name));
188+
if (mode.kind === "Fork") {
189+
// The empty samples tell the parent that this fork measured its benchmark.
190+
writeForkSamples(mode.samplesFile, []);
191+
}
170192
}
171193
return results;
172194
}

‎packages/vitest-plugin/src/vitestBackend.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import {
2+
analysisIsolation,
23
getGitDir,
34
getInstrumentMode,
45
walltimeIsolation,
6+
type IsolationMode,
57
type WalltimeOptions,
68
} from "@codspeed/core";
79
import { join } from "path";
@@ -58,9 +60,7 @@ class V5Backend implements VitestBackend {
5860
}
5961

6062
configureIsolation(userConfig: ViteUserConfig): void {
61-
if (getInstrumentMode() !== "walltime") return;
62-
63-
const isolationMode = walltimeIsolation();
63+
const isolationMode = isolation();
6464
if (isolationMode.kind !== "Fork") return;
6565
restrictToBenchmarkFile(userConfig, isolationMode.uri);
6666
// The parent's global setup is still up while its forks run: forks skip
@@ -69,16 +69,15 @@ class V5Backend implements VitestBackend {
6969
}
7070

7171
/**
72-
* The parent of a forked walltime run measures nothing in its workers: they
73-
* queue the benchmarks, and the main process forks them once the run is over.
72+
* The parent of a forked run measures nothing in its workers: they queue the
73+
* benchmarks, and the main process forks them once the run is over.
7474
*/
7575
configureVitest(
7676
project: TestProject,
7777
vitest: Vitest,
7878
options: WalltimeOptions,
7979
): void {
80-
if (getInstrumentMode() !== "walltime") return;
81-
const isolationMode = walltimeIsolation();
80+
const isolationMode = isolation();
8281
if (isolationMode.kind === "Fork") {
8382
provideParentContext(project);
8483
return;
@@ -109,6 +108,17 @@ class V5Backend implements VitestBackend {
109108
}
110109
}
111110

111+
function isolation(): IsolationMode {
112+
switch (getInstrumentMode()) {
113+
case "walltime":
114+
return walltimeIsolation();
115+
case "analysis":
116+
return analysisIsolation();
117+
case "disabled":
118+
return { kind: "SharedProcess" };
119+
}
120+
}
121+
112122
function restrictToBenchmarkFile(
113123
userConfig: ViteUserConfig,
114124
uri: string,

0 commit comments

Comments
 (0)