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.
- package/README.md +43 -16
- package/docs/cli.md +322 -2
- package/docs/getting-started.md +18 -0
- package/docs/mutation.md +539 -0
- package/docs/supported-suites.md +109 -60
- package/package.json +11 -10
- package/runtime/javascript/atomic.mjs +6 -2
- package/runtime/javascript/ava.mjs +12 -0
- package/runtime/javascript/bunTest.mjs +17 -0
- package/runtime/javascript/jest.cjs +67 -0
- package/runtime/javascript/jest.config.mjs +46 -6
- package/runtime/javascript/jestReporter.mjs +5 -2
- package/runtime/javascript/mocha.mjs +79 -5
- package/runtime/javascript/nodeTest.mjs +28 -0
- package/runtime/javascript/playwright.mjs +33 -0
- package/runtime/javascript/playwrightStrong.mjs +477 -0
- package/runtime/javascript/playwrightStrongReporter.mjs +377 -0
- package/runtime/javascript/runnerEntry.mjs +62 -0
- package/runtime/javascript/runtime.mjs +752 -13
- package/runtime/javascript/snapshots.mjs +16 -1
- package/runtime/javascript/strongJestHost.mjs +103 -0
- package/runtime/javascript/strongJob.mjs +78 -0
- package/runtime/javascript/strongJobs.mjs +809 -0
- package/runtime/javascript/strongMochaHost.mjs +166 -0
- package/runtime/javascript/strongWasmOut.cjs +96 -0
- package/runtime/javascript/tap.mjs +43 -1
- package/runtime/javascript/transport.mjs +5 -0
- package/runtime/javascript/vitest.mjs +74 -2
- package/runtime/javascript/vitestBrowser.mjs +34 -2
- package/runtime/javascript/vitestStrong.mjs +234 -0
- package/runtime/javascript/vitestStrongReporter.mjs +2268 -0
- package/runtime/javascript/vitestStrongSpawner.mjs +248 -0
|
@@ -0,0 +1,2268 @@
|
|
|
1
|
+
// Strong mutation's driver for Vitest (docs/design/strong-mutation.md).
|
|
2
|
+
//
|
|
3
|
+
// Vitest hands its reporters the running instance before it runs a file
|
|
4
|
+
// (`onInit`). In strong mode this reporter takes the instance's `runFiles`
|
|
5
|
+
// over: instead of one run of every file, it runs the plan in stages through
|
|
6
|
+
// the same resident instance -- the project's own pool and workers, no new
|
|
7
|
+
// process -- and records each mutant's verdict.
|
|
8
|
+
//
|
|
9
|
+
// A stage is one Vitest run of every copy the pass can run yet: each copy is
|
|
10
|
+
// one test file with at most one mutant. A file is evaluated in an isolated
|
|
11
|
+
// module graph, so copies of one stage can each carry a different mutant
|
|
12
|
+
// without one reaching another. A mutant with candidates in several files
|
|
13
|
+
// runs its cheapest file first and, if that leaves it alive, its other files
|
|
14
|
+
// in the next stage, and stops at its first kill. Where the project does not
|
|
15
|
+
// isolate files, a stage holds one mutant.
|
|
16
|
+
import childProcess from "node:child_process";
|
|
17
|
+
import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { EventEmitter } from "node:events";
|
|
20
|
+
import { syncBuiltinESMExports } from "node:module";
|
|
21
|
+
import { PassThrough } from "node:stream";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { availableParallelism } from "node:os";
|
|
24
|
+
import { relative, sep } from "node:path";
|
|
25
|
+
|
|
26
|
+
// A mutant's test, and its copy, get twice StrykerJS's limit: 1.5× the
|
|
27
|
+
// measured time and 5 s, doubled.
|
|
28
|
+
const TIMEOUT_FACTOR = 1.5;
|
|
29
|
+
const TIMEOUT_CONSTANT_MS = 5_000;
|
|
30
|
+
const HIT_LIMIT_FLOOR = 1_000;
|
|
31
|
+
// A baseline's tests run with no mutant, and only a test that cannot finish
|
|
32
|
+
// at all needs a limit there.
|
|
33
|
+
const BASELINE_TEST_TIMEOUT_MS = 60_000;
|
|
34
|
+
// How often a stage's copies are looked at while it runs, and how long a
|
|
35
|
+
// cancelled run gets to end: its workers are asked to stop, and after
|
|
36
|
+
// CANCEL_FORCE_AFTER_MS stopped by force.
|
|
37
|
+
const WATCH_INTERVAL_MS = 500;
|
|
38
|
+
const CANCEL_FORCE_AFTER_MS = 3_000;
|
|
39
|
+
const CANCEL_GRACE_MS = 15_000;
|
|
40
|
+
// The pass summary keeps this many stages' figures.
|
|
41
|
+
const PROFILED_STAGES = 50;
|
|
42
|
+
// How often the continuous pass looks at its copies (a free slot waits on
|
|
43
|
+
// their ends).
|
|
44
|
+
const CONTINUOUS_LOOK_MS = 50;
|
|
45
|
+
// How much each of a mutant's batches of later files grows over the one before.
|
|
46
|
+
const BATCH_GROWTH = Math.max(1, Number(process.env["SUPERCOV_STRONG_BATCH_GROWTH"]) || 4);
|
|
47
|
+
// A continuous run's slots beyond each file's own, and the bytes of test
|
|
48
|
+
// files they may name: Vitest reads every slot's file at once as the run
|
|
49
|
+
// starts (with a buffer of up to 512 KB each), and 50,000 slots (a pass over
|
|
50
|
+
// all of hono's mutants at once) ran its main process out of memory within
|
|
51
|
+
// seconds. A pass that needs more slots runs again; between runs its workers
|
|
52
|
+
// wait for the run's last copies, which cost tRPC's shards 9% at 1,000 slots
|
|
53
|
+
// (SUPERCOV_STRONG_RUN_SLOTS sets the count).
|
|
54
|
+
const RUN_SLOTS = Math.max(1, Number(process.env["SUPERCOV_STRONG_RUN_SLOTS"]) || 2_000);
|
|
55
|
+
const RUN_BYTES = 1024 * 1024 * 1024;
|
|
56
|
+
|
|
57
|
+
function toRelative(root, file) {
|
|
58
|
+
return relative(root, file).split(sep).join("/");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isolated(vitest) {
|
|
62
|
+
for (const project of vitest.projects ?? [vitest.getCoreWorkspaceProject?.()]) {
|
|
63
|
+
const config = project?.config;
|
|
64
|
+
if (!config)
|
|
65
|
+
continue;
|
|
66
|
+
const pool = config.pool ?? "forks";
|
|
67
|
+
const options = config.poolOptions?.[pool] ?? {};
|
|
68
|
+
if (options.isolate === false || config.isolate === false)
|
|
69
|
+
return false;
|
|
70
|
+
if (options.singleThread || options.singleFork)
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// The longest a hook may take, as the projects set it (Vitest's default 10 s).
|
|
77
|
+
function hookTimeoutOf(vitest) {
|
|
78
|
+
const configs = [vitest.config, ...(vitest.projects ?? []).map((project) => project.config)];
|
|
79
|
+
return Math.max(10_000, ...configs.map((config) => Number(config?.hookTimeout) || 0));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
83
|
+
|
|
84
|
+
// This process's memory, in MB: a worker is forked from it, and a fork takes
|
|
85
|
+
// longer the more memory it maps.
|
|
86
|
+
function memoryOf() {
|
|
87
|
+
const { rss, heapUsed, heapTotal, external } = process.memoryUsage();
|
|
88
|
+
const memory = { rssMb: Math.round(rss / 1e6), heapMb: Math.round(heapUsed / 1e6), heapTotalMb: Math.round(heapTotal / 1e6), externalMb: Math.round(external / 1e6) };
|
|
89
|
+
// Linux: the page tables a fork copies, and what the resident memory is.
|
|
90
|
+
try {
|
|
91
|
+
const status = readFileSync("/proc/self/status", "utf8");
|
|
92
|
+
for (const [name, key] of [["VmPTE", "pageTablesMb"], ["RssAnon", "anonMb"], ["RssFile", "fileMb"], ["Threads", "threads"]]) {
|
|
93
|
+
const kb = Number(status.match(new RegExp(`^${name}:\\s+(\\d+)`, "m"))?.[1]);
|
|
94
|
+
if (kb)
|
|
95
|
+
memory[key] = key === "threads" ? kb : Math.round(kb / 1e3);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Not Linux.
|
|
100
|
+
}
|
|
101
|
+
return memory;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Linux: the machine's CPU time so far, busy and in all, to tell how much of
|
|
105
|
+
// the machine a stage kept busy.
|
|
106
|
+
function machineCpu() {
|
|
107
|
+
try {
|
|
108
|
+
const fields = readFileSync("/proc/stat", "utf8").split("\n", 1)[0].trim().split(/\s+/).slice(1).map(Number);
|
|
109
|
+
const idle = fields[3] + (fields[4] ?? 0);
|
|
110
|
+
const total = fields.reduce((sum, value) => sum + value, 0);
|
|
111
|
+
return { busy: total - idle, total };
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// What a copy reported (vitestStrong.mjs): its claim, its tests starting,
|
|
119
|
+
// each test's outcome, errors outside any test, its end.
|
|
120
|
+
function readOutcome(out) {
|
|
121
|
+
const outcome = { claimed: false, done: false, tests: [], outside: [], records: 0 };
|
|
122
|
+
if (!existsSync(out))
|
|
123
|
+
return outcome;
|
|
124
|
+
for (const line of readFileSync(out, "utf8").split("\n")) {
|
|
125
|
+
if (!line.trim())
|
|
126
|
+
continue;
|
|
127
|
+
let record;
|
|
128
|
+
try {
|
|
129
|
+
record = JSON.parse(line);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// A line the copy is still writing.
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
outcome.records += 1;
|
|
136
|
+
if (record.claimed) {
|
|
137
|
+
outcome.claimed = true;
|
|
138
|
+
outcome.claimedAt = record.at;
|
|
139
|
+
outcome.pid = record.pid;
|
|
140
|
+
outcome.up = record.up;
|
|
141
|
+
outcome.skipped = Boolean(record.skipped);
|
|
142
|
+
outcome.notRun = Boolean(record.notRun);
|
|
143
|
+
}
|
|
144
|
+
else if (record.started)
|
|
145
|
+
outcome.startedAt = record.at;
|
|
146
|
+
else if (record.done) {
|
|
147
|
+
outcome.done = true;
|
|
148
|
+
outcome.doneAt = record.at;
|
|
149
|
+
outcome.channelLost = Boolean(record.channelLost);
|
|
150
|
+
}
|
|
151
|
+
else if (record.test)
|
|
152
|
+
outcome.tests.push(record);
|
|
153
|
+
else if (record.outside)
|
|
154
|
+
outcome.outside.push(record);
|
|
155
|
+
}
|
|
156
|
+
return outcome;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// What a write to a worker process that has ended fails with.
|
|
160
|
+
const CLOSED_CHANNEL = new Set(["ERR_IPC_CHANNEL_CLOSED", "EPIPE", "ERR_IPC_DISCONNECTED"]);
|
|
161
|
+
|
|
162
|
+
// Whether a process is still running (signal 0 sends nothing).
|
|
163
|
+
function alive(pid) {
|
|
164
|
+
try {
|
|
165
|
+
process.kill(pid, 0);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
return error?.code === "EPERM";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Vitest 4 and later fork each worker from `dist/workers/forks.js` (or
|
|
174
|
+
// `vmForks.js`); Vitest 1-3 fork through tinypool, and are left as they are.
|
|
175
|
+
const VITEST_WORKER = /[\\/]vitest[\\/]dist[\\/]workers[\\/](?:forks|vmForks)\.js$/;
|
|
176
|
+
// The spawner's process id while it runs (vitestStrongSpawner.mjs), and the
|
|
177
|
+
// workers it forked.
|
|
178
|
+
const spawnerPids = new Set();
|
|
179
|
+
let spawnedWorkers = 0;
|
|
180
|
+
// When the spawner handed each worker process to Vitest: a worker started
|
|
181
|
+
// ahead was waiting before that, and its copy's start counts from here.
|
|
182
|
+
const handedAt = new Map();
|
|
183
|
+
// What the spawner reports of its workers started ahead.
|
|
184
|
+
let spawnerStats;
|
|
185
|
+
let askStats = async () => undefined;
|
|
186
|
+
// While a stage runs: which of its assignments a copy of a test file takes
|
|
187
|
+
// (vitestStrongSpawner.mjs's stand-ins ask as Vitest tells them the file),
|
|
188
|
+
// and whether any copy got its assignment this way.
|
|
189
|
+
let claimRun;
|
|
190
|
+
let mainClaims = false;
|
|
191
|
+
// The continuous pass learns each test file's project and environment from
|
|
192
|
+
// Vitest's "start" to its worker.
|
|
193
|
+
let observeRun;
|
|
194
|
+
// Whether Supercov's spawner forks Vitest's workers.
|
|
195
|
+
let spawnerInstalled = false;
|
|
196
|
+
|
|
197
|
+
// Vitest 3's workers are tinypool's processes, forked by tinypool. One the
|
|
198
|
+
// pass stops (a copy a failed test decided, or one past its limit), or one a
|
|
199
|
+
// mutant ends, has lost its channel while tinypool still relays to it: the
|
|
200
|
+
// write fails with "Channel closed" or EPIPE, which tinypool 1.1 rejects with
|
|
201
|
+
// nothing to catch it, and Vitest 3.2 ended the whole run at that, the
|
|
202
|
+
// mutants left without verdicts (destr: 81 of 141, in every pass). The
|
|
203
|
+
// process's exit tells tinypool it is gone, as it does for any worker that
|
|
204
|
+
// dies; the failed write says nothing more, and is dropped.
|
|
205
|
+
const TINYPOOL_WORKER = /[\\/]tinypool[\\/]dist[\\/]entry[\\/]process\.js$/;
|
|
206
|
+
function quietWhenGone(modulePath, child) {
|
|
207
|
+
const path = modulePath instanceof URL ? fileURLToPath(modulePath) : String(modulePath);
|
|
208
|
+
if (!TINYPOOL_WORKER.test(path) || !child)
|
|
209
|
+
return child;
|
|
210
|
+
const emit = child.emit;
|
|
211
|
+
child.emit = function (event, ...rest) {
|
|
212
|
+
if (event === "error" && CLOSED_CHANNEL.has(rest[0]?.code))
|
|
213
|
+
return false;
|
|
214
|
+
return emit.call(this, event, ...rest);
|
|
215
|
+
};
|
|
216
|
+
return child;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Vitest's workers forked by a small process of their own instead of
|
|
220
|
+
// Vitest's: forking copies the parent's memory map, and Vitest's process
|
|
221
|
+
// held about a gigabyte (on hono each fork held its event loop for 24 ms,
|
|
222
|
+
// 72% of its time, while its workers waited on it). Each worker Vitest asks
|
|
223
|
+
// for is a stand-in here, relaying to and from the real one through the
|
|
224
|
+
// spawner. SUPERCOV_STRONG_DIRECT_FORK=1 forks them directly.
|
|
225
|
+
//
|
|
226
|
+
// The spawner also keeps `ahead` workers started ahead of Vitest's requests
|
|
227
|
+
// for them (vitestStrongSpawner.mjs; SUPERCOV_STRONG_WORKERS_AHEAD=0 starts
|
|
228
|
+
// each when Vitest asks).
|
|
229
|
+
function forkThroughSpawner(ahead) {
|
|
230
|
+
const original = childProcess.fork;
|
|
231
|
+
if (process.env["SUPERCOV_STRONG_DIRECT_FORK"] === "1") {
|
|
232
|
+
childProcess.fork = function fork(modulePath) {
|
|
233
|
+
return quietWhenGone(modulePath, original.apply(this, arguments));
|
|
234
|
+
};
|
|
235
|
+
syncBuiltinESMExports();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
spawnerInstalled = true;
|
|
239
|
+
const standIns = new Map();
|
|
240
|
+
// One spawner: every message to and from a worker goes through it, and
|
|
241
|
+
// four of them sharing the workers were no faster on hono.
|
|
242
|
+
const spawner = { process: undefined, live: 0 };
|
|
243
|
+
let nextId = 0;
|
|
244
|
+
// A spawner's channel keeps this process alive only while one of its
|
|
245
|
+
// workers does, as the worker's own handle did.
|
|
246
|
+
const hold = (spawner) => {
|
|
247
|
+
if (!spawner.process)
|
|
248
|
+
return;
|
|
249
|
+
if (spawner.live > 0) {
|
|
250
|
+
spawner.process.ref();
|
|
251
|
+
spawner.process.channel?.ref?.();
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
spawner.process.unref();
|
|
255
|
+
spawner.process.channel?.unref?.();
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const start = (spawner) => {
|
|
259
|
+
const child = original(fileURLToPath(new URL("./vitestStrongSpawner.mjs", import.meta.url)), [], {
|
|
260
|
+
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
|
261
|
+
serialization: "advanced",
|
|
262
|
+
execArgv: [],
|
|
263
|
+
});
|
|
264
|
+
spawner.process = child;
|
|
265
|
+
spawnerPids.add(child.pid);
|
|
266
|
+
child.send({ pool: ahead });
|
|
267
|
+
child.on("message", (record) => {
|
|
268
|
+
if (record.stats) {
|
|
269
|
+
spawnerStats = record.stats;
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
standIns.get(record.id)?.receive(record);
|
|
273
|
+
});
|
|
274
|
+
child.on("error", () => { });
|
|
275
|
+
child.on("exit", () => {
|
|
276
|
+
spawnerPids.delete(child.pid);
|
|
277
|
+
spawner.process = undefined;
|
|
278
|
+
for (const standIn of [...standIns.values()])
|
|
279
|
+
if (standIn.spawner === spawner)
|
|
280
|
+
standIn.receive({ exit: [null, "SIGKILL"] });
|
|
281
|
+
});
|
|
282
|
+
};
|
|
283
|
+
// The environments the spawner was told of, by worker entry.
|
|
284
|
+
const environments = new Set();
|
|
285
|
+
askStats = async () => {
|
|
286
|
+
if (!spawner.process?.connected)
|
|
287
|
+
return spawnerStats;
|
|
288
|
+
spawner.process.send({ stats: true });
|
|
289
|
+
for (let waited = 0; waited < 1_000 && !spawnerStats; waited += 20)
|
|
290
|
+
await pause(20);
|
|
291
|
+
return spawnerStats;
|
|
292
|
+
};
|
|
293
|
+
// A stand-in takes its process only once Vitest says which test file it
|
|
294
|
+
// runs. Vitest's first message ("start") is answered here, and kept; its
|
|
295
|
+
// "run" names the file, and the stage running (`claimRun`) says which of
|
|
296
|
+
// that file's assignments the copy takes. A copy with nothing to run
|
|
297
|
+
// (its mutant decided meanwhile, or beyond its file's assignments) gets
|
|
298
|
+
// no process at all: it ends here, as its setup file would have ended
|
|
299
|
+
// it. Any other copy's process gets the kept "start", then the "run".
|
|
300
|
+
const response = (type, extra) => ({ __vitest_worker_response__: true, type, ...extra });
|
|
301
|
+
class Worker extends EventEmitter {
|
|
302
|
+
constructor(id, spawner, modulePath, forkRequest) {
|
|
303
|
+
super();
|
|
304
|
+
this.id = id;
|
|
305
|
+
this.spawner = spawner;
|
|
306
|
+
this.modulePath = modulePath;
|
|
307
|
+
this.forkRequest = forkRequest;
|
|
308
|
+
// Before its process: what Vitest sent it, and how it ends.
|
|
309
|
+
this.attached = false;
|
|
310
|
+
this.ended = false;
|
|
311
|
+
this.held = [];
|
|
312
|
+
this.pid = undefined;
|
|
313
|
+
this.exitCode = null;
|
|
314
|
+
this.signalCode = null;
|
|
315
|
+
this.killed = false;
|
|
316
|
+
this.connected = true;
|
|
317
|
+
this.stdin = null;
|
|
318
|
+
this.stdout = new PassThrough();
|
|
319
|
+
this.stderr = new PassThrough();
|
|
320
|
+
this.stdio = [null, this.stdout, this.stderr];
|
|
321
|
+
this.channel = { ref() { }, unref() { } };
|
|
322
|
+
}
|
|
323
|
+
attach() {
|
|
324
|
+
this.attached = true;
|
|
325
|
+
spawnedWorkers += 1;
|
|
326
|
+
this.spawner.process.send(this.forkRequest);
|
|
327
|
+
}
|
|
328
|
+
receive(record) {
|
|
329
|
+
if (record.spawned !== undefined) {
|
|
330
|
+
this.pid = record.spawned;
|
|
331
|
+
handedAt.set(this.pid, Date.now());
|
|
332
|
+
this.emit("spawn");
|
|
333
|
+
}
|
|
334
|
+
else if (record.error) {
|
|
335
|
+
// A write to a worker that is ending: its exit says the rest.
|
|
336
|
+
if (!CLOSED_CHANNEL.has(record.error.code))
|
|
337
|
+
this.emit("error", Object.assign(new Error(record.error.message), { code: record.error.code }));
|
|
338
|
+
}
|
|
339
|
+
else if (record.exit) {
|
|
340
|
+
this.exited(...record.exit);
|
|
341
|
+
}
|
|
342
|
+
else if (record.stdout)
|
|
343
|
+
this.stdout.write(record.stdout);
|
|
344
|
+
else if (record.stderr)
|
|
345
|
+
this.stderr.write(record.stderr);
|
|
346
|
+
else if ("message" in record) {
|
|
347
|
+
const message = record.message;
|
|
348
|
+
// The kept "start" was answered already: the process's own
|
|
349
|
+
// answer lets the "run" go, or fails it.
|
|
350
|
+
if (this.pendingRun && message?.__vitest_worker_response__ && message.type === "started") {
|
|
351
|
+
const run = this.pendingRun;
|
|
352
|
+
this.pendingRun = undefined;
|
|
353
|
+
if (message.error)
|
|
354
|
+
this.emit("message", response("testfileFinished", { error: message.error }));
|
|
355
|
+
else
|
|
356
|
+
this.relay(run);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (message?.__vitest_worker_response__ && message.type === "testfileFinished")
|
|
360
|
+
this.between = true;
|
|
361
|
+
this.emit("message", message);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
exited(code, signal) {
|
|
365
|
+
if (this.ended)
|
|
366
|
+
return;
|
|
367
|
+
// Between its file's end and Vitest's "stop" (a worker the pass
|
|
368
|
+
// stopped once its mutant was decided), Vitest has nothing that
|
|
369
|
+
// takes a worker's exit and fails: the exit waits for the "stop".
|
|
370
|
+
if (this.between && !this.stopping) {
|
|
371
|
+
this.exitAfterStop = [code, signal];
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
this.ended = true;
|
|
375
|
+
[this.exitCode, this.signalCode] = [code, signal];
|
|
376
|
+
this.connected = false;
|
|
377
|
+
standIns.delete(this.id);
|
|
378
|
+
this.spawner.live -= 1;
|
|
379
|
+
hold(this.spawner);
|
|
380
|
+
this.stdout.end();
|
|
381
|
+
this.stderr.end();
|
|
382
|
+
this.emit("disconnect");
|
|
383
|
+
this.emit("exit", this.exitCode, this.signalCode);
|
|
384
|
+
this.emit("close", this.exitCode, this.signalCode);
|
|
385
|
+
}
|
|
386
|
+
relay(message) {
|
|
387
|
+
this.spawner.process?.send({ id: this.id, send: true, message });
|
|
388
|
+
}
|
|
389
|
+
// Vitest's "run", once the stage said what this copy takes: nothing
|
|
390
|
+
// (it ends here, with no process), or its assignment, and in the
|
|
391
|
+
// continuous pass possibly another test file than the slot's.
|
|
392
|
+
run(message, claimed) {
|
|
393
|
+
if (this.ended || this.nothingToRun)
|
|
394
|
+
return;
|
|
395
|
+
if (claimed?.nothingToRun) {
|
|
396
|
+
this.nothingToRun = true;
|
|
397
|
+
process.nextTick(() => this.emit("message", response("testfileFinished")));
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (claimed) {
|
|
401
|
+
const provided = message.context.providedContext ?? {};
|
|
402
|
+
const [file] = message.context.files;
|
|
403
|
+
const files = claimed.filepath
|
|
404
|
+
? [{ filepath: claimed.filepath, fileTags: file.fileTags }]
|
|
405
|
+
: message.context.files;
|
|
406
|
+
message = {
|
|
407
|
+
...message,
|
|
408
|
+
context: {
|
|
409
|
+
...message.context,
|
|
410
|
+
files,
|
|
411
|
+
providedContext: { ...provided, supercovStrong: { ...provided.supercovStrong, claim: claimed.index } },
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
this.attach();
|
|
416
|
+
this.relay(this.start);
|
|
417
|
+
this.pendingRun = message;
|
|
418
|
+
}
|
|
419
|
+
send(message, ...rest) {
|
|
420
|
+
const callback = rest.find((value) => typeof value === "function");
|
|
421
|
+
// A worker that ended, or is ending: its exit says the rest, and
|
|
422
|
+
// an error here would only tell Vitest the channel closed.
|
|
423
|
+
if (!this.connected || !this.spawner.process) {
|
|
424
|
+
// Vitest waits for a stopped worker's answer to its "stop".
|
|
425
|
+
if (message?.__vitest_worker_request__ && message.type === "stop")
|
|
426
|
+
process.nextTick(() => this.emit("message", response("stopped")));
|
|
427
|
+
if (callback)
|
|
428
|
+
process.nextTick(callback, Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" }));
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
if (callback)
|
|
432
|
+
process.nextTick(callback, null);
|
|
433
|
+
const request = message?.__vitest_worker_request__ ? message.type : undefined;
|
|
434
|
+
// Vitest's first message to a worker names the environment it
|
|
435
|
+
// runs in: workers started ahead load its package too.
|
|
436
|
+
const environment = request === "start" ? message.context?.environment?.name : undefined;
|
|
437
|
+
if (environment && !environments.has(`${this.modulePath}\0${environment}`)) {
|
|
438
|
+
environments.add(`${this.modulePath}\0${environment}`);
|
|
439
|
+
this.spawner.process.send({ environment, modulePath: this.modulePath });
|
|
440
|
+
}
|
|
441
|
+
if (this.attached) {
|
|
442
|
+
if (request === "stop") {
|
|
443
|
+
this.stopping = true;
|
|
444
|
+
if (this.exitAfterStop) {
|
|
445
|
+
const [code, signal] = this.exitAfterStop;
|
|
446
|
+
process.nextTick(() => {
|
|
447
|
+
this.emit("message", response("stopped"));
|
|
448
|
+
this.exited(code, signal);
|
|
449
|
+
});
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
else if (request === "run" || request === "collect")
|
|
454
|
+
this.between = false;
|
|
455
|
+
this.relay(message);
|
|
456
|
+
return true;
|
|
457
|
+
}
|
|
458
|
+
// Stopped while it waited for work (a cancelled run): it ends
|
|
459
|
+
// with no process.
|
|
460
|
+
if (this.waitingRun && request === "stop")
|
|
461
|
+
this.nothingToRun = true;
|
|
462
|
+
if (this.nothingToRun) {
|
|
463
|
+
if (request === "stop")
|
|
464
|
+
process.nextTick(() => this.emit("message", response("stopped")));
|
|
465
|
+
return true;
|
|
466
|
+
}
|
|
467
|
+
if (request === "start" && !this.start) {
|
|
468
|
+
this.start = message;
|
|
469
|
+
process.nextTick(() => this.emit("message", response("started")));
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
const files = request === "run" ? message.context?.files : undefined;
|
|
473
|
+
if (this.start && files?.length === 1) {
|
|
474
|
+
const filepath = files[0].filepath ?? files[0];
|
|
475
|
+
observeRun?.(filepath, this.start);
|
|
476
|
+
const claimed = claimRun?.(filepath, this.start, () => !this.ended && !this.nothingToRun);
|
|
477
|
+
if (typeof claimed?.then === "function") {
|
|
478
|
+
this.waitingRun = true;
|
|
479
|
+
claimed.then((value) => {
|
|
480
|
+
this.waitingRun = false;
|
|
481
|
+
this.run(message, value);
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
else
|
|
485
|
+
this.run(message, claimed);
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
// Vitest's calls to a worker (its cancel) before the worker has a
|
|
489
|
+
// process: nothing to tell.
|
|
490
|
+
if (!request)
|
|
491
|
+
return true;
|
|
492
|
+
// Anything else: the process now, and what Vitest sent it so far.
|
|
493
|
+
this.attach();
|
|
494
|
+
if (this.start)
|
|
495
|
+
this.relay(this.start);
|
|
496
|
+
this.relay(message);
|
|
497
|
+
return true;
|
|
498
|
+
}
|
|
499
|
+
kill(signal = "SIGTERM") {
|
|
500
|
+
// Its exit was held for Vitest's "stop", which a forced stop (a
|
|
501
|
+
// cancelled run) skips: the exit comes now.
|
|
502
|
+
if (this.exitAfterStop && !this.ended) {
|
|
503
|
+
const [code, held] = this.exitAfterStop;
|
|
504
|
+
this.exitAfterStop = undefined;
|
|
505
|
+
this.stopping = true;
|
|
506
|
+
process.nextTick(() => this.exited(code, held));
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
if (this.exitCode !== null || this.signalCode !== null || this.ended)
|
|
510
|
+
return false;
|
|
511
|
+
this.killed = true;
|
|
512
|
+
if (!this.attached) {
|
|
513
|
+
process.nextTick(() => this.exited(null, signal));
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
this.spawner.process?.send({ id: this.id, kill: signal });
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
disconnect() {
|
|
520
|
+
if (this.attached)
|
|
521
|
+
this.spawner.process?.send({ id: this.id, disconnect: true });
|
|
522
|
+
}
|
|
523
|
+
// Vitest waits for "exit" when stopping a worker whose `exitCode` is
|
|
524
|
+
// null, as it is for a process a signal ended: one the pass stopped
|
|
525
|
+
// already (a copy a failed test decided) has emitted it, and would
|
|
526
|
+
// hold Vitest's close for its teardown limit.
|
|
527
|
+
once(event, listener) {
|
|
528
|
+
if (event === "exit" && this.ended) {
|
|
529
|
+
process.nextTick(listener, this.exitCode, this.signalCode);
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
return super.once(event, listener);
|
|
533
|
+
}
|
|
534
|
+
ref() { }
|
|
535
|
+
unref() { }
|
|
536
|
+
}
|
|
537
|
+
childProcess.fork = function fork(modulePath, args, options) {
|
|
538
|
+
const path = modulePath instanceof URL ? fileURLToPath(modulePath) : String(modulePath);
|
|
539
|
+
if (!VITEST_WORKER.test(path))
|
|
540
|
+
return quietWhenGone(path, original.apply(this, arguments));
|
|
541
|
+
if (!Array.isArray(args)) {
|
|
542
|
+
options = args;
|
|
543
|
+
args = [];
|
|
544
|
+
}
|
|
545
|
+
if (!spawner.process)
|
|
546
|
+
start(spawner);
|
|
547
|
+
const id = nextId++;
|
|
548
|
+
const worker = new Worker(id, spawner, path, { id, fork: true, modulePath: path, args, options: { ...options } });
|
|
549
|
+
spawner.live += 1;
|
|
550
|
+
hold(spawner);
|
|
551
|
+
standIns.set(worker.id, worker);
|
|
552
|
+
return worker;
|
|
553
|
+
};
|
|
554
|
+
syncBuiltinESMExports();
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// How many workers the spawner keeps started ahead: one per worker Vitest
|
|
558
|
+
// runs at once.
|
|
559
|
+
function workersAhead(vitest) {
|
|
560
|
+
const set = process.env["SUPERCOV_STRONG_WORKERS_AHEAD"];
|
|
561
|
+
if (set !== undefined && set !== "")
|
|
562
|
+
return Math.max(0, Number(set) || 0);
|
|
563
|
+
return Math.max(1, Number(vitest.config?.maxWorkers) || availableParallelism());
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// How long a copy's worker took to start before it claimed: from when the
|
|
567
|
+
// spawner handed it to Vitest, or from its process's start.
|
|
568
|
+
function startOf(outcome) {
|
|
569
|
+
const handed = outcome.pid ? handedAt.get(outcome.pid) : undefined;
|
|
570
|
+
if (handed !== undefined && outcome.claimedAt !== undefined)
|
|
571
|
+
return Math.max(0, outcome.claimedAt - handed);
|
|
572
|
+
return outcome.up ?? 0;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// Whether a process is one of this process's own workers: running, and its
|
|
576
|
+
// child (or the spawner's) where /proc tells (a worker that ended may leave
|
|
577
|
+
// its id to another).
|
|
578
|
+
function ownWorker(pid) {
|
|
579
|
+
if (!pid || pid === process.pid || !alive(pid))
|
|
580
|
+
return false;
|
|
581
|
+
let stat;
|
|
582
|
+
try {
|
|
583
|
+
stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
584
|
+
}
|
|
585
|
+
catch {
|
|
586
|
+
return true;
|
|
587
|
+
}
|
|
588
|
+
const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
|
|
589
|
+
return parent === process.pid || spawnerPids.has(parent);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// The whole lines appended to `path` since the cursor, which moves past them.
|
|
593
|
+
function readAppended(path, cursor) {
|
|
594
|
+
let descriptor;
|
|
595
|
+
try {
|
|
596
|
+
descriptor = openSync(path, "r");
|
|
597
|
+
}
|
|
598
|
+
catch {
|
|
599
|
+
return [];
|
|
600
|
+
}
|
|
601
|
+
try {
|
|
602
|
+
const size = fstatSync(descriptor).size;
|
|
603
|
+
if (size <= cursor.offset)
|
|
604
|
+
return [];
|
|
605
|
+
const buffer = Buffer.alloc(size - cursor.offset);
|
|
606
|
+
const read = readSync(descriptor, buffer, 0, buffer.length, cursor.offset);
|
|
607
|
+
const end = buffer.subarray(0, read).lastIndexOf(10);
|
|
608
|
+
if (end < 0)
|
|
609
|
+
return [];
|
|
610
|
+
cursor.offset += end + 1;
|
|
611
|
+
return buffer.subarray(0, end).toString("utf8").split("\n").filter(Boolean);
|
|
612
|
+
}
|
|
613
|
+
finally {
|
|
614
|
+
closeSync(descriptor);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Vitest sorts a run's files (slowest file first, by its own cache); the pass
|
|
619
|
+
// lists its copies longest first itself, and each copy claims the next of its
|
|
620
|
+
// file's assignments as it starts.
|
|
621
|
+
function keepOrder(vitest) {
|
|
622
|
+
const Sequencer = vitest.config?.sequence?.sequencer;
|
|
623
|
+
if (typeof Sequencer !== "function")
|
|
624
|
+
return;
|
|
625
|
+
class InOrder extends Sequencer {
|
|
626
|
+
async sort(files) {
|
|
627
|
+
return files;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
vitest.config.sequence.sequencer = InOrder;
|
|
631
|
+
// Vitest 3 and later keep the sequencer they made first.
|
|
632
|
+
if (vitest.sequencer)
|
|
633
|
+
vitest.sequencer = new InOrder(vitest);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function provide(vitest, value) {
|
|
637
|
+
for (const project of vitest.projects ?? []) {
|
|
638
|
+
project.provide?.("supercovStrong", value);
|
|
639
|
+
}
|
|
640
|
+
vitest.provide?.("supercovStrong", value);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function setTestTimeout(vitest, ms) {
|
|
644
|
+
for (const project of vitest.projects ?? []) {
|
|
645
|
+
if (project.config)
|
|
646
|
+
project.config.testTimeout = ms;
|
|
647
|
+
}
|
|
648
|
+
if (vitest.config)
|
|
649
|
+
vitest.config.testTimeout = ms;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// SUPERCOV_STRONG_CPU_PROFILE=<file>: a CPU profile of this process -- the
|
|
653
|
+
// one that schedules the copies and serves its workers' modules -- for the
|
|
654
|
+
// whole pass, to see what holds the workers up.
|
|
655
|
+
async function profileMainProcess() {
|
|
656
|
+
const path = process.env["SUPERCOV_STRONG_CPU_PROFILE"];
|
|
657
|
+
if (!path)
|
|
658
|
+
return async () => { };
|
|
659
|
+
const { Session } = await import("node:inspector");
|
|
660
|
+
const session = new Session();
|
|
661
|
+
session.connect();
|
|
662
|
+
const post = (method, params) => new Promise((resolve, reject) => session.post(method, params, (error, result) => error ? reject(error) : resolve(result)));
|
|
663
|
+
await post("Profiler.enable");
|
|
664
|
+
await post("Profiler.setSamplingInterval", { interval: 1000 });
|
|
665
|
+
await post("Profiler.start");
|
|
666
|
+
return async () => {
|
|
667
|
+
const { profile } = await post("Profiler.stop");
|
|
668
|
+
writeFileSync(path, JSON.stringify(profile));
|
|
669
|
+
session.disconnect();
|
|
670
|
+
// Linux: this process's largest mappings by resident memory, for what
|
|
671
|
+
// a fork of it copies.
|
|
672
|
+
try {
|
|
673
|
+
const mappings = readFileSync("/proc/self/smaps", "utf8").split(/\n(?=[0-9a-f]+-[0-9a-f]+ )/).map((entry) => {
|
|
674
|
+
const rss = Number(entry.match(/^Rss:\s+(\d+)/m)?.[1] ?? 0);
|
|
675
|
+
return { rss, line: entry.split("\n")[0] };
|
|
676
|
+
}).sort((a, b) => b.rss - a.rss);
|
|
677
|
+
const total = mappings.reduce((sum, mapping) => sum + mapping.rss, 0);
|
|
678
|
+
writeFileSync(`${path}.mappings.txt`, `${mappings.length} mappings, ${Math.round(total / 1e3)} MB resident\n${mappings.slice(0, 40).map((mapping) => `${Math.round(mapping.rss / 1e3)} MB ${mapping.line}`).join("\n")}\n`);
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
// Not Linux.
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
export default class SupercovStrongReporter {
|
|
687
|
+
constructor(configureProjects) {
|
|
688
|
+
this.configureProjects = configureProjects;
|
|
689
|
+
}
|
|
690
|
+
onInit(vitest) {
|
|
691
|
+
this.configureProjects?.(vitest.projects);
|
|
692
|
+
const planPath = process.env["SUPERCOV_STRONG_PLAN"];
|
|
693
|
+
const resultsPath = process.env["SUPERCOV_STRONG_RESULTS"];
|
|
694
|
+
if (!planPath || !resultsPath)
|
|
695
|
+
return;
|
|
696
|
+
forkThroughSpawner(workersAhead(vitest));
|
|
697
|
+
const original = vitest.runFiles.bind(vitest);
|
|
698
|
+
vitest.runFiles = async (specs) => {
|
|
699
|
+
const stopProfile = await profileMainProcess();
|
|
700
|
+
const last = await drive(vitest, original, specs, JSON.parse(readFileSync(planPath, "utf8")), resultsPath);
|
|
701
|
+
await stopProfile();
|
|
702
|
+
// A killed mutant fails its test, and that is the point: the
|
|
703
|
+
// command's exit code is the pass's, not the rounds'.
|
|
704
|
+
process.exitCode = 0;
|
|
705
|
+
// Vitest 3 and later read what the run gave back.
|
|
706
|
+
return last ?? { testModules: [], unhandledErrors: [] };
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async function drive(vitest, runFiles, specs, plan, resultsPath) {
|
|
712
|
+
const root = vitest.config.root;
|
|
713
|
+
// Vitest 2 and later pass specifications; Vitest 1, [project, file].
|
|
714
|
+
const fileOf = (spec) => spec.moduleId ?? (Array.isArray(spec) ? spec[1] : spec);
|
|
715
|
+
const specOf = new Map(specs.map((spec) => [toRelative(root, fileOf(spec)), spec]));
|
|
716
|
+
const write = (record) => appendFileSync(resultsPath, `${JSON.stringify(record)}\n`);
|
|
717
|
+
const tests = plan.tests;
|
|
718
|
+
const started = Date.now();
|
|
719
|
+
const passCpu = machineCpu();
|
|
720
|
+
let last;
|
|
721
|
+
|
|
722
|
+
// The copy's own list: the mutant at each index must be the run's, and
|
|
723
|
+
// one the instrumenter could not place has no switch to turn on.
|
|
724
|
+
let listed = {};
|
|
725
|
+
try {
|
|
726
|
+
listed = JSON.parse(readFileSync(`${root}/.supercov/frontend-evidence/mutants.json`, "utf8")).files ?? {};
|
|
727
|
+
}
|
|
728
|
+
catch {
|
|
729
|
+
listed = {};
|
|
730
|
+
}
|
|
731
|
+
// A mutant's switch, by its id in the copy's list: the index the copy
|
|
732
|
+
// gave it, or why it has none.
|
|
733
|
+
const idOf = (file, entry) => entry.id ||
|
|
734
|
+
`${file}:${entry.start?.[0]}:${entry.start?.[1]}-${entry.end?.[0]}:${entry.end?.[1]}:${entry.mutator}:${entry.replacement}`;
|
|
735
|
+
const indexes = new Map();
|
|
736
|
+
for (const [file, entries] of Object.entries(listed)) {
|
|
737
|
+
entries.forEach((entry, index) => indexes.set(idOf(file, entry), { index, entry }));
|
|
738
|
+
}
|
|
739
|
+
const placed = (mutant) => {
|
|
740
|
+
// A Rust mutant (Rust compiled to wasm) by its index, as the pass's build placed it.
|
|
741
|
+
if (mutant.language === "rust")
|
|
742
|
+
return { index: mutant.index };
|
|
743
|
+
const found = indexes.get(mutant.id);
|
|
744
|
+
if (!found)
|
|
745
|
+
return { error: "the copy lists no such mutant: the source changed since the run" };
|
|
746
|
+
if (found.entry.unplaceable)
|
|
747
|
+
return { error: `no switch could be placed (${found.entry.unplaceable})` };
|
|
748
|
+
return { index: found.index };
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
// Each mutant to run: its candidates grouped by test file, the cheapest
|
|
752
|
+
// file first.
|
|
753
|
+
const pending = [];
|
|
754
|
+
for (let mutant of plan.mutants) {
|
|
755
|
+
if (mutant.decided)
|
|
756
|
+
continue;
|
|
757
|
+
const switchOf = placed(mutant);
|
|
758
|
+
if (switchOf.error) {
|
|
759
|
+
write({ id: mutant.id, status: "error", reason: switchOf.error, tests: 0, durationMs: 0 });
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
mutant = { ...mutant, index: switchOf.index };
|
|
763
|
+
const byFile = new Map();
|
|
764
|
+
for (const candidate of mutant.candidates) {
|
|
765
|
+
const test = tests[candidate.test];
|
|
766
|
+
if (!test?.file || !specOf.has(test.file))
|
|
767
|
+
continue;
|
|
768
|
+
if (!byFile.has(test.file))
|
|
769
|
+
byFile.set(test.file, { file: test.file, tests: [], cost: 0, whole: false });
|
|
770
|
+
const group = byFile.get(test.file);
|
|
771
|
+
// A Rust wasm run names a test by its file too (`<file>::vitest:<id>`).
|
|
772
|
+
group.tests.push(test.id.startsWith(`${test.file}::`) ? test.id.slice(test.file.length + 2) : test.id);
|
|
773
|
+
group.cost += test.durationMs ?? 1_000;
|
|
774
|
+
}
|
|
775
|
+
for (const file of mutant.wholeFiles ?? []) {
|
|
776
|
+
if (!specOf.has(file))
|
|
777
|
+
continue;
|
|
778
|
+
if (!byFile.has(file))
|
|
779
|
+
byFile.set(file, { file, tests: [], cost: 0, whole: true });
|
|
780
|
+
byFile.get(file).whole = true;
|
|
781
|
+
}
|
|
782
|
+
const files = [...byFile.values()].sort((a, b) => a.cost - b.cost);
|
|
783
|
+
if (!files.length) {
|
|
784
|
+
write({ id: mutant.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
pending.push({ mutant, files, ran: 0, started: 0 });
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
// Stages run through claims: each assignment is a file in the stage's
|
|
791
|
+
// directory, and each copy of a test file Vitest runs takes the next one
|
|
792
|
+
// for its file (vitestStrong.mjs) and reports its tests' outcomes beside it.
|
|
793
|
+
const stagesDirectory = `${root}/.supercov/strong-stages`;
|
|
794
|
+
rmSync(stagesDirectory, { recursive: true, force: true });
|
|
795
|
+
const keyOf = (file) => createHash("sha256").update(file).digest("hex").slice(0, 24);
|
|
796
|
+
keepOrder(vitest);
|
|
797
|
+
let stageNumber = 0;
|
|
798
|
+
let stalled = false;
|
|
799
|
+
// The stage running: where each of its assignments was placed.
|
|
800
|
+
let running;
|
|
801
|
+
// Where the pass's time goes: each stage's wall time against the copies'
|
|
802
|
+
// own (claim to end) and when its last copy started.
|
|
803
|
+
const profile = { stages: [], spawnedWorkers: 0, wallMs: 0, copies: 0, mutantCopies: 0, checkCopies: 0, skippedCopies: 0, killedCopies: 0, settledCopies: 0, baselineCopies: 0, besideCopies: 0, unevaluatedReruns: 0, filesByStatus: {}, hungCopies: 0, deferredCopies: 0, cancelledStages: 0, testsRun: 0, copyMs: 0, startMs: 0, baselineMs: 0 };
|
|
804
|
+
// Runs one stage. `early(at, outcome)` is offered each copy's outcome as
|
|
805
|
+
// soon as the copy ends, and says whether it took it; a stage's copies
|
|
806
|
+
// are otherwise judged when its run has ended. `limitOf(assignment)` is
|
|
807
|
+
// how long a mutant's copy may run, if known yet; `expectedOf` how long it
|
|
808
|
+
// should take.
|
|
809
|
+
async function runStage(assignments, early, limitOf, expectedOf) {
|
|
810
|
+
const directory = `${stagesDirectory}/${stageNumber++}`;
|
|
811
|
+
const counts = new Map();
|
|
812
|
+
const outs = [];
|
|
813
|
+
const placed = [];
|
|
814
|
+
const positionOf = new Map();
|
|
815
|
+
mkdirSync(directory, { recursive: true });
|
|
816
|
+
assignments.forEach((assignment, at) => {
|
|
817
|
+
const key = keyOf(assignment.file);
|
|
818
|
+
const index = counts.get(key) ?? 0;
|
|
819
|
+
counts.set(key, index + 1);
|
|
820
|
+
if (!index)
|
|
821
|
+
mkdirSync(`${directory}/${key}`, { recursive: true });
|
|
822
|
+
writeFileSync(`${directory}/${key}/${index}.json`, JSON.stringify(assignment.claim));
|
|
823
|
+
outs.push(`${directory}/${key}/${index}.out`);
|
|
824
|
+
placed.push(`${directory}/${key}/${index}`);
|
|
825
|
+
positionOf.set(`${key}/${index}`, at);
|
|
826
|
+
});
|
|
827
|
+
running = { placed };
|
|
828
|
+
provide(vitest, { root, stage: directory });
|
|
829
|
+
// A copy whose worker Vitest has just told the file it runs takes
|
|
830
|
+
// the file's next assignment, here, in the order Vitest starts them.
|
|
831
|
+
// One with nothing to run ends without a process: its mutant was
|
|
832
|
+
// decided meanwhile (recorded as its setup file would), or it is
|
|
833
|
+
// beyond its file's assignments.
|
|
834
|
+
const nextOf = new Map();
|
|
835
|
+
// A copy held back (`gated`: a mutant's next files, listed after the
|
|
836
|
+
// stage's other work) runs only once its mutant's other copies in the
|
|
837
|
+
// stage have ended with every test passing, else it goes back to its
|
|
838
|
+
// mutant's files to run later.
|
|
839
|
+
const ended = (position) => stopped.has(position) || deferred.has(position) || decided.has(position) || readOutcome(outs[position]).done;
|
|
840
|
+
claimRun = (filepath) => {
|
|
841
|
+
mainClaims = true;
|
|
842
|
+
const key = keyOf(toRelative(root, String(filepath)));
|
|
843
|
+
const index = nextOf.get(key) ?? 0;
|
|
844
|
+
nextOf.set(key, index + 1);
|
|
845
|
+
const at = `${directory}/${key}/${index}`;
|
|
846
|
+
if (!existsSync(`${at}.json`))
|
|
847
|
+
return { nothingToRun: true };
|
|
848
|
+
const position = positionOf.get(`${key}/${index}`);
|
|
849
|
+
const assignment = assignments[position];
|
|
850
|
+
const skipped = existsSync(`${at}.skip`);
|
|
851
|
+
// Held back too where a copy before it failed a test: most such
|
|
852
|
+
// failures kill the mutant, which the stage judges a moment later.
|
|
853
|
+
const notRun = !skipped && assignment?.gated &&
|
|
854
|
+
assignment.job.positions.some((other) => !assignments[other].gated &&
|
|
855
|
+
(!ended(other) || decided.has(other) || readOutcome(outs[other]).tests.some((test) => test.failed)));
|
|
856
|
+
if (skipped || notRun) {
|
|
857
|
+
const now = Date.now();
|
|
858
|
+
appendFileSync(`${at}.out`, `${JSON.stringify({ claimed: true, at: now, up: 0, skipped: true, notRun })}\n${JSON.stringify({ done: true, at: now })}\n`);
|
|
859
|
+
appendFileSync(`${directory}/claimed`, `${key}/${index}\n`);
|
|
860
|
+
return { nothingToRun: true };
|
|
861
|
+
}
|
|
862
|
+
return { index };
|
|
863
|
+
};
|
|
864
|
+
// A copy sets its own test limit (vi.setConfig); the longest is the
|
|
865
|
+
// run's, for a setup that cannot.
|
|
866
|
+
const testTimeoutMs = Math.max(...assignments.map((assignment) => assignment.claim.testTimeout));
|
|
867
|
+
setTestTimeout(vitest, testTimeoutMs);
|
|
868
|
+
const hookMs = hookTimeoutOf(vitest);
|
|
869
|
+
const stageStarted = Date.now();
|
|
870
|
+
const cpuBefore = machineCpu();
|
|
871
|
+
let settled;
|
|
872
|
+
const ran = runFiles(assignments.map((assignment) => specOf.get(assignment.file)), false)
|
|
873
|
+
.then((result) => {
|
|
874
|
+
settled = { result };
|
|
875
|
+
}, (error) => {
|
|
876
|
+
settled = { error };
|
|
877
|
+
});
|
|
878
|
+
// A copy reports as it goes: its claim, each test, its end. One that
|
|
879
|
+
// stops (a mutant that left a module's import waiting forever, a
|
|
880
|
+
// loop that never yields) must not hold its worker. A mutant's copy
|
|
881
|
+
// may take three times its file's baseline copy and 10 s more (twice
|
|
882
|
+
// StrykerJS's limit), plus the longest test or hook limit: a test
|
|
883
|
+
// that hangs is Vitest's to end, as a timeout. Past that its worker
|
|
884
|
+
// process is stopped, and the stage goes on. A worker that is a
|
|
885
|
+
// thread of Vitest's own process cannot be stopped alone: once every
|
|
886
|
+
// copy still going is such a one past its limit, or nothing has
|
|
887
|
+
// reported for twice the longest test or hook limit and 30 s more,
|
|
888
|
+
// the stage's run is cancelled.
|
|
889
|
+
const quietLimit = Math.max(testTimeoutMs, hookMs) * 2 + 30_000;
|
|
890
|
+
const claims = { offset: 0 };
|
|
891
|
+
const going = new Map();
|
|
892
|
+
const handled = new Set();
|
|
893
|
+
const stopped = new Map();
|
|
894
|
+
// Copies stopped once a failed test decided them.
|
|
895
|
+
const decided = new Map();
|
|
896
|
+
const settles = (at, outcome) => {
|
|
897
|
+
const assignment = assignments[at];
|
|
898
|
+
return Boolean(assignment.job && assignment.claim.mutant && known(assignment.file) &&
|
|
899
|
+
failedTest(outcome) && ownWorker(outcome.pid));
|
|
900
|
+
};
|
|
901
|
+
// Copies stopped at the stage's end, to run again in the next.
|
|
902
|
+
const deferred = new Map();
|
|
903
|
+
let claimedCount = 0;
|
|
904
|
+
let lastReport = stageStarted;
|
|
905
|
+
let lastClaim = stageStarted;
|
|
906
|
+
// What every copy had reported when the run was cancelled. A
|
|
907
|
+
// cancelled copy ends gracefully, its tests left skipped: only what
|
|
908
|
+
// it reported before counts. A copy still going then is a timeout
|
|
909
|
+
// unless a test had already failed; one no worker had taken runs in
|
|
910
|
+
// a later stage.
|
|
911
|
+
let atCancel;
|
|
912
|
+
// Past its limit, and past Vitest's own test and hook limits after
|
|
913
|
+
// that.
|
|
914
|
+
const overdue = (at, outcome, now) => {
|
|
915
|
+
const assignment = assignments[at];
|
|
916
|
+
const limit = assignment.job ? limitOf(assignment) : undefined;
|
|
917
|
+
if (limit === undefined || outcome.claimedAt === undefined)
|
|
918
|
+
return false;
|
|
919
|
+
return now - outcome.claimedAt > limit + Math.max(assignment.claim.testTimeout, hookMs);
|
|
920
|
+
};
|
|
921
|
+
const stop = (at, outcome) => {
|
|
922
|
+
if (ownWorker(outcome.pid)) {
|
|
923
|
+
try {
|
|
924
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
925
|
+
}
|
|
926
|
+
catch {
|
|
927
|
+
// It ended meanwhile.
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
going.delete(at);
|
|
931
|
+
stopped.set(at, outcome);
|
|
932
|
+
profile.killedCopies += 1;
|
|
933
|
+
};
|
|
934
|
+
const look = () => {
|
|
935
|
+
const now = Date.now();
|
|
936
|
+
let reported = false;
|
|
937
|
+
for (const line of readAppended(`${directory}/claimed`, claims)) {
|
|
938
|
+
const at = positionOf.get(line);
|
|
939
|
+
if (at === undefined || going.has(at) || handled.has(at) || stopped.has(at))
|
|
940
|
+
continue;
|
|
941
|
+
claimedCount += 1;
|
|
942
|
+
going.set(at, { records: -1 });
|
|
943
|
+
reported = true;
|
|
944
|
+
lastClaim = now;
|
|
945
|
+
}
|
|
946
|
+
for (const [at, seen] of going) {
|
|
947
|
+
let outcome = readOutcome(outs[at]);
|
|
948
|
+
// A copy whose worker process is gone without its end (its
|
|
949
|
+
// test file failed to load, its worker crashed) is over: what
|
|
950
|
+
// it reported, read once its process is gone, is all there is.
|
|
951
|
+
const gone = !outcome.done && outcome.pid && outcome.pid !== process.pid && !alive(outcome.pid);
|
|
952
|
+
if (gone)
|
|
953
|
+
outcome = readOutcome(outs[at]);
|
|
954
|
+
if (outcome.records !== seen.records) {
|
|
955
|
+
seen.records = outcome.records;
|
|
956
|
+
reported = true;
|
|
957
|
+
}
|
|
958
|
+
seen.outcome = outcome;
|
|
959
|
+
// A mutant's copy that has failed a test its file's known
|
|
960
|
+
// baseline passed is decided by that test: the rest of its
|
|
961
|
+
// tests are skipped, and what it does from here on cannot
|
|
962
|
+
// change its verdict. Its worker stops now, rather than at
|
|
963
|
+
// its file's end, which a timed-out test can leave a runaway
|
|
964
|
+
// loop holding (on tRPC such copies held 2 GB each).
|
|
965
|
+
if (!outcome.done && settles(at, outcome)) {
|
|
966
|
+
try {
|
|
967
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
968
|
+
}
|
|
969
|
+
catch {
|
|
970
|
+
// It ended meanwhile.
|
|
971
|
+
}
|
|
972
|
+
outcome = { ...outcome, done: true, doneAt: now };
|
|
973
|
+
decided.set(at, outcome);
|
|
974
|
+
seen.outcome = outcome;
|
|
975
|
+
profile.settledCopies += 1;
|
|
976
|
+
}
|
|
977
|
+
if (outcome.done) {
|
|
978
|
+
going.delete(at);
|
|
979
|
+
if (early(at, outcome))
|
|
980
|
+
handled.add(at);
|
|
981
|
+
}
|
|
982
|
+
else if (gone)
|
|
983
|
+
going.delete(at);
|
|
984
|
+
}
|
|
985
|
+
if (reported)
|
|
986
|
+
lastReport = now;
|
|
987
|
+
const quiet = going.size > 0 && now - lastReport > quietLimit;
|
|
988
|
+
let cancel = false;
|
|
989
|
+
for (const [at, { outcome }] of going) {
|
|
990
|
+
if (!outcome?.claimed || !(quiet || overdue(at, outcome, now)))
|
|
991
|
+
continue;
|
|
992
|
+
// A worker process of its own (forks), not Vitest's.
|
|
993
|
+
if (outcome.pid && outcome.pid !== process.pid)
|
|
994
|
+
stop(at, outcome);
|
|
995
|
+
else
|
|
996
|
+
cancel = true;
|
|
997
|
+
}
|
|
998
|
+
// Every copy started: the stage ends with its last ones. A
|
|
999
|
+
// mutant's copy still going well past what it should take (1.5×
|
|
1000
|
+
// and 1 s) holds the stage alone; it stops, and runs again with
|
|
1001
|
+
// its whole limit in the next stage, beside that stage's work.
|
|
1002
|
+
if (claimedCount === assignments.length) {
|
|
1003
|
+
for (const [at, { outcome }] of going) {
|
|
1004
|
+
const assignment = assignments[at];
|
|
1005
|
+
if (!assignment.job || assignment.group.deferredOnce || !outcome?.claimed || !ownWorker(outcome.pid))
|
|
1006
|
+
continue;
|
|
1007
|
+
if (now - outcome.claimedAt > expectedOf(assignment) * TIMEOUT_FACTOR + 1_000) {
|
|
1008
|
+
try {
|
|
1009
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
1010
|
+
}
|
|
1011
|
+
catch {
|
|
1012
|
+
// It ended meanwhile.
|
|
1013
|
+
}
|
|
1014
|
+
going.delete(at);
|
|
1015
|
+
deferred.set(at, outcome);
|
|
1016
|
+
profile.deferredCopies += 1;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
const stuck = [...going].every(([at, { outcome }]) => outcome?.claimed && (quiet || overdue(at, outcome, now)));
|
|
1021
|
+
return cancel && (quiet || stuck);
|
|
1022
|
+
};
|
|
1023
|
+
let cancelled = false;
|
|
1024
|
+
while (!settled) {
|
|
1025
|
+
await Promise.race([ran, pause(WATCH_INTERVAL_MS)]);
|
|
1026
|
+
if (settled)
|
|
1027
|
+
break;
|
|
1028
|
+
if (look()) {
|
|
1029
|
+
cancelled = true;
|
|
1030
|
+
atCancel = outs.map(readOutcome);
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
if (cancelled) {
|
|
1035
|
+
profile.cancelledStages += 1;
|
|
1036
|
+
const cancel = () => {
|
|
1037
|
+
try {
|
|
1038
|
+
vitest.cancelCurrentRun?.("supercov: a test file stopped reporting")?.catch?.(() => { });
|
|
1039
|
+
}
|
|
1040
|
+
catch {
|
|
1041
|
+
// Nothing to cancel with: the grace below runs out.
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
cancel();
|
|
1045
|
+
await Promise.race([ran, pause(CANCEL_FORCE_AFTER_MS)]);
|
|
1046
|
+
// A second cancel stops the workers by force.
|
|
1047
|
+
if (!settled)
|
|
1048
|
+
cancel();
|
|
1049
|
+
await Promise.race([ran, pause(CANCEL_GRACE_MS)]);
|
|
1050
|
+
// Workers that will not stop even then: the pass ends here, and
|
|
1051
|
+
// the mutants left run in the next pass `mutants test` starts.
|
|
1052
|
+
if (!settled)
|
|
1053
|
+
stalled = true;
|
|
1054
|
+
}
|
|
1055
|
+
if (settled?.result)
|
|
1056
|
+
last = settled.result;
|
|
1057
|
+
running = undefined;
|
|
1058
|
+
claimRun = undefined;
|
|
1059
|
+
const stageEnded = Date.now();
|
|
1060
|
+
const outcomes = assignments.map((assignment, at) => {
|
|
1061
|
+
let outcome;
|
|
1062
|
+
if (decided.has(at))
|
|
1063
|
+
outcome = decided.get(at);
|
|
1064
|
+
else if (stopped.has(at))
|
|
1065
|
+
outcome = { ...stopped.get(at), hung: true };
|
|
1066
|
+
else if (deferred.has(at))
|
|
1067
|
+
outcome = { ...deferred.get(at), deferred: true };
|
|
1068
|
+
else if (cancelled) {
|
|
1069
|
+
outcome = atCancel[at];
|
|
1070
|
+
outcome.hung = outcome.claimed && !outcome.done;
|
|
1071
|
+
}
|
|
1072
|
+
else
|
|
1073
|
+
outcome = readOutcome(outs[at]);
|
|
1074
|
+
outcome.cancelled = cancelled;
|
|
1075
|
+
if (outcome.hung)
|
|
1076
|
+
profile.hungCopies += 1;
|
|
1077
|
+
return outcome;
|
|
1078
|
+
});
|
|
1079
|
+
let copyMs = 0;
|
|
1080
|
+
let claimed = 0;
|
|
1081
|
+
outcomes.forEach((outcome, at) => {
|
|
1082
|
+
if (!outcome.claimedAt)
|
|
1083
|
+
return;
|
|
1084
|
+
claimed += 1;
|
|
1085
|
+
profile.copies += 1;
|
|
1086
|
+
if (outcome.skipped)
|
|
1087
|
+
profile.skippedCopies += 1;
|
|
1088
|
+
else if (assignments[at].claim.mutant)
|
|
1089
|
+
profile.mutantCopies += 1;
|
|
1090
|
+
profile.testsRun += outcome.tests.length;
|
|
1091
|
+
profile.startMs += startOf(outcome);
|
|
1092
|
+
if (outcome.doneAt)
|
|
1093
|
+
copyMs += outcome.doneAt - outcome.claimedAt;
|
|
1094
|
+
});
|
|
1095
|
+
profile.copyMs += copyMs;
|
|
1096
|
+
profile.wallMs += stageEnded - stageStarted;
|
|
1097
|
+
const cpuAfter = machineCpu();
|
|
1098
|
+
const cpuBusy = cpuBefore && cpuAfter && cpuAfter.total > cpuBefore.total
|
|
1099
|
+
? Math.round((cpuAfter.busy - cpuBefore.busy) / (cpuAfter.total - cpuBefore.total) * 100) / 100
|
|
1100
|
+
: undefined;
|
|
1101
|
+
if (profile.stages.length < PROFILED_STAGES)
|
|
1102
|
+
profile.stages.push({ copies: assignments.length, claimed, wallMs: stageEnded - stageStarted, lastClaimMs: lastClaim - stageStarted, copyMs, cpuBusy, ...memoryOf() });
|
|
1103
|
+
return { outcomes, handled };
|
|
1104
|
+
}
|
|
1105
|
+
// A baseline: each file with the union of its candidates, no mutant.
|
|
1106
|
+
// A test that fails there cannot count as a kill. A file's baseline runs
|
|
1107
|
+
// in the same stage as its mutants' first copies, listed before them: a
|
|
1108
|
+
// copy is judged once its file's baseline is known.
|
|
1109
|
+
const baselines = new Map();
|
|
1110
|
+
for (const job of pending) {
|
|
1111
|
+
for (const group of job.files) {
|
|
1112
|
+
const entry = baselines.get(group.file) ?? { file: group.file, tests: new Set(), whole: false, state: "waiting", tries: 0 };
|
|
1113
|
+
group.tests.forEach((id) => entry.tests.add(id));
|
|
1114
|
+
entry.whole ||= group.whole;
|
|
1115
|
+
baselines.set(group.file, entry);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
const baselineFailed = new Set();
|
|
1119
|
+
// What each file's baseline ran, in order, and the files it ran whole:
|
|
1120
|
+
// a kill by a test whose file's baseline ran the same tests before it
|
|
1121
|
+
// is certain; any other is confirmed without the mutant first.
|
|
1122
|
+
const baselineOrder = new Map();
|
|
1123
|
+
const wholeBaseline = new Set();
|
|
1124
|
+
// How long each file's baseline copy took, from its claim to its end:
|
|
1125
|
+
// a mutant's copy of the file that runs past a multiple of that has
|
|
1126
|
+
// stopped.
|
|
1127
|
+
const baselineCopyMs = new Map();
|
|
1128
|
+
// What the baselines tell of the time a copy takes: each test's own, and
|
|
1129
|
+
// each file's beyond its tests (loading, hooks, teardown).
|
|
1130
|
+
const baselineTestMs = new Map();
|
|
1131
|
+
const fileOverheadMs = new Map();
|
|
1132
|
+
const known = (file) => baselines.get(file)?.state === "known";
|
|
1133
|
+
// A baseline's outcome. A candidate that fails with only the candidates
|
|
1134
|
+
// of its file around it leans on a test before it: its file runs whole
|
|
1135
|
+
// (`widened`), and only what fails then, with nothing mutated, is no
|
|
1136
|
+
// kill. A copy no worker took (a cancelled stage) runs again.
|
|
1137
|
+
const recordBaseline = (entry, outcome) => {
|
|
1138
|
+
entry.state = "waiting";
|
|
1139
|
+
if (outcome.cancelled && !outcome.claimed && !stalled && ++entry.tries < 3)
|
|
1140
|
+
return;
|
|
1141
|
+
const failed = outcome.tests.some((test) => test.failed);
|
|
1142
|
+
if ((failed || !outcome.done) && !entry.whole) {
|
|
1143
|
+
entry.whole = true;
|
|
1144
|
+
entry.tests = new Set();
|
|
1145
|
+
baselineCopyMs.delete(entry.file);
|
|
1146
|
+
for (const job of pending)
|
|
1147
|
+
for (const group of job.files)
|
|
1148
|
+
if (group.file === entry.file)
|
|
1149
|
+
group.whole = true;
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
entry.state = "known";
|
|
1153
|
+
baselineOrder.set(entry.file, outcome.tests.map((test) => test.test));
|
|
1154
|
+
if (outcome.done) {
|
|
1155
|
+
baselineCopyMs.set(entry.file, outcome.doneAt - outcome.claimedAt);
|
|
1156
|
+
let testsMs = 0;
|
|
1157
|
+
for (const test of outcome.tests) {
|
|
1158
|
+
baselineTestMs.set(test.test, test.ms ?? 0);
|
|
1159
|
+
testsMs += test.ms ?? 0;
|
|
1160
|
+
}
|
|
1161
|
+
fileOverheadMs.set(entry.file, Math.max(0, outcome.doneAt - outcome.claimedAt - testsMs));
|
|
1162
|
+
}
|
|
1163
|
+
else
|
|
1164
|
+
baselineCopyMs.delete(entry.file);
|
|
1165
|
+
if (entry.whole)
|
|
1166
|
+
wholeBaseline.add(entry.file);
|
|
1167
|
+
if (outcome.outside.length)
|
|
1168
|
+
baselineFailed.add(`${entry.file}#outside`);
|
|
1169
|
+
if (!outcome.done)
|
|
1170
|
+
baselineFailed.add(`${entry.file}#file`);
|
|
1171
|
+
for (const test of outcome.tests)
|
|
1172
|
+
if (test.failed)
|
|
1173
|
+
baselineFailed.add(test.test);
|
|
1174
|
+
};
|
|
1175
|
+
|
|
1176
|
+
const oneAtATime = !isolated(vitest);
|
|
1177
|
+
const workers = Math.max(1, Number(vitest.config.maxWorkers) || availableParallelism());
|
|
1178
|
+
const durationOf = new Map(tests.map((test) => [test.id, test.durationMs ?? 1_000]));
|
|
1179
|
+
const testsOf = new Map();
|
|
1180
|
+
for (const test of tests) {
|
|
1181
|
+
if (!test.file)
|
|
1182
|
+
continue;
|
|
1183
|
+
if (!testsOf.has(test.file))
|
|
1184
|
+
testsOf.set(test.file, []);
|
|
1185
|
+
testsOf.get(test.file).push(test.id);
|
|
1186
|
+
}
|
|
1187
|
+
// A copy's estimated time: its file's own beyond its tests and its tests'
|
|
1188
|
+
// durations (as its baseline ran them, or as measured), or its file's
|
|
1189
|
+
// baseline copy where it runs the file whole.
|
|
1190
|
+
const testMsOf = (id) => baselineTestMs.get(id) ?? durationOf.get(id) ?? 1_000;
|
|
1191
|
+
const overheadOf = (file) => fileOverheadMs.get(file) ??
|
|
1192
|
+
(fileOverheadMs.size ? [...fileOverheadMs.values()].reduce((sum, ms) => sum + ms, 0) / fileOverheadMs.size : 0);
|
|
1193
|
+
const estimateOf = (group) => group.whole
|
|
1194
|
+
? baselineCopyMs.get(group.file) ?? group.cost
|
|
1195
|
+
: overheadOf(group.file) + group.tests.reduce((sum, id) => sum + (baselineFailed.has(id) ? 0 : testMsOf(id)), 0);
|
|
1196
|
+
const baselineEstimateOf = (entry) => entry.whole
|
|
1197
|
+
? tests.reduce((sum, test) => sum + (test.file === entry.file ? test.durationMs ?? 1_000 : 0), 0)
|
|
1198
|
+
: [...entry.tests].reduce((sum, id) => sum + (durationOf.get(id) ?? 1_000), 0);
|
|
1199
|
+
// A mutant runs its cheapest file first; if that does not kill it, its
|
|
1200
|
+
// other files in batches of 1, 4, 16, ... (`job.batch`), the files most
|
|
1201
|
+
// likely to kill it first: a copy listed in a stage costs a worker's
|
|
1202
|
+
// start even where it ends at once (its mutant decided meanwhile), and a
|
|
1203
|
+
// mutant's later files mostly belong to survivors, which need them all.
|
|
1204
|
+
// On the public benchmark's kill matrix all-at-once listed 30% more
|
|
1205
|
+
// copies than this.
|
|
1206
|
+
for (const job of pending) {
|
|
1207
|
+
job.waiting = [job.files[0]];
|
|
1208
|
+
job.later = job.files.slice(1);
|
|
1209
|
+
job.batch = 1;
|
|
1210
|
+
job.open = 0;
|
|
1211
|
+
}
|
|
1212
|
+
// How often each test file killed the mutants it ran, learned as the
|
|
1213
|
+
// pass goes: a file's chance to kill over its cost (its tests' measured
|
|
1214
|
+
// time and a copy's start) orders a mutant's later files.
|
|
1215
|
+
const fileRuns = new Map();
|
|
1216
|
+
const fileKills = new Map();
|
|
1217
|
+
const startCost = () => profile.copies ? profile.startMs / profile.copies : 300;
|
|
1218
|
+
const killScore = (group) => ((fileKills.get(group.file) ?? 0) + 1) / ((fileRuns.get(group.file) ?? 0) + 2) / (estimateOf(group) + startCost());
|
|
1219
|
+
const nextBatch = (job) => {
|
|
1220
|
+
job.later.sort((a, b) => killScore(b) - killScore(a));
|
|
1221
|
+
const batch = job.later.splice(0, job.batch);
|
|
1222
|
+
job.batch *= BATCH_GROWTH;
|
|
1223
|
+
return batch;
|
|
1224
|
+
};
|
|
1225
|
+
// A mutant's copies of the stage running that no worker has taken yet
|
|
1226
|
+
// are not needed once a copy killed it: they end before their test file
|
|
1227
|
+
// loads (one taken already runs on).
|
|
1228
|
+
const skipRest = (job) => {
|
|
1229
|
+
if (!running)
|
|
1230
|
+
return;
|
|
1231
|
+
for (const at of job.positions ?? [])
|
|
1232
|
+
writeFileSync(`${running.placed[at]}.skip`, "");
|
|
1233
|
+
job.positions = [];
|
|
1234
|
+
};
|
|
1235
|
+
const finish = (job, verdict) => {
|
|
1236
|
+
write({ id: job.mutant.id, ...verdict, tests: job.ran, durationMs: Date.now() - (job.started || Date.now()) });
|
|
1237
|
+
job.done = true;
|
|
1238
|
+
job.deferred = [];
|
|
1239
|
+
skipRest(job);
|
|
1240
|
+
};
|
|
1241
|
+
// A copy runs only a mutant's candidates, and a test can lean on one
|
|
1242
|
+
// the copy left out (state an earlier test built): it fails then with
|
|
1243
|
+
// or without the mutant. A kill counts where the file's baseline ran
|
|
1244
|
+
// the same tests before the killing one (or the copy ran what the
|
|
1245
|
+
// baseline ran whole); any other kill is confirmed by running the same
|
|
1246
|
+
// tests without the mutant. Where they fail that way too, it is no
|
|
1247
|
+
// kill: the mutant runs again with its test file whole, and only what
|
|
1248
|
+
// fails there without the mutant as well is none.
|
|
1249
|
+
const confirmations = new Map();
|
|
1250
|
+
let overturned = 0;
|
|
1251
|
+
const confirmationKey = (file, chosen, whole) => `${file}\0${whole ? "*" : chosen.join("\0")}`;
|
|
1252
|
+
const certain = (group, chosen, evidence) => {
|
|
1253
|
+
if (group.whole)
|
|
1254
|
+
return wholeBaseline.has(group.file);
|
|
1255
|
+
const order = baselineOrder.get(group.file);
|
|
1256
|
+
if (!order)
|
|
1257
|
+
return false;
|
|
1258
|
+
if (evidence.test) {
|
|
1259
|
+
const at = order.indexOf(evidence.test);
|
|
1260
|
+
return at >= 0 && order.slice(0, at).every((id) => chosen.includes(id));
|
|
1261
|
+
}
|
|
1262
|
+
return order.length === chosen.length && order.every((id) => chosen.includes(id));
|
|
1263
|
+
};
|
|
1264
|
+
const confirm = (job, group, chosen, evidence, verdict) => {
|
|
1265
|
+
const key = confirmationKey(group.file, chosen, group.whole);
|
|
1266
|
+
if (!confirmations.has(key))
|
|
1267
|
+
confirmations.set(key, {
|
|
1268
|
+
file: group.file,
|
|
1269
|
+
claim: { mutant: null, tests: chosen, wholeFile: group.whole },
|
|
1270
|
+
tries: 0,
|
|
1271
|
+
result: undefined,
|
|
1272
|
+
});
|
|
1273
|
+
(job.confirming ??= []).push({ key, group, evidence, verdict });
|
|
1274
|
+
// Most such kills stand: its other copies wait for the confirmation
|
|
1275
|
+
// (job.deferred), and run only if it overturns the kill.
|
|
1276
|
+
skipRest(job);
|
|
1277
|
+
};
|
|
1278
|
+
// Each of a job's kills waiting on a confirmation, once it has run.
|
|
1279
|
+
const settle = (job) => {
|
|
1280
|
+
for (const waiting of [...job.confirming]) {
|
|
1281
|
+
const { key, group, evidence, verdict } = waiting;
|
|
1282
|
+
const result = confirmations.get(key).result;
|
|
1283
|
+
if (!result)
|
|
1284
|
+
continue;
|
|
1285
|
+
job.confirming.splice(job.confirming.indexOf(waiting), 1);
|
|
1286
|
+
const alsoWithout = evidence.test ? result.failed.has(evidence.test)
|
|
1287
|
+
: evidence.outside ? result.outside
|
|
1288
|
+
: !result.done;
|
|
1289
|
+
if (!alsoWithout) {
|
|
1290
|
+
finish(job, verdict);
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
overturned += 1;
|
|
1294
|
+
if (!group.whole)
|
|
1295
|
+
job.waiting.push({ file: group.file, tests: [], cost: group.cost, whole: true });
|
|
1296
|
+
else if (evidence.test)
|
|
1297
|
+
baselineFailed.add(evidence.test);
|
|
1298
|
+
}
|
|
1299
|
+
// Every kill overturned: the files its kills held back run now.
|
|
1300
|
+
if (!job.confirming.length && job.deferred?.length) {
|
|
1301
|
+
job.waiting.push(...job.deferred);
|
|
1302
|
+
job.deferred = [];
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
// The test a mutant's copy failed first, where it failed with nothing
|
|
1306
|
+
// mutated too only in its file's baseline.
|
|
1307
|
+
const failedTest = (outcome) => outcome.tests.find((test) => test.failed && !baselineFailed.has(test.test));
|
|
1308
|
+
// A copy that ran beside its file's baseline cannot always be judged:
|
|
1309
|
+
// its file then failed to finish (its mutants are not run), or had to
|
|
1310
|
+
// run whole (the copy runs again whole), or the copy stopped at a test
|
|
1311
|
+
// that fails without the mutant too (it runs again without it).
|
|
1312
|
+
const usable = ({ job, group, claim }, outcome) => {
|
|
1313
|
+
if (baselineFailed.has(`${group.file}#file`)) {
|
|
1314
|
+
job.unrun = group.file;
|
|
1315
|
+
return false;
|
|
1316
|
+
}
|
|
1317
|
+
const firstFailed = outcome.tests.find((test) => test.failed);
|
|
1318
|
+
if (claim.wholeFile !== group.whole || (claim.unknownBaseline && firstFailed && baselineFailed.has(firstFailed.test))) {
|
|
1319
|
+
job.waiting.push(group);
|
|
1320
|
+
return false;
|
|
1321
|
+
}
|
|
1322
|
+
return true;
|
|
1323
|
+
};
|
|
1324
|
+
// What a mutant's copy says of it.
|
|
1325
|
+
const judge = (assignment, outcome) => {
|
|
1326
|
+
const { job, group, claim } = assignment;
|
|
1327
|
+
job.open -= 1;
|
|
1328
|
+
if (job.done)
|
|
1329
|
+
return;
|
|
1330
|
+
// Held back: its mutant's other copies had not ended.
|
|
1331
|
+
if (outcome.notRun) {
|
|
1332
|
+
job.later.unshift(group);
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
// Skipped while a kill waits on its confirmation.
|
|
1336
|
+
if (outcome.skipped) {
|
|
1337
|
+
(job.deferred ??= []).push(group);
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
if (!outcome.claimed) {
|
|
1341
|
+
if (stalled)
|
|
1342
|
+
return;
|
|
1343
|
+
// A cancelled stage's copies no worker took are not this
|
|
1344
|
+
// mutant's doing.
|
|
1345
|
+
if (outcome.cancelled) {
|
|
1346
|
+
job.waiting.push(group);
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
group.unclaimed = (group.unclaimed ?? 0) + 1;
|
|
1350
|
+
if (group.unclaimed > 2)
|
|
1351
|
+
finish(job, { status: "error", reason: "no copy of its test file ran it" });
|
|
1352
|
+
else
|
|
1353
|
+
job.waiting.push(group);
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
if (!usable(assignment, outcome))
|
|
1357
|
+
return;
|
|
1358
|
+
// Stopped at its stage's end before a test failed: it runs again.
|
|
1359
|
+
if (outcome.deferred && !failedTest(outcome)) {
|
|
1360
|
+
group.deferredOnce = true;
|
|
1361
|
+
job.waiting.unshift(group);
|
|
1362
|
+
return;
|
|
1363
|
+
}
|
|
1364
|
+
job.ran += outcome.tests.length;
|
|
1365
|
+
const chosen = claim.tests;
|
|
1366
|
+
fileRuns.set(group.file, (fileRuns.get(group.file) ?? 0) + 1);
|
|
1367
|
+
const kill = (evidence, verdict) => {
|
|
1368
|
+
fileKills.set(group.file, (fileKills.get(group.file) ?? 0) + 1);
|
|
1369
|
+
if (certain(group, chosen, evidence))
|
|
1370
|
+
finish(job, verdict);
|
|
1371
|
+
else if (evidence.test && !group.whole) {
|
|
1372
|
+
// Tests after the failing one cannot change it: the
|
|
1373
|
+
// confirmation runs what ran up to it, which many
|
|
1374
|
+
// mutants' copies share.
|
|
1375
|
+
const ran = outcome.tests.map((test) => test.test);
|
|
1376
|
+
confirm(job, group, ran.slice(0, ran.indexOf(evidence.test) + 1), evidence, verdict);
|
|
1377
|
+
}
|
|
1378
|
+
else
|
|
1379
|
+
confirm(job, group, chosen, evidence, verdict);
|
|
1380
|
+
};
|
|
1381
|
+
const failed = failedTest(outcome);
|
|
1382
|
+
const outside = baselineFailed.has(`${group.file}#outside`) ? undefined : outcome.outside[0];
|
|
1383
|
+
if (!failed && outside) {
|
|
1384
|
+
kill({ outside: true }, outside.timeout
|
|
1385
|
+
? { status: "timeout", reason: "outside any test: the mutant's evaluations passed its limit" }
|
|
1386
|
+
: { status: "killed", killedBy: group.file, reason: `an error outside any test: ${outside.message}` });
|
|
1387
|
+
}
|
|
1388
|
+
else if (failed) {
|
|
1389
|
+
kill({ test: failed.test }, { status: failed.timeout ? "timeout" : "killed", killedBy: failed.test });
|
|
1390
|
+
}
|
|
1391
|
+
else if (outcome.hung && !stalled) {
|
|
1392
|
+
// The copy stopped reporting past its limit, as its file's
|
|
1393
|
+
// baseline did not: a timeout, unless its tests left out hang
|
|
1394
|
+
// the same way without the mutant.
|
|
1395
|
+
kill({ unfinished: true }, { status: "timeout", killedBy: group.file, reason: "its test file stopped before its end, past its limit" });
|
|
1396
|
+
}
|
|
1397
|
+
else if (!outcome.done) {
|
|
1398
|
+
// The copy started and its file did not finish: the mutant
|
|
1399
|
+
// broke it while it loaded or ran.
|
|
1400
|
+
if (stalled)
|
|
1401
|
+
finish(job, { status: "timeout", reason: "its test file did not finish by the stage's deadline" });
|
|
1402
|
+
else
|
|
1403
|
+
kill({ unfinished: true }, { status: "killed", killedBy: group.file, reason: "the test file did not finish" });
|
|
1404
|
+
}
|
|
1405
|
+
else {
|
|
1406
|
+
const short = ranNone(claim, outcome, { order: baselineOrder.get(group.file) }, group.file);
|
|
1407
|
+
if (short)
|
|
1408
|
+
finish(job, { status: "error", reason: short });
|
|
1409
|
+
}
|
|
1410
|
+
};
|
|
1411
|
+
// What a confirmation's copy says: the tests that fail without the
|
|
1412
|
+
// mutant, and whether the file finished.
|
|
1413
|
+
const record = ({ check }, outcome) => {
|
|
1414
|
+
check.running = false;
|
|
1415
|
+
if (!outcome.claimed && outcome.cancelled && !stalled)
|
|
1416
|
+
return;
|
|
1417
|
+
check.tries += 1;
|
|
1418
|
+
if (!outcome.claimed && !stalled && check.tries < 3)
|
|
1419
|
+
return;
|
|
1420
|
+
check.result = {
|
|
1421
|
+
failed: new Set(outcome.tests.filter((test) => test.failed).map((test) => test.test)),
|
|
1422
|
+
outside: outcome.outside.length > 0,
|
|
1423
|
+
// A copy no worker took cannot say the tests fail without the
|
|
1424
|
+
// mutant: the kill stands.
|
|
1425
|
+
done: outcome.done || !outcome.claimed,
|
|
1426
|
+
};
|
|
1427
|
+
};
|
|
1428
|
+
// What a copy of a mutant should take, by its file's baseline copy.
|
|
1429
|
+
const limitBaseOf = ({ group }) => group.whole && !baselines.get(group.file)?.whole
|
|
1430
|
+
? undefined
|
|
1431
|
+
: baselineCopyMs.get(group.file);
|
|
1432
|
+
// How long a copy of a mutant may run: its file's baseline copy, as a
|
|
1433
|
+
// test's limit, unless it runs its file whole and the baseline did not.
|
|
1434
|
+
// Read while the copy runs: its baseline may end meanwhile.
|
|
1435
|
+
const limitOf = ({ group }) => {
|
|
1436
|
+
const baselineMs = baselineCopyMs.get(group.file);
|
|
1437
|
+
if (baselineMs === undefined || (group.whole && !baselines.get(group.file)?.whole))
|
|
1438
|
+
return undefined;
|
|
1439
|
+
return (baselineMs * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * 2;
|
|
1440
|
+
};
|
|
1441
|
+
// The continuous pass (where Supercov's spawner forks Vitest's workers,
|
|
1442
|
+
// Vitest 4 and later, files isolated): no stages. Each file's baselines
|
|
1443
|
+
// run first, once per shape a mutant needs (its candidates' union, or
|
|
1444
|
+
// the file whole), in a run of their own. Then one Vitest run lists more
|
|
1445
|
+
// worker slots than the pass can use; a slot takes its work only when
|
|
1446
|
+
// Vitest tells its worker the test file (the stand-in waits for it), and
|
|
1447
|
+
// the work it takes is whatever is ready: a baseline a mutant now needs,
|
|
1448
|
+
// a confirmation, or the next file of a mutant whose copy before has
|
|
1449
|
+
// ended with every test passing, the mutant with the most work left
|
|
1450
|
+
// first. The worker is then told to run that work's test file, in place
|
|
1451
|
+
// of the slot's (a file of the same project and environment). A
|
|
1452
|
+
// mutant's files run one after another, likeliest killer first, and its
|
|
1453
|
+
// chain stops at its first kill: parallelism comes from many mutants at
|
|
1454
|
+
// once. When nothing is left, the run is cancelled.
|
|
1455
|
+
// A copy that ended with no test failing proves the mutant survives its
|
|
1456
|
+
// file only where it ran every test it was to run: one that ran fewer
|
|
1457
|
+
// (its tests' ids matched none of the file's, say) says nothing, and its
|
|
1458
|
+
// mutant is an error, never a survivor. `baselineOrder` is what the file
|
|
1459
|
+
// ran whole, for a copy of the whole file.
|
|
1460
|
+
function ranNone(claim, outcome, baselineEntry, file) {
|
|
1461
|
+
const ran = new Set(outcome.tests.map((test) => test.test));
|
|
1462
|
+
const expected = claim.wholeFile ? baselineEntry?.order ?? [] : claim.tests;
|
|
1463
|
+
const missing = expected.filter((id) => !ran.has(id));
|
|
1464
|
+
if (!missing.length && (ran.size || !claim.wholeFile))
|
|
1465
|
+
return undefined;
|
|
1466
|
+
if (!ran.size)
|
|
1467
|
+
return `its copy of ${file} ran none of the tests it was to run`;
|
|
1468
|
+
return `its copy of ${file} ran ${expected.length - missing.length} of the ${expected.length} tests it was to run`;
|
|
1469
|
+
}
|
|
1470
|
+
async function runContinuous() {
|
|
1471
|
+
// Each file's baselines: `union` (its mutants' candidates together)
|
|
1472
|
+
// and `whole`, as mutants need them.
|
|
1473
|
+
const base = new Map();
|
|
1474
|
+
const baseOf = (file) => {
|
|
1475
|
+
if (!base.has(file))
|
|
1476
|
+
base.set(file, { union: { tests: new Set(), state: "unneeded" }, whole: { state: "unneeded" } });
|
|
1477
|
+
return base.get(file);
|
|
1478
|
+
};
|
|
1479
|
+
const need = (file, shape) => {
|
|
1480
|
+
const entry = baseOf(file)[shape];
|
|
1481
|
+
if (entry.state === "unneeded")
|
|
1482
|
+
entry.state = "waiting";
|
|
1483
|
+
};
|
|
1484
|
+
// A candidate that fails beside only its file's other candidates leans
|
|
1485
|
+
// on a test before it: the file's copies run it whole from then on.
|
|
1486
|
+
const forceWhole = new Set();
|
|
1487
|
+
// A file's whole baseline runs before the copies of the whole file.
|
|
1488
|
+
// (Run only once such a copy failed, it made tRPC's pass a third
|
|
1489
|
+
// slower: a whole file's tests that fail without a mutant then cost a
|
|
1490
|
+
// copy, a baseline and the copy again, one after another.)
|
|
1491
|
+
for (const job of pending) {
|
|
1492
|
+
for (const group of job.files) {
|
|
1493
|
+
if (group.whole)
|
|
1494
|
+
need(group.file, "whole");
|
|
1495
|
+
else {
|
|
1496
|
+
need(group.file, "union");
|
|
1497
|
+
group.tests.forEach((id) => baseOf(group.file).union.tests.add(id));
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
const shapeOf = (group) => group.whole || forceWhole.has(group.file) ? "whole" : "union";
|
|
1502
|
+
const baselineReady = (group) => baseOf(group.file)[shapeOf(group)].state === "known";
|
|
1503
|
+
const unusable = (group) => {
|
|
1504
|
+
const entry = baseOf(group.file)[shapeOf(group)];
|
|
1505
|
+
return entry.state === "known" && !entry.done;
|
|
1506
|
+
};
|
|
1507
|
+
const recordShape = (file, shape, outcome) => {
|
|
1508
|
+
const entry = baseOf(file)[shape];
|
|
1509
|
+
if (!outcome.claimed && ++entry.tries < 3) {
|
|
1510
|
+
entry.state = "waiting";
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
if (shape === "union" && (!outcome.done || outcome.tests.some((test) => test.failed))) {
|
|
1514
|
+
// Recorded, and the file's copies run whole from now on.
|
|
1515
|
+
entry.state = "known";
|
|
1516
|
+
entry.done = false;
|
|
1517
|
+
forceWhole.add(file);
|
|
1518
|
+
need(file, "whole");
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
entry.state = "known";
|
|
1522
|
+
entry.done = outcome.done;
|
|
1523
|
+
entry.order = outcome.tests.map((test) => test.test);
|
|
1524
|
+
entry.failed = new Set(outcome.tests.filter((test) => test.failed).map((test) => test.test));
|
|
1525
|
+
entry.outside = outcome.outside.length > 0;
|
|
1526
|
+
if (outcome.done) {
|
|
1527
|
+
entry.copyMs = outcome.doneAt - outcome.claimedAt;
|
|
1528
|
+
let testsMs = 0;
|
|
1529
|
+
for (const test of outcome.tests) {
|
|
1530
|
+
baselineTestMs.set(test.test, test.ms ?? 0);
|
|
1531
|
+
testsMs += test.ms ?? 0;
|
|
1532
|
+
}
|
|
1533
|
+
if (shape === "union" || !fileOverheadMs.has(file))
|
|
1534
|
+
fileOverheadMs.set(file, Math.max(0, entry.copyMs - testsMs));
|
|
1535
|
+
if (shape === "union" || !baselineCopyMs.has(file))
|
|
1536
|
+
baselineCopyMs.set(file, entry.copyMs);
|
|
1537
|
+
}
|
|
1538
|
+
};
|
|
1539
|
+
const baselineItem = (file, shape) => {
|
|
1540
|
+
const entry = baseOf(file)[shape];
|
|
1541
|
+
entry.state = "running";
|
|
1542
|
+
entry.tries ??= 0;
|
|
1543
|
+
const ids = shape === "union" ? [...entry.tests] : testsOf.get(file) ?? [];
|
|
1544
|
+
const estimate = ids.reduce((sum, id) => sum + (durationOf.get(id) ?? 1_000), 0);
|
|
1545
|
+
return { baseline: { file, shape }, file, estimate, rank: -1, claim: { mutant: null, tests: shape === "union" ? ids : [], wholeFile: shape === "whole", testTimeout: BASELINE_TEST_TIMEOUT_MS } };
|
|
1546
|
+
};
|
|
1547
|
+
// A file's project and environment, learned from the "start" Vitest
|
|
1548
|
+
// sends its worker: work for a file runs only in a slot of the same.
|
|
1549
|
+
const classOf = new Map();
|
|
1550
|
+
const slotOf = new Map();
|
|
1551
|
+
const classKeyOf = (start) => JSON.stringify([start?.context?.config?.name ?? "", start?.context?.environment ?? null, start?.context?.pool ?? ""]);
|
|
1552
|
+
observeRun = (filepath, start) => {
|
|
1553
|
+
const file = toRelative(root, String(filepath));
|
|
1554
|
+
const key = classKeyOf(start);
|
|
1555
|
+
if (!classOf.has(file))
|
|
1556
|
+
classOf.set(file, key);
|
|
1557
|
+
if (!slotOf.has(key))
|
|
1558
|
+
slotOf.set(key, file);
|
|
1559
|
+
};
|
|
1560
|
+
|
|
1561
|
+
// The baselines run in the same run as the mutants, first: each in a
|
|
1562
|
+
// slot of its own test file at the head of the run (Vitest's "start"
|
|
1563
|
+
// for it says the file's project and environment), and a mutant's
|
|
1564
|
+
// file runs once the file's baseline is known.
|
|
1565
|
+
// The run.
|
|
1566
|
+
const directory = `${stagesDirectory}/${stageNumber++}`;
|
|
1567
|
+
mkdirSync(directory, { recursive: true });
|
|
1568
|
+
provide(vitest, { root, stage: directory });
|
|
1569
|
+
const fileKeyOf = new Map();
|
|
1570
|
+
const nextIndex = new Map();
|
|
1571
|
+
// Every mutant's files, in the order it would take them; the most
|
|
1572
|
+
// work left first (long chains do not end the pass).
|
|
1573
|
+
// A copy of the whole file costs what its tests took in the measured
|
|
1574
|
+
// run (its whole baseline may never run).
|
|
1575
|
+
const estimateC = (group) => shapeOf(group) === "whole"
|
|
1576
|
+
? overheadOf(group.file) + (testsOf.get(group.file) ?? []).reduce((sum, id) => sum + testMsOf(id), 0)
|
|
1577
|
+
: estimateOf(group);
|
|
1578
|
+
const scoreC = (group) => ((fileKills.get(group.file) ?? 0) + 1) / ((fileRuns.get(group.file) ?? 0) + 2) / (estimateC(group) + startCost());
|
|
1579
|
+
const remainingOf = (job) => job.chain.reduce((sum, group) => sum + estimateC(group) + startCost(), 0);
|
|
1580
|
+
// A mutant's copies running, and its kills waiting on a confirmation.
|
|
1581
|
+
for (const job of pending) {
|
|
1582
|
+
job.chain = [...job.files];
|
|
1583
|
+
job.open = 0;
|
|
1584
|
+
job.confirmingKills = 0;
|
|
1585
|
+
}
|
|
1586
|
+
const idle = (job) => !job.done && !job.open && !job.confirmingKills;
|
|
1587
|
+
const order = [...pending].sort((a, b) => remainingOf(b) - remainingOf(a));
|
|
1588
|
+
const rankOf = new Map(order.map((job, rank) => [job, rank]));
|
|
1589
|
+
const checks = [];
|
|
1590
|
+
const waiters = [];
|
|
1591
|
+
const runningCopies = new Map();
|
|
1592
|
+
let over = false;
|
|
1593
|
+
let testTimeoutMs = BASELINE_TEST_TIMEOUT_MS;
|
|
1594
|
+
const hookMs = hookTimeoutOf(vitest);
|
|
1595
|
+
// A file whose own slot has not started yet has no known class: only
|
|
1596
|
+
// its own slots run its work.
|
|
1597
|
+
const classOfFile = (file) => classOf.get(file) ?? `file:${file}`;
|
|
1598
|
+
// A mutant's next file: the likeliest killer of those whose baseline
|
|
1599
|
+
// is known (where a baseline is still running, the mutant waits).
|
|
1600
|
+
const nextOf = (job) => {
|
|
1601
|
+
let best;
|
|
1602
|
+
for (const group of job.chain) {
|
|
1603
|
+
if (!baselineReady(group) || unusable(group))
|
|
1604
|
+
continue;
|
|
1605
|
+
if (!best || scoreC(group) > scoreC(best))
|
|
1606
|
+
best = group;
|
|
1607
|
+
}
|
|
1608
|
+
return best;
|
|
1609
|
+
};
|
|
1610
|
+
const finishC = (job, verdict) => {
|
|
1611
|
+
if (job.done)
|
|
1612
|
+
return;
|
|
1613
|
+
// How many files each verdict took, for the pass summary.
|
|
1614
|
+
const counts = (profile.filesByStatus[verdict.status] ??= { mutants: 0, files: 0 });
|
|
1615
|
+
counts.mutants += 1;
|
|
1616
|
+
counts.files += job.copies ?? 0;
|
|
1617
|
+
finish(job, verdict);
|
|
1618
|
+
};
|
|
1619
|
+
// A mutant with nothing left to run is decided.
|
|
1620
|
+
const conclude = (job) => {
|
|
1621
|
+
if (!idle(job))
|
|
1622
|
+
return;
|
|
1623
|
+
job.chain = job.chain.filter((group) => {
|
|
1624
|
+
if (!unusable(group))
|
|
1625
|
+
return true;
|
|
1626
|
+
job.unrun = group.file;
|
|
1627
|
+
return false;
|
|
1628
|
+
});
|
|
1629
|
+
if (job.chain.length)
|
|
1630
|
+
return;
|
|
1631
|
+
if (job.unrun)
|
|
1632
|
+
finishC(job, { status: "error", reason: `${job.unrun} does not finish without a mutant, so it could not test this one` });
|
|
1633
|
+
else
|
|
1634
|
+
finishC(job, { status: "survived" });
|
|
1635
|
+
};
|
|
1636
|
+
const claimOf = (job, group) => {
|
|
1637
|
+
const whole = shapeOf(group) === "whole";
|
|
1638
|
+
const failedBefore = baseOf(group.file)[shapeOf(group)].failed ?? new Set();
|
|
1639
|
+
const chosen = whole ? [] : group.tests.filter((id) => !failedBefore.has(id));
|
|
1640
|
+
const timed = whole ? testsOf.get(group.file) ?? [] : chosen;
|
|
1641
|
+
const budget = Math.max(...timed.map((id) => Math.max(durationOf.get(id) ?? 1_000, baselineTestMs.get(id) ?? 0)), 1_000);
|
|
1642
|
+
const testTimeout = Math.ceil((budget * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * 2);
|
|
1643
|
+
// A whole copy goes on past a test that fails without the mutant
|
|
1644
|
+
// too, as its file's whole baseline did.
|
|
1645
|
+
const continueAfter = whole ? [...failedBefore] : undefined;
|
|
1646
|
+
return { mutant: { file: job.mutant.file, index: job.mutant.index }, tests: chosen, wholeFile: whole, continueAfter, unknownBaseline: false, hitLimit: Math.max(HIT_LIMIT_FLOOR, 1_000_000), testTimeout };
|
|
1647
|
+
};
|
|
1648
|
+
// The work a slot of class `cls` takes now, if any.
|
|
1649
|
+
const take = (cls, slotFile) => {
|
|
1650
|
+
const own = base.get(slotFile);
|
|
1651
|
+
for (const shape of ["union", "whole"]) {
|
|
1652
|
+
if (own?.[shape].state === "waiting")
|
|
1653
|
+
return baselineItem(slotFile, shape);
|
|
1654
|
+
}
|
|
1655
|
+
for (const [file, entry] of base) {
|
|
1656
|
+
for (const shape of ["union", "whole"]) {
|
|
1657
|
+
if (entry[shape].state === "waiting" && classOf.get(file) === cls)
|
|
1658
|
+
return baselineItem(file, shape);
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
for (const check of checks) {
|
|
1662
|
+
if (!check.result && !check.running && classOfFile(check.file) === cls) {
|
|
1663
|
+
check.running = true;
|
|
1664
|
+
const budget = Math.max(...check.claim.tests.map((id) => durationOf.get(id) ?? 1_000), 1_000);
|
|
1665
|
+
return { check, file: check.file, claim: { ...check.claim, testTimeout: Math.ceil(budget * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) } };
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
const start = (job, group) => {
|
|
1669
|
+
job.chain.splice(job.chain.indexOf(group), 1);
|
|
1670
|
+
job.open += 1;
|
|
1671
|
+
job.copies = (job.copies ?? 0) + 1;
|
|
1672
|
+
if (!job.started)
|
|
1673
|
+
job.started = Date.now();
|
|
1674
|
+
return { job, group, file: group.file, claim: claimOf(job, group) };
|
|
1675
|
+
};
|
|
1676
|
+
for (const job of order) {
|
|
1677
|
+
if (!idle(job))
|
|
1678
|
+
continue;
|
|
1679
|
+
const group = nextOf(job);
|
|
1680
|
+
if (group && classOfFile(group.file) === cls)
|
|
1681
|
+
return start(job, group);
|
|
1682
|
+
}
|
|
1683
|
+
// No mutant is waiting for its next file: rather than leave the
|
|
1684
|
+
// worker idle, a mutant whose copy is still running takes its
|
|
1685
|
+
// next file beside it (the most work left first). Its verdict
|
|
1686
|
+
// is the same either way; a copy its mutant's kill makes moot is
|
|
1687
|
+
// stopped.
|
|
1688
|
+
for (const job of order) {
|
|
1689
|
+
if (job.done || job.confirmingKills || !job.open)
|
|
1690
|
+
continue;
|
|
1691
|
+
const group = nextOf(job);
|
|
1692
|
+
if (group && classOfFile(group.file) === cls) {
|
|
1693
|
+
profile.besideCopies += 1;
|
|
1694
|
+
return start(job, group);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
return undefined;
|
|
1698
|
+
};
|
|
1699
|
+
const readyElsewhere = (cls) => {
|
|
1700
|
+
for (const [file, entry] of base)
|
|
1701
|
+
if ((entry.union.state === "waiting" || entry.whole.state === "waiting") && classOfFile(file) !== cls)
|
|
1702
|
+
return true;
|
|
1703
|
+
if (checks.some((check) => !check.result && !check.running && classOfFile(check.file) !== cls))
|
|
1704
|
+
return true;
|
|
1705
|
+
return order.some((job) => idle(job) && nextOf(job) && classOfFile(nextOf(job).file) !== cls);
|
|
1706
|
+
};
|
|
1707
|
+
const assign = (item) => {
|
|
1708
|
+
const key = fileKeyOf.get(item.file) ?? keyOf(item.file);
|
|
1709
|
+
fileKeyOf.set(item.file, key);
|
|
1710
|
+
const index = nextIndex.get(key) ?? 0;
|
|
1711
|
+
nextIndex.set(key, index + 1);
|
|
1712
|
+
if (!index)
|
|
1713
|
+
mkdirSync(`${directory}/${key}`, { recursive: true });
|
|
1714
|
+
writeFileSync(`${directory}/${key}/${index}.json`, JSON.stringify(item.claim));
|
|
1715
|
+
testTimeoutMs = Math.max(testTimeoutMs, item.claim.testTimeout);
|
|
1716
|
+
if (item.job)
|
|
1717
|
+
profile.mutantCopies += 1;
|
|
1718
|
+
else if (item.check)
|
|
1719
|
+
profile.checkCopies += 1;
|
|
1720
|
+
else
|
|
1721
|
+
profile.baselineCopies += 1;
|
|
1722
|
+
runningCopies.set(`${key}/${index}`, { item, out: `${directory}/${key}/${index}.out`, records: -1, lastReport: Date.now() });
|
|
1723
|
+
return { index, filepath: `${root}/${item.file}` };
|
|
1724
|
+
};
|
|
1725
|
+
const dispatch = () => {
|
|
1726
|
+
for (let at = 0; at < waiters.length;) {
|
|
1727
|
+
const waiter = waiters[at];
|
|
1728
|
+
// A slot Vitest stopped meanwhile takes nothing.
|
|
1729
|
+
if (waiter.waiting && !waiter.waiting()) {
|
|
1730
|
+
waiters.splice(at, 1);
|
|
1731
|
+
waiter.resolve({ nothingToRun: true });
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
const item = over ? undefined : take(waiter.cls, waiter.slotFile);
|
|
1735
|
+
if (item) {
|
|
1736
|
+
waiters.splice(at, 1);
|
|
1737
|
+
waiter.resolve(assign(item));
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
// Nothing of its class to run: it lets the slot go where
|
|
1741
|
+
// other work is ready, or nothing runs that could make some.
|
|
1742
|
+
if (over || runningCopies.size === 0 || readyElsewhere(waiter.cls)) {
|
|
1743
|
+
waiters.splice(at, 1);
|
|
1744
|
+
waiter.resolve({ nothingToRun: true });
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
at += 1;
|
|
1748
|
+
}
|
|
1749
|
+
};
|
|
1750
|
+
claimRun = (filepath, start, waiting) => {
|
|
1751
|
+
if (over)
|
|
1752
|
+
return { nothingToRun: true };
|
|
1753
|
+
return new Promise((resolve) => {
|
|
1754
|
+
waiters.push({ cls: classKeyOf(start), slotFile: toRelative(root, String(filepath)), resolve, waiting });
|
|
1755
|
+
dispatch();
|
|
1756
|
+
});
|
|
1757
|
+
};
|
|
1758
|
+
// What a copy's end says.
|
|
1759
|
+
const kill = (job, group, claim, outcome, evidence, verdict) => {
|
|
1760
|
+
fileKills.set(group.file, (fileKills.get(group.file) ?? 0) + 1);
|
|
1761
|
+
const shape = claim.wholeFile ? "whole" : "union";
|
|
1762
|
+
const entry = baseOf(group.file)[shape];
|
|
1763
|
+
let sure;
|
|
1764
|
+
if (claim.wholeFile)
|
|
1765
|
+
sure = entry.state === "known" && entry.done;
|
|
1766
|
+
else if (evidence.test) {
|
|
1767
|
+
const at = entry.order?.indexOf(evidence.test) ?? -1;
|
|
1768
|
+
sure = at >= 0 && entry.order.slice(0, at).every((id) => claim.tests.includes(id));
|
|
1769
|
+
}
|
|
1770
|
+
else
|
|
1771
|
+
sure = entry.order?.length === claim.tests.length && entry.order.every((id) => claim.tests.includes(id));
|
|
1772
|
+
if (sure) {
|
|
1773
|
+
finishC(job, verdict);
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
// The copy left out tests its file's baseline ran before the
|
|
1777
|
+
// failure: they run again with no mutant, up to the failing one.
|
|
1778
|
+
// A copy of the whole file left out none: its file's whole
|
|
1779
|
+
// baseline, run once for every such kill, says whether the test
|
|
1780
|
+
// fails without the mutant too.
|
|
1781
|
+
const ran = outcome.tests.map((test) => test.test);
|
|
1782
|
+
const chosen = claim.wholeFile ? [] : evidence.test ? ran.slice(0, ran.indexOf(evidence.test) + 1) : claim.tests;
|
|
1783
|
+
const key = confirmationKey(group.file, chosen, claim.wholeFile);
|
|
1784
|
+
let check = checks.find((candidate) => candidate.key === key);
|
|
1785
|
+
if (!check) {
|
|
1786
|
+
check = { key, file: group.file, claim: { mutant: null, tests: chosen, wholeFile: claim.wholeFile }, tries: 0, result: undefined, baseline: claim.wholeFile };
|
|
1787
|
+
checks.push(check);
|
|
1788
|
+
confirmations.set(key, check);
|
|
1789
|
+
}
|
|
1790
|
+
job.confirmingKills += 1;
|
|
1791
|
+
const waiting = { job, group, evidence, verdict, whole: claim.wholeFile };
|
|
1792
|
+
// Confirmed already, for another mutant's kill.
|
|
1793
|
+
if (check.result)
|
|
1794
|
+
settleKill(check.result, waiting);
|
|
1795
|
+
else
|
|
1796
|
+
(check.jobs ??= []).push(waiting);
|
|
1797
|
+
};
|
|
1798
|
+
const judgeC = ({ job, group, claim }, outcome) => {
|
|
1799
|
+
job.open -= 1;
|
|
1800
|
+
if (job.done)
|
|
1801
|
+
return;
|
|
1802
|
+
if (!outcome.claimed) {
|
|
1803
|
+
job.chain.unshift(group);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
// The file's copies run whole since: this copy says nothing.
|
|
1807
|
+
if (!claim.wholeFile && forceWhole.has(group.file)) {
|
|
1808
|
+
job.chain.unshift(group);
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
job.ran += outcome.tests.length;
|
|
1812
|
+
fileRuns.set(group.file, (fileRuns.get(group.file) ?? 0) + 1);
|
|
1813
|
+
const entry = baseOf(group.file)[claim.wholeFile ? "whole" : "union"];
|
|
1814
|
+
const failed = outcome.tests.find((test) => test.failed && !entry.failed?.has(test.test));
|
|
1815
|
+
const outside = entry.outside ? undefined : outcome.outside[0];
|
|
1816
|
+
// Up to the mutant's first evaluation a copy runs exactly as its
|
|
1817
|
+
// file does without it: a test that failed before then (its
|
|
1818
|
+
// switch never taken in this process) failed for another reason,
|
|
1819
|
+
// such as a test that depends on timing. The copy runs again,
|
|
1820
|
+
// once; a failure that repeats counts (the mutant may have run in
|
|
1821
|
+
// a process the copy started).
|
|
1822
|
+
const unevaluated = (evidence) => evidence?.hits === 0;
|
|
1823
|
+
if (!group.rerunUnevaluated && (unevaluated(failed) || (!failed && unevaluated(outside)))) {
|
|
1824
|
+
group.rerunUnevaluated = true;
|
|
1825
|
+
profile.unevaluatedReruns += 1;
|
|
1826
|
+
job.ran -= outcome.tests.length;
|
|
1827
|
+
job.chain.unshift(group);
|
|
1828
|
+
conclude(job);
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
if (failed)
|
|
1832
|
+
kill(job, group, claim, outcome, { test: failed.test }, { status: failed.timeout ? "timeout" : "killed", killedBy: failed.test });
|
|
1833
|
+
else if (outside)
|
|
1834
|
+
kill(job, group, claim, outcome, { outside: true }, outside.timeout
|
|
1835
|
+
? { status: "timeout", reason: "outside any test: the mutant's evaluations passed its limit" }
|
|
1836
|
+
: { status: "killed", killedBy: group.file, reason: `an error outside any test: ${outside.message}` });
|
|
1837
|
+
else if (outcome.hung)
|
|
1838
|
+
kill(job, group, claim, outcome, { unfinished: true }, { status: "timeout", killedBy: group.file, reason: "its test file stopped before its end, past its limit" });
|
|
1839
|
+
else if (!outcome.done)
|
|
1840
|
+
kill(job, group, claim, outcome, { unfinished: true }, { status: "killed", killedBy: group.file, reason: "the test file did not finish" });
|
|
1841
|
+
else if (ranNone(claim, outcome, entry, group.file))
|
|
1842
|
+
finishC(job, { status: "error", reason: ranNone(claim, outcome, entry, group.file) });
|
|
1843
|
+
else
|
|
1844
|
+
conclude(job);
|
|
1845
|
+
};
|
|
1846
|
+
// A kill once the tests up to it have run with no mutant: it stands
|
|
1847
|
+
// unless they fail that way too, which a test the copy left out
|
|
1848
|
+
// caused; the mutant then runs the file whole.
|
|
1849
|
+
const settleKill = (result, { job, group, evidence, verdict, whole }) => {
|
|
1850
|
+
job.confirmingKills -= 1;
|
|
1851
|
+
if (job.done)
|
|
1852
|
+
return;
|
|
1853
|
+
// The whole file does not finish without the mutant: it cannot
|
|
1854
|
+
// test it.
|
|
1855
|
+
if (whole && !result.done) {
|
|
1856
|
+
job.unrun = group.file;
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
const alsoWithout = evidence.test ? result.failed.has(evidence.test)
|
|
1860
|
+
: evidence.outside ? result.outside
|
|
1861
|
+
: !result.done;
|
|
1862
|
+
if (!alsoWithout) {
|
|
1863
|
+
finishC(job, verdict);
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1866
|
+
overturned += 1;
|
|
1867
|
+
// A copy of the whole file runs again, past what fails without
|
|
1868
|
+
// the mutant; a copy of some tests runs the file whole, once its
|
|
1869
|
+
// whole baseline is known.
|
|
1870
|
+
if (!whole)
|
|
1871
|
+
need(group.file, "whole");
|
|
1872
|
+
job.chain.unshift(whole ? group : { file: group.file, tests: [], cost: group.cost, whole: true });
|
|
1873
|
+
};
|
|
1874
|
+
const recordCheck = (check, outcome) => {
|
|
1875
|
+
check.running = false;
|
|
1876
|
+
check.tries += 1;
|
|
1877
|
+
if (!outcome.claimed && check.tries < 3)
|
|
1878
|
+
return;
|
|
1879
|
+
check.result = {
|
|
1880
|
+
failed: new Set(outcome.tests.filter((test) => test.failed).map((test) => test.test)),
|
|
1881
|
+
outside: outcome.outside.length > 0,
|
|
1882
|
+
done: outcome.done || !outcome.claimed,
|
|
1883
|
+
};
|
|
1884
|
+
// A run of the whole file with no mutant is its whole baseline.
|
|
1885
|
+
if (check.baseline && outcome.claimed)
|
|
1886
|
+
recordShape(check.file, "whole", outcome);
|
|
1887
|
+
for (const waiting of check.jobs ?? [])
|
|
1888
|
+
settleKill(check.result, waiting);
|
|
1889
|
+
check.jobs = [];
|
|
1890
|
+
};
|
|
1891
|
+
const ended = (entry, outcome) => {
|
|
1892
|
+
const { item } = entry;
|
|
1893
|
+
if (outcome.claimedAt !== undefined) {
|
|
1894
|
+
profile.copies += 1;
|
|
1895
|
+
profile.testsRun += outcome.tests.length;
|
|
1896
|
+
profile.startMs += startOf(outcome);
|
|
1897
|
+
if (outcome.doneAt)
|
|
1898
|
+
profile.copyMs += outcome.doneAt - outcome.claimedAt;
|
|
1899
|
+
// A baseline's share of the workers' time, start included.
|
|
1900
|
+
if (item.baseline)
|
|
1901
|
+
profile.baselineMs += startOf(outcome) + (outcome.doneAt ? outcome.doneAt - outcome.claimedAt : 0);
|
|
1902
|
+
if (outcome.hung)
|
|
1903
|
+
profile.hungCopies += 1;
|
|
1904
|
+
}
|
|
1905
|
+
if (item.baseline)
|
|
1906
|
+
recordShape(item.baseline.file, item.baseline.shape, outcome);
|
|
1907
|
+
else if (item.check)
|
|
1908
|
+
recordCheck(item.check, outcome);
|
|
1909
|
+
else
|
|
1910
|
+
judgeC(item, outcome);
|
|
1911
|
+
if (item.job)
|
|
1912
|
+
conclude(item.job);
|
|
1913
|
+
};
|
|
1914
|
+
// The copies going, looked at often: a free slot waits on them.
|
|
1915
|
+
const limitFor = (item) => {
|
|
1916
|
+
const entry = item.job ? baseOf(item.file)[item.claim.wholeFile ? "whole" : "union"] : undefined;
|
|
1917
|
+
// A whole copy before its file's whole baseline: the file as the
|
|
1918
|
+
// measured run ran it.
|
|
1919
|
+
const copyMs = entry?.copyMs ?? (item.job && item.claim.wholeFile
|
|
1920
|
+
? overheadOf(item.file) + (testsOf.get(item.file) ?? []).reduce((sum, id) => sum + testMsOf(id), 0)
|
|
1921
|
+
: undefined);
|
|
1922
|
+
if (!copyMs)
|
|
1923
|
+
return undefined;
|
|
1924
|
+
return (copyMs * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * 2 + Math.max(item.claim.testTimeout, hookMs);
|
|
1925
|
+
};
|
|
1926
|
+
const look = () => {
|
|
1927
|
+
const now = Date.now();
|
|
1928
|
+
for (const [name, entry] of [...runningCopies]) {
|
|
1929
|
+
let outcome = readOutcome(entry.out);
|
|
1930
|
+
const gone = !outcome.done && outcome.pid && outcome.pid !== process.pid && !alive(outcome.pid);
|
|
1931
|
+
if (gone)
|
|
1932
|
+
outcome = readOutcome(entry.out);
|
|
1933
|
+
if (outcome.records !== entry.records) {
|
|
1934
|
+
entry.records = outcome.records;
|
|
1935
|
+
entry.lastReport = now;
|
|
1936
|
+
}
|
|
1937
|
+
// A copy whose worker lost its channel to Vitest (a mutant that
|
|
1938
|
+
// disconnects it) did not finish its file, whatever it wrote:
|
|
1939
|
+
// Vitest never hears the file end.
|
|
1940
|
+
let end = outcome.done || gone ? outcome : undefined;
|
|
1941
|
+
if (end && outcome.channelLost)
|
|
1942
|
+
end = { ...outcome, done: false };
|
|
1943
|
+
// Its mutant was decided by another copy meanwhile.
|
|
1944
|
+
if (!end && entry.item.job?.done && outcome.pid && ownWorker(outcome.pid)) {
|
|
1945
|
+
try {
|
|
1946
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
1947
|
+
}
|
|
1948
|
+
catch {
|
|
1949
|
+
// It ended meanwhile.
|
|
1950
|
+
}
|
|
1951
|
+
end = { ...outcome, done: true, doneAt: now };
|
|
1952
|
+
}
|
|
1953
|
+
// Decided by a failed test (its baseline known): stopped now.
|
|
1954
|
+
if (!end && entry.item.job && outcome.tests.some((test) => test.failed && !baseOf(entry.item.file)[entry.item.claim.wholeFile ? "whole" : "union"].failed?.has(test.test)) && ownWorker(outcome.pid)) {
|
|
1955
|
+
try {
|
|
1956
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
1957
|
+
}
|
|
1958
|
+
catch {
|
|
1959
|
+
// It ended meanwhile.
|
|
1960
|
+
}
|
|
1961
|
+
end = { ...outcome, done: true, doneAt: now };
|
|
1962
|
+
profile.settledCopies += 1;
|
|
1963
|
+
}
|
|
1964
|
+
const limit = limitFor(entry.item);
|
|
1965
|
+
if (!end && outcome.claimedAt !== undefined && limit !== undefined && now - outcome.claimedAt > limit && ownWorker(outcome.pid)) {
|
|
1966
|
+
try {
|
|
1967
|
+
process.kill(outcome.pid, "SIGKILL");
|
|
1968
|
+
}
|
|
1969
|
+
catch {
|
|
1970
|
+
// It ended meanwhile.
|
|
1971
|
+
}
|
|
1972
|
+
end = { ...outcome, hung: true };
|
|
1973
|
+
profile.killedCopies += 1;
|
|
1974
|
+
}
|
|
1975
|
+
if (end) {
|
|
1976
|
+
runningCopies.delete(name);
|
|
1977
|
+
ended(entry, end);
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
for (const job of pending)
|
|
1981
|
+
conclude(job);
|
|
1982
|
+
if (!over && pending.every((job) => job.done) && checks.every((check) => check.result) && runningCopies.size === 0)
|
|
1983
|
+
over = true;
|
|
1984
|
+
dispatch();
|
|
1985
|
+
};
|
|
1986
|
+
// Slots: each file's own first (its baseline, the longest first),
|
|
1987
|
+
// then enough for every copy the pass could run, the files in turn.
|
|
1988
|
+
const files = [...base.keys()].filter((file) => specOf.has(file));
|
|
1989
|
+
const firstEstimate = (file) => (testsOf.get(file) ?? []).reduce((sum, id) => sum + (durationOf.get(id) ?? 1_000), 0);
|
|
1990
|
+
files.sort((x, y) => firstEstimate(y) - firstEstimate(x));
|
|
1991
|
+
const bound = pending.reduce((sum, job) => sum + job.files.length * 3 + 4, 0) + files.length * 2 + workers;
|
|
1992
|
+
const sizeOf = new Map(files.map((file) => {
|
|
1993
|
+
try {
|
|
1994
|
+
return [file, statSync(`${root}/${file}`).size];
|
|
1995
|
+
}
|
|
1996
|
+
catch {
|
|
1997
|
+
return [file, 0];
|
|
1998
|
+
}
|
|
1999
|
+
}));
|
|
2000
|
+
const slots = files.map((file) => specOf.get(file));
|
|
2001
|
+
let bytes = 0;
|
|
2002
|
+
for (let at = 0; slots.length < bound && files.length; at++) {
|
|
2003
|
+
const file = files[at % files.length];
|
|
2004
|
+
bytes += sizeOf.get(file);
|
|
2005
|
+
if (slots.length > files.length && (bytes > RUN_BYTES || slots.length >= files.length + RUN_SLOTS))
|
|
2006
|
+
break;
|
|
2007
|
+
slots.push(specOf.get(file));
|
|
2008
|
+
}
|
|
2009
|
+
setTestTimeout(vitest, Math.max(testTimeoutMs, ...pending.flatMap((job) => job.files.map((group) => claimOf(job, group).testTimeout))));
|
|
2010
|
+
// A run's slots are bounded, and a slot a waiting copy gives
|
|
2011
|
+
// up uses one, so a run can run out of slots before the pass is over:
|
|
2012
|
+
// another run of the same slots goes on where it stopped, for as
|
|
2013
|
+
// long as runs make progress, within the slots the pass could need.
|
|
2014
|
+
let offered = 0;
|
|
2015
|
+
for (let runs = 0; !over && slots.length && offered < bound * 2; runs++) {
|
|
2016
|
+
const decidedBefore = pending.filter((job) => job.done).length;
|
|
2017
|
+
const copiesBefore = profile.copies;
|
|
2018
|
+
offered += slots.length;
|
|
2019
|
+
const runStarted = Date.now();
|
|
2020
|
+
let settledRun;
|
|
2021
|
+
const ran = runFiles(slots, false).then((result) => {
|
|
2022
|
+
settledRun = { result };
|
|
2023
|
+
}, (error) => {
|
|
2024
|
+
settledRun = { error };
|
|
2025
|
+
});
|
|
2026
|
+
let cancelled = false;
|
|
2027
|
+
while (!settledRun) {
|
|
2028
|
+
await Promise.race([ran, pause(CONTINUOUS_LOOK_MS)]);
|
|
2029
|
+
look();
|
|
2030
|
+
if (over && !cancelled) {
|
|
2031
|
+
cancelled = true;
|
|
2032
|
+
dispatch();
|
|
2033
|
+
try {
|
|
2034
|
+
vitest.cancelCurrentRun?.("supercov: the strong pass is over")?.catch?.(() => { });
|
|
2035
|
+
}
|
|
2036
|
+
catch {
|
|
2037
|
+
// Nothing to cancel.
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
look();
|
|
2042
|
+
if (settledRun.result)
|
|
2043
|
+
last = settledRun.result;
|
|
2044
|
+
profile.wallMs += Date.now() - runStarted;
|
|
2045
|
+
profile.continuousRuns = runs + 1;
|
|
2046
|
+
if (!over && runs > 0 && pending.filter((job) => job.done).length === decidedBefore && profile.copies === copiesBefore)
|
|
2047
|
+
break;
|
|
2048
|
+
}
|
|
2049
|
+
claimRun = undefined;
|
|
2050
|
+
observeRun = undefined;
|
|
2051
|
+
// Whatever the run left undecided (its slots ran out): an error,
|
|
2052
|
+
// which the next `mutants test` runs again.
|
|
2053
|
+
for (const job of pending) {
|
|
2054
|
+
if (job.done)
|
|
2055
|
+
continue;
|
|
2056
|
+
// What it was waiting for, for the pass summary.
|
|
2057
|
+
if ((profile.left ??= []).length < 20)
|
|
2058
|
+
profile.left.push({
|
|
2059
|
+
id: job.mutant.id,
|
|
2060
|
+
open: job.open,
|
|
2061
|
+
confirming: job.confirmingKills,
|
|
2062
|
+
chain: job.chain.map((group) => ({ file: group.file, shape: shapeOf(group), baseline: baseOf(group.file)[shapeOf(group)].state, class: classOf.has(group.file) })),
|
|
2063
|
+
checks: checks.filter((check) => check.jobs?.some((waiting) => waiting.job === job)).map((check) => ({ file: check.file, running: check.running, tries: check.tries })),
|
|
2064
|
+
});
|
|
2065
|
+
finishC(job, { status: "error", reason: "the pass ended before its files ran" });
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
const continuous = spawnerInstalled && !oneAtATime && Number(String(vitest.version ?? "0").split(".")[0]) >= 4 &&
|
|
2069
|
+
process.env["SUPERCOV_STRONG_STAGES"] !== "1";
|
|
2070
|
+
if (continuous) {
|
|
2071
|
+
await runContinuous();
|
|
2072
|
+
pending.length = 0;
|
|
2073
|
+
}
|
|
2074
|
+
while (pending.length && !stalled) {
|
|
2075
|
+
// A file whose baseline did not finish runs no mutant: a mutant it
|
|
2076
|
+
// was to test cannot be called a survivor.
|
|
2077
|
+
for (const job of pending) {
|
|
2078
|
+
for (const group of job.waiting.filter((group) => baselineFailed.has(`${group.file}#file`)))
|
|
2079
|
+
job.unrun = group.file;
|
|
2080
|
+
job.waiting = job.waiting.filter((group) => !baselineFailed.has(`${group.file}#file`));
|
|
2081
|
+
}
|
|
2082
|
+
// A stage whose work would not keep every worker busy for twice its
|
|
2083
|
+
// longest copy ends waiting on that copy: each mutant in it takes its
|
|
2084
|
+
// next batch of later files beside it, until it would.
|
|
2085
|
+
while (!oneAtATime) {
|
|
2086
|
+
const files = new Set(pending.flatMap((job) => job.waiting.map((group) => group.file)));
|
|
2087
|
+
const estimates = [
|
|
2088
|
+
...pending.flatMap((job) => job.waiting.map((group) => estimateOf(group) + startCost())),
|
|
2089
|
+
...[...baselines.values()].filter((entry) => entry.state === "waiting" && files.has(entry.file)).map((entry) => baselineEstimateOf(entry) + startCost()),
|
|
2090
|
+
];
|
|
2091
|
+
const work = estimates.reduce((sum, estimate) => sum + estimate, 0);
|
|
2092
|
+
const growing = pending.filter((job) => job.waiting.length && job.later.length);
|
|
2093
|
+
if (!estimates.length || !growing.length || work >= workers * Math.max(...estimates) * 2)
|
|
2094
|
+
break;
|
|
2095
|
+
for (const job of growing)
|
|
2096
|
+
job.waiting.push(...nextBatch(job));
|
|
2097
|
+
}
|
|
2098
|
+
// Every copy the pass can run now: the baselines not known yet
|
|
2099
|
+
// (where a mutant waits on the file), the confirmations not run
|
|
2100
|
+
// yet, and each mutant's files waiting.
|
|
2101
|
+
const needed = new Set(pending.flatMap((job) => job.waiting.map((group) => group.file)));
|
|
2102
|
+
const work = [];
|
|
2103
|
+
for (const entry of baselines.values()) {
|
|
2104
|
+
if (entry.state === "waiting" && needed.has(entry.file))
|
|
2105
|
+
work.push({ baseline: entry, rank: -1 });
|
|
2106
|
+
}
|
|
2107
|
+
for (const [key, check] of confirmations) {
|
|
2108
|
+
if (!check.result && !check.running)
|
|
2109
|
+
work.push({ check, key, rank: 0 });
|
|
2110
|
+
}
|
|
2111
|
+
for (const job of pending) {
|
|
2112
|
+
job.waiting.forEach((group, rank) => work.push({ job, group, rank }));
|
|
2113
|
+
}
|
|
2114
|
+
// Where the reporter gives copies their assignments (Supercov's
|
|
2115
|
+
// spawner), each mutant in the stage also takes its next batch of
|
|
2116
|
+
// files, held back (`gated`) until its copies before them end: a
|
|
2117
|
+
// mutant they leave alive goes on in the same stage, in what would
|
|
2118
|
+
// be the stage's idle end, instead of waiting for the next stage.
|
|
2119
|
+
// One its other copies killed skips them, and costs no process.
|
|
2120
|
+
if (mainClaims && !oneAtATime) {
|
|
2121
|
+
for (const job of pending) {
|
|
2122
|
+
if (!job.waiting.length || !job.later.length || job.confirming?.length)
|
|
2123
|
+
continue;
|
|
2124
|
+
nextBatch(job).forEach((group, rank) => work.push({ job, group, rank: rank + job.waiting.length, gated: true }));
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
// Where files are not isolated, one copy at a time: its file's
|
|
2128
|
+
// baseline first.
|
|
2129
|
+
const stage = oneAtATime ? work.slice(0, 1) : work;
|
|
2130
|
+
const assignments = stage.map((item) => {
|
|
2131
|
+
if (item.baseline) {
|
|
2132
|
+
const entry = item.baseline;
|
|
2133
|
+
entry.state = "running";
|
|
2134
|
+
const chosen = [...entry.tests];
|
|
2135
|
+
const estimate = baselineEstimateOf(entry);
|
|
2136
|
+
return { ...item, file: entry.file, estimate, claim: { mutant: null, tests: chosen, wholeFile: entry.whole, testTimeout: BASELINE_TEST_TIMEOUT_MS } };
|
|
2137
|
+
}
|
|
2138
|
+
if (item.check) {
|
|
2139
|
+
const { check } = item;
|
|
2140
|
+
check.running = true;
|
|
2141
|
+
const chosen = check.claim.tests;
|
|
2142
|
+
const budget = Math.max(...chosen.map((id) => durationOf.get(id) ?? 1_000), 1_000);
|
|
2143
|
+
const work = chosen.reduce((sum, id) => sum + (durationOf.get(id) ?? 1_000), 0);
|
|
2144
|
+
return { ...item, file: check.file, estimate: work, claim: { ...check.claim, testTimeout: Math.ceil(budget * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) } };
|
|
2145
|
+
}
|
|
2146
|
+
const { job, group } = item;
|
|
2147
|
+
if (!item.gated)
|
|
2148
|
+
job.waiting.splice(job.waiting.indexOf(group), 1);
|
|
2149
|
+
job.open += 1;
|
|
2150
|
+
if (!job.started)
|
|
2151
|
+
job.started = Date.now();
|
|
2152
|
+
const chosen = group.tests.filter((id) => !baselineFailed.has(id));
|
|
2153
|
+
// Its slowest test, as measured or as its baseline ran it (a copy
|
|
2154
|
+
// that runs its file whole, the file's slowest).
|
|
2155
|
+
const timed = group.whole ? testsOf.get(group.file) ?? [] : chosen;
|
|
2156
|
+
const budget = Math.max(...timed.map((id) => Math.max(durationOf.get(id) ?? 1_000, baselineTestMs.get(id) ?? 0)), 1_000);
|
|
2157
|
+
const testTimeout = Math.ceil((budget * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * 2);
|
|
2158
|
+
// One stopped at a stage's end likely hangs to its limit: it goes
|
|
2159
|
+
// first, so that the stage's other work runs beside it.
|
|
2160
|
+
const estimate = group.deferredOnce
|
|
2161
|
+
? Math.max(estimateOf(group), limitOf({ group }) ?? testTimeout)
|
|
2162
|
+
: estimateOf(group);
|
|
2163
|
+
return {
|
|
2164
|
+
...item,
|
|
2165
|
+
file: group.file,
|
|
2166
|
+
estimate,
|
|
2167
|
+
claim: {
|
|
2168
|
+
mutant: { file: job.mutant.file, index: job.mutant.index },
|
|
2169
|
+
tests: chosen,
|
|
2170
|
+
wholeFile: group.whole,
|
|
2171
|
+
// Its file's baseline runs in the same stage.
|
|
2172
|
+
unknownBaseline: !known(group.file),
|
|
2173
|
+
hitLimit: Math.max(HIT_LIMIT_FLOOR, 1_000_000),
|
|
2174
|
+
testTimeout,
|
|
2175
|
+
},
|
|
2176
|
+
};
|
|
2177
|
+
});
|
|
2178
|
+
if (!assignments.length) {
|
|
2179
|
+
for (const job of pending)
|
|
2180
|
+
finish(job, { status: "error", reason: "could not be scheduled" });
|
|
2181
|
+
break;
|
|
2182
|
+
}
|
|
2183
|
+
// Baselines first. Then a mutant's next file before its files after
|
|
2184
|
+
// it (a mutant's files wait cheapest first), so that most mutants
|
|
2185
|
+
// are decided before their later copies start, and those skip; and
|
|
2186
|
+
// long copies early, so that the stage does not end waiting on a
|
|
2187
|
+
// long copy that started last: by the copy's estimate over its rank.
|
|
2188
|
+
const priority = (assignment) => assignment.estimate / (Math.max(assignment.rank, 0) + 1);
|
|
2189
|
+
assignments.sort((a, b) => Number(b.rank < 0) - Number(a.rank < 0) || Number(Boolean(a.gated)) - Number(Boolean(b.gated)) || priority(b) - priority(a));
|
|
2190
|
+
profile.checkCopies += assignments.filter((assignment) => assignment.check).length;
|
|
2191
|
+
for (const assignment of assignments) {
|
|
2192
|
+
if (assignment.job)
|
|
2193
|
+
assignment.job.positions = [];
|
|
2194
|
+
}
|
|
2195
|
+
assignments.forEach((assignment, at) => assignment.job?.positions.push(at));
|
|
2196
|
+
// A mutant's copy that ended with a failed test, its file's baseline
|
|
2197
|
+
// known, is judged at once (no later record changes which test
|
|
2198
|
+
// failed first), so a verdict shows while the stage runs, and its
|
|
2199
|
+
// other copies not yet started skip.
|
|
2200
|
+
// A baseline that ended is recorded at once: its file's copies beside
|
|
2201
|
+
// it are judged by it, and bounded by its time.
|
|
2202
|
+
const { outcomes, handled } = await runStage(assignments, (at, outcome) => {
|
|
2203
|
+
const assignment = assignments[at];
|
|
2204
|
+
if (assignment.baseline) {
|
|
2205
|
+
recordBaseline(assignment.baseline, outcome);
|
|
2206
|
+
return true;
|
|
2207
|
+
}
|
|
2208
|
+
if (!assignment.job || !known(assignment.file) || !failedTest(outcome))
|
|
2209
|
+
return false;
|
|
2210
|
+
judge(assignment, outcome);
|
|
2211
|
+
return true;
|
|
2212
|
+
}, limitOf, (assignment) => Math.max(assignment.estimate, limitBaseOf(assignment) ?? 0));
|
|
2213
|
+
assignments.forEach((assignment, at) => {
|
|
2214
|
+
if (!assignment.baseline)
|
|
2215
|
+
return;
|
|
2216
|
+
// An error outside any test can come after a copy's end.
|
|
2217
|
+
if (handled.has(at)) {
|
|
2218
|
+
if (outcomes[at].outside.length && known(assignment.file))
|
|
2219
|
+
baselineFailed.add(`${assignment.file}#outside`);
|
|
2220
|
+
}
|
|
2221
|
+
else
|
|
2222
|
+
recordBaseline(assignment.baseline, outcomes[at]);
|
|
2223
|
+
});
|
|
2224
|
+
assignments.forEach((assignment, at) => {
|
|
2225
|
+
if (handled.has(at) || assignment.baseline)
|
|
2226
|
+
return;
|
|
2227
|
+
if (assignment.check)
|
|
2228
|
+
record(assignment, outcomes[at]);
|
|
2229
|
+
else
|
|
2230
|
+
judge(assignment, outcomes[at]);
|
|
2231
|
+
});
|
|
2232
|
+
for (const job of pending) {
|
|
2233
|
+
if (job.confirming?.length && !job.done)
|
|
2234
|
+
settle(job);
|
|
2235
|
+
if (job.done || job.open || job.waiting.length || job.confirming?.length)
|
|
2236
|
+
continue;
|
|
2237
|
+
if (job.later.length) {
|
|
2238
|
+
job.waiting = nextBatch(job);
|
|
2239
|
+
}
|
|
2240
|
+
else if (job.unrun)
|
|
2241
|
+
finish(job, { status: "error", reason: `${job.unrun} does not finish without a mutant, so it could not test this one` });
|
|
2242
|
+
else
|
|
2243
|
+
finish(job, { status: "survived" });
|
|
2244
|
+
}
|
|
2245
|
+
for (let index = pending.length - 1; index >= 0; index--) {
|
|
2246
|
+
if (pending[index].done)
|
|
2247
|
+
pending.splice(index, 1);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
// SUPERCOV_STRONG_KEEP_STAGES=1 keeps each stage's assignments and what
|
|
2251
|
+
// every copy reported, to read where a verdict came from.
|
|
2252
|
+
if (!process.env["SUPERCOV_STRONG_KEEP_STAGES"])
|
|
2253
|
+
rmSync(stagesDirectory, { recursive: true, force: true });
|
|
2254
|
+
profile.spawnedWorkers = spawnedWorkers;
|
|
2255
|
+
const endCpu = machineCpu();
|
|
2256
|
+
if (passCpu && endCpu && endCpu.total > passCpu.total)
|
|
2257
|
+
profile.cpuBusy = Math.round((endCpu.busy - passCpu.busy) / (endCpu.total - passCpu.total) * 100) / 100;
|
|
2258
|
+
const ahead = await askStats();
|
|
2259
|
+
if (ahead)
|
|
2260
|
+
Object.assign(profile, ahead);
|
|
2261
|
+
write({ summary: true, durationMs: Date.now() - started, isolated: !oneAtATime, stalled, left: pending.filter((job) => !job.done).length, confirmations: confirmations.size, overturned, workers, stages: stageNumber, profile });
|
|
2262
|
+
if (stalled) {
|
|
2263
|
+
// A worker that will not end keeps Vitest from closing: the mutants
|
|
2264
|
+
// left run in the next pass `mutants test` starts.
|
|
2265
|
+
process.exit(0);
|
|
2266
|
+
}
|
|
2267
|
+
return last;
|
|
2268
|
+
}
|