supercov 4.29.4 → 4.29.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/cli.md CHANGED
@@ -542,7 +542,9 @@ phpunit`). See `docs/design/strong-mutation.md`,
542
542
  job's run holds its share's verdicts, `merge` keeps them all in the merged
543
543
  run, and a later `supercov mutants` keeps each verdict nothing changed could
544
544
  move from whichever earlier run holds it (see
545
- [Combine shards](#combine-shards)).
545
+ [Combine shards](#combine-shards)). `supercov mutants --shard` measures a
546
+ run of its own even on an unchanged checkout, so a job never saves into a
547
+ run it restored, which every job of its round holds a copy of.
546
548
  - `--critical <glob>` (repeatable): every mutant there must be killed or
547
549
  accepted, or the command fails.
548
550
  - `--fail-on survived,timeout,no-coverage,error`: fail on any asked mutant with
@@ -559,6 +561,10 @@ phpunit`). See `docs/design/strong-mutation.md`,
559
561
  - `--budget <seconds>` stops the pass once it is spent: it ends as a finished
560
562
  pass, its verdicts saved, and says how many mutants it left for the next.
561
563
  The cheapest mutants run first, by their tests' recorded times.
564
+ - `--timeout-factor <x>`: a Playwright test that runs with a mutant is
565
+ stopped past x times its baseline + 5 s (default 1.5, StrykerJS's), and the
566
+ mutant is a `timeout`. `SUPERCOV_STRONG_TIMEOUT_FACTOR` sets it where the
567
+ option is not given.
562
568
  - After an edit, `supercov mutants` measures the checkout again and keeps an
563
569
  earlier run's verdict for each mutant whose file is as it was and whose
564
570
  candidate tests, and their test files, nothing changed could reach (as
@@ -1211,8 +1217,11 @@ adds none, and where its tests ran a mutant, a verdict that needs values they
1211
1217
  did not record is `unknown`.
1212
1218
 
1213
1219
  The merged run keeps the strong verdicts the runs saved (`mutants test`,
1214
- `--shard` among them), by mutant, and `merge` prints how many and from which
1215
- runs. A kill in any run is a kill. A survival stands only where the run that
1220
+ `--shard` among them), by mutant, and `merge` prints how many, how many came
1221
+ from each run, and how many the merged run's plan decides without running
1222
+ them (`1265 strong verdict(s) kept from runs r8, r7: 1103 from r8, 150 from
1223
+ r7, 12 the merged run's plan decides`). A verdict two runs hold alike counts
1224
+ for the first run named. A kill in any run is a kill. A survival stands only where the run that
1216
1225
  let the mutant survive measured every test of the merged suite that could
1217
1226
  kill it; where another run's tests could, and it has no verdict, the mutant is
1218
1227
  left for a pass over the merged run to run. An error stands only where no run
@@ -1220,7 +1229,16 @@ holds anything else. A run whose verdicts are of another mutant set than the
1220
1229
  merged run lists lends none, and `merge` names it; a run some of whose tests
1221
1230
  another measured again lends none either. Split a strong pass across jobs this
1222
1231
  way: each job measures and runs `supercov mutants --shard k/n -- <command>`,
1223
- and the last merges (see `docs/mutation.md`, A pass split across jobs).
1232
+ and the last merges (see `docs/mutation.md`, A pass split across jobs). A
1233
+ second round on the same commit restores the first round's runs and does the
1234
+ same: each job measures a run of its own, which keeps the restored runs'
1235
+ verdicts and replaces them, and the last job's `merge` takes the new runs.
1236
+
1237
+ A run named twice is refused (`Each merged run must be unique: r1 is named
1238
+ more than once`): copies of one run that several jobs saved verdicts into
1239
+ share its id, and `.supercov/runs` holds one of them. Up to 4.29.5,
1240
+ `supercov mutants --shard` on a checkout unchanged since the runs it restored
1241
+ saved into the latest of them; run such a round again.
1224
1242
 
1225
1243
  `assertions assess` assesses a merged run across every suite merged into it,
1226
1244
  reusing the answers saved when its parts were assessed. `tests affected` of a
@@ -1316,6 +1334,7 @@ terminal or offline environment after the package has been downloaded.
1316
1334
  | `SUPERCOV_KEEP_WORKSPACE` | Set to `1` to leave the instrumented copy of the project in `.supercov/workspaces/` after the run, to inspect what the command ran |
1317
1335
  | `SUPERCOV_MUTANTS` | Set to `1` to measure a run with the probes that record the values its mutants' verdicts read, and list its mutants as it runs (see [Mutants](#mutants)); a plain run lists none and places no probe |
1318
1336
  | `SUPERCOV_STRONG_WORKERS` | How many test processes a JavaScript or Python strong pass runs at once (default: about one per CPU) |
1337
+ | `SUPERCOV_STRONG_TIMEOUT_FACTOR` | A Playwright strong pass's time limit for a test run with a mutant: this many times the test's baseline, + 5 s (default `1.5`; `--timeout-factor` overrides it) |
1319
1338
  | `SUPERCOV_COMMAND_TIMEOUT_MS` | Stop the test command after this many milliseconds: what is still running is asked to stop, then made to five seconds later, what ran is recorded, and Supercov exits `124`. No deadline by default |
1320
1339
 
1321
1340
  Examples:
package/docs/mutation.md CHANGED
@@ -104,7 +104,10 @@ summary gives the mutation score, every verdict counted, and ends with the
104
104
  mutants the tests let survive.
105
105
 
106
106
  - **Unchanged checkout.** The next `supercov mutants` reads the same run again
107
- and runs nothing it already decided.
107
+ and runs nothing it already decided. With `--shard` it measures a run of its
108
+ own all the same, as after an edit, so that each job's share is saved into a
109
+ run no other job writes (see
110
+ [A pass split across jobs](#a-pass-split-across-jobs)).
108
111
  - **After an edit.** It measures the checkout again and keeps an earlier
109
112
  verdict for each mutant whose file is as it was and whose candidate tests,
110
113
  and their test files, nothing changed could reach, as `runs latest tests
@@ -224,6 +227,10 @@ npx supercov runs latest mutants test --plan --json
224
227
  [A pass split across jobs](#a-pass-split-across-jobs)).
225
228
  - `--budget <seconds>` stops the pass once that time is spent, its verdicts
226
229
  saved, and leaves the rest for the next pass.
230
+ - `--timeout-factor <x>` (or `SUPERCOV_STRONG_TIMEOUT_FACTOR`) sets a
231
+ Playwright test's time limit when it runs with a mutant: x times its
232
+ baseline, + 5 s (default 1.5, StrykerJS's `timeoutFactor`). See
233
+ [Playwright](#javascript-and-typescript).
227
234
  - `--plan` prints what would run, and runs nothing.
228
235
 
229
236
  Some mutants no test can tell apart from the original. Accept them in
@@ -244,12 +251,20 @@ and stays the same while that code does.
244
251
 
245
252
  A large application suite's strong pass can be split across machines. Each
246
253
  job measures the whole suite and runs its share of the mutants; a last job
247
- merges the runs, and the merged run holds every job's verdicts:
254
+ merges the runs, and the merged run holds every job's verdicts. A pass whose
255
+ budgets leave mutants undecided goes on in another round, the same workflow run
256
+ again on the same commit, and later commits go on from where the last round
257
+ ended:
248
258
 
249
259
  ```yaml
250
260
  # Each of four jobs (matrix.shard 1 to 4):
251
261
  - uses: actions/cache/restore@v4
252
- with: { path: .supercov/runs, key: "mutants-${{ github.sha }}", restore-keys: "mutants-" }
262
+ with:
263
+ path: .supercov/runs
264
+ key: mutants-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }}
265
+ restore-keys: |
266
+ mutants-${{ github.sha }}-
267
+ mutants-
253
268
  - run: npx supercov mutants --shard ${{ matrix.shard }}/4 --budget 2400 -- npm test
254
269
  - uses: actions/upload-artifact@v4
255
270
  with: { name: "mutants-${{ matrix.shard }}", path: .supercov/runs, include-hidden-files: true }
@@ -258,11 +273,16 @@ merges the runs, and the merged run holds every job's verdicts:
258
273
  with: { pattern: "mutants-*", path: .supercov/runs, merge-multiple: true }
259
274
  - run: npx supercov merge
260
275
  - run: npx supercov runs latest mutants --status survived
261
- - run: npx supercov runs clean --keep 5 # the four jobs' runs and their merge
276
+ - run: npx supercov runs clean --keep 5 # this round's four runs and their merge
262
277
  - uses: actions/cache/save@v4
263
- with: { path: .supercov/runs, key: "mutants-${{ github.sha }}" }
278
+ with:
279
+ path: .supercov/runs
280
+ key: mutants-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }}
264
281
  ```
265
282
 
283
+ The cache key names the round, so each round saves its own; a round restores
284
+ the latest one saved for its commit, or else the latest one saved.
285
+
266
286
  `supercov mutants --shard k/n -- <command>` is `supercov -- <command>` with
267
287
  the mutants' probes on, then `runs latest mutants test --shard k/n`, keeping
268
288
  earlier verdicts as after an edit. Name the command after `--`: without it,
@@ -290,11 +310,28 @@ merge ([CLI reference](cli.md#combine-shards)).
290
310
  that run has no verdict for it, as a unit run merged with an end-to-end run
291
311
  can, the mutant is left undecided, and a pass over the merged run runs it.
292
312
  Verdicts of another mutant set are not kept, and the merge says whose.
313
+ - **Another round.** On the commit the restored runs measured, each job still
314
+ measures a run of its own: `supercov mutants --shard` never saves into a run
315
+ it restored, of which every job of the round holds a copy. It keeps every
316
+ verdict the restored runs hold (`429 verdict(s) kept from runs r4, r3, r2,
317
+ r1`), and the shares are of what is left. Each job's run replaces the
318
+ restored ones of its command, so the last job's `supercov merge` takes this
319
+ round's runs, whose verdicts hold the earlier rounds'. It says how many
320
+ verdicts came from each run (`1265 strong verdict(s) kept from runs r8, r7,
321
+ r6, r5: 802 from r8, 151 from r7, 160 from r6, 140 from r5, 12 the merged
322
+ run's plan decides`): a verdict two runs hold alike, as every job's copy of
323
+ the earlier rounds' verdicts, counts for the first run named.
293
324
  - **The next pass.** The restored runs lend their verdicts on a later
294
325
  commit: each job keeps every verdict nothing changed could move, from
295
326
  whichever earlier job's run holds it, and the shares are of what is left.
296
327
  Keep the merged run's parts with it: a merged run's `tests affected` is
297
328
  answered from them.
329
+ - **Copies of one run.** Up to 4.29.5, `supercov mutants --shard` on a
330
+ checkout unchanged since the runs it restored saved into the latest of them,
331
+ so every job of a second round wrote its share into a copy of one run. The
332
+ copies share an id, one directory of `.supercov/runs` holds one of them, and
333
+ `supercov merge` refuses a run named more than once, saying so. Run that
334
+ round again: each job now measures a run of its own.
298
335
 
299
336
  ### Runners without a driver
300
337
 
@@ -368,6 +405,26 @@ no mutants shows none of this.
368
405
  serves different mutants to different workers. A mutant of a server's
369
406
  start-up runs with the server started again for it. StrykerJS has no
370
407
  Playwright runner, so Playwright's verdicts are checked by hand (see below).
408
+ A test run with a mutant gets StrykerJS's time limit: its baseline (the
409
+ longest of its measured run and its runs without a mutant in the pass)
410
+ × 1.5 + 5 s, or its own timeout where that is shorter. Playwright's test
411
+ timeout is set to it, and a `test.setTimeout()` or `test.slow()` in the
412
+ test may shorten it but not lengthen it, so a click or an `expect` that
413
+ waits for an element the mutant broke ends there, not at its own 30 s. A
414
+ test that runs out of its limit makes its mutant a `timeout`, which counts
415
+ as detected; the summary says how many, and against what limit.
416
+ `--timeout-factor <x>` (or `SUPERCOV_STRONG_TIMEOUT_FACTOR`) changes the
417
+ 1.5: a suite whose tests' times vary widely between runs may want 2 or 3.
418
+ A mutant tries its candidates cheapest to a kill first (a test's time over
419
+ how likely it is to kill: one that infected the mutant counts as four
420
+ times likelier than one that only reached it), and a slow test runs it only
421
+ once its cheaper candidates let it live; a file's tests take one mutant
422
+ each in turn, so mutants are decided one after another rather than all at
423
+ the end. The progress lines name the tests with the most work left (how
424
+ many mutants wait for each, and its time a run) and the time the round
425
+ has left. A candidate in a project others start from (a login `setup`)
426
+ never runs with a mutant: a mutant no other test kills is an `error` that
427
+ says so.
371
428
  - **Jest and Mocha** run in resident runners, as StrykerJS's do; `node:test`,
372
429
  AVA, node-tap, `bun:test` and Vitest Browser Mode run one test file per
373
430
  start of the command, with the mutant on from its start.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "supercov",
3
- "version": "4.29.4",
3
+ "version": "4.29.6",
4
4
  "description": "Coverage, security and code quality for coding agents",
5
5
  "keywords": [
6
6
  "coverage",
@@ -125,14 +125,14 @@
125
125
  "test:windows-tls": "node scripts/windows-tls-test.mjs"
126
126
  },
127
127
  "optionalDependencies": {
128
- "@supercov/cli-darwin-arm64": "4.29.4",
129
- "@supercov/cli-darwin-x64": "4.29.4",
130
- "@supercov/cli-linux-arm64-gnu": "4.29.4",
131
- "@supercov/cli-linux-arm64-musl": "4.29.4",
132
- "@supercov/cli-linux-x64-gnu": "4.29.4",
133
- "@supercov/cli-linux-x64-musl": "4.29.4",
134
- "@supercov/cli-win32-arm64": "4.29.4",
135
- "@supercov/cli-win32-x64": "4.29.4"
128
+ "@supercov/cli-darwin-arm64": "4.29.6",
129
+ "@supercov/cli-darwin-x64": "4.29.6",
130
+ "@supercov/cli-linux-arm64-gnu": "4.29.6",
131
+ "@supercov/cli-linux-arm64-musl": "4.29.6",
132
+ "@supercov/cli-linux-x64-gnu": "4.29.6",
133
+ "@supercov/cli-linux-x64-musl": "4.29.6",
134
+ "@supercov/cli-win32-arm64": "4.29.6",
135
+ "@supercov/cli-win32-x64": "4.29.6"
136
136
  },
137
137
  "peerDependencies": {
138
138
  "@playwright/test": ">=1.55.0",
@@ -9,12 +9,23 @@
9
9
  // disk that every worker and every invocation of the pass share. A mutant
10
10
  // goes from candidate to candidate as copies take it, and stops at its first
11
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.
12
+ // mutant. A test's first run in each invocation is a control, with no
13
+ // mutant: the pass's baseline the first time; and after a kill, the test's
14
+ // next run is one too, the check that it still passes without the mutant on
15
+ // the same server, which confirms the kill. A harness may start several
16
+ // invocations at once, each with a share of the tests; they share the pass's
17
+ // files and decide the same way.
18
+ //
19
+ // The order (docs/design/strong-mutation.md, "Which candidate first"): a
20
+ // mutant's candidates are ordered cheapest to a kill first (each test's time
21
+ // over how likely it is to kill: those whose own evidence infected it are
22
+ // taken as likelier), so a slow test comes last; a file's copies run in
23
+ // sweeps, the k-th copy of each of its tests in turn, cheapest test first;
24
+ // and a copy takes, of the mutants waiting for its test, the one with the
25
+ // fewest earlier candidates still to try, the one its test infected, and the
26
+ // one closest to a verdict, in that order. So a slow test runs a mutant once
27
+ // its cheaper candidates let it live, and a file's tests finish one mutant
28
+ // before the next rather than one test's mutants before the next test's.
18
29
  //
19
30
  // The attempt's mutant goes into its scope, which reaches the app's server
20
31
  // with every request (header, cookies, child processes) and the page through
@@ -22,10 +33,17 @@
22
33
  // no request named, or is a server module's top level, or ran for a request
23
34
  // that named no test) is run alone afterwards, in an invocation of its own
24
35
  // 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.
36
+ // record the judge writes (javascript_run.rs). So do a kill (or a timeout)
37
+ // that ran beside another mutant's attempt or whose control failed (one test
38
+ // at a time), and the mutants one invocation had no room for.
39
+ //
40
+ // An attempt with a mutant has a time limit: its test's baseline (the
41
+ // longest of its measured run and every control of this pass that passed) ×
42
+ // the pass's timeout factor (1.5, `--timeout-factor`) + 5 s, StrykerJS's
43
+ // limit, or the test's own timeout where that is shorter. Playwright's test
44
+ // timeout is set to it, so an action or an `expect` that waits for what the
45
+ // mutant broke ends there; an attempt that ran out of it is a `timeout`,
46
+ // confirmed as a kill is.
29
47
  //
30
48
  // This module holds what the config, the fixture (playwright.mjs) and the
31
49
  // reporter (playwrightStrongReporter.mjs) share.
@@ -36,6 +54,10 @@ import { basename, dirname, resolve, sep } from "node:path";
36
54
  const TIMEOUT_FACTOR = 1.5;
37
55
  const TIMEOUT_CONSTANT_MS = 5_000;
38
56
  const DEFAULT_DURATION_MS = 1_000;
57
+ // How much likelier to kill a mutant a test is taken to be where its own
58
+ // evidence infected it than where it only reached it: what orders a mutant's
59
+ // candidates, with their times.
60
+ const INFECTED_LIKELIER = 4;
39
61
  const POLL_MS = 50;
40
62
  // Playwright makes every test case of every file it loads before the first
41
63
  // test runs, in the runner: an invocation holds about this many copies, and
@@ -50,6 +72,8 @@ export const PAGE_TIMEOUT_MARKER = "SUPERCOV_MUTANT_TIMEOUT";
50
72
 
51
73
  /** A copy's describe: `[supercov copy <k>]`, k from 1. */
52
74
  const COPY_TITLE = /^\[supercov copy (\d+)\]$/;
75
+ // The most costly tests a status file names.
76
+ const COSTLY_SHOWN = 3;
53
77
  export function copyTitle(copy) {
54
78
  return `[supercov copy ${copy}]`;
55
79
  }
@@ -84,8 +108,15 @@ export function strongPass() {
84
108
  };
85
109
  }
86
110
 
111
+ const keys = new Map();
87
112
  export function key(text) {
88
- return createHash("sha256").update(String(text)).digest("hex").slice(0, 24);
113
+ const said = String(text);
114
+ let found = keys.get(said);
115
+ if (found === undefined) {
116
+ found = createHash("sha256").update(said).digest("hex").slice(0, 24);
117
+ keys.set(said, found);
118
+ }
119
+ return found;
89
120
  }
90
121
 
91
122
  export function writeJson(path, value) {
@@ -135,9 +166,30 @@ export function mark(path) {
135
166
  }
136
167
  }
137
168
 
138
- function budgetOf(durations, factor = 1) {
139
- const longest = Math.max(DEFAULT_DURATION_MS, ...durations.map((ms) => ms ?? DEFAULT_DURATION_MS));
140
- return Math.ceil((longest * TIMEOUT_FACTOR + TIMEOUT_CONSTANT_MS) * factor);
169
+ /**
170
+ * How long a test takes without a mutant: the longest of its measured run
171
+ * and every control of it that passed in this pass, in any worker or round
172
+ * (a test whose time varies is given its slowest), and a second at least.
173
+ */
174
+ export function baselineMsOf(pass, original, test) {
175
+ let longest = Math.max(DEFAULT_DURATION_MS, test.durationMs ?? 0);
176
+ for (const name of entries(`${pass.shared}/durations/${key(original)}`))
177
+ longest = Math.max(longest, Number(name.split("-")[1]) || 0);
178
+ return longest;
179
+ }
180
+
181
+ /** A mutant attempt's time limit from its test's baseline: StrykerJS's `timeoutMS`. */
182
+ export function limitOf(baselineMs, factor) {
183
+ return Math.ceil(baselineMs * factor + TIMEOUT_CONSTANT_MS);
184
+ }
185
+
186
+ /** What a verdict says of an attempt that ran out of its time limit. */
187
+ function limitReason(attempt) {
188
+ const seconds = (ms) => `${(ms / 1000).toFixed(1)} s`;
189
+ const why = attempt.limitMs < limitOf(attempt.baselineMs, attempt.timeoutFactor)
190
+ ? "the test's own timeout"
191
+ : `${attempt.timeoutFactor} × its ${seconds(attempt.baselineMs)} baseline + ${TIMEOUT_CONSTANT_MS / 1000} s`;
192
+ return `ran past its time limit of ${seconds(attempt.limitMs)} (${why})`;
141
193
  }
142
194
 
143
195
  /**
@@ -176,7 +228,8 @@ function serialFilesOf(plan, tests, fullyParallel) {
176
228
  /**
177
229
  * The projects others depend on (`dependencies`, `teardown`): their tests,
178
230
  * 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.
231
+ * every invocation, with no mutant, whether or not a mutant needs them. A
232
+ * mutant's candidate among them is never run with it.
180
233
  */
181
234
  function setupProjectsOf(config) {
182
235
  const names = new Set();
@@ -195,6 +248,12 @@ function fullyParallelOf(config) {
195
248
  return projects.every((project) => project.fullyParallel ?? config?.fullyParallel ?? false);
196
249
  }
197
250
 
251
+ /** The project others start from that a plan test is in, by its name (`<project> > <file> > ...`). */
252
+ function inSetupProject(test, setupProjects) {
253
+ const name = test.name ?? "";
254
+ return setupProjects.find((project) => project && name.startsWith(`${project} > `));
255
+ }
256
+
198
257
  // A plan test's id as Playwright knows it: a Rust wasm run names a test by
199
258
  // its file too (`<file>::<id>`).
200
259
  function playwrightId(test) {
@@ -225,10 +284,12 @@ function declarationKey(file, title) {
225
284
  /**
226
285
  * The pass's work, worked out in the runner from the plan (or the job the
227
286
  * 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.
287
+ * takes them (cheapest to a kill first: by measured time, those whose own
288
+ * evidence infected it counted as likelier), each test's queue of mutants (those
289
+ * it is the likeliest killer of first), and how many copies each test needs:
290
+ * one for each mutant that may take it, one more for each control a kill may
291
+ * call for, and the first control. A candidate in a project others start
292
+ * from is never run with the mutant: the mutant's verdict says so.
232
293
  */
233
294
  function buildPass(pass, root, config) {
234
295
  const plan = readJson(pass.planPath);
@@ -245,11 +306,13 @@ function buildPass(pass, root, config) {
245
306
  const restarts = [];
246
307
  const deferred = [];
247
308
  const otherRunners = { ...(job?.otherRunners ?? {}) };
309
+ const setupOnly = { ...(job?.setupOnly ?? {}) };
310
+ const setupProjects = setupProjectsOf(config);
248
311
  const mutants = [];
249
312
  if (job && job.kind !== "main") {
250
313
  for (const entry of job.mutants) {
251
314
  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 });
315
+ mutants.push({ id: entry.id, mutant: entry.mutant, tests: [...new Set(all)], reason: entry.reason });
253
316
  }
254
317
  // A serial round runs one test at a time: what it kills, nothing
255
318
  // beside it did.
@@ -284,34 +347,56 @@ function buildPass(pass, root, config) {
284
347
  });
285
348
  continue;
286
349
  }
287
- // Its candidates, cheapest first (the plan's order), those whose own
288
- // evidence shows it infected first of all.
350
+ // Its candidates, and which of them infected it.
289
351
  const own = [];
290
352
  const others = new Set();
353
+ const setup = new Set();
291
354
  for (const candidate of mutant.candidates) {
292
355
  const test = plan.tests[candidate.test];
293
- if (test && tests[playwrightId(test)])
356
+ const project = test && tests[playwrightId(test)] && inSetupProject(test, setupProjects);
357
+ if (project)
358
+ setup.add(project);
359
+ else if (test && tests[playwrightId(test)])
294
360
  own.push({ id: playwrightId(test), infected: candidate.reason === "infected" });
295
361
  else if (test)
296
362
  others.add(test.runner);
297
363
  }
298
364
  if (others.size)
299
365
  otherRunners[mutant.id] = [...others].sort();
366
+ if (setup.size)
367
+ setupOnly[mutant.id] = [...setup].sort();
300
368
  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 }
369
+ const unrun = unrunReason(otherRunners[mutant.id], setupOnly[mutant.id], "its candidates");
370
+ immediate.push(unrun
371
+ ? { id: mutant.id, status: "error", reason: unrun, tests: 0, durationMs: 0 }
303
372
  : { id: mutant.id, status: "survived", reason: "no-runnable-candidate", tests: 0, durationMs: 0 });
304
373
  continue;
305
374
  }
306
- const ordered = [...new Set([...own.filter((test) => test.infected), ...own.filter((test) => !test.infected)].map((test) => test.id))];
375
+ // Cheapest to a kill first: each test's measured time (one the
376
+ // run timed none of counts as a second, the least a baseline
377
+ // is), over how likely it is to kill, a test whose own evidence
378
+ // infected it `INFECTED_LIKELIER` times likelier than one that
379
+ // only reached it; the plan's order between equals. So a test
380
+ // that infected it goes first unless it is that much slower,
381
+ // and a slow test goes last.
382
+ const costOf = (test) => (tests[test.id].durationMs ?? DEFAULT_DURATION_MS) * (test.infected ? 1 : INFECTED_LIKELIER);
383
+ own.sort((a, b) => costOf(a) - costOf(b));
384
+ const infected = [...new Set(own.filter((test) => test.infected).map((test) => test.id))];
385
+ const ordered = [...new Set(own.map((test) => test.id))];
307
386
  const switched = `${mutant.file}#${found.index}`;
308
387
  if (mutant.serverWide) {
309
- restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: mutant.serverWide, budgetFactor: 1 });
388
+ restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: mutant.serverWide });
310
389
  continue;
311
390
  }
312
- mutants.push({ id: mutant.id, mutant: switched, tests: ordered, budgetFactor: 1 });
391
+ mutants.push({ id: mutant.id, mutant: switched, tests: ordered, infected });
313
392
  }
314
393
  }
394
+ // What a survivor's verdict says of the candidates it was not run with.
395
+ for (const entry of mutants) {
396
+ const unrun = unrunReason(otherRunners[entry.id], setupOnly[entry.id], "its other candidates");
397
+ if (unrun)
398
+ entry.unrun = unrun;
399
+ }
315
400
  // Each test's queue, and the copies the round's mutants need, as many as
316
401
  // an invocation holds; the mutants past them wait for the next.
317
402
  const limit = copiesPerInvocation();
@@ -319,7 +404,10 @@ function buildPass(pass, root, config) {
319
404
  let copies = 0;
320
405
  const entries = {};
321
406
  for (const entry of mutants) {
322
- const added = entry.tests.reduce((sum, id) => sum + 2 + (queues.has(id) ? 0 : 1), 0);
407
+ // Two copies a candidate (an attempt, and a control should it
408
+ // kill), one more where it is not the first (a sweep it may wait
409
+ // out), and each test's first run.
410
+ const added = entry.tests.reduce((sum, id, at) => sum + 2 + (at > 0 ? 1 : 0) + (queues.has(id) ? 0 : 1), 0);
323
411
  if (copies && copies + added > limit && kind === "main") {
324
412
  deferred.push({ id: entry.id });
325
413
  continue;
@@ -333,14 +421,21 @@ function buildPass(pass, root, config) {
333
421
  });
334
422
  }
335
423
  const declared = {};
424
+ // What orders a sweep of a file's copies: each test's measured time.
425
+ const costs = {};
336
426
  for (const [id, queue] of queues) {
337
- // The likeliest killers' mutants first; the plan's order between equals.
427
+ // The likeliest killers' mutants first; the plan's order between
428
+ // equals. A copy takes from it by each mutant's standing then.
338
429
  queue.sort((a, b) => a.at - b.at);
339
430
  const test = tests[id];
340
431
  test.jobs = queue.length;
341
432
  test.queue = queue.map((job) => job.id);
342
433
  const where = declarationKey(resolve(root, test.file), test.title);
343
- declared[where] = Math.max(declared[where] ?? 0, 2 * queue.length + 1);
434
+ // A copy for each sweep the test may wait out: one for each mutant
435
+ // with a candidate before it.
436
+ const later = queue.filter((job) => job.at > 0).length;
437
+ declared[where] = Math.max(declared[where] ?? 0, 2 * queue.length + later + 1);
438
+ costs[where] = Math.max(costs[where] ?? 0, test.durationMs ?? DEFAULT_DURATION_MS);
344
439
  }
345
440
  return {
346
441
  pass: pass.name,
@@ -354,18 +449,36 @@ function buildPass(pass, root, config) {
354
449
  batch: kind === "alone" && Boolean(job?.batch),
355
450
  // A main round's first control of a test is its baseline.
356
451
  baselines: kind === "main",
452
+ // A mutant attempt's time limit: its test's baseline × this + 5 s.
453
+ timeoutFactor: Number(plan.timeoutFactor) > 0 ? Number(plan.timeoutFactor) : TIMEOUT_FACTOR,
357
454
  tests,
358
455
  declared,
456
+ costs,
359
457
  entries,
360
- setupProjects: setupProjectsOf(config),
458
+ setupProjects,
361
459
  concurrency,
362
460
  immediate,
363
461
  restarts,
364
462
  otherRunners,
463
+ setupOnly,
365
464
  deferred,
366
465
  };
367
466
  }
368
467
 
468
+ /**
469
+ * Why a mutant no Playwright test killed has no verdict of `survived`: the
470
+ * candidates this pass does not run with it (`lead` names them), or
471
+ * `undefined` where it runs every one.
472
+ */
473
+ export function unrunReason(others, setup, lead) {
474
+ const parts = [];
475
+ if (others?.length)
476
+ parts.push(`${lead} ran under ${others.join(", ")}, which this pass does not run`);
477
+ if (setup?.length)
478
+ parts.push(`${lead} are in the project${setup.length > 1 ? "s" : ""} ${setup.map((name) => JSON.stringify(name)).join(", ")}, which the others start from and which run${setup.length > 1 ? "" : "s"} without a mutant`);
479
+ return parts.length ? parts.join("; ") : undefined;
480
+ }
481
+
369
482
  /** The round's work: built and written by the runner, read by its judge. */
370
483
  let passCache;
371
484
  export function loadPass(pass) {
@@ -394,8 +507,10 @@ function writeRoundFiles(pass, work) {
394
507
  everywhere: work.everywhere,
395
508
  batch: work.batch,
396
509
  baselines: work.baselines,
510
+ timeoutFactor: work.timeoutFactor,
397
511
  tests,
398
512
  declared: work.declared,
513
+ costs: work.costs,
399
514
  setupProjects: work.setupProjects,
400
515
  concurrency: work.concurrency,
401
516
  });
@@ -533,6 +648,11 @@ function invocationMutant(pass) {
533
648
  * describe runs as a default one: in order, in one worker, but a failed test
534
649
  * (a kill) does not skip the rest; a test that leans on an earlier one's
535
650
  * state is caught by its control.
651
+ *
652
+ * A worker runs a file's tests in the order they are declared, so the
653
+ * copies are arranged in sweeps as they are declared (`arrange`): after the
654
+ * tests themselves, every test's first copy, cheapest test first, then
655
+ * every test's second copy, and so on, beside the tests of their describe.
536
656
  */
537
657
  export function installCopies(baseTest) {
538
658
  if (!copying())
@@ -552,9 +672,18 @@ export function installCopies(baseTest) {
552
672
  if (type === "skip" || type === "fixme")
553
673
  return;
554
674
  const suite = this._currentSuite?.(location, "test()");
555
- const copies = copiesOf(suite?._requireFile ?? location?.file, title);
556
- for (let copy = 1; copy < copies; copy++)
675
+ const file = suite?._requireFile ?? location?.file;
676
+ const copies = copiesOf(file, title);
677
+ if (copies < 2)
678
+ return;
679
+ const cost = costOf(file, title);
680
+ for (let copy = 1; copy < copies; copy++) {
557
681
  describe.call(this, "default", location, copyTitle(copy), () => declare.call(this, type, location, title, fnOrDetails, fn));
682
+ const made = Array.isArray(suite?._entries) ? suite._entries[suite._entries.length - 1] : undefined;
683
+ if (made)
684
+ sweeps.set(made, { copy, cost });
685
+ }
686
+ arrange(suite);
558
687
  };
559
688
  prototype._describe = function (type, ...rest) {
560
689
  return describe.call(this, type === "serial" ? "default" : type === "serial.only" ? "only" : type, ...rest);
@@ -569,8 +698,36 @@ let declaredCopies;
569
698
  function copiesOf(file, title) {
570
699
  if (!file)
571
700
  return 1;
572
- declaredCopies ??= readJsonOr(`${strongPass().round}/worker.json`, { declared: {} }).declared;
573
- return declaredCopies[declarationKey(file, title)] ?? 1;
701
+ declaredCopies ??= readJsonOr(`${strongPass().round}/worker.json`, { declared: {}, costs: {} });
702
+ return declaredCopies.declared[declarationKey(file, title)] ?? 1;
703
+ }
704
+
705
+ /** A test's measured time, which places its copies in each sweep. */
706
+ function costOf(file, title) {
707
+ return declaredCopies.costs?.[declarationKey(file, title)] ?? DEFAULT_DURATION_MS;
708
+ }
709
+
710
+ /** Each copy's describe: which copy it is and its test's cost. */
711
+ const sweeps = new WeakMap();
712
+
713
+ /**
714
+ * Puts a describe's entries in sweeps: what is not a copy first, as
715
+ * declared, then the copies by their number, the cheapest test's first,
716
+ * the declared order between equals. The worker runs a file's tests in this
717
+ * order (it loads the file itself), so a file's tests take one mutant each
718
+ * in turn rather than one test all its mutants before the next test starts,
719
+ * and a slow test runs last in each sweep. A Playwright whose suites keep
720
+ * their entries otherwise is left as declared.
721
+ */
722
+ export function arrange(suite) {
723
+ const list = suite?._entries;
724
+ if (!Array.isArray(list))
725
+ return;
726
+ const placed = list.map((entry, at) => ({ entry, at, sweep: sweeps.get(entry) ?? { copy: 0, cost: 0 } }));
727
+ placed.sort((a, b) => a.sweep.copy - b.sweep.copy || a.sweep.cost - b.sweep.cost || a.at - b.at);
728
+ placed.forEach((place, at) => {
729
+ list[at] = place.entry;
730
+ });
574
731
  }
575
732
 
576
733
  /** How a test did with no mutant: `passed`, `failed`, or `undefined` before it ended. */
@@ -662,14 +819,28 @@ export function invocation() {
662
819
  return process.env["SUPERCOV_PLAYWRIGHT_INVOCATION"] ?? "0";
663
820
  }
664
821
 
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();
822
+ /**
823
+ * Whether a test's next run in this invocation has no mutant: none of its
824
+ * runs without one passed here yet (or the last failed), or a kill of it
825
+ * here waits for one to confirm it. A test runs with a mutant only on a
826
+ * server where it passed without one, whichever worker runs it.
827
+ */
828
+ function needsControl(pass, test) {
829
+ return !existsSync(readyPath(pass, invocation(), test)) || entries(`${pass.round}/pending/${invocation()}/${key(test)}`).length > 0;
830
+ }
831
+
832
+ function readyPath(pass, at, test) {
833
+ return `${pass.round}/ready/${at}/${key(test)}`;
834
+ }
835
+
836
+ function claimPath(pass, id, test) {
837
+ return `${pass.round}/claims/${key(id)}/${key(test)}`;
838
+ }
668
839
 
669
840
  /** Whether a mutant needs no more attempts: a verdict given, killed, or held for a later round. */
670
841
  function settled(pass, id) {
671
842
  const at = key(id);
672
- return existsSync(`${pass.shared}/verdicts/${at}`) || existsSync(`${pass.round}/killed/${at}`) || existsSync(`${pass.round}/held/${at}`);
843
+ return existsSync(`${pass.shared}/verdicts/${at}`) || existsSync(`${pass.round}/killed/${at}`);
673
844
  }
674
845
 
675
846
  /**
@@ -695,44 +866,104 @@ function inFlightSince(pass, id) {
695
866
  }
696
867
 
697
868
  /**
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.
869
+ * The next mutant for a copy of `test`: of its queue, one not settled, not
870
+ * yet tried against it and run by no other attempt now, the best by its
871
+ * standing (`standingOf`). Taken by making its mark, which only one copy
872
+ * can. Where even the best has a candidate before `test` still to try (a
873
+ * cheaper test, or one likelier to kill it), the copy takes none while the
874
+ * test's copies left (`copiesLeft`, after this one) still cover every mutant
875
+ * waiting for it and a control for each: the test's next copy, a sweep
876
+ * later, looks again. So a slow test's copies go to the mutants its cheaper
877
+ * candidates let live, and it runs every mutant all the same before its
878
+ * copies are spent.
701
879
  */
702
- function takeJob(pass, test, only, budgetMs) {
880
+ function takeJob(pass, shape, test, only, limitMs, copiesLeft) {
703
881
  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;
882
+ // A test that fails without any mutant is no candidate: it holds back
883
+ // no later one.
884
+ const failed = new Map();
885
+ const unrunnable = (other) => {
886
+ if (!failed.has(other))
887
+ failed.set(other, baselineOf(pass, other) === "failed");
888
+ return failed.get(other);
889
+ };
890
+ let busy;
891
+ for (;;) {
892
+ busy = [];
893
+ let best;
894
+ let waiting = 0;
895
+ for (let at = queue.done; at < queue.ids.length; at++) {
896
+ const id = queue.ids[at];
897
+ if (only !== undefined && id !== only)
898
+ continue;
899
+ if (existsSync(claimPath(pass, id, test)) || settled(pass, id)) {
900
+ // Nothing undoes either: no copy looks at it again.
901
+ if (at === queue.done)
902
+ queue.done += 1;
903
+ continue;
904
+ }
905
+ waiting += 1;
906
+ const since = inFlightSince(pass, id);
907
+ if (since !== undefined) {
908
+ // One that has run longer than this test's limit may hang:
909
+ // a second attempt would only wait as long.
910
+ if (Date.now() - since < limitMs)
911
+ busy.push(id);
912
+ continue;
913
+ }
914
+ const standing = standingOf(pass, shape, id, test, at, unrunnable);
915
+ if (!best || before(standing, best.standing))
916
+ best = { id, standing };
723
917
  }
724
- if (mark(tried))
725
- return id;
918
+ if (!best)
919
+ break;
920
+ const controls = entries(`${pass.round}/pending/${invocation()}/${key(test)}`).length;
921
+ if (only === undefined && best.standing[0] > 0 && copiesLeft >= 2 * waiting + controls)
922
+ return undefined;
923
+ if (mark(claimPath(pass, best.id, test)))
924
+ return best.id;
925
+ // Another copy took it first: choose again.
726
926
  }
727
927
  // Every mutant left runs elsewhere now: one of them here too, rather
728
928
  // than leave this test's copies unused while its attempt runs.
729
929
  for (const id of busy) {
730
- if (only === undefined && !settled(pass, id) && mark(`${pass.round}/claims/${key(id)}/${key(test)}`))
930
+ if (only === undefined && !settled(pass, id) && mark(claimPath(pass, id, test)))
731
931
  return id;
732
932
  }
733
933
  return undefined;
734
934
  }
735
935
 
936
+ /**
937
+ * Where a mutant stands for a copy of `test`, best first: how many of its
938
+ * candidates before `test` are still to try (none: its cheaper candidates
939
+ * let it live, and this test is the next that may kill it), whether `test`
940
+ * infected it, how long its candidates still to try take (the closest to a
941
+ * verdict first), and its place in the test's queue.
942
+ */
943
+ function standingOf(pass, shape, id, test, at, unrunnable) {
944
+ const entry = mutantOf(pass, id);
945
+ const passed = passedWith(pass, id);
946
+ const place = entry.tests.indexOf(test);
947
+ let earlier = 0;
948
+ let leftMs = 0;
949
+ entry.tests.forEach((other, index) => {
950
+ if (passed.has(key(other)) || unrunnable(other))
951
+ return;
952
+ leftMs += shape.tests[other]?.durationMs ?? DEFAULT_DURATION_MS;
953
+ if (index < place)
954
+ earlier += 1;
955
+ });
956
+ return [earlier, entry.infected?.includes(test) ? 0 : 1, leftMs, at];
957
+ }
958
+
959
+ function before(a, b) {
960
+ for (let at = 0; at < a.length; at++) {
961
+ if (a[at] !== b[at])
962
+ return a[at] < b[at];
963
+ }
964
+ return false;
965
+ }
966
+
736
967
  /** Whether a test has mutants left to take, or kills to confirm, in this invocation. */
737
968
  function workLeft(pass, test) {
738
969
  if (entries(`${pass.round}/pending/${invocation()}/${key(test)}`).length)
@@ -740,12 +971,46 @@ function workLeft(pass, test) {
740
971
  const queue = queueOf(pass, test);
741
972
  for (let at = queue.done; at < queue.ids.length; at++) {
742
973
  const id = queue.ids[at];
743
- if (!existsSync(`${pass.round}/claims/${key(id)}/${key(test)}`) && !settled(pass, id))
974
+ if (!existsSync(claimPath(pass, id, test)) && !settled(pass, id))
744
975
  return true;
745
976
  }
746
977
  return false;
747
978
  }
748
979
 
980
+ /**
981
+ * The work left in this invocation's tests, for the progress lines: how
982
+ * many mutants wait for each test it runs (not settled, not yet tried
983
+ * against it), how long that takes at the test's baseline, and the costliest
984
+ * few tests, those whose runs left take longest. `held` are the tests the
985
+ * invocation runs.
986
+ */
987
+ export function queuedWork(pass, work, held) {
988
+ const settledNow = new Set([...entries(`${pass.shared}/verdicts`), ...entries(`${pass.round}/killed`)]);
989
+ const claimed = new Map();
990
+ const tests = [];
991
+ let ms = 0;
992
+ for (const id of held) {
993
+ const test = work.tests[id];
994
+ let waiting = 0;
995
+ for (const mutant of test?.queue ?? []) {
996
+ const at = key(mutant);
997
+ if (settledNow.has(at))
998
+ continue;
999
+ if (!claimed.has(at))
1000
+ claimed.set(at, new Set(entries(`${pass.round}/claims/${at}`)));
1001
+ if (!claimed.get(at).has(key(id)))
1002
+ waiting += 1;
1003
+ }
1004
+ if (!waiting)
1005
+ continue;
1006
+ const baselineMs = baselineMsOf(pass, id, test);
1007
+ ms += waiting * baselineMs;
1008
+ tests.push({ title: test.title ?? id, waiting, baselineMs, limitMs: limitOf(baselineMs, work.timeoutFactor) });
1009
+ }
1010
+ tests.sort((a, b) => b.waiting * b.baselineMs - a.waiting * a.baselineMs || a.title.localeCompare(b.title));
1011
+ return { ms, tests: tests.slice(0, COSTLY_SHOWN) };
1012
+ }
1013
+
749
1014
  /**
750
1015
  * Notes that an attempt runs, and whether another mutant's attempt runs
751
1016
  * beside it in this invocation (its server): each attempt that starts looks
@@ -769,10 +1034,33 @@ function startRunning(pass, testId, mutant) {
769
1034
  return { running: `${running}/${mine}`, beside };
770
1035
  }
771
1036
 
1037
+ /**
1038
+ * Holds a mutant attempt to its time limit (`timeout`, from the test's
1039
+ * start): the test's own `test.setTimeout()` and `test.slow()` may shorten
1040
+ * it, never lengthen it. Its baseline ran with them, so its time already
1041
+ * says how long they let it take.
1042
+ */
1043
+ function holdTimeout(testInfo, timeout) {
1044
+ const setTimeout = testInfo.setTimeout.bind(testInfo);
1045
+ setTimeout(timeout);
1046
+ testInfo.setTimeout = (asked) => setTimeout(asked > 0 ? Math.min(asked, timeout) : timeout);
1047
+ // `test.slow()` in a test's body (Playwright's own modifier): it
1048
+ // triples the time, which is held to the limit again.
1049
+ const modifier = testInfo._modifier;
1050
+ if (typeof modifier !== "function")
1051
+ return;
1052
+ testInfo._modifier = function (type, ...rest) {
1053
+ const result = modifier.call(this, type, ...rest);
1054
+ if (type === "slow")
1055
+ setTimeout(Math.min(this.timeout, timeout));
1056
+ return result;
1057
+ };
1058
+ }
1059
+
772
1060
  /**
773
1061
  * What this copy of a test does: `undefined` outside strong mode, `null` to
774
1062
  * 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
1063
+ * (`file#index`), and its time limit. A file whose tests the measured run
776
1064
  * never ran side by side runs one at a time here too.
777
1065
  */
778
1066
  export async function strongClaim(testInfo) {
@@ -795,9 +1083,10 @@ export async function strongClaim(testInfo) {
795
1083
  if (entries(unreliable).length >= CONTROL_FAILURES)
796
1084
  return null;
797
1085
  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.
1086
+ if (!shape.everywhere && needsControl(pass, original)) {
1087
+ // The test's first run in this invocation, the first since it failed
1088
+ // here, or the first since a kill here: without a mutant, the
1089
+ // round's baseline or a kill's control.
801
1090
  if (!workLeft(pass, original))
802
1091
  return null;
803
1092
  attempt = shape.baselines && baselineOf(pass, original) === undefined
@@ -808,31 +1097,30 @@ export async function strongClaim(testInfo) {
808
1097
  // A later round's test that failed without any mutant in the main one.
809
1098
  if (baselineOf(pass, original) === "failed")
810
1099
  return null;
811
- const id = takeJob(pass, original, shape.batch ? invocationMutant(pass) ?? null : undefined, budgetOf([test.durationMs]));
1100
+ const baselineMs = baselineMsOf(pass, original, test);
1101
+ const derived = limitOf(baselineMs, shape.timeoutFactor);
1102
+ // The test's own timeout, where shorter, ends it first anyway.
1103
+ const limitMs = configured > 0 ? Math.min(derived, configured) : derived;
1104
+ // This copy's number, and the test's copies after it in this
1105
+ // invocation: what a copy that waits a sweep may spend.
1106
+ const copy = withoutCopy(testInfo.titlePath).copy;
1107
+ const copiesLeft = copiesOf(testInfo.file, testInfo.title) - 1 - copy;
1108
+ const id = takeJob(pass, shape, original, shape.batch ? invocationMutant(pass) ?? null : undefined, limitMs, copiesLeft);
812
1109
  if (!id)
813
1110
  return null;
814
1111
  const entry = mutantOf(pass, id);
815
- attempt = { kind: "mutant", id, mutant: entry.mutant, budgetMs: budgetOf([test.durationMs], entry.budgetFactor ?? 1) };
1112
+ attempt = { kind: "mutant", id, mutant: entry.mutant, baselineMs, limitMs, timeoutFactor: shape.timeoutFactor };
816
1113
  mark(`${pass.round}/inflight/${key(id)}`);
817
1114
  writeFileSync(`${pass.round}/inflight/${key(id)}/${process.pid}-${key(testInfo.testId)}`, String(Date.now()));
818
1115
  }
819
1116
  const lock = shape.concurrency.workers !== 1 && shape.concurrency.serialFiles.includes(test.file)
820
1117
  ? await lockFile(pass, test.file)
821
1118
  : undefined;
822
- // The test's time from here: a mutant's from the test's measured
823
- // duration and the time Playwright gives an assertion and an action to
824
- // fail in (a failing `expect` waits for its own timeout), a control's as
825
- // configured.
826
- if (attempt.kind === "mutant") {
827
- const expectTimeout = testInfo.project?.expect?.timeout ?? 5_000;
828
- const actionTimeout = testInfo.project?.use?.actionTimeout ?? 0;
829
- // Playwright itself ends the test at its configured timeout (the
830
- // project's, or its own `test.slow()` / `describe.configure`), and an
831
- // assertion may wait up to there with a timeout of its own: that is
832
- // the floor.
833
- const budget = Math.max(attempt.budgetMs + expectTimeout + actionTimeout, configured > 0 ? configured : 0);
834
- testInfo.setTimeout(Date.now() - started + budget);
835
- }
1119
+ // The test's time from here: a mutant's its limit, which ends whatever
1120
+ // the test waits on there (an action, an `expect` with a timeout of its
1121
+ // own); a control's, the baseline's above all, as configured.
1122
+ if (attempt.kind === "mutant")
1123
+ holdTimeout(testInfo, Date.now() - started + attempt.limitMs);
836
1124
  else if (configured > 0)
837
1125
  testInfo.setTimeout(Date.now() - started + configured);
838
1126
  const { running, beside } = startRunning(pass, testInfo.testId, attempt.mutant);
@@ -845,6 +1133,7 @@ export async function strongClaim(testInfo) {
845
1133
  kind: attempt.kind,
846
1134
  id: attempt.id,
847
1135
  mutant: attempt.mutant,
1136
+ ...(attempt.kind === "mutant" ? { baselineMs: attempt.baselineMs, limitMs: attempt.limitMs, timeoutFactor: attempt.timeoutFactor } : {}),
848
1137
  startedAt: Date.now(),
849
1138
  lock,
850
1139
  running,
@@ -868,18 +1157,20 @@ export function firstWords(message) {
868
1157
 
869
1158
  /**
870
1159
  * 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.
1160
+ * an action failed, or the test threw), `timed-out` (its time ran out first:
1161
+ * Playwright's timeout, or an `expect` it cut short, which says so, came
1162
+ * before any other error; what failed after it failed for it), or
1163
+ * `skipped`; and why it failed.
873
1164
  */
874
1165
  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];
1166
+ const timeout = (error) => TEST_TIMEOUT.test(stripAnsi(error?.message ?? ""));
1167
+ const reported = errors.find((error) => !timeout(error)) ?? errors[0];
877
1168
  const message = reported ? firstWords(reported.message ?? reported.value) : undefined;
878
1169
  if (status === "passed")
879
1170
  return { outcome: "passed" };
880
1171
  if (status === "skipped")
881
1172
  return { outcome: "skipped" };
882
- if (status === "timedOut" && timeoutOnly)
1173
+ if (errors.length > 0 && timeout(errors[0]))
883
1174
  return { outcome: "timed-out", message };
884
1175
  return { outcome: "failed", message };
885
1176
  }
@@ -908,9 +1199,8 @@ function surviveIfDone(pass, id) {
908
1199
  if (!entry.tests.every((test) => passed.has(key(test))))
909
1200
  return;
910
1201
  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 }
1202
+ giveVerdict(pass, entry.unrun
1203
+ ? { id, status: "error", reason: `no Playwright test killed it, and ${entry.unrun}`, tests: ran, durationMs: 0 }
914
1204
  : { id, status: "survived", ...(entry.reason ? { reason: reasonOf(loadWorker(pass).kind, entry.reason) } : {}), tests: ran, durationMs: 0 });
915
1205
  }
916
1206
 
@@ -918,7 +1208,6 @@ export const WHY = {
918
1208
  "background": "its code ran in server work no request named",
919
1209
  "module-level": "it is a server module's top-level code",
920
1210
  "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
1211
  "unfinished": "not every candidate test ran in the shared pass",
923
1212
  "confirm": "a test killed it beside other mutants' attempts",
924
1213
  "doubt": "the test that killed it failed without it too, on the same server",
@@ -977,7 +1266,6 @@ export function settleAttempt(pass, attempt) {
977
1266
  return ended;
978
1267
  }
979
1268
  if (ended.outcome === "passed") {
980
- passedHere.add(test);
981
1269
  mark(`${pass.round}/passed/${key(attempt.id)}/${key(test)}`);
982
1270
  // One mutant an invocation: a survivor waits for the judge, who
983
1271
  // knows whether its server ran it.
@@ -985,30 +1273,30 @@ export function settleAttempt(pass, attempt) {
985
1273
  surviveIfDone(pass, attempt.id);
986
1274
  return ended;
987
1275
  }
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")
1276
+ if (ended.outcome !== "failed" && ended.outcome !== "timed-out")
997
1277
  return ended;
998
- // A kill: no other copy takes the mutant now.
999
- passedHere.delete(test);
1278
+ // A kill, or a timeout (it ran out of its limit): no other copy takes
1279
+ // the mutant now, and either is confirmed alike.
1280
+ const { status, reason } = verdictOf(ended);
1000
1281
  mark(`${pass.round}/killed/${key(attempt.id)}`);
1001
1282
  if (beside)
1002
1283
  mark(`${pass.round}/confirm/${key(attempt.id)}`);
1003
1284
  else if (shape.everywhere)
1004
- giveVerdict(pass, verdict("killed", ended.message ?? "the test failed"));
1285
+ giveVerdict(pass, verdict(status, reason));
1005
1286
  else {
1006
1287
  // 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 });
1288
+ 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 });
1008
1289
  }
1009
1290
  return ended;
1010
1291
  }
1011
1292
 
1293
+ /** A mutant attempt that failed or ran out of its limit: its verdict's status and reason. */
1294
+ export function verdictOf(attempt) {
1295
+ if (attempt.outcome === "timed-out")
1296
+ return { status: "timeout", reason: limitReason(attempt) };
1297
+ return { status: "killed", reason: attempt.message ?? "the test failed" };
1298
+ }
1299
+
1012
1300
  function suffix(shape, entry) {
1013
1301
  const said = reasonOf(shape.kind, entry.reason);
1014
1302
  return said ? `; ${said}` : "";
@@ -1017,9 +1305,9 @@ function suffix(shape, entry) {
1017
1305
  /**
1018
1306
  * A run with no mutant: the test's baseline (the first in a main round), or
1019
1307
  * 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.
1308
+ * invocation and confirms the kills before it on this server; failing, it
1309
+ * puts them in doubt, and a test that fails so twice in an invocation is not
1310
+ * run there again.
1023
1311
  */
1024
1312
  function settleControl(pass, ended, shape) {
1025
1313
  const test = ended.original;
@@ -1041,27 +1329,25 @@ function settleControl(pass, ended, shape) {
1041
1329
  rmSync(`${pending}/${name}`, { force: true });
1042
1330
  if (passed && !ended.beside) {
1043
1331
  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 });
1332
+ giveVerdict(pass, { id: kill.id, status: kill.status, killedBy: kill.test, reason: `${kill.message}${suffix(shape, entry)}`, tests: 1, durationMs: kill.durationMs });
1045
1333
  }
1046
1334
  else
1047
1335
  mark(`${pass.round}/doubt/${key(kill.id)}`);
1048
1336
  }
1049
1337
  if (passed) {
1050
- passedHere.add(test);
1338
+ mark(readyPath(pass, ended.invocation, test));
1339
+ // Its time, for its mutants' limits.
1340
+ mark(`${pass.shared}/durations/${key(test)}`);
1341
+ writeFileSync(`${pass.shared}/durations/${key(test)}/${ended.worker}-${ended.endedAt - ended.startedAt}`, "");
1051
1342
  return;
1052
1343
  }
1053
1344
  if (ended.outcome === "skipped")
1054
1345
  return;
1055
- passedHere.delete(test);
1346
+ rmSync(readyPath(pass, ended.invocation, test), { recursive: true, force: true });
1056
1347
  mark(`${pass.round}/unreliable/${ended.invocation}/${key(test)}`);
1057
1348
  writeFileSync(`${pass.round}/unreliable/${ended.invocation}/${key(test)}/${ended.worker}-${Date.now()}`, "");
1058
1349
  }
1059
1350
 
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
1351
  /**
1066
1352
  * Whether the attempt's mutant ran in this worker's own process: code the
1067
1353
  * test itself runs, in a process the strong pass otherwise keeps. Such a
@@ -11,10 +11,12 @@
11
11
  // from whichever invocations ran it, and what was cut short is unfinished.
12
12
  import { appendFileSync, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
13
  import { pathToFileURL } from "node:url";
14
- import { attemptPath, baselineOf, entries, invocation, EVERYWHERE, firstWords, giveVerdict, key, loadPass, outcomeOf, placeOf, readJson, reasonOf, settleAttempt, strongPass, withoutCopy, writeJson } from "./playwrightStrong.mjs";
14
+ import { attemptPath, baselineOf, entries, invocation, EVERYWHERE, firstWords, giveVerdict, key, loadPass, outcomeOf, placeOf, queuedWork, readJson, reasonOf, settleAttempt, strongPass, verdictOf, withoutCopy, writeJson } from "./playwrightStrong.mjs";
15
15
 
16
16
  // How often, at most, the status file is written.
17
17
  const STATUS_MS = 1_000;
18
+ // How often, at most, the work left is counted for it.
19
+ const QUEUED_MS = 5_000;
18
20
 
19
21
  /** Each JSON file in a directory of the pass, or none. */
20
22
  function readAll(directory) {
@@ -61,8 +63,13 @@ export default class SupercovPlaywrightStrongReporter {
61
63
  constructor() {
62
64
  this.pass = strongPass();
63
65
  this.running = new Map();
64
- this.counts = { baselines: 0, controls: 0, failedControls: 0, attempts: 0, killed: 0, passed: 0 };
66
+ this.counts = { baselines: 0, controls: 0, failedControls: 0, attempts: 0, killed: 0, timedOut: 0, passed: 0 };
65
67
  this.writtenAt = 0;
68
+ // The tests this invocation runs, and the baseline time of the runs
69
+ // it ended: its pace, for the time its work left takes.
70
+ this.held = [];
71
+ this.doneMs = 0;
72
+ this.queuedAt = 0;
66
73
  }
67
74
  // It prints its own lines, and says it prints: Playwright adds a reporter
68
75
  // of its own where none does. The command's output is a log beside the
@@ -84,6 +91,8 @@ export default class SupercovPlaywrightStrongReporter {
84
91
  if (withoutCopy(test.titlePath()).copy)
85
92
  continue;
86
93
  writeJson(`${this.pass.round}/originals/${key(placeOf(test))}`, test.id);
94
+ if (this.work.tests[test.id]?.jobs)
95
+ this.held.push(test.id);
87
96
  }
88
97
  this.copies = copies;
89
98
  const mutants = Object.keys(this.work.entries).length;
@@ -137,6 +146,8 @@ export default class SupercovPlaywrightStrongReporter {
137
146
  /** A line on the command's output for each attempt with a mutant, and each control that failed. */
138
147
  say(attempt) {
139
148
  const took = seconds((attempt.endedAt ?? Date.now()) - attempt.startedAt);
149
+ this.firstStartedAt ??= attempt.startedAt;
150
+ this.doneMs += attempt.baselineMs ?? this.work.tests[attempt.original]?.durationMs ?? 0;
140
151
  if (attempt.kind !== "mutant") {
141
152
  this.counts[attempt.kind === "baseline" ? "baselines" : "controls"] += 1;
142
153
  if (attempt.outcome === "failed" || attempt.outcome === "timed-out") {
@@ -151,7 +162,13 @@ export default class SupercovPlaywrightStrongReporter {
151
162
  this.counts.passed += 1;
152
163
  else if (attempt.outcome === "failed")
153
164
  this.counts.killed += 1;
154
- const said = attempt.outcome === "passed" ? "lives" : attempt.outcome === "failed" ? "fails" : attempt.outcome;
165
+ else if (attempt.outcome === "timed-out")
166
+ this.counts.timedOut += 1;
167
+ const said = {
168
+ "passed": "lives",
169
+ "failed": "fails",
170
+ "timed-out": `ran out of its ${seconds(attempt.limitMs)} limit (its baseline ${seconds(attempt.baselineMs)})`,
171
+ }[attempt.outcome] ?? attempt.outcome;
155
172
  console.log(`[supercov] ${attempt.id}: ${JSON.stringify(attempt.title)} ${said} (${took})`);
156
173
  }
157
174
  /**
@@ -177,8 +194,11 @@ export default class SupercovPlaywrightStrongReporter {
177
194
  kind: attempt?.kind,
178
195
  mutant: attempt?.id ?? undefined,
179
196
  startedAt: attempt?.startedAt,
197
+ limitMs: attempt?.limitMs,
180
198
  };
181
199
  });
200
+ if (now && this.work && Date.now() - this.queuedAt >= QUEUED_MS)
201
+ this.countQueued();
182
202
  try {
183
203
  writeJson(`${this.pass.shared}/status/${process.pid}.json`, {
184
204
  round: this.pass.name,
@@ -191,12 +211,32 @@ export default class SupercovPlaywrightStrongReporter {
191
211
  firstMutantAt: this.firstMutantAt,
192
212
  lastEndedAt: this.lastEndedAt,
193
213
  running,
214
+ ...(this.queued ? { queued: this.queued } : {}),
194
215
  });
195
216
  }
196
217
  catch {
197
218
  // The status is for the progress line; the pass goes on without it.
198
219
  }
199
220
  }
221
+ /**
222
+ * The work left in this invocation's tests (`queuedWork`), and the time
223
+ * it takes at the pace so far: the baseline time of the runs it ended
224
+ * over the time they took, which counts what runs besides the tests (a
225
+ * copy with nothing to run, a new worker after a kill).
226
+ */
227
+ countQueued() {
228
+ this.queuedAt = Date.now();
229
+ try {
230
+ const queued = queuedWork(this.pass, this.work, this.held);
231
+ const spent = (this.lastEndedAt ?? 0) - (this.firstStartedAt ?? 0);
232
+ if (this.doneMs > 0 && spent > 0)
233
+ queued.leftMs = Math.round((queued.ms * spent) / this.doneMs);
234
+ this.queued = queued;
235
+ }
236
+ catch {
237
+ // Counted again at the next status.
238
+ }
239
+ }
200
240
  onEnd() {
201
241
  if (!this.pass)
202
242
  return;
@@ -264,13 +304,13 @@ export default class SupercovPlaywrightStrongReporter {
264
304
  const rest = [];
265
305
  const aloneAgain = [];
266
306
  const aloneEach = [];
267
- const next = (entry, reason, tests, budgetFactor = 1) => {
307
+ const next = (entry, reason, tests) => {
268
308
  const runnable = tests.filter((test) => baselineOf(pass, test) !== "failed");
269
309
  if (!runnable.length) {
270
310
  write({ id: entry.id, status: "error", reason: "its candidate tests fail without any mutant", tests: 0, durationMs: 0 });
271
311
  return;
272
312
  }
273
- const job = { id: entry.id, mutant: entry.mutant, tests: runnable, reason, budgetFactor };
313
+ const job = { id: entry.id, mutant: entry.mutant, tests: runnable, reason };
274
314
  // What an alone round left runs alone again, as it was.
275
315
  if (kind === "alone")
276
316
  aloneEach.push({ ...job, reason: entry.reason });
@@ -305,7 +345,8 @@ export default class SupercovPlaywrightStrongReporter {
305
345
  const own = byMutant.get(id) ?? [];
306
346
  const ended = own.filter((attempt) => attempt.endedAt !== undefined);
307
347
  const ranAway = own.find((attempt) => timedOut.has(attempt.attemptId) || timedOutAnywhere.has(entry.mutant));
308
- const failed = ended.filter((attempt) => attempt.outcome === "failed");
348
+ // Kills, and attempts that ran out of their time limit.
349
+ const failed = ended.filter((attempt) => attempt.outcome === "failed" || attempt.outcome === "timed-out");
309
350
  const after = reasonOf(kind, entry.reason);
310
351
  const suffix = after ? `; ${after}` : "";
311
352
  const durationMs = ended.length
@@ -327,17 +368,14 @@ export default class SupercovPlaywrightStrongReporter {
327
368
  // kill on a server no other mutant's attempt shared.
328
369
  const killer = failed.find((attempt) => !attempt.beside && attempt.endedAt < trustedUntil);
329
370
  if (killer) {
330
- verdict({ status: "killed", killedBy: killer.original, reason: `${killer.message ?? "the test failed"}${suffix}` });
371
+ const { status, reason } = verdictOf(killer);
372
+ verdict({ status, killedBy: killer.original, reason: `${reason}${suffix}` });
331
373
  continue;
332
374
  }
333
375
  if (ranAway) {
334
376
  verdict({ status: "timeout", killedBy: ranAway.original, reason: `evaluated past its hit limit${suffix}` });
335
377
  continue;
336
378
  }
337
- if (existsSync(`${round}/held/${key(id)}`)) {
338
- next(entry, "timeout-retry", entry.tests, 2 * (entry.budgetFactor ?? 1));
339
- continue;
340
- }
341
379
  // Alone, the command failed outside any test: the mutant broke the
342
380
  // app (a server that would not start with it).
343
381
  // (Where one invocation of several failed so, it runs alone with
@@ -364,9 +402,8 @@ export default class SupercovPlaywrightStrongReporter {
364
402
  next(entry, "unfinished", left);
365
403
  continue;
366
404
  }
367
- const others = work.otherRunners[id];
368
- verdict(others
369
- ? { status: "error", reason: `no Playwright test killed it, and its other candidates ran under ${others.join(", ")}, which this pass does not run` }
405
+ verdict(entry.unrun
406
+ ? { status: "error", reason: `no Playwright test killed it, and ${entry.unrun}` }
370
407
  : { status: "survived", ...(after ? { reason: after } : {}) });
371
408
  }
372
409
  for (const job of work.restarts)
@@ -400,15 +437,15 @@ export default class SupercovPlaywrightStrongReporter {
400
437
  // command started with it.
401
438
  const takenAny = claimedBy.size > 0;
402
439
  for (const entry of aloneAgain)
403
- (takenAny ? alone : aloneEach).push({ ...entry, budgetFactor: entry.budgetFactor ?? 1 });
440
+ (takenAny ? alone : aloneEach).push(entry);
404
441
  if (alone.length)
405
- write({ restart: { kind: "alone", everywhere: true, batch: true, reason: "server-wide", mutants: alone, otherRunners: work.otherRunners } });
442
+ write({ restart: { kind: "alone", everywhere: true, batch: true, reason: "server-wide", mutants: alone, otherRunners: work.otherRunners, setupOnly: work.setupOnly } });
406
443
  for (const job of aloneEach)
407
- write({ restart: { kind: "alone", everywhere: true, reason: job.reason, mutants: [job], otherRunners: work.otherRunners } });
444
+ write({ restart: { kind: "alone", everywhere: true, reason: job.reason, mutants: [job], otherRunners: work.otherRunners, setupOnly: work.setupOnly } });
408
445
  if (rest.length)
409
- write({ restart: { kind: "rest", reason: "unfinished", mutants: rest, otherRunners: work.otherRunners } });
446
+ write({ restart: { kind: "rest", reason: "unfinished", mutants: rest, otherRunners: work.otherRunners, setupOnly: work.setupOnly } });
410
447
  if (serial.length)
411
- write({ restart: { kind: "serial", reason: [...new Set(serial.map((job) => job.reason))].join(", "), mutants: serial, otherRunners: work.otherRunners } });
448
+ write({ restart: { kind: "serial", reason: [...new Set(serial.map((job) => job.reason))].join(", "), mutants: serial, otherRunners: work.otherRunners, setupOnly: work.setupOnly } });
412
449
  const mutated = attempts.filter((attempt) => attempt.kind === "mutant");
413
450
  write({
414
451
  summary: true,
@@ -422,6 +459,8 @@ export default class SupercovPlaywrightStrongReporter {
422
459
  workerProcesses: new Set(attempts.map((attempt) => attempt.worker)).size,
423
460
  durationMs: Date.now() - started,
424
461
  attempts: mutated.length,
462
+ timedOut: mutated.filter((attempt) => attempt.outcome === "timed-out").length,
463
+ timeoutFactor: work.timeoutFactor,
425
464
  baselines: attempts.filter((attempt) => attempt.kind === "baseline").length,
426
465
  decided,
427
466
  next: { alone: alone.length, rest: rest.length, serial: serial.length },