Skip to content

Commit d51f2ba

Browse files
committed
feat(vitest): run walltime benchmarks in forks
With Vitest 5, each walltime benchmark runs in fresh `vitest bench` processes restricted to its file. The fork count resolves as `CODSPEED_WALLTIME_FORKS`, the benchmark's or run's `forks` option, `codspeedPlugin({ forks })`, then 3. The test timeout is scaled by the env or plugin fork count, since every fork of a test runs within it. Vitest's own report shows zeroed statistics for forked benchmarks; the CodSpeed results hold the pooled rounds. Vitest 3/4 don't fork. Closes COD-3960
1 parent c76b5b4 commit d51f2ba

13 files changed

Lines changed: 574 additions & 29 deletions

File tree

‎packages/tinybench-plugin/tests/isolation.integ.test.ts‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -153,19 +153,6 @@ describe("walltime forks", () => {
153153
RUN_TIMEOUT_MS,
154154
);
155155

156-
it(
157-
"takes the fork count from the environment over the option",
158-
async () => {
159-
const run = await runFixture({ forksOption: 2, forksEnv: 1 });
160-
161-
expect(run.status).toBe(0);
162-
for (const name of BENCHMARKS) {
163-
expect(forkPids(run, name).size).toBe(1);
164-
}
165-
},
166-
RUN_TIMEOUT_MS,
167-
);
168-
169156
it(
170157
"runs every benchmark in the parent process when isolation is disabled",
171158
async () => {

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { getV8Flags } from "@codspeed/core";
22
import { fromPartial } from "@total-typescript/shoehorn";
33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
44
import { type ViteUserConfig } from "vitest/config";
5+
import { type Vitest } from "vitest/node";
56
import codspeedPlugin from "../index";
67

78
const coreMocks = vi.hoisted(() => {
@@ -162,5 +163,17 @@ describe("codSpeedPlugin", () => {
162163

163164
expect(result.test?.benchmark?.suppressExportGetterWarnings).toBe(false);
164165
});
166+
167+
it("should register the fork reporter once across projects", () => {
168+
vi.stubEnv("CODSPEED_RUNNER_MODE", "walltime");
169+
if (typeof plugin.configureVitest !== "function")
170+
throw new Error("configureVitest is not a function");
171+
const vitest = fromPartial<Vitest>({ config: { reporters: [] } });
172+
for (const name of ["a (bench)", "b (bench)"]) {
173+
plugin.configureVitest(fromPartial({ vitest, project: { name } }));
174+
}
175+
176+
expect(vitest.config.reporters).toHaveLength(1);
177+
});
165178
});
166179
});
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import { spawn } from "child_process";
2+
import { once } from "events";
3+
import {
4+
mkdtempSync,
5+
readdirSync,
6+
readFileSync,
7+
rmSync,
8+
writeFileSync,
9+
} from "fs";
10+
import { createRequire } from "module";
11+
import { tmpdir } from "os";
12+
import { dirname, join } from "path";
13+
import { fileURLToPath } from "url";
14+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
15+
16+
const FIXTURE_DIR = fileURLToPath(
17+
new URL("../../tests/fixtures/isolation", import.meta.url),
18+
);
19+
const VITEST_BIN = join(
20+
dirname(createRequire(import.meta.url).resolve("vitest/package.json")),
21+
"vitest.mjs",
22+
);
23+
const PROCESS_ISOLATION_ENV = "CODSPEED_PROCESS_ISOLATION";
24+
const WALLTIME_FORKS_ENV = "CODSPEED_WALLTIME_FORKS";
25+
const DEFAULT_FORKS = 3;
26+
/** The fixture's `iterations`: every fork measures at least this many rounds. */
27+
const MIN_ROUNDS_PER_FORK = 4;
28+
const RUN_TIMEOUT_MS = 180_000;
29+
const RAN_LINE = /^ran (\d+) (.+)$/;
30+
31+
let tmpDir: string;
32+
33+
beforeEach(() => {
34+
tmpDir = mkdtempSync(join(tmpdir(), "codspeed-isolation-"));
35+
});
36+
37+
afterEach(() => {
38+
rmSync(tmpDir, { recursive: true, force: true });
39+
});
40+
41+
interface FixtureOptions {
42+
isolation?: string;
43+
forksEnv?: number;
44+
pluginForks?: number;
45+
firstForks?: number;
46+
failing?: boolean;
47+
}
48+
49+
async function runFixture(options: FixtureOptions = {}) {
50+
const logFile = join(tmpDir, "ran.log");
51+
writeFileSync(logFile, "");
52+
const profileFolder = join(tmpDir, "profile");
53+
const env: NodeJS.ProcessEnv = {
54+
...process.env,
55+
CODSPEED_ENV: "true",
56+
CODSPEED_RUNNER_MODE: "walltime",
57+
CODSPEED_PROFILE_FOLDER: profileFolder,
58+
ISOLATION_LOG_FILE: logFile,
59+
[PROCESS_ISOLATION_ENV]: options.isolation,
60+
[WALLTIME_FORKS_ENV]: options.forksEnv?.toString(),
61+
ISOLATION_FIXTURE_PLUGIN_FORKS: options.pluginForks?.toString(),
62+
ISOLATION_FIXTURE_FIRST_FORKS: options.firstForks?.toString(),
63+
ISOLATION_FIXTURE_FAIL: options.failing ? "1" : undefined,
64+
};
65+
66+
// Not spawnSync: blocking this worker times out its calls to Vitest.
67+
const child = spawn(process.execPath, [VITEST_BIN, "bench", "--run"], {
68+
cwd: FIXTURE_DIR,
69+
env,
70+
timeout: RUN_TIMEOUT_MS,
71+
stdio: "ignore",
72+
});
73+
const [status] = (await once(child, "close")) as [number | null];
74+
75+
const pidsByName = new Map<string, Set<number>>();
76+
for (const line of readFileSync(logFile, "utf8").split("\n")) {
77+
const match = RAN_LINE.exec(line);
78+
if (!match) continue;
79+
const pids = pidsByName.get(match[2]) ?? new Set<number>();
80+
pids.add(Number(match[1]));
81+
pidsByName.set(match[2], pids);
82+
}
83+
84+
const roundsByName = new Map<string, number>();
85+
const resultsDir = join(profileFolder, "results");
86+
for (const file of status === 0 ? readdirSync(resultsDir) : []) {
87+
const data = JSON.parse(readFileSync(join(resultsDir, file), "utf8"));
88+
for (const benchmark of data.benchmarks) {
89+
roundsByName.set(benchmark.name, benchmark.stats.rounds);
90+
}
91+
}
92+
return { status, pidsByName, roundsByName };
93+
}
94+
95+
describe("walltime forks", () => {
96+
it(
97+
"runs every benchmark in 3 forks by default and pools their rounds",
98+
async () => {
99+
const run = await runFixture();
100+
101+
expect(run.status).toBe(0);
102+
for (const name of ["first", "second", "third"]) {
103+
expect(run.pidsByName.get(name)?.size).toBe(DEFAULT_FORKS);
104+
expect(run.roundsByName.get(name)).toBeGreaterThanOrEqual(
105+
DEFAULT_FORKS * MIN_ROUNDS_PER_FORK,
106+
);
107+
}
108+
},
109+
RUN_TIMEOUT_MS,
110+
);
111+
112+
it(
113+
"takes the benchmark's option over the plugin's",
114+
async () => {
115+
const run = await runFixture({ firstForks: 2, pluginForks: 1 });
116+
117+
expect(run.status).toBe(0);
118+
expect(run.pidsByName.get("first")?.size).toBe(2);
119+
expect(run.pidsByName.get("second")?.size).toBe(1);
120+
},
121+
RUN_TIMEOUT_MS,
122+
);
123+
124+
it(
125+
"runs every benchmark in one process when isolation is disabled",
126+
async () => {
127+
const run = await runFixture({ isolation: "false" });
128+
129+
expect(run.status).toBe(0);
130+
const pids = new Set(
131+
[...run.pidsByName.values()].flatMap((set) => [...set]),
132+
);
133+
expect(pids.size).toBe(1);
134+
},
135+
RUN_TIMEOUT_MS,
136+
);
137+
138+
it(
139+
"fails the run when a benchmark throws in its fork",
140+
async () => {
141+
const run = await runFixture({ failing: true, forksEnv: 1 });
142+
143+
expect(run.status).not.toBe(0);
144+
},
145+
RUN_TIMEOUT_MS,
146+
);
147+
});

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,20 @@ import {
55
mongoMeasurement,
66
SetupInstrumentsRequestBody,
77
SetupInstrumentsResponse,
8+
type WalltimeOptions,
89
} from "@codspeed/core";
910
import { join } from "path";
1011
import { Plugin } from "vite";
1112
import { type ViteUserConfig } from "vitest/config";
1213
import { resolveVitestBackend } from "./vitestBackend";
1314

15+
declare module "vitest" {
16+
interface BenchFnOptions {
17+
/** This benchmark's `forks`, over the plugin's; see {@link WalltimeOptions}. */
18+
forks?: WalltimeOptions["forks"];
19+
}
20+
}
21+
1422
// get this file's directory path from import.meta.url
1523
const __dirname = new URL(".", import.meta.url).pathname;
1624
const isFileInTs = import.meta.url.endsWith(".ts");
@@ -21,7 +29,8 @@ function resolveFile(name: string): string {
2129
return join(__dirname, `${name}.${fileExtension}`);
2230
}
2331

24-
export default function codspeedPlugin(): Plugin {
32+
/** `options.forks`: see {@link WalltimeOptions}; isolation requires Vitest 5. */
33+
export default function codspeedPlugin(options: WalltimeOptions = {}): Plugin {
2534
return {
2635
name: "codspeed:vitest",
2736
apply(_, { mode }) {
@@ -37,19 +46,24 @@ export default function codspeedPlugin(): Plugin {
3746
return true;
3847
},
3948
enforce: "post",
40-
config(userConfig): ViteUserConfig {
49+
config(userConfig: ViteUserConfig): ViteUserConfig {
50+
const backend = resolveVitestBackend();
51+
backend.configureIsolation(userConfig);
4152
return {
4253
test: {
4354
pool: "forks",
4455
globalSetup: [resolveFile("globalSetup")],
45-
...resolveVitestBackend().getBenchmarkTestConfig(
56+
...backend.getBenchmarkTestConfig(
4657
getV8Flags(),
4758
resolveFile,
48-
(userConfig as ViteUserConfig).test,
59+
userConfig.test,
4960
),
5061
},
5162
};
5263
},
64+
configureVitest({ project, vitest }) {
65+
resolveVitestBackend().configureVitest(project, vitest, options);
66+
},
5367
};
5468
}
5569

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

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@ import {
55
MARKER_TYPE_BENCHMARK_START,
66
msToNs,
77
msToS,
8+
sortedSamplesNs,
89
writeWalltimeResults,
910
type Benchmark,
1011
type BenchmarkStats,
1112
} from "@codspeed/core";
1213
import type * as tinybench from "tinybench";
14+
import type { TaskMeta } from "vitest";
1315

1416
export type Tinybench = typeof tinybench;
1517

@@ -33,7 +35,7 @@ interface TinybenchStatistics {
3335
max: number;
3436
mean: number;
3537
sd: number;
36-
samples: number[] | undefined;
38+
samples: ArrayLike<number> | undefined;
3739
}
3840

3941
interface TinybenchTaskResult {
@@ -51,6 +53,41 @@ export interface TinybenchOptions {
5153
iterations?: number;
5254
}
5355

56+
/** A benchmark the main process measures in forks once the run is over. */
57+
export interface ForkedBenchmark {
58+
uri: string;
59+
name: string;
60+
/** The benchmark's own `forks` option; the plugin option applies otherwise. */
61+
forks: number | undefined;
62+
options: TinybenchOptions;
63+
}
64+
65+
// Vitest ships a test's meta to the main process with its result, so the
66+
// worker hands its queued benchmarks to the reporter through it.
67+
const FORKED_BENCHMARKS_META = "codspeedForkedBenchmarks";
68+
69+
type ForkMeta = TaskMeta & { [FORKED_BENCHMARKS_META]?: ForkedBenchmark[] };
70+
71+
/**
72+
* Adds benchmarks to the test's queue: a test can run several groups
73+
* (`bench.compare()`, `registration.run()`), and a retried or repeated test
74+
* queues the same ones again, which replace the earlier entries.
75+
*/
76+
export function queueForkedBenchmarks(
77+
meta: TaskMeta,
78+
benchmarks: ForkedBenchmark[],
79+
): void {
80+
const uris = new Set(benchmarks.map(({ uri }) => uri));
81+
(meta as ForkMeta)[FORKED_BENCHMARKS_META] = [
82+
...forkedBenchmarks(meta).filter(({ uri }) => !uris.has(uri)),
83+
...benchmarks,
84+
];
85+
}
86+
87+
export function forkedBenchmarks(meta: TaskMeta): ForkedBenchmark[] {
88+
return (meta as ForkMeta)[FORKED_BENCHMARKS_META] ?? [];
89+
}
90+
5491
/**
5592
* Drive the instrumentation window from each bench's run-mode setup/teardown
5693
* hooks so it brackets only tinybench's measured loop, excluding the warmup
@@ -142,7 +179,7 @@ function tinybenchResultToStats(
142179
const { totalTime, latency } = result;
143180
const { min, max, mean, sd, samples } = latency;
144181

145-
const sortedTimesNs = (samples ?? []).map(msToNs).sort((a, b) => a - b);
182+
const sortedTimesNs = sortedSamplesNs(samples ?? []);
146183
const meanNs = msToNs(mean);
147184
const stdevNs = msToNs(sd);
148185

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { randomUUID } from "crypto";
2+
import { readFileSync, rmSync, writeFileSync } from "fs";
3+
import { tmpdir } from "os";
4+
import { join } from "path";
5+
import { deserialize, serialize } from "v8";
6+
import type { TestModule, TestProject } from "vitest/node";
7+
8+
const FORK_CONTEXT_FILE_ENV = "CODSPEED_VITEST_FORK_CONTEXT_FILE";
9+
10+
/** What each project's global setup provided, by project name. */
11+
type ProvidedContexts = Record<string, Record<string, unknown>>;
12+
13+
/**
14+
* Hands the modules' provided context to the forks `run` starts, through a
15+
* file the forks inherit by its environment variable (not the environment
16+
* itself: a large provided fixture would exceed its size limit).
17+
*/
18+
export async function withForkContext<T>(
19+
modules: readonly TestModule[],
20+
run: () => Promise<T>,
21+
): Promise<T> {
22+
const contexts: ProvidedContexts = {};
23+
for (const { project } of modules) {
24+
contexts[project.name] = { ...project.getProvidedContext() };
25+
}
26+
const file = join(tmpdir(), `codspeed-vitest-context-${randomUUID()}`);
27+
writeFileSync(file, serialize(contexts));
28+
process.env[FORK_CONTEXT_FILE_ENV] = file;
29+
try {
30+
return await run();
31+
} finally {
32+
delete process.env[FORK_CONTEXT_FILE_ENV];
33+
rmSync(file, { force: true });
34+
}
35+
}
36+
37+
/** In a fork: provides `project` what the parent's global setup provided it. */
38+
export function provideParentContext(project: TestProject): void {
39+
const file = process.env[FORK_CONTEXT_FILE_ENV];
40+
if (file === undefined) {
41+
throw new Error("[CodSpeed] fork started without its parent's context");
42+
}
43+
const contexts: ProvidedContexts = deserialize(readFileSync(file));
44+
// `provide` is typed by the user's `ProvidedContext` augmentation, empty here.
45+
const provide = project.provide as (key: string, value: unknown) => void;
46+
for (const [key, value] of Object.entries(contexts[project.name] ?? {})) {
47+
provide(key, value);
48+
}
49+
}

0 commit comments

Comments
 (0)