supercov 4.29.3 → 4.29.4

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.
@@ -1,60 +1,66 @@
1
1
  // Strong mutation for Playwright (docs/design/strong-mutation.md, browser
2
2
  // tests against a server).
3
3
  //
4
- // An invocation of Playwright runs the plan, or as many of its rows as one
5
- // invocation holds (the rest run in further invocations, which the engine
6
- // starts); a harness may start several invocations at once, each with a
7
- // share of the tests, and they share the pass's files. The generated config repeats every
8
- // test (`repeatEach`) as often as the busiest test file has rows: a file's row
9
- // k is what every test of the file does in its k-th repetition -- run with
10
- // one mutant, run with none (the baseline, row 0, and canaries), or skip. A
11
- // test's repetition finds its row from its file and `repeatEachIndex`, so
12
- // nothing is claimed at run time and no two repetitions can take the same
13
- // work. The attempt's mutant goes into its scope, which reaches the app's
14
- // server with every request (header, cookies, child processes) and the page
15
- // through an init script, so the workers of one run each test their own
16
- // mutant against one server.
4
+ // One invocation of the command runs the whole plan. Every test some mutant
5
+ // needs is declared several times over as the spec loads (its copies, each
6
+ // in a describe of its own, `[supercov copy <k>]`), so that one worker runs
7
+ // them one after another with the browser it already has; a copy takes its
8
+ // work when it starts: the next mutant whose candidate it is, in a queue on
9
+ // disk that every worker and every invocation of the pass share. A mutant
10
+ // goes from candidate to candidate as copies take it, and stops at its first
11
+ // kill; nothing waits for a stage to end, and no worker restarts for a
12
+ // mutant. The first run of a test in each worker is a control, with no
13
+ // mutant: the pass's baseline the first time, and after a kill (a failed
14
+ // test gives Playwright's next test a new worker) the check that the test
15
+ // still passes without the mutant on the same server, which confirms the
16
+ // kill. A harness may start several invocations at once, each with a share
17
+ // of the tests; they share the pass's files and decide the same way.
17
18
  //
18
- // A mutant the server must start with (its code ran in work no request named,
19
- // or is a server module's top level, or ran for a request that named no test)
20
- // gets no row: it is run alone afterwards, in an invocation of its own with
21
- // SUPERCOV_ACTIVE_MUTANT set, which the engine starts for each `restart`
22
- // record the reporter writes (javascript_run.rs). So do a test that ran out
23
- // of time (again, with twice the time) and every verdict a failing canary
24
- // puts in doubt.
19
+ // The attempt's mutant goes into its scope, which reaches the app's server
20
+ // with every request (header, cookies, child processes) and the page through
21
+ // an init script. A mutant the server must start with (its code ran in work
22
+ // no request named, or is a server module's top level, or ran for a request
23
+ // that named no test) is run alone afterwards, in an invocation of its own
24
+ // with SUPERCOV_ACTIVE_MUTANT set, which the engine starts for each `restart`
25
+ // record the judge writes (javascript_run.rs). So do a test that only ran
26
+ // out of time (again, with twice the time), a kill that ran beside another
27
+ // mutant's attempt or whose control failed (one test at a time), and the
28
+ // mutants one invocation had no room for.
25
29
  //
26
30
  // This module holds what the config, the fixture (playwright.mjs) and the
27
31
  // reporter (playwrightStrongReporter.mjs) share.
28
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
32
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
29
33
  import { createHash } from "node:crypto";
30
- import { basename, dirname, resolve } from "node:path";
34
+ import { basename, dirname, resolve, sep } from "node:path";
31
35
 
32
36
  const TIMEOUT_FACTOR = 1.5;
33
37
  const TIMEOUT_CONSTANT_MS = 5_000;
34
38
  const DEFAULT_DURATION_MS = 1_000;
35
- const CANARY_FILES = 3;
36
39
  const POLL_MS = 50;
37
- // Playwright makes every repetition of every test of a file it loads before
38
- // the first test runs, in the runner, whether a row names the test or not:
39
- // an invocation holds about this many of them, and the main pass's other
40
- // rows go to further invocations.
41
- const TEST_CASES_PER_INVOCATION = 20_000;
42
- // A baseline, two canaries and one mutant's row at least.
43
- const MIN_REPETITIONS = 4;
40
+ // Playwright makes every test case of every file it loads before the first
41
+ // test runs, in the runner: an invocation holds about this many copies, and
42
+ // the mutants past them run in a further invocation.
43
+ const COPIES_PER_INVOCATION = 20_000;
44
+ // A test whose control fails this often in one invocation is not run again
45
+ // there: its mutants wait for a later invocation.
46
+ const CONTROL_FAILURES = 2;
44
47
 
45
48
  /** What a page writes to its console when its mutant passed the hit limit. */
46
49
  export const PAGE_TIMEOUT_MARKER = "SUPERCOV_MUTANT_TIMEOUT";
47
50
 
51
+ /** A copy's describe: `[supercov copy <k>]`, k from 1. */
52
+ const COPY_TITLE = /^\[supercov copy (\d+)\]$/;
53
+ export function copyTitle(copy) {
54
+ return `[supercov copy ${copy}]`;
55
+ }
56
+
48
57
  /**
49
- * How many repetitions of each test one invocation holds: what fits
50
- * `TEST_CASES_PER_INVOCATION` for the plan's Playwright tests, or
51
- * `SUPERCOV_PLAYWRIGHT_REPETITIONS`.
58
+ * How many test cases one invocation holds: `COPIES_PER_INVOCATION`, or
59
+ * `SUPERCOV_PLAYWRIGHT_COPIES`.
52
60
  */
53
- export function repetitionsPerInvocation(testCount) {
54
- const asked = Number(process.env["SUPERCOV_PLAYWRIGHT_REPETITIONS"]);
55
- if (Number.isInteger(asked) && asked >= MIN_REPETITIONS)
56
- return asked;
57
- return Math.max(MIN_REPETITIONS, Math.floor(TEST_CASES_PER_INVOCATION / Math.max(1, testCount)));
61
+ export function copiesPerInvocation() {
62
+ const asked = Number(process.env["SUPERCOV_PLAYWRIGHT_COPIES"]);
63
+ return Number.isInteger(asked) && asked > 0 ? asked : COPIES_PER_INVOCATION;
58
64
  }
59
65
 
60
66
  /** The pass this process belongs to, or `undefined` outside strong mode. */
@@ -65,12 +71,16 @@ export function strongPass() {
65
71
  return undefined;
66
72
  const restart = process.env["SUPERCOV_STRONG_RESTART"] || undefined;
67
73
  const name = restart ? basename(restart).replace(/\.json$/, "") : "main";
74
+ const shared = resolve(dirname(resultsPath), "playwright");
68
75
  return {
69
76
  planPath,
70
77
  resultsPath,
71
78
  restart,
72
79
  name,
73
- round: resolve(dirname(resultsPath), "playwright", name),
80
+ // What every invocation of every round shares: the baselines, the
81
+ // verdicts given, each process's status.
82
+ shared,
83
+ round: resolve(shared, name),
74
84
  };
75
85
  }
76
86
 
@@ -89,6 +99,42 @@ export function readJson(path) {
89
99
  return JSON.parse(readFileSync(path, "utf8"));
90
100
  }
91
101
 
102
+ function readJsonOr(path, fallback) {
103
+ try {
104
+ return readJson(path);
105
+ }
106
+ catch {
107
+ return fallback;
108
+ }
109
+ }
110
+
111
+ /** Each entry of a directory of the pass, or none. */
112
+ export function entries(directory) {
113
+ try {
114
+ return readdirSync(directory).sort();
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ }
120
+
121
+ /** Makes a directory that marks something done once: `false` where it was already made. */
122
+ export function mark(path) {
123
+ try {
124
+ mkdirSync(path);
125
+ return true;
126
+ }
127
+ catch (error) {
128
+ if (error?.code === "ENOENT") {
129
+ mkdirSync(dirname(path), { recursive: true });
130
+ return mark(path);
131
+ }
132
+ if (error?.code === "EEXIST")
133
+ return false;
134
+ throw error;
135
+ }
136
+ }
137
+
92
138
  function budgetOf(durations, factor = 1) {
93
139
  const longest = Math.max(DEFAULT_DURATION_MS, ...durations.map((ms) => ms ?? DEFAULT_DURATION_MS));
94
140
  return Math.ceil((longest * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * factor);
@@ -127,207 +173,232 @@ function serialFilesOf(plan, tests, fullyParallel) {
127
173
  return serialFiles.sort();
128
174
  }
129
175
 
176
+ /**
177
+ * The projects others depend on (`dependencies`, `teardown`): their tests,
178
+ * a login that stores the session others start from, run as they are in
179
+ * every invocation, with no mutant, whether or not a mutant needs them.
180
+ */
181
+ function setupProjectsOf(config) {
182
+ const names = new Set();
183
+ for (const project of Array.isArray(config?.projects) ? config.projects : []) {
184
+ for (const name of project.dependencies ?? [])
185
+ names.add(name);
186
+ if (project.teardown)
187
+ names.add(project.teardown);
188
+ }
189
+ return [...names].sort();
190
+ }
191
+
130
192
  /** Whether the project runs a file's tests side by side: every project, or the config, says `fullyParallel`. */
131
193
  function fullyParallelOf(config) {
132
194
  const projects = Array.isArray(config?.projects) && config.projects.length ? config.projects : [{}];
133
195
  return projects.every((project) => project.fullyParallel ?? config?.fullyParallel ?? false);
134
196
  }
135
197
 
136
- /** A mutant's rows: one per file its tests are in, each with its tests there. */
137
- function mutantRows(tests, entry) {
138
- const grouped = new Map();
139
- for (const id of entry.tests) {
140
- const file = tests[id].file;
141
- if (!grouped.has(file))
142
- grouped.set(file, []);
143
- grouped.get(file).push(id);
144
- }
145
- return [...grouped].map(([file, ids]) => [file, {
146
- kind: "mutant",
147
- id: entry.id,
148
- mutant: entry.mutant,
149
- tests: ids,
150
- budgetMs: budgetOf(ids.map((id) => tests[id].durationMs), entry.budgetFactor ?? 1),
151
- }]);
152
- }
153
-
154
- /**
155
- * The pass's rows: for each test file, what each repetition of its tests
156
- * does. Worked out once, in the runner, from the plan (or the job the pass
157
- * runs). The main pass runs each mutant against its likeliest killer alone
158
- * (a test that infected it, cheapest first): its other candidates run in a
159
- * later pass only if that one survives.
160
- */
161
198
  // A plan test's id as Playwright knows it: a Rust wasm run names a test by
162
199
  // its file too (`<file>::<id>`).
163
200
  function playwrightId(test) {
164
201
  return test.file && test.id.startsWith(`${test.file}::`) ? test.id.slice(test.file.length + 2) : test.id;
165
202
  }
166
203
 
167
- function buildRows(pass, root, config) {
204
+ /** A spec file as both the runner and a test's declaration name it: its real path. */
205
+ const realFiles = new Map();
206
+ function realFile(path) {
207
+ if (!realFiles.has(path)) {
208
+ let real = path;
209
+ try {
210
+ real = realpathSync(path);
211
+ }
212
+ catch {
213
+ real = path;
214
+ }
215
+ realFiles.set(path, real);
216
+ }
217
+ return realFiles.get(path);
218
+ }
219
+
220
+ /** What a test's copies are counted by where it is declared: its spec file and title. */
221
+ function declarationKey(file, title) {
222
+ return `${realFile(file)}\0${title}`;
223
+ }
224
+
225
+ /**
226
+ * The pass's work, worked out in the runner from the plan (or the job the
227
+ * round runs): each mutant to run with its candidate tests in the order it
228
+ * takes them (those whose own evidence infected it first, cheapest first),
229
+ * each test's queue of mutants (those it is the likeliest killer of first),
230
+ * and how many copies each test needs: one for each mutant that may take it,
231
+ * one more for each control a kill may call for, and the first control.
232
+ */
233
+ function buildPass(pass, root, config) {
168
234
  const plan = readJson(pass.planPath);
169
235
  const tests = {};
170
236
  plan.tests.forEach((test) => {
171
237
  if (test.runner === "playwright" && test.file)
172
- tests[playwrightId(test)] = { file: test.file, durationMs: test.durationMs ?? null };
238
+ tests[playwrightId(test)] = { file: test.file, title: test.title ?? null, durationMs: test.durationMs ?? null, jobs: 0 };
173
239
  });
174
- // `workers` set only where the pass runs one test at a time.
240
+ // `workers` set only where the round runs one test at a time.
175
241
  const concurrency = { workers: undefined, serialFiles: serialFilesOf(plan, tests, fullyParallelOf(config)) };
176
242
  const job = pass.restart ? readJson(pass.restart) : null;
177
- const perInvocation = repetitionsPerInvocation(Object.keys(tests).length);
243
+ const kind = job?.kind ?? "main";
244
+ const immediate = [];
245
+ const restarts = [];
246
+ const deferred = [];
247
+ const otherRunners = { ...(job?.otherRunners ?? {}) };
248
+ const mutants = [];
178
249
  if (job && job.kind !== "main") {
179
- const files = {};
180
- const entries = {};
181
- // A mutant with a row in a file this invocation has filled waits
182
- // for the next invocation, which runs the same job.
183
- const deferred = [];
184
250
  for (const entry of job.mutants) {
185
- const known = { ...entry, tests: entry.tests.filter((id) => tests[id]) };
186
- const rows = mutantRows(tests, known);
187
- if (rows.some(([file]) => (files[file]?.length ?? 0) >= perInvocation)) {
188
- deferred.push(entry);
189
- continue;
190
- }
191
- entries[entry.id] = known;
192
- for (const [file, row] of rows)
193
- (files[file] ??= []).push(row);
251
+ const all = [...entry.tests, ...(entry.rest ?? [])].filter((id) => tests[id]);
252
+ mutants.push({ id: entry.id, mutant: entry.mutant, tests: [...new Set(all)], reason: entry.reason, budgetFactor: entry.budgetFactor ?? 1 });
194
253
  }
195
- // A serial pass runs one test at a time: what it kills, nothing
254
+ // A serial round runs one test at a time: what it kills, nothing
196
255
  // beside it did.
197
- if (job.kind === "serial")
256
+ if (kind === "serial")
198
257
  concurrency.workers = 1;
199
- return { pass: pass.name, kind: job.kind, job, tests, files, entries, concurrency, immediate: [], restarts: [], otherRunners: job.otherRunners ?? {}, deferred };
200
- }
201
- // A main pass's later invocation runs the mutants the one before had no
202
- // room for, as the main pass would.
203
- const only = job ? new Set(job.mutants.map((mutant) => mutant.id)) : undefined;
204
-
205
- // The copy's own list: the mutant at each index must be the run's, and
206
- // one the instrumenter could not place has no switch to turn on.
207
- let listed = {};
208
- try {
209
- listed = readJson(`${root}/.supercov/frontend-evidence/mutants.json`).files ?? {};
210
258
  }
211
- catch {
212
- listed = {};
259
+ else {
260
+ // A main round's later invocation runs the mutants the one before had
261
+ // no room for, as the main round would.
262
+ const only = job ? new Set(job.mutants.map((mutant) => mutant.id)) : undefined;
263
+ // The copy's own list: the mutant at each index must be the run's, and
264
+ // one the instrumenter could not place has no switch to turn on.
265
+ const listed = readJsonOr(`${root}/.supercov/frontend-evidence/mutants.json`, {}).files ?? {};
266
+ const idOf = (file, entry) => entry.id ||
267
+ `${file}:${entry.start?.[0]}:${entry.start?.[1]}-${entry.end?.[0]}:${entry.end?.[1]}:${entry.mutator}:${entry.replacement}`;
268
+ const indexes = new Map();
269
+ for (const [file, fileEntries] of Object.entries(listed))
270
+ fileEntries.forEach((entry, index) => indexes.set(idOf(file, entry), { index, entry }));
271
+ for (const mutant of plan.mutants) {
272
+ if (mutant.decided || (only && !only.has(mutant.id)))
273
+ continue;
274
+ // A Rust mutant (Rust compiled to wasm) is switched by its index in
275
+ // its file's list, as the pass's build placed it.
276
+ const found = mutant.language === "rust" ? { index: mutant.index, entry: {} } : indexes.get(mutant.id);
277
+ if (!found || found.entry.unplaceable) {
278
+ immediate.push({
279
+ id: mutant.id,
280
+ status: "error",
281
+ reason: found ? `no switch could be placed (${found.entry.unplaceable})` : "the copy lists no such mutant: the source changed since the run",
282
+ tests: 0,
283
+ durationMs: 0,
284
+ });
285
+ continue;
286
+ }
287
+ // Its candidates, cheapest first (the plan's order), those whose own
288
+ // evidence shows it infected first of all.
289
+ const own = [];
290
+ const others = new Set();
291
+ for (const candidate of mutant.candidates) {
292
+ const test = plan.tests[candidate.test];
293
+ if (test && tests[playwrightId(test)])
294
+ own.push({ id: playwrightId(test), infected: candidate.reason === "infected" });
295
+ else if (test)
296
+ others.add(test.runner);
297
+ }
298
+ if (others.size)
299
+ otherRunners[mutant.id] = [...others].sort();
300
+ if (!own.length) {
301
+ immediate.push(others.size
302
+ ? { id: mutant.id, status: "error", reason: `its candidates ran under ${[...others].sort().join(", ")}, which this pass does not run`, tests: 0, durationMs: 0 }
303
+ : { id: mutant.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
304
+ continue;
305
+ }
306
+ const ordered = [...new Set([...own.filter((test) => test.infected), ...own.filter((test) => !test.infected)].map((test) => test.id))];
307
+ const switched = `${mutant.file}#${found.index}`;
308
+ if (mutant.serverWide) {
309
+ restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: mutant.serverWide, budgetFactor: 1 });
310
+ continue;
311
+ }
312
+ mutants.push({ id: mutant.id, mutant: switched, tests: ordered, budgetFactor: 1 });
313
+ }
213
314
  }
214
- const idOf = (file, entry) => entry.id ||
215
- `${file}:${entry.start?.[0]}:${entry.start?.[1]}-${entry.end?.[0]}:${entry.end?.[1]}:${entry.mutator}:${entry.replacement}`;
216
- const indexes = new Map();
217
- for (const [file, entries] of Object.entries(listed))
218
- entries.forEach((entry, index) => indexes.set(idOf(file, entry), { index, entry }));
219
-
220
- const immediate = [];
221
- const restarts = [];
222
- const deferred = [];
223
- // A file's mutated rows, beside its baseline and two canaries.
224
- const rowsPerFile = perInvocation - 3;
225
- const otherRunners = {};
315
+ // Each test's queue, and the copies the round's mutants need, as many as
316
+ // an invocation holds; the mutants past them wait for the next.
317
+ const limit = copiesPerInvocation();
318
+ const queues = new Map();
319
+ let copies = 0;
226
320
  const entries = {};
227
- const byFile = new Map();
228
- const baseline = new Map();
229
- const needBaseline = (file, id) => {
230
- if (!baseline.has(file))
231
- baseline.set(file, new Set());
232
- baseline.get(file).add(id);
233
- };
234
- for (const mutant of plan.mutants) {
235
- if (mutant.decided || (only && !only.has(mutant.id)))
236
- continue;
237
- // A Rust mutant (Rust compiled to wasm) is switched by its index in
238
- // its file's list, as the pass's build placed it.
239
- const found = mutant.language === "rust" ? { index: mutant.index, entry: {} } : indexes.get(mutant.id);
240
- if (!found || found.entry.unplaceable) {
241
- immediate.push({
242
- id: mutant.id,
243
- status: "error",
244
- reason: found ? `no switch could be placed (${found.entry.unplaceable})` : "the copy lists no such mutant: the source changed since the run",
245
- tests: 0,
246
- durationMs: 0,
247
- });
248
- continue;
249
- }
250
- // Its candidates, cheapest first (the plan's order), those whose own
251
- // evidence shows it infected first of all.
252
- const own = [];
253
- const others = new Set();
254
- for (const candidate of mutant.candidates) {
255
- const test = plan.tests[candidate.test];
256
- if (test && tests[playwrightId(test)])
257
- own.push({ id: playwrightId(test), infected: candidate.reason === "infected" });
258
- else if (test)
259
- others.add(test.runner);
260
- }
261
- if (others.size)
262
- otherRunners[mutant.id] = [...others].sort();
263
- if (!own.length) {
264
- immediate.push(others.size
265
- ? { id: mutant.id, status: "error", reason: `its candidates ran under ${[...others].sort().join(", ")}, which this pass does not run`, tests: 0, durationMs: 0 }
266
- : { id: mutant.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
267
- continue;
268
- }
269
- const ordered = [...own.filter((test) => test.infected), ...own.filter((test) => !test.infected)].map((test) => test.id);
270
- const switched = `${mutant.file}#${found.index}`;
271
- if (mutant.serverWide) {
272
- for (const id of ordered)
273
- needBaseline(tests[id].file, id);
274
- restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: mutant.serverWide, budgetFactor: 1 });
275
- continue;
276
- }
277
- const entry = { id: mutant.id, mutant: switched, tests: [ordered[0]], rest: ordered.slice(1), budgetFactor: 1 };
278
- // One row, in its first test's file.
279
- const [[file, row]] = mutantRows(tests, entry);
280
- if (!byFile.has(file))
281
- byFile.set(file, []);
282
- // A file's rows past what this invocation holds wait for the next.
283
- if (byFile.get(file).length >= rowsPerFile) {
284
- deferred.push({ id: mutant.id });
321
+ for (const entry of mutants) {
322
+ const added = entry.tests.reduce((sum, id) => sum + 2 + (queues.has(id) ? 0 : 1), 0);
323
+ if (copies && copies + added > limit && kind === "main") {
324
+ deferred.push({ id: entry.id });
285
325
  continue;
286
326
  }
287
- byFile.get(file).push(row);
288
- entries[mutant.id] = entry;
289
- for (const id of ordered)
290
- needBaseline(tests[id].file, id);
291
- }
292
- const files = {};
293
- for (const [file, ids] of baseline) {
294
- files[file] = [{ kind: "baseline", id: null, mutant: null, tests: [...ids], budgetMs: null }, ...(byFile.get(file) ?? [])];
295
- }
296
- // Canaries: rows with no mutant among the mutated ones, in the files
297
- // with the most mutants. One that fails means what one attempt did to
298
- // the shared server reached another's (or the test is flaky).
299
- const busiest = [...byFile.entries()]
300
- .sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1))
301
- .slice(0, CANARY_FILES);
302
- for (const [file, mutated] of busiest) {
303
- const canary = () => ({ kind: "canary", id: null, mutant: null, tests: files[file][0].tests, budgetMs: null });
304
- const rows = files[file];
305
- if (mutated.length >= 2)
306
- rows.splice(1 + Math.floor(mutated.length / 2), 0, canary());
307
- rows.push(canary());
308
- }
309
- return { pass: pass.name, kind: "main", job: null, tests, files, entries, concurrency, immediate, restarts, otherRunners, deferred };
310
- }
311
-
312
- /** The rows of this pass: built and written by the runner, read by its reporter. */
313
- let rowsCache;
314
- export function loadRows(pass) {
315
- rowsCache ??= readJson(`${pass.round}/rows.json`);
316
- return rowsCache;
327
+ copies += added;
328
+ entries[entry.id] = entry;
329
+ entry.tests.forEach((id, at) => {
330
+ if (!queues.has(id))
331
+ queues.set(id, []);
332
+ queues.get(id).push({ id: entry.id, at });
333
+ });
334
+ }
335
+ const declared = {};
336
+ for (const [id, queue] of queues) {
337
+ // The likeliest killers' mutants first; the plan's order between equals.
338
+ queue.sort((a, b) => a.at - b.at);
339
+ const test = tests[id];
340
+ test.jobs = queue.length;
341
+ test.queue = queue.map((job) => job.id);
342
+ const where = declarationKey(resolve(root, test.file), test.title);
343
+ declared[where] = Math.max(declared[where] ?? 0, 2 * queue.length + 1);
344
+ }
345
+ return {
346
+ pass: pass.name,
347
+ kind,
348
+ job,
349
+ // A round whose server runs one mutant everywhere has no control: the
350
+ // test cannot run without it there.
351
+ everywhere: kind === "alone",
352
+ // One mutant an invocation: each runner takes one as it starts, and
353
+ // the processes it starts (its web server) run with it on.
354
+ batch: kind === "alone" && Boolean(job?.batch),
355
+ // A main round's first control of a test is its baseline.
356
+ baselines: kind === "main",
357
+ tests,
358
+ declared,
359
+ entries,
360
+ setupProjects: setupProjectsOf(config),
361
+ concurrency,
362
+ immediate,
363
+ restarts,
364
+ otherRunners,
365
+ deferred,
366
+ };
367
+ }
368
+
369
+ /** The round's work: built and written by the runner, read by its judge. */
370
+ let passCache;
371
+ export function loadPass(pass) {
372
+ passCache ??= readJson(`${pass.round}/pass.json`);
373
+ return passCache;
317
374
  }
318
375
 
319
376
  /**
320
- * What a worker reads: the pass's shape (`worker.json`: the repetitions,
321
- * the tests and how they run side by side), and the rows of the one
322
- * repetition index it serves (`rows/<index>.json`), never the plan or the
323
- * other rows. Each is small and the same size whatever the plan's.
377
+ * What a worker reads: the round's shape (`worker.json`: the tests, their
378
+ * copies and how they run side by side), each test's queue of mutants
379
+ * (`queues/<test>.json`) and each mutant it takes (`mutants/<mutant>.json`),
380
+ * never the plan.
324
381
  */
325
- function writeWorkerFiles(pass, rows, repeatEach) {
326
- writeJson(`${pass.round}/worker.json`, { repeatEach, tests: rows.tests, concurrency: rows.concurrency, job: Boolean(rows.job) });
327
- const byIndex = Array.from({ length: repeatEach }, () => ({}));
328
- for (const [file, fileRows] of Object.entries(rows.files))
329
- fileRows.forEach((row, index) => { byIndex[index][file] = row; });
330
- byIndex.forEach((at, index) => writeJson(`${pass.round}/rows/${index}.json`, at));
382
+ function writeRoundFiles(pass, work) {
383
+ const tests = {};
384
+ for (const [id, test] of Object.entries(work.tests)) {
385
+ if (!test.jobs)
386
+ continue;
387
+ tests[id] = { file: test.file, title: test.title, durationMs: test.durationMs, jobs: test.jobs };
388
+ writeJson(`${pass.round}/queues/${key(id)}.json`, test.queue);
389
+ }
390
+ for (const entry of Object.values(work.entries))
391
+ writeJson(`${pass.round}/mutants/${key(entry.id)}.json`, entry);
392
+ writeJson(`${pass.round}/worker.json`, {
393
+ kind: work.kind,
394
+ everywhere: work.everywhere,
395
+ batch: work.batch,
396
+ baselines: work.baselines,
397
+ tests,
398
+ declared: work.declared,
399
+ setupProjects: work.setupProjects,
400
+ concurrency: work.concurrency,
401
+ });
331
402
  }
332
403
 
333
404
  let workerCache;
@@ -336,11 +407,18 @@ function loadWorker(pass) {
336
407
  return workerCache;
337
408
  }
338
409
 
339
- const indexCache = new Map();
340
- function rowsAt(pass, index) {
341
- if (!indexCache.has(index))
342
- indexCache.set(index, readJson(`${pass.round}/rows/${index}.json`));
343
- return indexCache.get(index);
410
+ const queueCache = new Map();
411
+ function queueOf(pass, test) {
412
+ if (!queueCache.has(test))
413
+ queueCache.set(test, { ids: readJsonOr(`${pass.round}/queues/${key(test)}.json`, []), done: 0 });
414
+ return queueCache.get(test);
415
+ }
416
+
417
+ const mutantCache = new Map();
418
+ function mutantOf(pass, id) {
419
+ if (!mutantCache.has(id))
420
+ mutantCache.set(id, readJson(`${pass.round}/mutants/${key(id)}.json`));
421
+ return mutantCache.get(id);
344
422
  }
345
423
 
346
424
  /**
@@ -352,40 +430,45 @@ function listing() {
352
430
  return process.argv.includes("--list");
353
431
  }
354
432
 
433
+ /** Whether this process runs the strong pass's tests: not outside it, and not to list them. */
434
+ export function copying() {
435
+ return Boolean(strongPass()) && !listing();
436
+ }
437
+
355
438
  /**
356
- * The generated config in strong mode: every test repeated once per row,
357
- * no retries (a retry would be a repetition of its own), no failure limit
358
- * (a killed mutant fails a test), the project's own workers (one in a
359
- * serial pass), and the strong reporter alone.
439
+ * The generated config in strong mode: no retries (a retry would be a copy
440
+ * of its own), no failure limit (a killed mutant fails a test), the
441
+ * project's own workers (one in a serial round), and the strong reporter
442
+ * alone.
360
443
  */
361
444
  export function strongConfig(normalized, root, reporterPath) {
362
445
  if (listing())
363
446
  return normalized;
364
447
  const pass = strongPass();
365
- let shape;
448
+ let concurrency;
366
449
  if (process.env.TEST_WORKER_INDEX === undefined) {
367
- // Every invocation of the pass (a harness may start several at
368
- // once, each with a share of the tests) works out the same rows from
369
- // the same plan and writes them alike; none removes what another
370
- // wrote. The pass's directory is new with the pass.
371
- const rows = buildRows(pass, root, normalized);
372
- const repeatEach = Math.max(1, ...Object.values(rows.files).map((fileRows) => fileRows.length));
450
+ // Every invocation of the round (a harness may start several at
451
+ // once, each with a share of the tests) works out the same work from
452
+ // the same plan and writes it alike; none removes what another
453
+ // wrote. The round's directory is new with the round.
454
+ const work = buildPass(pass, root, normalized);
373
455
  // This invocation, for its workers: they share its server.
374
456
  process.env["SUPERCOV_PLAYWRIGHT_INVOCATION"] = String(process.pid);
375
- writeJson(`${pass.round}/rows.json`, rows);
376
- writeWorkerFiles(pass, rows, repeatEach);
377
- rowsCache = rows;
378
- shape = { repeatEach, concurrency: rows.concurrency };
457
+ writeJson(`${pass.round}/pass.json`, work);
458
+ writeRoundFiles(pass, work);
459
+ passCache = work;
460
+ if (work.batch)
461
+ takeAloneMutant(pass, work, root);
462
+ concurrency = work.concurrency;
379
463
  }
380
464
  else {
381
- shape = loadWorker(pass);
465
+ concurrency = loadWorker(pass).concurrency;
382
466
  }
383
- const { repeatEach, concurrency } = shape;
384
- const strongProject = (project) => ({ ...project, repeatEach, retries: 0 });
467
+ const strongProject = (project) => ({ ...project, repeatEach: 1, retries: 0 });
385
468
  return {
386
469
  ...normalized,
387
470
  ...(Array.isArray(normalized.projects) ? { projects: normalized.projects.map(strongProject) } : {}),
388
- repeatEach,
471
+ repeatEach: 1,
389
472
  retries: 0,
390
473
  maxFailures: 0,
391
474
  ...(concurrency.workers ? { workers: concurrency.workers } : {}),
@@ -394,11 +477,106 @@ export function strongConfig(normalized, root, reporterPath) {
394
477
  };
395
478
  }
396
479
 
480
+ /**
481
+ * In a round of mutants a server must start with, each invocation's runner
482
+ * takes the next one no other took, and switches it on for every process it
483
+ * starts from here (`webServer`, its workers): several mutants run alone at
484
+ * once, one per invocation of a harness that starts several. An invocation
485
+ * with none left runs nothing.
486
+ */
487
+ function takeAloneMutant(pass, work, root) {
488
+ const fileOf = (id) => realFile(resolve(root, work.tests[id]?.file ?? ""));
489
+ const named = namedSpecs(Object.keys(work.tests).map(fileOf));
490
+ const here = (entry) => !named || entry.tests.some((id) => named.has(fileOf(id)));
491
+ for (const entry of work.job.mutants) {
492
+ if (!here(entry) || !mark(`${pass.round}/alone/${key(entry.id)}`))
493
+ continue;
494
+ process.env["SUPERCOV_ACTIVE_MUTANT"] = entry.mutant;
495
+ writeJson(`${pass.round}/invocations/${process.pid}.json`, { id: entry.id, mutant: entry.mutant });
496
+ return;
497
+ }
498
+ writeJson(`${pass.round}/invocations/${process.pid}.json`, { id: null });
499
+ }
500
+
501
+ /**
502
+ * The plan's spec files this invocation's command line names, as a harness
503
+ * that shares the tests out names them (`a.spec.ts:12`, or a folder of
504
+ * them); `undefined` where it names none of them (every test is its).
505
+ */
506
+ function namedSpecs(specs) {
507
+ const named = new Set();
508
+ for (const arg of process.argv.slice(2)) {
509
+ if (arg.startsWith("-"))
510
+ continue;
511
+ const path = realFile(resolve(arg.replace(/(:\d+)+$/, "")));
512
+ for (const spec of specs) {
513
+ if (spec === path || spec.startsWith(`${path}${sep}`))
514
+ named.add(spec);
515
+ }
516
+ }
517
+ return named.size ? named : undefined;
518
+ }
519
+
520
+ /** The mutant this invocation runs, in a round of one mutant an invocation. */
521
+ let aloneMutant;
522
+ function invocationMutant(pass) {
523
+ aloneMutant ??= readJsonOr(`${pass.round}/invocations/${invocation()}.json`, { id: null }).id;
524
+ return aloneMutant;
525
+ }
526
+
527
+ /**
528
+ * Declares each test of the round as many times as its copies: Playwright's
529
+ * test declaration, wrapped, on the prototype every `test` object (and each
530
+ * one `test.extend` makes later) binds. Copies keep the test's title and
531
+ * place (a `file:line` filter takes them all); each is in a describe of its
532
+ * own, `[supercov copy <k>]`, so that its full title is new. A serial
533
+ * describe runs as a default one: in order, in one worker, but a failed test
534
+ * (a kill) does not skip the rest; a test that leans on an earlier one's
535
+ * state is caught by its control.
536
+ */
537
+ export function installCopies(baseTest) {
538
+ if (!copying())
539
+ return false;
540
+ const symbol = Object.getOwnPropertySymbols(baseTest).find((one) => one.description === "testType");
541
+ const prototype = symbol && Object.getPrototypeOf(baseTest[symbol]);
542
+ const declare = prototype?._createTest;
543
+ const describe = prototype?._describe;
544
+ const configure = prototype?._configure;
545
+ if (typeof declare !== "function" || typeof describe !== "function" || typeof configure !== "function")
546
+ throw new Error("Supercov's strong pass cannot declare copies of tests with this version of Playwright");
547
+ if (prototype.__supercovCopies)
548
+ return true;
549
+ Object.defineProperty(prototype, "__supercovCopies", { value: true });
550
+ prototype._createTest = function (type, location, title, fnOrDetails, fn) {
551
+ declare.call(this, type, location, title, fnOrDetails, fn);
552
+ if (type === "skip" || type === "fixme")
553
+ return;
554
+ const suite = this._currentSuite?.(location, "test()");
555
+ const copies = copiesOf(suite?._requireFile ?? location?.file, title);
556
+ for (let copy = 1; copy < copies; copy++)
557
+ describe.call(this, "default", location, copyTitle(copy), () => declare.call(this, type, location, title, fnOrDetails, fn));
558
+ };
559
+ prototype._describe = function (type, ...rest) {
560
+ return describe.call(this, type === "serial" ? "default" : type === "serial.only" ? "only" : type, ...rest);
561
+ };
562
+ prototype._configure = function (location, options) {
563
+ return configure.call(this, location, options?.mode === "serial" ? { ...options, mode: "default" } : options);
564
+ };
565
+ return true;
566
+ }
567
+
568
+ let declaredCopies;
569
+ function copiesOf(file, title) {
570
+ if (!file)
571
+ return 1;
572
+ declaredCopies ??= readJsonOr(`${strongPass().round}/worker.json`, { declared: {} }).declared;
573
+ return declaredCopies[declarationKey(file, title)] ?? 1;
574
+ }
575
+
397
576
  /** How a test did with no mutant: `passed`, `failed`, or `undefined` before it ended. */
398
577
  export function baselineOf(pass, original) {
399
- const marker = `${pass.round}/baseline/${key(original)}`;
400
578
  try {
401
- return readJson(marker);
579
+ return readJson(`${pass.shared}/baseline/${key(original)}`);
402
580
  }
403
581
  catch {
404
582
  return undefined;
@@ -408,21 +586,30 @@ export function baselineOf(pass, original) {
408
586
  const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
409
587
 
410
588
  /**
411
- * Where a test is, the same for each of its repetitions and in every
412
- * invocation: its project and title path. The reporter, from a test case.
589
+ * Where a test is, the same for each of its copies and in every invocation:
590
+ * its project and title path, without its copy's describe. The reporter, from
591
+ * a test case.
413
592
  */
414
593
  export function placeOf(test) {
415
- return JSON.stringify(test.titlePath().slice(1));
594
+ return JSON.stringify(withoutCopy(test.titlePath().slice(1)).path);
595
+ }
596
+
597
+ /** A title path without its copy's describe, and which copy it is: 0 for the test as declared. */
598
+ export function withoutCopy(path) {
599
+ const at = path.length - 2;
600
+ const found = at >= 0 ? COPY_TITLE.exec(path[at]) : null;
601
+ return found ? { path: [...path.slice(0, at), path[at + 1]], copy: Number(found[1]) } : { path, copy: 0 };
416
602
  }
417
603
 
418
- /** The test the plan names (its first repetition's id) for a repetition, as its invocation's reporter wrote it. */
604
+ /** The test the plan names for a copy, as its invocation's reporter wrote it. */
419
605
  async function originalTestId(pass, testInfo) {
420
- if (!testInfo.repeatEachIndex)
606
+ const { path, copy } = withoutCopy(testInfo.titlePath);
607
+ if (!copy)
421
608
  return testInfo.testId;
422
- const path = `${pass.round}/originals/${key(JSON.stringify([testInfo.project.name, ...testInfo.titlePath]))}`;
609
+ const file = `${pass.round}/originals/${key(JSON.stringify([testInfo.project.name, ...path]))}`;
423
610
  for (let waited = 0; waited < 10_000; waited += POLL_MS) {
424
- if (existsSync(path))
425
- return readJson(path);
611
+ if (existsSync(file))
612
+ return readJson(file);
426
613
  await sleep(POLL_MS);
427
614
  }
428
615
  return undefined;
@@ -439,25 +626,20 @@ function alive(pid) {
439
626
  }
440
627
 
441
628
  /**
442
- * One test of `file` at a time, across the pass's workers: the file's lock,
629
+ * One test of `file` at a time, across the round's workers: the file's lock,
443
630
  * a directory, held by this worker's process until the test ends. A lock
444
631
  * whose holder died is taken over.
445
632
  */
446
633
  async function lockFile(pass, file) {
447
634
  // Per invocation: another invocation's tests reach a server of their own.
448
- const locks = `${pass.round}/locks/${process.env["SUPERCOV_PLAYWRIGHT_INVOCATION"]}`;
635
+ const locks = `${pass.round}/locks/${invocation()}`;
449
636
  const lock = `${locks}/${key(file)}`;
450
637
  mkdirSync(locks, { recursive: true });
451
638
  for (;;) {
452
- try {
453
- mkdirSync(lock);
639
+ if (mark(lock)) {
454
640
  writeFileSync(`${lock}/owner`, String(process.pid));
455
641
  return lock;
456
642
  }
457
- catch (error) {
458
- if (error?.code !== "EEXIST")
459
- throw error;
460
- }
461
643
  let owner;
462
644
  try {
463
645
  owner = Number(readFileSync(`${lock}/owner`, "utf8"));
@@ -471,88 +653,425 @@ async function lockFile(pass, file) {
471
653
  }
472
654
  }
473
655
 
656
+ /** Where an invocation keeps its attempt of a test case: several may run the same test. */
657
+ export function attemptPath(pass, at, testId) {
658
+ return `${pass.round}/attempts/${at}-${key(testId)}.json`;
659
+ }
660
+
661
+ export function invocation() {
662
+ return process.env["SUPERCOV_PLAYWRIGHT_INVOCATION"] ?? "0";
663
+ }
664
+
665
+ // The tests that passed without a mutant in this worker (a control): a test
666
+ // runs with a mutant only in a worker where it passed without one.
667
+ const passedHere = new Set();
668
+
669
+ /** Whether a mutant needs no more attempts: a verdict given, killed, or held for a later round. */
670
+ function settled(pass, id) {
671
+ const at = key(id);
672
+ return existsSync(`${pass.shared}/verdicts/${at}`) || existsSync(`${pass.round}/killed/${at}`) || existsSync(`${pass.round}/held/${at}`);
673
+ }
674
+
675
+ /**
676
+ * Whether another attempt runs the mutant now, and since when: the earliest
677
+ * start of those running, or `undefined` where none does.
678
+ */
679
+ function inFlightSince(pass, id) {
680
+ let since;
681
+ for (const entry of entries(`${pass.round}/inflight/${key(id)}`)) {
682
+ if (!alive(Number(entry.split("-")[0])))
683
+ continue;
684
+ let started;
685
+ try {
686
+ started = Number(readFileSync(`${pass.round}/inflight/${key(id)}/${entry}`, "utf8")) || 0;
687
+ }
688
+ catch {
689
+ // It ended as this looked.
690
+ continue;
691
+ }
692
+ since = since === undefined ? started : Math.min(since, started);
693
+ }
694
+ return since;
695
+ }
696
+
697
+ /**
698
+ * The next mutant for a copy of `test`: the first of its queue not settled
699
+ * and not yet tried against it, one no other attempt runs first. Taken by
700
+ * making its mark, which only one copy can.
701
+ */
702
+ function takeJob(pass, test, only, budgetMs) {
703
+ const queue = queueOf(pass, test);
704
+ const busy = [];
705
+ for (let at = queue.done; at < queue.ids.length; at++) {
706
+ const id = queue.ids[at];
707
+ if (only !== undefined && id !== only)
708
+ continue;
709
+ const tried = `${pass.round}/claims/${key(id)}/${key(test)}`;
710
+ if (existsSync(tried) || settled(pass, id)) {
711
+ // Nothing undoes either: no copy looks at it again.
712
+ if (at === queue.done)
713
+ queue.done += 1;
714
+ continue;
715
+ }
716
+ const since = inFlightSince(pass, id);
717
+ if (since !== undefined) {
718
+ // One that has run longer than this test would take may hang:
719
+ // a second attempt would only wait as long.
720
+ if (Date.now() - since < budgetMs)
721
+ busy.push(id);
722
+ continue;
723
+ }
724
+ if (mark(tried))
725
+ return id;
726
+ }
727
+ // Every mutant left runs elsewhere now: one of them here too, rather
728
+ // than leave this test's copies unused while its attempt runs.
729
+ for (const id of busy) {
730
+ if (only === undefined && !settled(pass, id) && mark(`${pass.round}/claims/${key(id)}/${key(test)}`))
731
+ return id;
732
+ }
733
+ return undefined;
734
+ }
735
+
736
+ /** Whether a test has mutants left to take, or kills to confirm, in this invocation. */
737
+ function workLeft(pass, test) {
738
+ if (entries(`${pass.round}/pending/${invocation()}/${key(test)}`).length)
739
+ return true;
740
+ const queue = queueOf(pass, test);
741
+ for (let at = queue.done; at < queue.ids.length; at++) {
742
+ const id = queue.ids[at];
743
+ if (!existsSync(`${pass.round}/claims/${key(id)}/${key(test)}`) && !settled(pass, id))
744
+ return true;
745
+ }
746
+ return false;
747
+ }
748
+
749
+ /**
750
+ * Notes that an attempt runs, and whether another mutant's attempt runs
751
+ * beside it in this invocation (its server): each attempt that starts looks
752
+ * at those running, and marks them and itself, so of two that overlap one
753
+ * sees the other.
754
+ */
755
+ function startRunning(pass, testId, mutant) {
756
+ const running = `${pass.round}/running/${invocation()}`;
757
+ const mine = `${process.pid}-${key(testId)}`;
758
+ writeJson(`${running}/${mine}`, { mutant, testId });
759
+ let beside = false;
760
+ for (const entry of entries(running)) {
761
+ if (entry === mine || entry.endsWith(".draft") || !alive(Number(entry.split("-")[0])))
762
+ continue;
763
+ const other = readJsonOr(`${running}/${entry}`, undefined);
764
+ if (!other || other.mutant === mutant || (other.mutant === "-" && mutant === "-"))
765
+ continue;
766
+ beside = true;
767
+ mark(`${pass.round}/beside/${invocation()}-${key(other.testId)}`);
768
+ }
769
+ return { running: `${running}/${mine}`, beside };
770
+ }
771
+
474
772
  /**
475
- * What this repetition of a test does: `undefined` outside strong mode,
476
- * `null` to skip, else the mutant (`file#index`, `-` for none) and its time
477
- * budget. A row after the baseline waits for the test's own baseline: a test
478
- * that fails with no mutant cannot tell one. A file whose tests the measured
479
- * run never ran side by side runs one at a time here too.
773
+ * What this copy of a test does: `undefined` outside strong mode, `null` to
774
+ * skip, else its attempt: a control (no mutant, `-`) or the mutant it took
775
+ * (`file#index`), and its time budget. A file whose tests the measured run
776
+ * never ran side by side runs one at a time here too.
480
777
  */
481
778
  export async function strongClaim(testInfo) {
482
779
  const pass = strongPass();
483
780
  if (!pass)
484
781
  return undefined;
485
782
  const started = Date.now();
486
- const rows = loadWorker(pass);
783
+ const shape = loadWorker(pass);
784
+ // A project others start from runs as it is.
785
+ if (shape.setupProjects.includes(testInfo.project.name))
786
+ return undefined;
487
787
  const original = await originalTestId(pass, testInfo);
488
- const test = original && rows.tests[original];
489
- const row = test && rowsAt(pass, testInfo.repeatEachIndex)[test.file];
490
- if (!row || !row.tests.includes(original))
788
+ const test = original && shape.tests[original];
789
+ if (!test)
491
790
  return null;
492
791
  const configured = testInfo.timeout;
493
792
  // Waiting is not the test's time.
494
793
  testInfo.setTimeout(0);
495
- if (row.kind !== "baseline" && !rows.job) {
496
- const deadline = Date.now() + Math.max(120_000, budgetOf([test.durationMs]) * 4);
497
- while (baselineOf(pass, original) === undefined && Date.now() < deadline)
498
- await sleep(POLL_MS);
499
- if (baselineOf(pass, original) !== "passed")
794
+ const unreliable = `${pass.round}/unreliable/${invocation()}/${key(original)}`;
795
+ if (entries(unreliable).length >= CONTROL_FAILURES)
796
+ return null;
797
+ let attempt;
798
+ if (!shape.everywhere && !passedHere.has(original)) {
799
+ // The test's first run in this worker, or the first since it failed
800
+ // here: without a mutant, the round's baseline or a kill's control.
801
+ if (!workLeft(pass, original))
500
802
  return null;
803
+ attempt = shape.baselines && baselineOf(pass, original) === undefined
804
+ ? { kind: "baseline", id: null, mutant: "-" }
805
+ : { kind: "control", id: null, mutant: "-" };
501
806
  }
502
- const killed = () => row.kind === "mutant" && existsSync(`${pass.round}/killed/${key(row.id)}`);
503
- if (killed())
504
- return null;
505
- const lock = rows.concurrency.workers !== 1 && rows.concurrency.serialFiles.includes(test.file)
807
+ else {
808
+ // A later round's test that failed without any mutant in the main one.
809
+ if (baselineOf(pass, original) === "failed")
810
+ return null;
811
+ const id = takeJob(pass, original, shape.batch ? invocationMutant(pass) ?? null : undefined, budgetOf([test.durationMs]));
812
+ if (!id)
813
+ return null;
814
+ const entry = mutantOf(pass, id);
815
+ attempt = { kind: "mutant", id, mutant: entry.mutant, budgetMs: budgetOf([test.durationMs], entry.budgetFactor ?? 1) };
816
+ mark(`${pass.round}/inflight/${key(id)}`);
817
+ writeFileSync(`${pass.round}/inflight/${key(id)}/${process.pid}-${key(testInfo.testId)}`, String(Date.now()));
818
+ }
819
+ const lock = shape.concurrency.workers !== 1 && shape.concurrency.serialFiles.includes(test.file)
506
820
  ? await lockFile(pass, test.file)
507
821
  : undefined;
508
- if (killed()) {
509
- if (lock)
510
- rmSync(lock, { recursive: true, force: true });
511
- return null;
512
- }
513
822
  // The test's time from here: a mutant's from the test's measured
514
823
  // duration and the time Playwright gives an assertion and an action to
515
- // fail in (a failing `expect` waits for its own timeout), a canary's as
824
+ // fail in (a failing `expect` waits for its own timeout), a control's as
516
825
  // configured.
517
- if (row.kind === "mutant") {
826
+ if (attempt.kind === "mutant") {
518
827
  const expectTimeout = testInfo.project?.expect?.timeout ?? 5_000;
519
828
  const actionTimeout = testInfo.project?.use?.actionTimeout ?? 0;
520
829
  // Playwright itself ends the test at its configured timeout (the
521
830
  // project's, or its own `test.slow()` / `describe.configure`), and an
522
831
  // assertion may wait up to there with a timeout of its own: that is
523
832
  // the floor.
524
- const budget = Math.max(row.budgetMs + expectTimeout + actionTimeout, configured > 0 ? configured : 0);
833
+ const budget = Math.max(attempt.budgetMs + expectTimeout + actionTimeout, configured > 0 ? configured : 0);
525
834
  testInfo.setTimeout(Date.now() - started + budget);
526
835
  }
527
836
  else if (configured > 0)
528
837
  testInfo.setTimeout(Date.now() - started + configured);
838
+ const { running, beside } = startRunning(pass, testInfo.testId, attempt.mutant);
529
839
  const claimed = {
530
840
  original,
531
- index: testInfo.repeatEachIndex,
841
+ title: test.title,
532
842
  testId: testInfo.testId,
533
- invocation: process.env["SUPERCOV_PLAYWRIGHT_INVOCATION"],
534
- kind: row.kind,
535
- id: row.id,
536
- mutant: row.mutant ?? "-",
843
+ invocation: invocation(),
844
+ worker: process.pid,
845
+ kind: attempt.kind,
846
+ id: attempt.id,
847
+ mutant: attempt.mutant,
537
848
  startedAt: Date.now(),
538
849
  lock,
850
+ running,
851
+ besideAtStart: beside,
539
852
  };
540
- writeJson(`${pass.round}/attempts/${key(testInfo.testId)}.json`, claimed);
853
+ writeJson(attemptPath(pass, invocation(), testInfo.testId), claimed);
541
854
  return claimed;
542
855
  }
543
856
 
544
- /** The attempt's end, and whether its page said the mutant ran away. */
857
+ const TEST_TIMEOUT = /Test timeout of \d+ms exceeded/;
858
+
859
+ export function stripAnsi(text) {
860
+ return String(text).replace(/\u001b\[[0-9;]*m/g, "");
861
+ }
862
+
863
+ /** An error's message, on one line, short enough to keep. */
864
+ export function firstWords(message) {
865
+ const text = stripAnsi(message ?? "").replace(/\s+/g, " ").trim();
866
+ return text.length > 300 ? `${text.slice(0, 299)}…` : text;
867
+ }
868
+
869
+ /**
870
+ * How an attempt ended, from its errors: `passed`, `failed` (an assertion or
871
+ * an action failed, or the test threw), `timed-out` (only its time ran out),
872
+ * or `skipped`; and why it failed.
873
+ */
874
+ export function outcomeOf(status, errors) {
875
+ const timeoutOnly = errors.length > 0 && errors.every((error) => TEST_TIMEOUT.test(stripAnsi(error?.message ?? "")));
876
+ const reported = errors.find((error) => !TEST_TIMEOUT.test(stripAnsi(error?.message ?? ""))) ?? errors[0];
877
+ const message = reported ? firstWords(reported.message ?? reported.value) : undefined;
878
+ if (status === "passed")
879
+ return { outcome: "passed" };
880
+ if (status === "skipped")
881
+ return { outcome: "skipped" };
882
+ if (status === "timedOut" && timeoutOnly)
883
+ return { outcome: "timed-out", message };
884
+ return { outcome: "failed", message };
885
+ }
886
+
887
+ /** Writes a mutant's verdict into the results as soon as it is known, once. */
888
+ export function giveVerdict(pass, record) {
889
+ if (!mark(`${pass.shared}/verdicts/${key(record.id)}`))
890
+ return false;
891
+ appendFileSync(pass.resultsPath, `${JSON.stringify(record)}\n`);
892
+ return true;
893
+ }
894
+
895
+ /** The candidate tests of a mutant that passed with it. */
896
+ function passedWith(pass, id) {
897
+ return new Set(entries(`${pass.round}/passed/${key(id)}`));
898
+ }
899
+
900
+ /** A mutant every candidate test lets live, now that one more passed with it: its verdict. */
901
+ function surviveIfDone(pass, id) {
902
+ if (settled(pass, id) || existsSync(`${pass.round}/confirm/${key(id)}`) || existsSync(`${pass.round}/doubt/${key(id)}`))
903
+ return;
904
+ const entry = mutantOf(pass, id);
905
+ const passed = passedWith(pass, id);
906
+ // Every candidate passed with it: one that failed without it is left to
907
+ // the round's judge, once its controls are all known.
908
+ if (!entry.tests.every((test) => passed.has(key(test))))
909
+ return;
910
+ const ran = entry.tests.length;
911
+ const others = readJsonOr(`${pass.round}/pass.json`, { otherRunners: {} }).otherRunners?.[id];
912
+ giveVerdict(pass, others
913
+ ? { id, status: "error", reason: `no Playwright test killed it, and its other candidates ran under ${others.join(", ")}, which this pass does not run`, tests: ran, durationMs: 0 }
914
+ : { id, status: "survived", ...(entry.reason ? { reason: reasonOf(loadWorker(pass).kind, entry.reason) } : {}), tests: ran, durationMs: 0 });
915
+ }
916
+
917
+ export const WHY = {
918
+ "background": "its code ran in server work no request named",
919
+ "module-level": "it is a server module's top-level code",
920
+ "by-time": "its code ran for a request that named no test",
921
+ "timeout-retry": "a test ran out of time with it switched on, and ran again alone with twice the time",
922
+ "unfinished": "not every candidate test ran in the shared pass",
923
+ "confirm": "a test killed it beside other mutants' attempts",
924
+ "doubt": "the test that killed it failed without it too, on the same server",
925
+ };
926
+ export const EVERYWHERE = ["background", "module-level", "by-time"];
927
+
928
+ /** What a verdict from a later round says of it. */
929
+ export function reasonOf(kind, reason) {
930
+ if (kind === "alone")
931
+ return `ran alone${EVERYWHERE.includes(reason) ? ", with the server started with it switched on" : ""}: ${WHY[reason] ?? reason}`;
932
+ if (kind === "serial")
933
+ return `ran one test at a time: ${WHY[reason] ?? reason}`;
934
+ return undefined;
935
+ }
936
+
937
+ /**
938
+ * The attempt's end: its outcome kept, and what it settles. A control that
939
+ * passes confirms the kills before it on this server; one that fails puts
940
+ * them in doubt. A mutated attempt that fails kills its mutant (confirmed by
941
+ * the test's next control, where the round has controls); one that passes
942
+ * may be its mutant's last candidate. `details` says what the fixture saw:
943
+ * the attempt's id and whether its page said the mutant ran away.
944
+ */
545
945
  export function strongFinish(testInfo, claimed, details) {
546
946
  const pass = strongPass();
547
947
  if (!pass || !claimed)
548
948
  return;
549
- // A kill is marked here, before the worker starts its next test: the
550
- // reporter hears of it later, and the next test of the row would run.
551
- if (claimed.kind === "mutant" && testInfo.status !== undefined && testInfo.status !== "passed" && testInfo.status !== "skipped")
552
- writeJson(`${pass.round}/killed/${key(claimed.id)}`, claimed.original);
553
- writeJson(`${pass.round}/attempts/${key(testInfo.testId)}.json`, { ...claimed, ...details, endedAt: Date.now() });
554
- if (claimed.lock)
555
- rmSync(claimed.lock, { recursive: true, force: true });
949
+ const { outcome, message } = outcomeOf(testInfo.status, testInfo.errors ?? []);
950
+ settleAttempt(pass, { ...claimed, ...details, outcome, message });
951
+ }
952
+
953
+ /**
954
+ * What an attempt that ended settles: the fixture's, or the reporter's for
955
+ * an attempt whose worker ended before its fixture could (a mutant that
956
+ * crashed it).
957
+ */
958
+ export function settleAttempt(pass, attempt) {
959
+ rmSync(attempt.running, { force: true });
960
+ if (attempt.lock)
961
+ rmSync(attempt.lock, { recursive: true, force: true });
962
+ const beside = attempt.besideAtStart || existsSync(`${pass.round}/beside/${attempt.invocation}-${key(attempt.testId)}`);
963
+ const ended = { ...attempt, beside, endedAt: Date.now() };
964
+ writeJson(attemptPath(pass, attempt.invocation, attempt.testId), ended);
965
+ const test = attempt.original;
966
+ const shape = loadWorker(pass);
967
+ if (attempt.kind !== "mutant") {
968
+ settleControl(pass, ended, shape);
969
+ return ended;
970
+ }
971
+ rmSync(`${pass.round}/inflight/${key(attempt.id)}/${attempt.worker}-${key(attempt.testId)}`, { force: true });
972
+ const entry = mutantOf(pass, attempt.id);
973
+ const verdict = (status, reason) => ({ id: attempt.id, status, killedBy: test, reason: `${reason}${suffix(shape, entry)}`, tests: 1, durationMs: ended.endedAt - ended.startedAt });
974
+ if (attempt.pageTimeout === true) {
975
+ mark(`${pass.round}/killed/${key(attempt.id)}`);
976
+ giveVerdict(pass, verdict("timeout", "evaluated past its hit limit"));
977
+ return ended;
978
+ }
979
+ if (ended.outcome === "passed") {
980
+ passedHere.add(test);
981
+ mark(`${pass.round}/passed/${key(attempt.id)}/${key(test)}`);
982
+ // One mutant an invocation: a survivor waits for the judge, who
983
+ // knows whether its server ran it.
984
+ if (!shape.batch)
985
+ surviveIfDone(pass, attempt.id);
986
+ return ended;
987
+ }
988
+ if (ended.outcome === "timed-out") {
989
+ // Only its time ran out: run again, alone, with twice the time.
990
+ if (shared(shape.kind))
991
+ mark(`${pass.round}/held/${key(attempt.id)}`);
992
+ else if (giveVerdict(pass, verdict("timeout", "ran out of time")))
993
+ mark(`${pass.round}/killed/${key(attempt.id)}`);
994
+ return ended;
995
+ }
996
+ if (ended.outcome !== "failed")
997
+ return ended;
998
+ // A kill: no other copy takes the mutant now.
999
+ passedHere.delete(test);
1000
+ mark(`${pass.round}/killed/${key(attempt.id)}`);
1001
+ if (beside)
1002
+ mark(`${pass.round}/confirm/${key(attempt.id)}`);
1003
+ else if (shape.everywhere)
1004
+ giveVerdict(pass, verdict("killed", ended.message ?? "the test failed"));
1005
+ else {
1006
+ // Confirmed by the test's next control on this server.
1007
+ writeJson(`${pass.round}/pending/${attempt.invocation}/${key(test)}/${key(attempt.id)}`, { id: attempt.id, test, message: ended.message, endedAt: ended.endedAt, durationMs: ended.endedAt - ended.startedAt });
1008
+ }
1009
+ return ended;
1010
+ }
1011
+
1012
+ function suffix(shape, entry) {
1013
+ const said = reasonOf(shape.kind, entry.reason);
1014
+ return said ? `; ${said}` : "";
1015
+ }
1016
+
1017
+ /**
1018
+ * A run with no mutant: the test's baseline (the first in a main round), or
1019
+ * a control after a kill. Passing, it lets the test take mutants in this
1020
+ * worker and confirms the kills before it on this server; failing, it puts
1021
+ * them in doubt, and a test that fails so twice in an invocation is not run
1022
+ * there again.
1023
+ */
1024
+ function settleControl(pass, ended, shape) {
1025
+ const test = ended.original;
1026
+ const passed = ended.outcome === "passed";
1027
+ if (ended.kind === "baseline" || shape.baselines) {
1028
+ // A test passes without a mutant once a control passed; it fails
1029
+ // without one where none did.
1030
+ if (passed)
1031
+ writeJson(`${pass.shared}/baseline/${key(test)}`, "passed");
1032
+ else if (ended.outcome !== "skipped" && baselineOf(pass, test) === undefined)
1033
+ writeJson(`${pass.shared}/baseline/${key(test)}`, "failed");
1034
+ }
1035
+ const pending = `${pass.round}/pending/${ended.invocation}/${key(test)}`;
1036
+ for (const name of entries(pending)) {
1037
+ const kill = readJsonOr(`${pending}/${name}`, undefined);
1038
+ // A kill that ended after this control started waits for the next.
1039
+ if (!kill || kill.endedAt > ended.startedAt)
1040
+ continue;
1041
+ rmSync(`${pending}/${name}`, { force: true });
1042
+ if (passed && !ended.beside) {
1043
+ const entry = mutantOf(pass, kill.id);
1044
+ giveVerdict(pass, { id: kill.id, status: "killed", killedBy: kill.test, reason: `${kill.message ?? "the test failed"}${suffix(shape, entry)}`, tests: 1, durationMs: kill.durationMs });
1045
+ }
1046
+ else
1047
+ mark(`${pass.round}/doubt/${key(kill.id)}`);
1048
+ }
1049
+ if (passed) {
1050
+ passedHere.add(test);
1051
+ return;
1052
+ }
1053
+ if (ended.outcome === "skipped")
1054
+ return;
1055
+ passedHere.delete(test);
1056
+ mark(`${pass.round}/unreliable/${ended.invocation}/${key(test)}`);
1057
+ writeFileSync(`${pass.round}/unreliable/${ended.invocation}/${key(test)}/${ended.worker}-${Date.now()}`, "");
1058
+ }
1059
+
1060
+ /** Whether a round runs mutants side by side on a shared server: the main round, and the rest of what it left. */
1061
+ export function shared(kind) {
1062
+ return kind === "main" || kind === "rest";
1063
+ }
1064
+
1065
+ /**
1066
+ * Whether the attempt's mutant ran in this worker's own process: code the
1067
+ * test itself runs, in a process the strong pass otherwise keeps. Such a
1068
+ * worker is not used again.
1069
+ */
1070
+ export function ranInWorker(claimed, attemptId) {
1071
+ if (!claimed || claimed.kind !== "mutant")
1072
+ return false;
1073
+ const strong = globalThis[Symbol.for("supercov.strongMutation")];
1074
+ return Boolean(strong?.requestHits?.get?.(`${attemptId}\0${claimed.mutant}`));
556
1075
  }
557
1076
 
558
1077
  /**