Skip to content

Commit d4c8e42

Browse files
committed
test: cover process isolation end to end
Run fixtures in simulation mode with the instrument hooks stubbed (they only exist under the CodSpeed runner) and check, for core, benchmark.js, tinybench and Vitest 5, that: - every benchmark runs in a fresh process by default; - `CODSPEED_PROCESS_ISOLATION=false` runs them all in one process; - a failing benchmark fails the run; - core forwards the child exit code (128 + N for signals) and the execArgv. Tests that drive a plugin in-process against a mocked core now set `CODSPEED_PROCESS_ISOLATION=false`, because isolation would start the test runner again for every benchmark.
1 parent b147415 commit d4c8e42

13 files changed

Lines changed: 674 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Run by `isolation.integ.test.ts`. Prints the PID that measures each benchmark.
2+
const { InstrumentHooks } = require("@codspeed/core");
3+
const Benchmark = require("benchmark");
4+
const { withCodSpeed } = require("../../dist/index.cjs.js");
5+
6+
// There is no instrument hook runtime outside the CodSpeed runner, so pretend
7+
// the hooks are active. The child processes run this file again, so they get
8+
// the same override.
9+
InstrumentHooks.isInstrumented = () => true;
10+
11+
// The plugin reports every measured benchmark here, with the PID of the
12+
// process that measured it.
13+
const setExecutedBenchmark = InstrumentHooks.setExecutedBenchmark;
14+
InstrumentHooks.setExecutedBenchmark = (pid, uri) => {
15+
setExecutedBenchmark(pid, uri);
16+
console.log(`executed ${pid} ${uri}`);
17+
};
18+
19+
const suite = withCodSpeed(new Benchmark.Suite("isolation"));
20+
21+
suite
22+
.add("first", () => {})
23+
.add("second", () => {})
24+
.add("third", () => {})
25+
.add("async", {
26+
defer: true,
27+
fn: (deferred) => deferred.resolve(),
28+
});
29+
30+
if (process.env.ISOLATION_FIXTURE_FAIL !== undefined) {
31+
suite.add("failing", () => {
32+
throw new Error("benchmark failed");
33+
});
34+
}
35+
36+
// An unhandled rejection ends the process with exit code 1.
37+
suite.run();

‎packages/benchmark.js-plugin/tests/index.integ.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ jest.mock("@codspeed/core", () => {
1111
const actual = jest.requireActual("@codspeed/core");
1212
mockCore.getGitDir = actual.getGitDir;
1313
mockCore.getCallingFile = actual.getCallingFile;
14+
mockCore.Isolation = actual.Isolation;
1415
mockCore.wrapWithRootFrame = actual.wrapWithRootFrame;
1516
mockCore.wrapWithRootFrameSync = actual.wrapWithRootFrameSync;
1617
return mockCore;
@@ -19,6 +20,9 @@ jest.mock("@codspeed/core", () => {
1920
beforeEach(() => {
2021
mockReset(mockCore);
2122
jest.clearAllMocks();
23+
// These tests drive the plugin in this process against a mocked core, so
24+
// there is no benchmark process to spawn.
25+
process.env.CODSPEED_PROCESS_ISOLATION = "false";
2226
});
2327

2428
const benchOptions: Benchmark.Options = {
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { getV8Flags } from "@codspeed/core";
2+
import { spawnSync } from "child_process";
3+
import { join } from "path";
4+
5+
const FIXTURE = join(__dirname, "fixtures", "isolation.cjs");
6+
const PROCESS_ISOLATION_ENV = "CODSPEED_PROCESS_ISOLATION";
7+
/** `first`, `second`, `third` and the deferred `async` benchmark. */
8+
const BENCHMARK_COUNT = 4;
9+
/** Fails a run whose benchmark process got stuck instead of blocking the suite. */
10+
const RUN_TIMEOUT_MS = 60_000;
11+
const EXECUTED_LINE = /^executed (\d+) (.+)$/;
12+
13+
interface FixtureRun {
14+
status: number | null;
15+
stderr: string;
16+
/** PID that measured each benchmark. */
17+
pidsByUri: Map<string, number>;
18+
/** PID of the process the test started. */
19+
parentPid: number;
20+
}
21+
22+
interface FixtureOptions {
23+
/** Value of CODSPEED_PROCESS_ISOLATION, unset when undefined. */
24+
isolation?: string;
25+
failing?: boolean;
26+
}
27+
28+
function runFixture({ isolation, failing }: FixtureOptions = {}): FixtureRun {
29+
const env: NodeJS.ProcessEnv = {
30+
...process.env,
31+
CODSPEED_ENV: "true",
32+
CODSPEED_RUNNER_MODE: "simulation",
33+
};
34+
delete env[PROCESS_ISOLATION_ENV];
35+
if (isolation !== undefined) {
36+
env[PROCESS_ISOLATION_ENV] = isolation;
37+
}
38+
if (failing) {
39+
env.ISOLATION_FIXTURE_FAIL = "1";
40+
}
41+
42+
// The runner starts Node with these flags, and children must keep them.
43+
const result = spawnSync(process.execPath, [...getV8Flags(), FIXTURE], {
44+
env,
45+
encoding: "utf8",
46+
timeout: RUN_TIMEOUT_MS,
47+
});
48+
49+
const pidsByUri = new Map<string, number>();
50+
for (const line of result.stdout.split("\n")) {
51+
const match = EXECUTED_LINE.exec(line);
52+
if (match) {
53+
pidsByUri.set(match[2], Number(match[1]));
54+
}
55+
}
56+
return {
57+
status: result.status,
58+
stderr: result.stderr,
59+
pidsByUri,
60+
parentPid: result.pid,
61+
};
62+
}
63+
64+
describe("process isolation", () => {
65+
it.each([undefined, "1", "true"])(
66+
"measures every benchmark in its own process (isolation=%s)",
67+
(isolation) => {
68+
const run = runFixture({ isolation });
69+
70+
expect(run.status).toBe(0);
71+
expect(run.pidsByUri.size).toBe(BENCHMARK_COUNT);
72+
const pids = new Set(run.pidsByUri.values());
73+
expect(pids.size).toBe(BENCHMARK_COUNT);
74+
// The parent only spawns children, it never measures.
75+
expect(pids).not.toContain(run.parentPid);
76+
},
77+
);
78+
79+
it.each(["0", "false"])(
80+
"measures all benchmarks in one process (isolation=%s)",
81+
(isolation) => {
82+
const run = runFixture({ isolation });
83+
84+
expect(run.status).toBe(0);
85+
expect(run.pidsByUri.size).toBe(BENCHMARK_COUNT);
86+
expect(new Set(run.pidsByUri.values())).toEqual(new Set([run.parentPid]));
87+
},
88+
);
89+
90+
it.each(["true", "false"])(
91+
"fails the run when a benchmark throws (isolation=%s)",
92+
(isolation) => {
93+
const run = runFixture({ isolation, failing: true });
94+
95+
expect(run.status).not.toBe(0);
96+
expect(run.stderr).toContain("benchmark failed");
97+
},
98+
);
99+
100+
it("rejects values other than true and false", () => {
101+
const run = runFixture({ isolation: "maybe" });
102+
103+
expect(run.status).not.toBe(0);
104+
expect(run.stderr).toContain(`${PROCESS_ISOLATION_ENV} must be`);
105+
expect(run.pidsByUri.size).toBe(0);
106+
});
107+
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Run by `isolation.integ.test.ts`. Runs two benchmarks through `Isolation`.
2+
const { Isolation } = require("../../dist/index.cjs.js");
3+
4+
const isolation = Isolation.current();
5+
6+
function bench(uri) {
7+
console.log(`ran ${process.pid} ${uri} ${JSON.stringify(process.execArgv)}`);
8+
switch (process.env.ISOLATION_FIXTURE_ACTION) {
9+
case "exit":
10+
process.exit(3);
11+
case "kill":
12+
process.kill(process.pid, "SIGKILL");
13+
}
14+
}
15+
16+
async function main() {
17+
for (const uri of ["a", "b"]) {
18+
if (!isolation.shouldRun(uri)) continue;
19+
if (process.env.ISOLATION_FIXTURE_SYNC !== undefined) {
20+
isolation.runSync(uri, () => bench(uri));
21+
} else {
22+
await isolation.run(uri, async () => bench(uri));
23+
}
24+
}
25+
}
26+
27+
main();
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import { spawnSync } from "child_process";
2+
import { constants } from "os";
3+
import { join } from "path";
4+
import {
5+
ISOLATED_BENCHMARK_ENV,
6+
Isolation,
7+
PROCESS_ISOLATION_ENV,
8+
} from "../src/isolation";
9+
10+
const FIXTURE = join(__dirname, "fixtures", "isolation.cjs");
11+
/** Fails a run whose benchmark process got stuck instead of blocking the suite. */
12+
const RUN_TIMEOUT_MS = 60_000;
13+
const SIGNAL_EXIT_CODE_OFFSET = 128;
14+
const CHILD_EXIT_CODE = 3;
15+
const RAN_LINE = /^ran (\d+) (\S+) (.+)$/;
16+
/** Passed to Node to check that children keep the flags of their parent. */
17+
const NODE_FLAG = "--no-warnings";
18+
19+
/** `Isolation.current()` reads the environment once, so load a fresh copy. */
20+
function currentIsolation(env: Record<string, string | undefined>): Isolation {
21+
const saved = Object.fromEntries(
22+
Object.keys(env).map((key) => [key, process.env[key]]),
23+
);
24+
setEnv(env);
25+
try {
26+
let isolation: Isolation | undefined;
27+
jest.isolateModules(() => {
28+
// eslint-disable-next-line @typescript-eslint/no-require-imports
29+
isolation = require("../src/isolation").Isolation.current();
30+
});
31+
return isolation as unknown as Isolation;
32+
} finally {
33+
setEnv(saved);
34+
}
35+
}
36+
37+
function setEnv(env: Record<string, string | undefined>): void {
38+
for (const [key, value] of Object.entries(env)) {
39+
if (value === undefined) {
40+
delete process.env[key];
41+
} else {
42+
process.env[key] = value;
43+
}
44+
}
45+
}
46+
47+
describe("Isolation.current", () => {
48+
it.each([undefined, "1", "true"])(
49+
"runs one process per benchmark (isolation=%s)",
50+
(value) => {
51+
const isolation = currentIsolation({
52+
[PROCESS_ISOLATION_ENV]: value,
53+
[ISOLATED_BENCHMARK_ENV]: undefined,
54+
});
55+
56+
expect(isolation.mode).toEqual({ kind: "ProcessPerBenchmark" });
57+
expect(isolation.onlyBenchmark()).toBeUndefined();
58+
expect(isolation.isChild()).toBe(false);
59+
expect(isolation.shouldRun("any")).toBe(true);
60+
},
61+
);
62+
63+
it.each(["0", "false"])("shares one process (isolation=%s)", (value) => {
64+
const isolation = currentIsolation({
65+
[PROCESS_ISOLATION_ENV]: value,
66+
[ISOLATED_BENCHMARK_ENV]: undefined,
67+
});
68+
69+
expect(isolation.mode).toEqual({ kind: "SharedProcess" });
70+
expect(isolation.isChild()).toBe(false);
71+
expect(isolation.shouldRun("any")).toBe(true);
72+
});
73+
74+
it("restricts a child to its benchmark, whatever the isolation setting", () => {
75+
const isolation = currentIsolation({
76+
[PROCESS_ISOLATION_ENV]: "false",
77+
[ISOLATED_BENCHMARK_ENV]: "file::bench",
78+
});
79+
80+
expect(isolation.mode).toEqual({
81+
kind: "IsolatedBenchmark",
82+
uri: "file::bench",
83+
});
84+
expect(isolation.onlyBenchmark()).toBe("file::bench");
85+
expect(isolation.isChild()).toBe(true);
86+
expect(isolation.shouldRun("file::bench")).toBe(true);
87+
// Exact match only: a prefix is another benchmark.
88+
expect(isolation.shouldRun("file::bench 2")).toBe(false);
89+
expect(isolation.shouldRun("file")).toBe(false);
90+
});
91+
92+
it("rejects any other value", () => {
93+
expect(() =>
94+
currentIsolation({
95+
[PROCESS_ISOLATION_ENV]: "maybe",
96+
[ISOLATED_BENCHMARK_ENV]: undefined,
97+
}),
98+
).toThrow(`${PROCESS_ISOLATION_ENV} must be \`true\` or \`false\``);
99+
});
100+
101+
it("never spawns when no instrument measures", () => {
102+
expect(Isolation.shared().mode).toEqual({ kind: "SharedProcess" });
103+
});
104+
});
105+
106+
interface FixtureOptions {
107+
action?: "exit" | "kill";
108+
sync?: boolean;
109+
}
110+
111+
function runFixture({ action, sync }: FixtureOptions = {}) {
112+
const env: NodeJS.ProcessEnv = {
113+
...process.env,
114+
ISOLATION_FIXTURE_ACTION: action,
115+
};
116+
delete env[PROCESS_ISOLATION_ENV];
117+
delete env[ISOLATED_BENCHMARK_ENV];
118+
if (sync) {
119+
env.ISOLATION_FIXTURE_SYNC = "1";
120+
}
121+
const result = spawnSync(process.execPath, [NODE_FLAG, FIXTURE], {
122+
env,
123+
encoding: "utf8",
124+
timeout: RUN_TIMEOUT_MS,
125+
});
126+
const ran = result.stdout
127+
.split("\n")
128+
.map((line) => RAN_LINE.exec(line))
129+
.filter((match): match is RegExpExecArray => match !== null);
130+
return { status: result.status, ran };
131+
}
132+
133+
describe.each([
134+
{ name: "async", sync: false },
135+
{ name: "sync", sync: true },
136+
])("Isolation child process ($name run)", ({ sync }) => {
137+
it("runs each benchmark in a fresh process with the flags of its parent", () => {
138+
const { status, ran } = runFixture({ sync });
139+
140+
expect(status).toBe(0);
141+
expect(ran.map((match) => match[2])).toEqual(["a", "b"]);
142+
expect(new Set(ran.map((match) => match[1])).size).toBe(2);
143+
for (const match of ran) {
144+
expect(JSON.parse(match[3])).toEqual([NODE_FLAG]);
145+
}
146+
});
147+
148+
it("exits with the exit code of a failing child", () => {
149+
const { status, ran } = runFixture({ sync, action: "exit" });
150+
151+
expect(status).toBe(CHILD_EXIT_CODE);
152+
// The parent stops at the first failure.
153+
expect(ran.map((match) => match[2])).toEqual(["a"]);
154+
});
155+
156+
it("exits with 128 + N when a signal N killed the child", () => {
157+
const { status, ran } = runFixture({ sync, action: "kill" });
158+
159+
expect(status).toBe(SIGNAL_EXIT_CODE_OFFSET + constants.signals.SIGKILL);
160+
expect(ran.map((match) => match[2])).toEqual(["a"]);
161+
});
162+
});

0 commit comments

Comments
 (0)