supercov 4.28.0 → 4.29.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.
Files changed (32) hide show
  1. package/README.md +43 -16
  2. package/docs/cli.md +322 -2
  3. package/docs/getting-started.md +18 -0
  4. package/docs/mutation.md +539 -0
  5. package/docs/supported-suites.md +109 -60
  6. package/package.json +11 -10
  7. package/runtime/javascript/atomic.mjs +6 -2
  8. package/runtime/javascript/ava.mjs +12 -0
  9. package/runtime/javascript/bunTest.mjs +17 -0
  10. package/runtime/javascript/jest.cjs +67 -0
  11. package/runtime/javascript/jest.config.mjs +46 -6
  12. package/runtime/javascript/jestReporter.mjs +5 -2
  13. package/runtime/javascript/mocha.mjs +79 -5
  14. package/runtime/javascript/nodeTest.mjs +28 -0
  15. package/runtime/javascript/playwright.mjs +33 -0
  16. package/runtime/javascript/playwrightStrong.mjs +477 -0
  17. package/runtime/javascript/playwrightStrongReporter.mjs +377 -0
  18. package/runtime/javascript/runnerEntry.mjs +62 -0
  19. package/runtime/javascript/runtime.mjs +752 -13
  20. package/runtime/javascript/snapshots.mjs +16 -1
  21. package/runtime/javascript/strongJestHost.mjs +103 -0
  22. package/runtime/javascript/strongJob.mjs +78 -0
  23. package/runtime/javascript/strongJobs.mjs +809 -0
  24. package/runtime/javascript/strongMochaHost.mjs +166 -0
  25. package/runtime/javascript/strongWasmOut.cjs +96 -0
  26. package/runtime/javascript/tap.mjs +43 -1
  27. package/runtime/javascript/transport.mjs +5 -0
  28. package/runtime/javascript/vitest.mjs +74 -2
  29. package/runtime/javascript/vitestBrowser.mjs +34 -2
  30. package/runtime/javascript/vitestStrong.mjs +234 -0
  31. package/runtime/javascript/vitestStrongReporter.mjs +2268 -0
  32. package/runtime/javascript/vitestStrongSpawner.mjs +248 -0
@@ -0,0 +1,809 @@
1
+ // The strong pass's driver for the runners whose processes are started with
2
+ // a mutant on (docs/design/strong-mutation.md): Jest, node:test, Mocha, AVA,
3
+ // node-tap, bun:test and Vitest Browser Mode. The engine starts it in place of
4
+ // the run's command, `node strongJobs.mjs -- <command>`, in the instrumented
5
+ // copy, with the plan (SUPERCOV_STRONG_PLAN) and where the verdicts go
6
+ // (SUPERCOV_STRONG_RESULTS).
7
+ //
8
+ // Each job is one start of the command for one test file: the mutant on in
9
+ // every process from its start (SUPERCOV_ACTIVE_MUTANT), only the job's tests
10
+ // run (SUPERCOV_STRONG_JOB, read by the runner's adapter through
11
+ // strongJob.mjs), and the first failure stops it. The tests' outcomes are the
12
+ // adapter's own evidence records, in the job's own evidence directory. A
13
+ // fresh process per job is how these runners isolate a test file anyway: no
14
+ // mutant's module state, timers or process-wide changes reach another's.
15
+ //
16
+ // For each mutant: its candidate tests by test file, the cheapest first; the
17
+ // next file only while it lives. Each file runs first without a mutant (its
18
+ // baseline), with every test a mutant will run there; a test that fails there
19
+ // is no kill, and a file whose baseline fails or leaves a test out (a subtest
20
+ // whose parent was not chosen) runs whole from then on. A kill by a job that
21
+ // ran other tests than its baseline did is confirmed by running the job's
22
+ // tests again without the mutant. A job past 3x its baseline and 10 s is
23
+ // stopped: a timeout, unless a test had already failed.
24
+ import { fork, spawn } from "node:child_process";
25
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
26
+ import { availableParallelism, constants, cpus } from "node:os";
27
+ import { basename, delimiter, join, resolve } from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+
30
+ // A file whose baseline job took at most this long, the start of the command
31
+ // included, runs all its baseline's tests beside a mutant's own candidates
32
+ // rather than confirm a kill apart (`tryFile`).
33
+ const UNION_MS = 1_500;
34
+ // What a job costs beyond its tests' own time, in the order a mutant's
35
+ // files run: a start of the runner, or a resident runner's file setup.
36
+ const JOB_START_MS = 300;
37
+ // Vitest's node tests run here where the run also had browser tests, which
38
+ // Vitest's own driver cannot run beside them.
39
+ const RUNNERS = new Set(["jest", "mocha", "node:test", "ava", "tap", "bun:test", "vitest-browser", "vitest"]);
40
+
41
+ // The wasm output wrapper's source (strongWasmOut.cjs), written beside a
42
+ // pass's jobs as `wasm-bindgen` and `wasm-pack` where the pass switches Rust
43
+ // compiled to wasm.
44
+ export const WASM_OUT = "#!/usr/bin/env node\n// A strong pass over Rust compiled to wasm (strongJobs.mjs): each job that\n// starts the command builds the wasm again, and wasm-bindgen (or wasm-pack\n// build) writes its glue where every other job's tests load it. This stands\n// in for the tool on the jobs' PATH: the tool writes into a fresh directory\n// beside its output directory, and each file is then renamed into place, and\n// only where its bytes changed. A rebuild of the same wasm changes nothing,\n// and a test never reads a file half written. It notes that it ran (`used`\n// beside it), so the driver knows the wasm is built this way.\n// CommonJS, as Node loads a file without an extension.\nconst { spawnSync } = require(\"node:child_process\");\nconst { accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } = require(\"node:fs\");\nconst { basename, delimiter, dirname, join, resolve } = require(\"node:path\");\n\nconst here = dirname(process.argv[1]);\nconst tool = basename(process.argv[1]);\nconst real = (process.env.PATH ?? \"\")\n .split(delimiter)\n .filter((directory) => directory && resolve(directory) !== here)\n .map((directory) => join(directory, tool))\n .find((candidate) => {\n try {\n accessSync(candidate, constants.X_OK);\n return true;\n }\n catch {\n return false;\n }\n });\nif (!real) {\n console.error(`supercov: no ${tool} on PATH`);\n process.exit(127);\n}\nconst args = process.argv.slice(2);\nconst passThrough = () => process.exit(spawnSync(real, args, { stdio: \"inherit\" }).status ?? 1);\n\n// The output directory the tool was asked for, and where it is in `args`.\nlet output;\nlet at = -1;\nfor (let index = 0; index < args.length; index += 1) {\n const argument = args[index];\n if (argument === \"--out-dir\" || (tool === \"wasm-pack\" && argument === \"-d\")) {\n output = args[index + 1];\n at = index + 1;\n break;\n }\n if (argument.startsWith(\"--out-dir=\")) {\n output = argument.slice(\"--out-dir=\".length);\n at = index;\n break;\n }\n}\nlet base = process.cwd();\nif (tool === \"wasm-pack\") {\n if (args[0] !== \"build\")\n passThrough();\n // wasm-pack reads its output directory against the crate's, `pkg`\n // where none is given.\n const crate = args.slice(1).find((argument, index, rest) => !argument.startsWith(\"-\") && ![\"-d\", \"--out-dir\", \"-t\", \"--target\", \"--scope\", \"--mode\", \"--out-name\", \"--profile\"].includes(rest[index - 1]));\n base = resolve(crate ?? \".\");\n output ??= \"pkg\";\n}\nif (output === undefined)\n passThrough();\nconst target = resolve(base, output);\nconst fresh = `${target}.supercov-${process.pid}`;\nrmSync(fresh, { recursive: true, force: true });\nconst changed = [...args];\nif (at < 0)\n changed.push(\"--out-dir\", fresh);\nelse if (changed[at].startsWith(\"--out-dir=\"))\n changed[at] = `--out-dir=${fresh}`;\nelse\n changed[at] = fresh;\nconst ran = spawnSync(real, changed, { stdio: \"inherit\" });\nif (ran.status === 0) {\n const move = (from, to) => {\n for (const name of readdirSync(from)) {\n const source = join(from, name);\n const destination = join(to, name);\n if (statSync(source).isDirectory()) {\n mkdirSync(destination, { recursive: true });\n move(source, destination);\n continue;\n }\n const same = existsSync(destination) && readFileSync(destination).equals(readFileSync(source));\n if (!same)\n renameSync(source, destination);\n }\n };\n mkdirSync(target, { recursive: true });\n move(fresh, target);\n writeFileSync(join(here, \"used\"), \"\");\n}\nrmSync(fresh, { recursive: true, force: true });\nprocess.exit(ran.status ?? 1);\n";
45
+
46
+ // Every process the pass started that may still run: each job's command and
47
+ // each resident runner, in a process group of its own. They are stopped with
48
+ // the pass, which a terminal's Ctrl-C does not reach them through.
49
+ const started = new Set();
50
+
51
+ function track(child) {
52
+ started.add(child);
53
+ child.once("exit", () => started.delete(child));
54
+ return child;
55
+ }
56
+
57
+ // Stops every process the pass started.
58
+ export function stopStarted() {
59
+ for (const child of started)
60
+ stop(child);
61
+ }
62
+
63
+ function parallelism() {
64
+ const given = Number(process.env.SUPERCOV_STRONG_WORKERS);
65
+ if (Number.isSafeInteger(given) && given > 0)
66
+ return given;
67
+ const available = typeof availableParallelism === "function" ? availableParallelism() : cpus().length;
68
+ return Math.max(1, available - 1);
69
+ }
70
+
71
+ // At most `size` jobs at once: the lowest `priority` first, and first come
72
+ // first served among equals.
73
+ export function slots(size) {
74
+ let free = size;
75
+ const waiting = [];
76
+ return async function run(work, priority = 0) {
77
+ if (free > 0)
78
+ free -= 1;
79
+ else {
80
+ await new Promise((resolve) => {
81
+ // After every waiting job of its priority or a lower one.
82
+ const at = waiting.findIndex((other) => other.priority > priority);
83
+ waiting.splice(at < 0 ? waiting.length : at, 0, { priority, resolve });
84
+ });
85
+ }
86
+ try {
87
+ return await work();
88
+ }
89
+ finally {
90
+ const next = waiting.shift();
91
+ if (next)
92
+ next.resolve();
93
+ else
94
+ free += 1;
95
+ }
96
+ };
97
+ }
98
+
99
+ // Every file under `directory`, recursively.
100
+ function filesUnder(directory) {
101
+ let entries;
102
+ try {
103
+ entries = readdirSync(directory, { withFileTypes: true });
104
+ }
105
+ catch {
106
+ return [];
107
+ }
108
+ return entries.flatMap((entry) => entry.isDirectory()
109
+ ? filesUnder(join(directory, entry.name))
110
+ : [join(directory, entry.name)]);
111
+ }
112
+
113
+ // Each test's outcome in a job's evidence: the last attempt's, where any
114
+ // record says more than `unknown` (Jest writes coverage and outcome apart),
115
+ // in the order the tests ended.
116
+ export function outcomes(directory) {
117
+ const records = [];
118
+ for (const path of filesUnder(directory)) {
119
+ let text;
120
+ try {
121
+ text = readFileSync(path, "utf8");
122
+ }
123
+ catch {
124
+ continue;
125
+ }
126
+ const lines = path.endsWith(".jsonl") ? text.split("\n") : path.endsWith(".json") ? [text] : [];
127
+ for (const line of lines) {
128
+ if (!line.trim())
129
+ continue;
130
+ try {
131
+ records.push(JSON.parse(line));
132
+ }
133
+ catch {
134
+ // A line cut short by a stopped process says nothing.
135
+ }
136
+ }
137
+ }
138
+ const tests = new Map();
139
+ for (const record of records) {
140
+ if (typeof record?.testId !== "string" || (record.role && record.role !== "test"))
141
+ continue;
142
+ const seen = tests.get(record.testId);
143
+ const retry = record.retry ?? 0;
144
+ const status = record.status ?? "unknown";
145
+ if (!seen) {
146
+ tests.set(record.testId, { status, retry });
147
+ continue;
148
+ }
149
+ if (status === "unknown" && seen.status !== "unknown")
150
+ continue;
151
+ if (retry >= seen.retry || seen.status === "unknown")
152
+ tests.set(record.testId, { status, retry: Math.max(retry, seen.retry) });
153
+ }
154
+ return new Map([...tests].map(([id, { status }]) => [id, status]));
155
+ }
156
+
157
+ // The command for one job: Bun's runner takes the file as an argument, as it
158
+ // loads every test file into one process; the other runners' adapters keep
159
+ // their runner from loading another file.
160
+ export function commandFor(command, file, root = process.cwd(), runner = undefined) {
161
+ const [program, first] = command;
162
+ // A tap test file is a program of its own, as tap's runner runs it (and
163
+ // StrykerJS's tap runner): run by itself, beside other jobs, it shares
164
+ // none of the working files tap's command keeps in the project.
165
+ if (runner === "tap" && /\.[cm]?js$/.test(file))
166
+ return [process.execPath, file];
167
+ if (program && /^bun(?:\.exe)?$/.test(basename(program)) && first === "test")
168
+ return [...command, `./${file}`];
169
+ return withoutNpx(command, root);
170
+ }
171
+
172
+ // `npx <tool> ...` where the project has the tool: the tool itself. npx
173
+ // costs a start of npm's CLI before each job's, a third of a small suite's
174
+ // job.
175
+ export function withoutNpx(command, root) {
176
+ const [program, ...rest] = command;
177
+ if (!program || !/^npx(?:\.cmd)?$/.test(basename(program)) || process.platform === "win32")
178
+ return command;
179
+ const at = rest.findIndex((word) => !/^(?:-y|--yes|--no-install|--offline)$/.test(word));
180
+ const tool = rest[at];
181
+ if (at < 0 || !tool || tool.startsWith("-") || tool.includes("@") || tool.includes("/"))
182
+ return command;
183
+ const binary = join(root, "node_modules", ".bin", tool);
184
+ return existsSync(binary) ? [binary, ...rest.slice(at + 1)] : command;
185
+ }
186
+
187
+ // The arguments a command gives Jest, where it starts Jest itself (`jest`,
188
+ // `npx jest`, `node_modules/.bin/jest`): a resident Jest parses them as
189
+ // Jest's CLI would.
190
+ export function jestArguments(command) {
191
+ const at = command.findIndex((word) => /(?:^|[\\/])jest(?:\.js)?$/.test(word) || /jest-cli[\\/]bin[\\/]jest\.js$/.test(word));
192
+ return at < 0 ? undefined : command.slice(at + 1);
193
+ }
194
+
195
+ // The arguments a command gives Mocha, where it starts Mocha itself.
196
+ export function mochaArguments(command) {
197
+ const at = command.findIndex((word) => /(?:^|[\\/])_?mocha(?:\.js)?$/.test(word));
198
+ return at < 0 ? undefined : command.slice(at + 1);
199
+ }
200
+
201
+ // Whether a project's .js files are CommonJS (its package.json has no
202
+ // `"type": "module"`).
203
+ export function packageIsCommonJs(root) {
204
+ try {
205
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf8")).type !== "module";
206
+ }
207
+ catch {
208
+ return true;
209
+ }
210
+ }
211
+
212
+ // Resident runners (strongJestHost.mjs, strongMochaHost.mjs), each running one
213
+ // job at a time. A host whose job passes its limit is stopped, and the next
214
+ // job starts another.
215
+ function residentHosts({ script, args, root, environment, log }) {
216
+ const idle = [];
217
+ const all = new Set();
218
+ const host = () => new Promise((resolveHost, rejectHost) => {
219
+ const child = fork(fileURLToPath(new URL(`./${script}`, import.meta.url)), [], {
220
+ cwd: root,
221
+ env: environment,
222
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
223
+ detached: process.platform !== "win32",
224
+ });
225
+ // Its output is drained, and kept for whoever reads why a job failed.
226
+ const keep = (chunk) => {
227
+ try {
228
+ appendFileSync(log, chunk);
229
+ }
230
+ catch {
231
+ // The log is for reading only.
232
+ }
233
+ };
234
+ child.stdout.on("data", keep);
235
+ child.stderr.on("data", keep);
236
+ track(child);
237
+ all.add(child);
238
+ child.once("exit", () => all.delete(child));
239
+ child.on("message", function started(message) {
240
+ if (message?.type === "started")
241
+ child.send({ type: "init", args: args ?? [] });
242
+ else if (message?.type === "ready") {
243
+ child.off("message", started);
244
+ if (message.error) {
245
+ stop(child);
246
+ rejectHost(new Error(message.error));
247
+ }
248
+ else
249
+ resolveHost(child);
250
+ }
251
+ });
252
+ child.once("error", rejectHost);
253
+ });
254
+ let number = 0;
255
+ return {
256
+ async run(job, limitMs) {
257
+ let child;
258
+ try {
259
+ child = idle.pop() ?? await host();
260
+ }
261
+ catch (error) {
262
+ try {
263
+ appendFileSync(log, `[supercov] the resident runner did not start: ${error?.stack ?? error}\n`);
264
+ }
265
+ catch {
266
+ // The log is for reading only.
267
+ }
268
+ return { timedOut: false, error, notStarted: true };
269
+ }
270
+ const id = ++number;
271
+ return new Promise((resolveRun) => {
272
+ let settled = false;
273
+ const settle = (outcome) => {
274
+ if (settled)
275
+ return;
276
+ settled = true;
277
+ clearTimeout(timer);
278
+ child.off("message", answered);
279
+ child.off("exit", exited);
280
+ resolveRun(outcome);
281
+ };
282
+ const answered = (message) => {
283
+ if (message?.type === "done" && message.id === id) {
284
+ idle.push(child);
285
+ settle({ timedOut: false, error: message.error });
286
+ }
287
+ };
288
+ const exited = () => settle({ timedOut: false, error: "the resident runner ended" });
289
+ const timer = setTimeout(() => {
290
+ stop(child);
291
+ settle({ timedOut: true });
292
+ }, limitMs);
293
+ child.on("message", answered);
294
+ child.once("exit", exited);
295
+ child.send({ type: "job", id, ...job });
296
+ });
297
+ },
298
+ close() {
299
+ for (const child of all)
300
+ stop(child);
301
+ },
302
+ };
303
+ }
304
+
305
+ function readTimeouts(path) {
306
+ try {
307
+ return readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => {
308
+ try {
309
+ return JSON.parse(line).mutant;
310
+ }
311
+ catch {
312
+ return undefined;
313
+ }
314
+ });
315
+ }
316
+ catch {
317
+ return [];
318
+ }
319
+ }
320
+
321
+ function stop(child) {
322
+ if (child.exitCode !== null || child.signalCode !== null)
323
+ return;
324
+ try {
325
+ if (process.platform === "win32")
326
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
327
+ else
328
+ process.kill(-child.pid, "SIGKILL");
329
+ }
330
+ catch {
331
+ try {
332
+ child.kill("SIGKILL");
333
+ }
334
+ catch {
335
+ // Already gone.
336
+ }
337
+ }
338
+ }
339
+
340
+ export async function drive({ command, plan, resultsPath, root = process.cwd(), workers = parallelism(), environment = process.env, graceMs = 10_000, baselineGraceMs = 60_000 }) {
341
+ const started = Date.now();
342
+ const write = (record) => appendFileSync(resultsPath, `${JSON.stringify(record)}\n`);
343
+ const work = `${resultsPath}.jobs`;
344
+ mkdirSync(work, { recursive: true });
345
+ const tests = plan.tests;
346
+ const byId = new Map(tests.map((test) => [test.id, test]));
347
+ const handled = (test) => RUNNERS.has(test?.runner);
348
+ // Every test file of the run under these runners: a job's adapter runs
349
+ // none of their tests but the job's.
350
+ const known = [...new Set(tests.filter(handled).map((test) => test.file).filter(Boolean))].sort();
351
+ const testsOf = new Map();
352
+ const runnerOf = new Map(tests.filter(handled).map((test) => [test.file, test.runner]));
353
+ for (const test of tests) {
354
+ if (!handled(test) || !test.file)
355
+ continue;
356
+ if (!testsOf.has(test.file))
357
+ testsOf.set(test.file, []);
358
+ testsOf.get(test.file).push(test);
359
+ }
360
+
361
+ // The copy's own list: the mutant at each index must be the run's, and
362
+ // one the instrumenter could not place has no switch to turn on.
363
+ let listed = {};
364
+ try {
365
+ listed = JSON.parse(readFileSync(join(root, ".supercov/frontend-evidence/mutants.json"), "utf8")).files ?? {};
366
+ }
367
+ catch {
368
+ listed = {};
369
+ }
370
+ const idOf = (file, entry) => entry.id ||
371
+ `${file}:${entry.start?.[0]}:${entry.start?.[1]}-${entry.end?.[0]}:${entry.end?.[1]}:${entry.mutator}:${entry.replacement}`;
372
+ const indexes = new Map();
373
+ for (const [file, entries] of Object.entries(listed))
374
+ entries.forEach((entry, index) => indexes.set(idOf(file, entry), { index, entry }));
375
+
376
+ // A command that starts Jest or Mocha itself: its jobs run in resident
377
+ // runners, one per worker, rather than start the command each.
378
+ const residentAllowed = environment.SUPERCOV_STRONG_RESIDENT !== "0";
379
+ const jestArgs = residentAllowed ? jestArguments(withoutNpx(command, root)) : undefined;
380
+ const mochaArgs = residentAllowed ? mochaArguments(withoutNpx(command, root)) : undefined;
381
+ const jestHosts = residentHosts({ script: "strongJestHost.mjs", args: jestArgs, root, environment, log: join(work, "jest-hosts.log") });
382
+ const mochaHosts = residentHosts({ script: "strongMochaHost.mjs", args: mochaArgs, root, environment, log: join(work, "mocha-hosts.log") });
383
+ // A suite of ES modules, which cannot be loaded again in one thread,
384
+ // runs each job in a fresh thread of a resident Mocha
385
+ // (SUPERCOV_STRONG_MOCHA_ESM=process: a process per job instead).
386
+ const esmHosts = residentHosts({ script: "strongMochaHost.mjs", args: mochaArgs, root, environment: { ...environment, SUPERCOV_MOCHA_FRESH_WORKERS: "1" }, log: join(work, "mocha-esm-hosts.log") });
387
+ const esmResident = process.env.SUPERCOV_STRONG_MOCHA_ESM !== "process";
388
+ const commonJs = packageIsCommonJs(root);
389
+ const broken = new Set();
390
+ const residentFor = (file) => {
391
+ const runner = runnerOf.get(file);
392
+ if (broken.has(runner))
393
+ return undefined;
394
+ if (runner === "jest" && jestArgs)
395
+ return jestHosts;
396
+ if (runner === "mocha" && mochaArgs && (/\.cjs$/.test(file) || (commonJs && /\.js$/.test(file))))
397
+ return mochaHosts;
398
+ if (runner === "mocha" && mochaArgs && esmResident)
399
+ return esmHosts;
400
+ return undefined;
401
+ };
402
+ // Rust compiled to wasm (SUPERCOV_WASM_STRONG): a job that starts the
403
+ // command builds the wasm again, writing it where every other job's
404
+ // tests load it, so where any file's jobs start the command, one job
405
+ // runs at a time.
406
+ const rebuilds = Boolean(process.env.SUPERCOV_WASM_STRONG) && known.some((file) => !residentFor(file));
407
+ // wasm-bindgen and wasm-pack build, first on the jobs' PATH, write the
408
+ // glue so that a rebuild of the same wasm changes nothing in place
409
+ // (strongWasmOut.cjs). Jobs start one at a time until one of them ran
410
+ // (it notes that it did): a build that writes its wasm another way
411
+ // keeps them so.
412
+ const wasmTools = join(work, "wasm-tools");
413
+ if (rebuilds) {
414
+ mkdirSync(wasmTools, { recursive: true });
415
+ for (const name of ["wasm-bindgen", "wasm-pack"])
416
+ writeFileSync(join(wasmTools, name), WASM_OUT, { mode: 0o755 });
417
+ }
418
+ const wasmOutUsed = () => existsSync(join(wasmTools, "used"));
419
+ const parallel = slots(workers);
420
+ const serial = slots(1);
421
+ const run = !rebuilds ? parallel : async (work, priority) => {
422
+ if (wasmOutUsed())
423
+ return parallel(work, priority);
424
+ let handed = false;
425
+ const result = await serial(async () => {
426
+ if (wasmOutUsed()) {
427
+ handed = true;
428
+ return undefined;
429
+ }
430
+ return work();
431
+ });
432
+ return handed ? parallel(work, priority) : result;
433
+ };
434
+ const profile = { jobs: 0, baselines: 0, confirmations: 0, overturned: 0, stopped: 0, jobMs: 0 };
435
+ let jobNumber = 0;
436
+
437
+ // One start of the command: `tests` of `file` (null: all of them), with
438
+ // `mutant` on (null: none), stopped at `limitMs`. A job of a mutant's
439
+ // later batch (`priority` 1, 2, ...) waits behind every first file's,
440
+ // so that the kills most mutants get at once come first, and a
441
+ // survivor's many files fill what is left.
442
+ function job({ mutant, file, tests: chosen, bail, limitMs, priority = 0 }) {
443
+ return run(() => new Promise((resolveJob) => {
444
+ const number = ++jobNumber;
445
+ profile.jobs += 1;
446
+ const directory = join(work, String(number));
447
+ const evidence = join(directory, "evidence");
448
+ mkdirSync(evidence, { recursive: true });
449
+ const spec = join(directory, "job.json");
450
+ writeFileSync(spec, JSON.stringify({ files: { [file]: chosen === null ? null : [...chosen] }, known, bail, mutant: mutant ? `${mutant.file}#${mutant.index}` : null }));
451
+ const results = join(directory, "results.jsonl");
452
+ const begun = Date.now();
453
+ const resident = residentFor(file);
454
+ // A job's outcome, read from its evidence; then its directory is
455
+ // removed, as nothing after reads it (a job's evidence ran to
456
+ // 24 MB on nanoid, a gigabyte a pass).
457
+ const read = (outcome) => {
458
+ const statuses = outcomes(evidence);
459
+ if (environment.SUPERCOV_STRONG_KEEP !== "1")
460
+ rmSync(directory, { recursive: true, force: true });
461
+ return { ...outcome, statuses };
462
+ };
463
+ // A runner's own command, started for this job alone.
464
+ const spawnJob = () => {
465
+ const [program, ...args] = commandFor(command, file, root, runnerOf.get(file));
466
+ try {
467
+ const overrides = {
468
+ // What tap's runner gives each test file it starts.
469
+ ...(runnerOf.get(file) === "tap" ? { TAP_CHILD_ID: String(number) } : {}),
470
+ SUPERCOV_EVIDENCE_DIR: evidence,
471
+ SUPERCOV_STRONG_JOB: spec,
472
+ SUPERCOV_ACTIVE_MUTANT: mutant ? `${mutant.file}#${mutant.index}` : "-",
473
+ SUPERCOV_STRONG_RESULTS: results,
474
+ // Only this driver reads the plan: Vitest's and
475
+ // Playwright's configurations would drive their own.
476
+ SUPERCOV_STRONG_PLAN: "",
477
+ ...(rebuilds ? { PATH: `${wasmTools}${delimiter}${environment.PATH ?? ""}` } : {}),
478
+ };
479
+ // Supercov's preload, in this process too, gives every child
480
+ // this process's own Supercov settings over the ones it is
481
+ // given: the job's are this process's while it starts.
482
+ const saved = Object.fromEntries(Object.keys(overrides).map((name) => [name, process.env[name]]));
483
+ Object.assign(process.env, overrides);
484
+ let child;
485
+ try {
486
+ child = spawn(program, args, {
487
+ cwd: root,
488
+ env: { ...environment, ...overrides },
489
+ stdio: ["ignore", "pipe", "pipe"],
490
+ detached: process.platform !== "win32",
491
+ shell: process.platform === "win32",
492
+ windowsHide: true,
493
+ });
494
+ }
495
+ finally {
496
+ for (const [name, value] of Object.entries(saved)) {
497
+ if (value === undefined)
498
+ delete process.env[name];
499
+ else
500
+ process.env[name] = value;
501
+ }
502
+ }
503
+ track(child);
504
+ // Its output is read by no one: drained, so the job never
505
+ // waits on a full pipe.
506
+ child.stdout.resume();
507
+ child.stderr.resume();
508
+ let timedOut = false;
509
+ const timer = setTimeout(() => {
510
+ timedOut = true;
511
+ profile.stopped += 1;
512
+ stop(child);
513
+ }, limitMs);
514
+ const finish = (code, error) => {
515
+ clearTimeout(timer);
516
+ profile.jobMs += Date.now() - begun;
517
+ const mutantKey = mutant ? `${mutant.file}#${mutant.index}` : undefined;
518
+ resolveJob(read({
519
+ timedOut,
520
+ mutantTimedOut: mutantKey !== undefined && readTimeouts(`${results}.timeouts.jsonl`).includes(mutantKey),
521
+ exitCode: code,
522
+ error,
523
+ durationMs: Date.now() - begun,
524
+ }));
525
+ };
526
+ child.on("error", (error) => finish(null, error));
527
+ child.on("close", (code) => finish(code));
528
+ }
529
+ catch (error) {
530
+ resolveJob(read({ timedOut: false, mutantTimedOut: false, exitCode: null, error, durationMs: 0 }));
531
+ }
532
+ };
533
+ if (!resident) {
534
+ spawnJob();
535
+ return;
536
+ }
537
+ // A resident runner runs the job (strongJestHost.mjs,
538
+ // strongMochaHost.mjs); one that cannot start leaves its runner's
539
+ // jobs to the command.
540
+ const environmentOfJob = {
541
+ SUPERCOV_EVIDENCE_DIR: evidence,
542
+ SUPERCOV_STRONG_JOB: spec,
543
+ SUPERCOV_STRONG_RESULTS: results,
544
+ SUPERCOV_STRONG_PLAN: "",
545
+ };
546
+ resident.run({ file: join(root, file), mutant: mutant ? { file: mutant.file, index: mutant.index } : null, environment: environmentOfJob }, limitMs).then(({ timedOut, error, notStarted }) => {
547
+ if (notStarted) {
548
+ broken.add(runnerOf.get(file));
549
+ spawnJob();
550
+ return;
551
+ }
552
+ if (timedOut)
553
+ profile.stopped += 1;
554
+ profile.jobMs += Date.now() - begun;
555
+ const mutantKey = mutant ? `${mutant.file}#${mutant.index}` : undefined;
556
+ resolveJob(read({
557
+ timedOut,
558
+ mutantTimedOut: mutantKey !== undefined && readTimeouts(`${results}.timeouts.jsonl`).includes(mutantKey),
559
+ exitCode: error ? 1 : 0,
560
+ error,
561
+ durationMs: Date.now() - begun,
562
+ }));
563
+ });
564
+ }), priority);
565
+ }
566
+
567
+ // What a file does without a mutant: once with every test a mutant will
568
+ // run there, and, where that cannot stand for the file, once whole.
569
+ const files = new Map();
570
+ const fileState = (file) => {
571
+ if (!files.has(file))
572
+ files.set(file, { union: new Set(), wholeNeeded: false, subset: undefined, whole: undefined });
573
+ return files.get(file);
574
+ };
575
+ const confirmations = new Map();
576
+ const cost = (file, chosen) => (chosen ? [...chosen] : (testsOf.get(file) ?? []).map((test) => test.id))
577
+ .reduce((sum, id) => sum + (byId.get(id)?.durationMs ?? 1_000), 0);
578
+ const baselineLimit = (file, chosen) => 3 * cost(file, chosen) + baselineGraceMs;
579
+ const passedAll = (result, chosen) => !result.timedOut && [...chosen].every((id) => result.statuses.get(id) === "passed");
580
+ async function wholeBaseline(file) {
581
+ const state = fileState(file);
582
+ state.whole ??= (async () => {
583
+ profile.baselines += 1;
584
+ const result = await job({ mutant: null, file, tests: null, bail: false, limitMs: baselineLimit(file, null) });
585
+ const passing = new Set([...result.statuses].filter(([, status]) => status === "passed").map(([id]) => id));
586
+ return { ...result, passing, finished: !result.timedOut && passing.size > 0 };
587
+ })();
588
+ return state.whole;
589
+ }
590
+ // The baseline a mutant's job in `file` is judged by: the subset's where
591
+ // it stood for the file, else the whole file's.
592
+ async function baselineFor(file) {
593
+ const state = fileState(file);
594
+ if (!state.wholeNeeded && state.union.size > 0) {
595
+ state.subset ??= (async () => {
596
+ profile.baselines += 1;
597
+ const chosen = new Set(state.union);
598
+ const result = await job({ mutant: null, file, tests: chosen, bail: false, limitMs: baselineLimit(file, chosen) });
599
+ return { ...result, chosen, finished: passedAll(result, chosen) };
600
+ })();
601
+ const subset = await state.subset;
602
+ if (subset.finished)
603
+ return subset;
604
+ state.wholeNeeded = true;
605
+ }
606
+ return { ...(await wholeBaseline(file)), chosen: null };
607
+ }
608
+ // The tests a kill ran, again without the mutant: whether the killing
609
+ // test fails without it too.
610
+ async function failsWithout(file, chosen, killer, limitMs) {
611
+ const key = `${file}\0${[...chosen].sort().join("\0")}`;
612
+ if (!confirmations.has(key)) {
613
+ profile.confirmations += 1;
614
+ confirmations.set(key, job({ mutant: null, file, tests: chosen, bail: false, limitMs }));
615
+ }
616
+ const result = await confirmations.get(key);
617
+ return result.timedOut || result.statuses.get(killer) !== "passed";
618
+ }
619
+
620
+ // A mutant against one file's tests: killed, timeout, or alive.
621
+ async function tryFile(mutant, group, priority) {
622
+ let baseline = group.whole ? { ...(await wholeBaseline(group.file)), chosen: null } : await baselineFor(group.file);
623
+ if (!baseline.finished)
624
+ return { status: "error", reason: `${group.file} does not finish without a mutant, so it could not test this one`, tests: 0 };
625
+ let whole = group.whole || baseline.chosen === null;
626
+ for (;;) {
627
+ // Where the baseline's tests take little time beside a start of
628
+ // the command, the job runs them all: a kill is then judged by a
629
+ // baseline that ran the same tests, and needs no confirmation.
630
+ const cheap = !whole && baseline.chosen && baseline.durationMs <= UNION_MS;
631
+ const chosen = whole ? null : new Set(cheap ? [...baseline.chosen, ...group.tests] : group.tests);
632
+ const excluded = whole ? (testId) => !baseline.passing.has(testId) : () => false;
633
+ const limitMs = 3 * baseline.durationMs + graceMs;
634
+ // A test that fails without the mutant must not stop the job.
635
+ const bail = !whole || [...baseline.statuses.values()].every((status) => status === "passed");
636
+ const result = await job({ mutant, file: group.file, tests: chosen, bail, limitMs, priority });
637
+ const ran = [...result.statuses].filter(([id, status]) => status !== "skipped" && (chosen === null || chosen.has(id)));
638
+ const killer = ran.find(([id, status]) => status === "failed" && !excluded(id))?.[0];
639
+ if (result.mutantTimedOut)
640
+ return { status: "timeout", reason: "the mutant's evaluations passed its limit", tests: ran.length };
641
+ if (killer === undefined) {
642
+ if (result.timedOut)
643
+ return { status: "timeout", reason: `${group.file} did not finish within its limit`, tests: ran.length };
644
+ // A test the baseline ran that this job never reported: the
645
+ // test file stopped short.
646
+ const expected = whole ? [...baseline.passing] : [...chosen];
647
+ if (expected.some((id) => !result.statuses.has(id)))
648
+ return { status: "killed", killedBy: group.file, reason: "the test file did not finish", tests: ran.length };
649
+ return { status: "alive", tests: ran.length };
650
+ }
651
+ const name = byId.get(killer)?.name ?? killer;
652
+ // Judged by a baseline that ran the same tests: certain.
653
+ const same = whole || (baseline.chosen !== null && baseline.chosen.size === chosen.size && [...chosen].every((id) => baseline.chosen.has(id)));
654
+ if (same || !(await failsWithout(group.file, chosen, killer, baselineLimit(group.file, chosen))))
655
+ return { status: "killed", killedBy: name, tests: ran.length };
656
+ // The killing test fails without the mutant too, with only these
657
+ // tests before it: the mutant runs again with its file whole.
658
+ profile.overturned += 1;
659
+ baseline = { ...(await wholeBaseline(group.file)), chosen: null };
660
+ if (!baseline.finished)
661
+ return { status: "error", reason: `${group.file} does not finish without a mutant, so it could not test this one`, tests: 0 };
662
+ whole = true;
663
+ }
664
+ }
665
+
666
+ // Each test file's kills over the mutants it ran so far in the pass: a
667
+ // mutant's next file is the one likeliest to kill it for its cost, as the
668
+ // Vitest driver orders its copies. Most killed mutants die in their first
669
+ // file, and the cheapest file is often not the one that kills.
670
+ const killsOf = new Map();
671
+ const promise = (group) => {
672
+ const seen = killsOf.get(group.file) ?? { ran: 0, kills: 0 };
673
+ return (seen.kills + 1) / (seen.ran + 2) / (group.cost + JOB_START_MS);
674
+ };
675
+ async function runMutant(mutant, groups, elsewhere) {
676
+ const begun = Date.now();
677
+ let ran = 0;
678
+ const left = [...groups];
679
+ // Its first file alone, as most killed mutants die in it; then the
680
+ // rest in batches of 4, 16, ... side by side, the likeliest first: a
681
+ // survivor needs them all, and one after another its files were the
682
+ // pass's longest wait (luxon: a module-level mutant's 58 test files).
683
+ for (let size = 1, stage = 0; left.length > 0; size *= 4, stage += 1) {
684
+ const batch = [];
685
+ while (batch.length < size && left.length > 0) {
686
+ // Ties go to the cheapest, as the groups are sorted by cost.
687
+ const at = left.reduce((best, group, index) => (promise(group) > promise(left[best]) ? index : best), 0);
688
+ batch.push(...left.splice(at, 1));
689
+ }
690
+ const verdicts = await Promise.all(batch.map(async (group) => {
691
+ const verdict = await tryFile(mutant, group, stage);
692
+ const seen = killsOf.get(group.file) ?? { ran: 0, kills: 0 };
693
+ seen.ran += 1;
694
+ if (verdict.status === "killed" || verdict.status === "timeout")
695
+ seen.kills += 1;
696
+ killsOf.set(group.file, seen);
697
+ return verdict;
698
+ }));
699
+ ran += verdicts.reduce((sum, verdict) => sum + verdict.tests, 0);
700
+ // A kill decides it, then a timeout, then a file that does not
701
+ // finish without it.
702
+ const verdict = ["killed", "timeout", "error"]
703
+ .map((status) => verdicts.find((one) => one.status === status))
704
+ .find(Boolean);
705
+ if (verdict) {
706
+ write({ id: mutant.id, status: verdict.status, ...(verdict.killedBy ? { killedBy: verdict.killedBy } : {}), tests: ran, durationMs: Date.now() - begun, ...(verdict.reason ? { reason: verdict.reason } : {}) });
707
+ return;
708
+ }
709
+ }
710
+ // A mutant that candidates under another runner may still kill is
711
+ // not a survivor this pass can tell.
712
+ if (elsewhere.size > 0) {
713
+ write({ id: mutant.id, status: "error", tests: ran, durationMs: Date.now() - begun, reason: `its other candidates ran under ${[...elsewhere].sort().join(", ")}, which this pass does not run` });
714
+ return;
715
+ }
716
+ write({ id: mutant.id, status: "survived", tests: ran, durationMs: Date.now() - begun });
717
+ }
718
+
719
+ const pending = [];
720
+ for (const planned of plan.mutants) {
721
+ if (planned.decided)
722
+ continue;
723
+ // A Rust mutant (Rust compiled to wasm) is switched by its index in
724
+ // its file's list, as the pass's build placed it.
725
+ const found = planned.language === "rust" ? { index: planned.index, entry: {} } : indexes.get(planned.id);
726
+ if (!found) {
727
+ write({ id: planned.id, status: "error", reason: "the copy lists no such mutant: the source changed since the run", tests: 0, durationMs: 0 });
728
+ continue;
729
+ }
730
+ if (found.entry.unplaceable) {
731
+ write({ id: planned.id, status: "error", reason: `no switch could be placed (${found.entry.unplaceable})`, tests: 0, durationMs: 0 });
732
+ continue;
733
+ }
734
+ const mutant = { ...planned, index: found.index };
735
+ const byFile = new Map();
736
+ const elsewhere = new Set();
737
+ for (const candidate of planned.candidates) {
738
+ const test = tests[candidate.test];
739
+ if (!handled(test) || !test.file) {
740
+ elsewhere.add(test?.runner ?? "an unknown runner");
741
+ continue;
742
+ }
743
+ if (!byFile.has(test.file))
744
+ byFile.set(test.file, { file: test.file, tests: [], cost: 0, whole: false });
745
+ const group = byFile.get(test.file);
746
+ group.tests.push(test.id);
747
+ group.cost += test.durationMs ?? 1_000;
748
+ }
749
+ for (const file of planned.wholeFiles ?? []) {
750
+ if (!testsOf.has(file))
751
+ continue;
752
+ if (!byFile.has(file))
753
+ byFile.set(file, { file, tests: [], cost: cost(file, null), whole: true });
754
+ byFile.get(file).whole = true;
755
+ }
756
+ const groups = [...byFile.values()].sort((a, b) => a.cost - b.cost);
757
+ if (!groups.length) {
758
+ write(elsewhere.size
759
+ ? { id: planned.id, status: "error", tests: 0, durationMs: 0, reason: `its candidates ran under ${[...elsewhere].sort().join(", ")}, which this pass does not run` }
760
+ : { id: planned.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
761
+ continue;
762
+ }
763
+ for (const group of groups) {
764
+ const state = fileState(group.file);
765
+ if (!group.whole)
766
+ group.tests.forEach((id) => state.union.add(id));
767
+ }
768
+ pending.push([mutant, groups, elsewhere]);
769
+ }
770
+ // Every file's baseline runs the tests of all its mutants: none starts
771
+ // before all are known. Eight times as many mutants as workers are under
772
+ // way at once, enough to keep every worker busy while some wait on a
773
+ // file's baseline; a mutant that starts later picks its first file from
774
+ // what the pass learned.
775
+ const queue = pending.values();
776
+ await Promise.all(Array.from({ length: Math.min(pending.length, 8 * workers) }, async () => {
777
+ for (const task of queue)
778
+ await runMutant(...task);
779
+ }));
780
+ jestHosts.close();
781
+ mochaHosts.close();
782
+ esmHosts.close();
783
+ write({ summary: true, driver: "jobs", workers, ...profile, durationMs: Date.now() - started });
784
+ return 0;
785
+ }
786
+
787
+ // `node strongJobs.mjs -- <command>`
788
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
789
+ // Bun leaves the `--` out of process.argv.
790
+ const at = process.argv.indexOf("--", 2);
791
+ const command = process.argv.slice(at < 0 ? 2 : at + 1);
792
+ const planPath = process.env.SUPERCOV_STRONG_PLAN;
793
+ const resultsPath = process.env.SUPERCOV_STRONG_RESULTS;
794
+ if (!command.length || !planPath || !resultsPath) {
795
+ console.error("[supercov] strongJobs.mjs: a strong pass starts it with its plan, its results and -- <command>");
796
+ process.exit(2);
797
+ }
798
+ // Ctrl-C reaches this process alone: the jobs' process groups are their
799
+ // own. They stop with it, and so does it.
800
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
801
+ process.on(signal, () => {
802
+ stopStarted();
803
+ process.exit(128 + constants.signals[signal]);
804
+ });
805
+ }
806
+ process.on("exit", stopStarted);
807
+ const plan = JSON.parse(readFileSync(planPath, "utf8"));
808
+ process.exitCode = await drive({ command, plan, resultsPath });
809
+ }