supercov 4.29.3 → 4.29.5

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