supercov 4.29.13 → 4.29.15

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
@@ -419,7 +419,9 @@ The output names the base, the merge base and how many changed lines hold a
419
419
  mutant, then lists the mutants the tests leave alive, not infected first and
420
420
  then not reached, each with the part it changes and why, and counts the rest
421
421
  in one line. `--json` lists every mutant of the change, survivors first, with
422
- `diff` (`base`, `mergeBase`, `commit`, `changedLines`, `linesWithMutants`).
422
+ `diff` (`base`, `mergeBase`, `commit`, `changedLines`, `linesWithMutants`, and
423
+ `unrunLines`: the changed lines of code no test of the run ran, by file).
424
+ Each mutant listed has `lineTests`: how many of the run's tests ran its line.
423
425
 
424
426
  `--format markdown` writes a table for a pull request's comment: the counts in
425
427
  one line, then up to 25 not-infected and not-reached mutants (or those
@@ -428,9 +430,15 @@ their status and why, and the command that lists the rest. Once `mutants test`
428
430
  gave verdicts, a second line has the mutation score, with how many mutants it
429
431
  is over (or, with none, why there is no score), and every verdict counted
430
432
  (killed, timed out, survived, no coverage, unviable, error, not run for want
431
- of a driver, and those with none yet), and the table lists the survivors: the
432
- mutants that survived or that no test covers, then those weak mutation shows
433
- no test can kill, each with its weak status, its strong verdict and why.
433
+ of a driver, survived so far, and those with none yet), and the table lists
434
+ the survivors: the mutants that survived or that no test covers, then those
435
+ weak mutation shows no test can kill, each with its weak status, its strong
436
+ verdict and why. Every table says how many of the run's tests ran each
437
+ mutant's line. A change's comment names its lines of code no test ran, file
438
+ by file. Survivors that only change a log line (`logOnly`) are folded apart
439
+ in a `<details>`, and so are the mutants `survived so far` (a first tier of
440
+ their candidates passed, the rest not run yet): not survivors, and not in the
441
+ score. A CI can post the file as it is.
434
442
 
435
443
  #### Mutation reports other tools read
436
444
 
@@ -1037,9 +1045,13 @@ TypeScript helper that only gained functions affects none), and every test
1037
1045
  where Supercov cannot read the imports. A dependency,
1038
1046
  lockfile, configuration or toolchain change affects every test and is reported
1039
1047
  as such; a test runner's settings affect only the runs that used that runner.
1040
- A source file
1041
- added since the run is outside every test's record; the working-tree check
1042
- says so, and the suite should run in full.
1048
+ A JavaScript or TypeScript source file added since the run, under the roots it
1049
+ measured, is outside every test's record: it affects the tests whose own file,
1050
+ or a file they ran code in, imports it now, directly or through other files
1051
+ (`src/new.ts added since the run (imported by src/app.ts, which this test ran
1052
+ code in)`). One that nothing of theirs imports is named as `unknown, new file`;
1053
+ run what can reach it in full. `--json` lists each under `newFiles`, with
1054
+ `importedBy` or `"reach": "unknown, new file"`.
1043
1055
 
1044
1056
  A Rust test loads what it names by path: a fixture, a data file or a script
1045
1057
  named in its own function (or in its entry of a macro that declares a test
@@ -1065,6 +1077,15 @@ others. A mock keeps its state between tests, so a mock's files count whole,
1065
1077
  not route by route; a file the application's server loaded, a preload of its
1066
1078
  own, affects every test it served.
1067
1079
 
1080
+ A changed file no test's import places -- a fixture another program reads, a
1081
+ file a command names, or another runner's test or helper -- is one any test
1082
+ may load. A Playwright run keeps what each of its Node processes (the
1083
+ runner, its workers, the servers) loaded and read, and then such a file
1084
+ affects its tests only where one of them did, or where it is in the tree of
1085
+ a configuration of a runner the run used (`tests/e2e/` for
1086
+ `tests/e2e/playwright.config.ts`): a changed integration test or its helper
1087
+ selects none of an e2e run's tests.
1088
+
1068
1089
  ### Which affected tests check the change
1069
1090
 
1070
1091
  When the run has an [assertion assessment](assertions.md), `tests affected`
@@ -1157,6 +1178,19 @@ timestamp, a path the test took, an outcome, is kept beside the others, so
1157
1178
  nothing any run recorded is lost. Jobs that each measured the whole suite
1158
1179
  record each test with times of their own, and keep a copy each.
1159
1180
 
1181
+ Runs made from one run without measuring whose archives are alike byte for
1182
+ byte (the jobs of a continuation round, each made from the same baseline)
1183
+ are read, merged and kept once, from the first of them: the merged run lists
1184
+ that one among its runs, keeps it alone under `parts/`, and says which runs
1185
+ were its copies (`7 run(s) hold run r1's evidence byte for byte, made from one
1186
+ run without measuring (r2; r3; r4; and 4 more): their evidence is kept once,
1187
+ from it, and their strong verdicts each`). Each copy's strong verdicts are
1188
+ kept as any run's. Eight such runs of a large e2e suite, each 232 MB with its
1189
+ baseline's archive and parts, merged in 12 s instead of 100 s and half the
1190
+ memory (a peak footprint of 12.5 GB, from 24.7 GB), into a run of 244 MB
1191
+ instead of 1 GB, which the next round's jobs each carry; its coverage and
1192
+ strong verdicts are the same.
1193
+
1160
1194
  The runs may differ in their tests, the helpers beside them, and the test
1161
1195
  runners' settings, as long as nothing that changed reaches what an earlier
1162
1196
  run's tests did. Measuring a new test alone and adding it to the runs before it
@@ -1282,6 +1316,20 @@ saved into the latest of them; run such a round again.
1282
1316
  reusing the answers saved when its parts were assessed. `tests affected` of a
1283
1317
  merged run is answered from the runs it was merged from, which hold the record
1284
1318
  of what each test ran; a test in several of them is affected where any says so.
1319
+ The merged run keeps what each of them answers with (in its `parts/`
1320
+ directory: each run's metadata, its record of what each test ran, and the
1321
+ few entries of its archive that say what its tests loaded), so it answers
1322
+ alone, with its runs gone from `.supercov/runs`: a merged baseline can be
1323
+ cached and restored by itself. A merge made by a Supercov before 4.29.14 kept
1324
+ none of that, and needs its runs.
1325
+
1326
+ A file a server of the run reads that the measured command itself wrote, and
1327
+ that git does not track -- a local stack's settings that a harness writes with
1328
+ each machine's ports and keys -- is not an input of the run: a later checkout
1329
+ cannot change it under the run, and each machine's part of a suite reads its
1330
+ own. The run leaves it out of what it records (and says so), so such parts
1331
+ merge, and a change to it affects no test. A tracked file the command
1332
+ rewrites, such as a mock's data it saves, stays an input.
1285
1333
 
1286
1334
  ## Add coverage measured elsewhere
1287
1335
 
package/docs/mutation.md CHANGED
@@ -60,6 +60,7 @@ switched on and records what the established tools record:
60
60
  | `survived` | Every test that could kill it passed |
61
61
  | `timeout` | A test ran past its time limit with the mutant in place |
62
62
  | `no-coverage` | No test ran the mutated code |
63
+ | `equivalent` | No test can tell it from the original, proven before running it; left out of the score |
63
64
  | `unviable` | The mutant does not compile (Rust and Go); counted apart and left out of the score |
64
65
  | `error` | The pass could not give it a verdict, with the reason; left out of the score |
65
66
 
@@ -78,9 +79,64 @@ first pass of their own:
78
79
  reached or infected it, the likeliest killer first, and stops at the first
79
80
  failure.
80
81
 
82
+ - a JavaScript or TypeScript mutant whose file compiles to the same code as
83
+ the original is `equivalent`, and is not run; mutants whose files compile
84
+ to the same code as each other run once, and each takes that run's verdict
85
+ (see Equivalent mutants, below).
86
+
81
87
  Each of these shortcuts is exact. Where the run cannot prove a test is
82
88
  irrelevant, the test runs.
83
89
 
90
+ ### Equivalent mutants
91
+
92
+ Some mutants change the source without changing the program: a branch that
93
+ can never run emptied, `if (false)` made `if (false)` again, `"a".trim()`
94
+ made `"a"`. No test can kill them, yet each one used to run every test
95
+ that reached it and then waited in the survivors for someone to dismiss it.
96
+
97
+ Before a strong pass runs a JavaScript or TypeScript mutant, Supercov
98
+ compiles its file twice -- once as written, once with the mutant -- with the
99
+ same optimising compiler and the same options (oxc's minifier, built into
100
+ Supercov, with every assumption that could change behaviour turned off),
101
+ and compares the two outputs. Where they are identical the mutant is the
102
+ original program, so it is `equivalent`: not run, not a survivor, and out of
103
+ the score. This is Trivial Compiler Equivalence (Papadakis et al., ICSE
104
+ 2015). It only ever says `equivalent` on an exact match; anything else, a
105
+ file it cannot compile included, runs as before. Two mutants of one file
106
+ that compile to the same code are one program: the pass runs one of them and
107
+ gives the other the same verdict.
108
+
109
+ There is nothing to set up or turn on. The pass says what it spared:
110
+
111
+ ```text
112
+ [supercov] 10 mutant(s) proven equivalent: each compiles to the same code as the original, so no test can tell it apart; 10 of them would have run and did not
113
+ [supercov] 6 mutant(s) compile to the same code as another mutant, which runs once and gives them its verdict
114
+ [supercov] about 1 s of test time saved by not running them
115
+ ```
116
+
117
+ Its summary says the same, and each one says why where it is listed:
118
+
119
+ ```text
120
+ $ supercov runs latest mutants src/shapes.ts:13
121
+ 13:7 ConditionalExpression infected strong: equivalent
122
+ empty → true
123
+ why: `empty` was false at least once (opposite-value)
124
+ strong: equivalent: compiles to the same code as the original: no test can tell it apart, so it was not run
125
+ id: src/shapes.ts:13:7-13:12:ConditionalExpression:true
126
+ ```
127
+
128
+ Here `if (empty) { return "none"; } return "none";` returns `"none"` whichever
129
+ way the test goes, so making it `true` changes nothing. A mutant that takes
130
+ another's verdict says whose: `compiles to the same code as <id>, which ran
131
+ for both`.
132
+
133
+ The markdown and HTML reports fold them into a section of their own, apart
134
+ from the survivors. A file that does not compile (a syntax Supercov's parser
135
+ does not take) is named, and its mutants run as before:
136
+ `could not compile 1 file(s) to compare their mutants' code, so their mutants run as before: src/legacy.js`. So is a file
137
+ whose mutants would take longer to compile than to run, such as a
138
+ generated file with thousands of mutants.
139
+
84
140
  ### How this differs from coverage
85
141
 
86
142
  A line can be covered, its branch taken both ways, and still have no test that
@@ -118,6 +174,26 @@ mutants the tests let survive.
118
174
  verdict a pass reached, whatever the two measurements recorded: a test
119
175
  whose path depends on the time, or that failed in one of them, moves no
120
176
  verdict.
177
+ - **A baseline of the checkout.** Where no run of the command can be read or
178
+ continued, a run of the checkout as it is that holds the tests the command
179
+ runs is: a merge of a suite measured in parts on several machines (a
180
+ weekly baseline restored into `.supercov/runs`), or a run of the whole
181
+ suite. The pass's run is made from it with those tests' records alone, as
182
+ measuring them would record, and nothing is measured (`not measuring: run
183
+ r4 of this checkout holds the tests the command runs (18 test(s) in 6 of
184
+ its 61 test file(s)); this pass saves its verdicts into run r9, made from
185
+ it with those tests alone`). The command's tests are every test of a merge
186
+ whose runs were each measured with the command itself, and otherwise those
187
+ of the test files the command names, by path or by the end of one
188
+ (`tests/e2e/billing.spec.ts`, `billing.spec.ts`), anywhere in its words,
189
+ where the run holds every one of them that any run holds; a command that
190
+ names none is measured. The baseline must be of the checkout
191
+ as it is, by its fingerprint: on a pull request, whose checkout differs, the
192
+ command is measured, so narrow it to the specs `tests affected --files`
193
+ names; the change's own mutants are run only by tests that ran changed
194
+ code, which those are. A test that failed in the baseline is no candidate.
195
+ It needs a merged run made by this release, which keeps what its runs
196
+ answer with.
121
197
  - **After an edit.** It measures the checkout again and keeps an earlier
122
198
  verdict for each mutant whose file is as it was and whose candidate tests,
123
199
  and their test files, nothing changed could reach, as `runs latest tests
@@ -157,8 +233,9 @@ mutants the tests let survive.
157
233
  merge and in a later round: a candidate a change could reach runs again.
158
234
  The Playwright driver records them.
159
235
  - **A first tier.** A Playwright mutant with more candidates than its first
160
- tier holds (32, or more where the run's kills come later) runs against
161
- that tier first, every such mutant before any runs the rest. One the tier
236
+ tier holds (32, or more where the run's kills come later, or as many as
237
+ take 60 s of their tests' time, at least four, whichever comes first)
238
+ runs against that tier first, every such mutant before any runs the rest. One the tier
162
239
  lets live is `survived-so-far` until the rest runs, in the same pass where
163
240
  it has the time: listed with the survivors as such, never in the score
164
241
  (`docs/design/strong-mutation.md`, A first tier, then the rest).
@@ -214,17 +291,22 @@ npx supercov mutants --diff origin/main --fail-on survived
214
291
  npx supercov mutants --diff origin/main --format markdown --output mutants.md
215
292
  ```
216
293
 
217
- - `--format markdown` writes a table for a pull request's comment: the counts,
218
- then up to 25 mutants left alive with where they are, what they change and
219
- why, and the command that lists the rest. Once a strong pass gave verdicts,
220
- it has the mutation score and lists the survivors. `supercov mutants` takes
221
- `--format markdown` and `--output <file>` too, and writes its own answer
222
- that way.
294
+ - `--format markdown` writes a pull request's comment, ready to post as it
295
+ is: the counts, the change's lines of code no test ran, then up to 25
296
+ mutants left alive with where they are, what they change, how many of the
297
+ run's tests ran their line and why, and the command that lists the rest.
298
+ Once a strong pass gave verdicts, it has the mutation score and lists the
299
+ survivors. Those that only change a log line are folded in a `<details>` of
300
+ their own, and so are those `survived so far` (counted apart, never with
301
+ the survivors). `supercov mutants` takes `--format markdown` and
302
+ `--output <file>` too, and writes its own answer that way.
223
303
  - A survivor that only changes a log line (its change lies wholly inside the
224
- arguments of `console.*`, or of a method named `info`, `warn`, `error`,
225
- `debug`, `trace` or `log`) is still `survived`, but marked `(only changes a
226
- log line)` (`logOnly` in JSON) and counted on its own: `survived 185 (109
227
- only change a log line)`. Triage can set those aside.
304
+ arguments of `console.*`, of a method named `info`, `warn`, `error`,
305
+ `debug`, `trace` or `log`, or of what makes a logger: `createLogger(...)`,
306
+ `getLogger(...)`, `pino(...)`, and `.child(...)` of a logger) is still
307
+ `survived`, but marked `(only changes a log line)` (`logOnly` in JSON) and
308
+ counted on its own: `survived 185 (109 only change a log line)`. Triage can
309
+ set those aside.
228
310
  - `--fail-on` exits `1` when a mutant asked about has one of the statuses
229
311
  given. On `runs latest mutants` they are weak statuses, from the run alone;
230
312
  on `supercov mutants` and `mutants test` they are verdicts: `survived`,
@@ -459,7 +541,11 @@ no mutants shows none of this.
459
541
  (`docs/design/strong-mutation.md`, Module-level values). A mutant whose
460
542
  code ran only for requests that named no test (a webhook a mock server
461
543
  sends while tests run) runs against the tests that were running then, not
462
- every test. A test runs without a mutant only after a failure, to confirm
544
+ every test. A survivor whose code its candidates' servers ran, but which no
545
+ test's request ran with its mutant in the pass (work in a route's
546
+ `after()`, a worker process the first request started), is not trusted: it
547
+ runs again alone, with the server started with it switched on, and the pass
548
+ warns about it. A test runs without a mutant only after a failure, to confirm
463
549
  it; a failure before any such run passed on its server (a cold server)
464
550
  runs the mutant again once one has. StrykerJS has no
465
551
  Playwright runner, so Playwright's verdicts are checked by hand (see below).
@@ -470,7 +556,18 @@ no mutants shows none of this.
470
556
  test may shorten it but not lengthen it, so a click or an `expect` that
471
557
  waits for an element the mutant broke ends there, not at its own 30 s. A
472
558
  test that runs out of its limit makes its mutant a `timeout`, which counts
473
- as detected; the summary says how many, and against what limit.
559
+ as detected; the summary says how many, and against what limit. An attempt
560
+ ends sooner, a `timeout` too, once it has stalled: its test's own code has
561
+ run for longer than any run of the test that passed (baseline × 1.5 + 1 s)
562
+ and waits on a Playwright call that cannot end by its own timeout before the
563
+ limit, its pages quiet for a second. An `expect` that gives up before the
564
+ limit still fails the test, a kill, and a page still sending requests runs
565
+ on. Nothing needs setting. Each timeout's verdict says what it waited on and
566
+ where, for example `stopped at 2.5 s of its 6.5 s time limit, ..., waiting
567
+ on Locator.click (#save) at tests/save.spec.ts:12:20`, and the summary says
568
+ how much time ending them early saved. A worker is kept after a mutant
569
+ fails its test, so the next test does not wait for a new worker and
570
+ browser; a test that fails without any mutant still gets a new one.
474
571
  `--timeout-factor <x>` (or `SUPERCOV_STRONG_TIMEOUT_FACTOR`) changes the
475
572
  1.5: a suite whose tests' times vary widely between runs may want 2 or 3.
476
573
  A mutant tries its candidates cheapest to a kill first (a test's time over
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "supercov",
3
- "version": "4.29.13",
3
+ "version": "4.29.15",
4
4
  "description": "Coverage, security and code quality for coding agents",
5
5
  "keywords": [
6
6
  "coverage",
@@ -83,7 +83,7 @@
83
83
  "eval:skill": "claude plugin eval plugins/supercov --scaffold --trust-plugin --no-publish --model claude-sonnet-5 --judge-model claude-haiku-4-5 --threshold 0.66 --tag behavior trigger --allow-tools Bash Edit Write --max-cost-usd 15",
84
84
  "eval:skill-triggers": "claude plugin eval plugins/supercov --scaffold --trust-plugin --no-publish --model claude-sonnet-5 --judge-model claude-haiku-4-5 --threshold 0.66 --tag trigger --ablation none --max-cost-usd 5",
85
85
  "test:engine": "cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace && npm run test:runtime && npm run test:rust-assets && npm run test:engine-integrations",
86
- "test:engine-integrations": "cargo build -p supercov && node scripts/html-report-integration.mjs && node scripts/mutation-report-formats.mjs && node scripts/rust-process-supervision.mjs && node scripts/rust-direct-node-integration.mjs && node scripts/rust-public-run-integration.mjs && node scripts/rust-embedded-runtime-integration.mjs && node scripts/rust-direct-vitest-integration.mjs && node scripts/rust-nested-vitest-integration.mjs && node scripts/rust-direct-jest-integration.mjs && node scripts/mocha-failure-output.mjs && node scripts/failure-output.mjs node ava tap && node scripts/side-by-side.mjs node && node scripts/merge-across.mjs && node scripts/import-line-evidence.mjs && node scripts/mock-reach.mjs && node scripts/rust-direct-playwright-integration.mjs && node scripts/rust-custom-browser-playwright-integration.mjs && node scripts/cross-origin-requests.mjs && node scripts/leaving-page.mjs && node scripts/shared-page.mjs && node scripts/context-script-copies.mjs && node scripts/context-headers.mjs && node scripts/context-cookies.mjs && node scripts/hidden-request-emit.mjs && node scripts/js-syntax-zoo.mjs && node scripts/ruby-syntax-zoo.mjs && node scripts/rust-syntax-zoo.mjs && node scripts/python-syntax-zoo.mjs && node scripts/go-syntax-zoo.mjs && node scripts/java-syntax-zoo.mjs && node scripts/background-by-time.mjs && node scripts/python-server-playwright.mjs && node scripts/ruby-server-playwright.mjs && node scripts/go-server-playwright.mjs && node scripts/jvm-server-playwright.mjs && node scripts/docker-server-playwright.mjs && node scripts/docker-clients-playwright.mjs && node scripts/docker-exec-playwright.mjs && node scripts/rust-classic-browser-integration.mjs && node scripts/exec-handover.mjs && node scripts/rust-region-container.mjs && node scripts/rust-top-packages-integration.mjs && node scripts/rust-generic-esbuild-integration.mjs && node scripts/rust-generic-tsc-integration.mjs && node scripts/rust-generic-build-matrix.mjs && node scripts/rust-vite-playwright-integration.mjs && node scripts/workspace-crash-integration.mjs",
86
+ "test:engine-integrations": "cargo build -p supercov && node scripts/html-report-integration.mjs && node scripts/mutation-report-formats.mjs && node scripts/rust-process-supervision.mjs && node scripts/rust-direct-node-integration.mjs && node scripts/rust-public-run-integration.mjs && node scripts/rust-embedded-runtime-integration.mjs && node scripts/rust-direct-vitest-integration.mjs && node scripts/rust-nested-vitest-integration.mjs && node scripts/rust-direct-jest-integration.mjs && node scripts/mocha-failure-output.mjs && node scripts/failure-output.mjs node ava tap && node scripts/side-by-side.mjs node && node scripts/merge-across.mjs && node scripts/import-line-evidence.mjs && node scripts/mock-reach.mjs && node scripts/generated-inputs.mjs && node scripts/baseline-continuation.mjs && node scripts/rust-direct-playwright-integration.mjs && node scripts/rust-custom-browser-playwright-integration.mjs && node scripts/cross-origin-requests.mjs && node scripts/leaving-page.mjs && node scripts/shared-page.mjs && node scripts/context-script-copies.mjs && node scripts/context-headers.mjs && node scripts/context-cookies.mjs && node scripts/hidden-request-emit.mjs && node scripts/js-syntax-zoo.mjs && node scripts/ruby-syntax-zoo.mjs && node scripts/rust-syntax-zoo.mjs && node scripts/python-syntax-zoo.mjs && node scripts/go-syntax-zoo.mjs && node scripts/java-syntax-zoo.mjs && node scripts/background-by-time.mjs && node scripts/next-after-webhook.mjs && node scripts/python-server-playwright.mjs && node scripts/ruby-server-playwright.mjs && node scripts/go-server-playwright.mjs && node scripts/jvm-server-playwright.mjs && node scripts/docker-server-playwright.mjs && node scripts/docker-clients-playwright.mjs && node scripts/docker-exec-playwright.mjs && node scripts/rust-classic-browser-integration.mjs && node scripts/exec-handover.mjs && node scripts/rust-region-container.mjs && node scripts/rust-top-packages-integration.mjs && node scripts/rust-generic-esbuild-integration.mjs && node scripts/rust-generic-tsc-integration.mjs && node scripts/rust-generic-build-matrix.mjs && node scripts/rust-vite-playwright-integration.mjs && node scripts/workspace-crash-integration.mjs",
87
87
  "test:platform": "cargo test --workspace && cargo build -p supercov && node scripts/rust-process-supervision.mjs && node scripts/workspace-crash-integration.mjs",
88
88
  "test:native-package": "cargo build --release -p supercov && node scripts/native-package-integration.mjs && node scripts/native-release-set-integration.mjs",
89
89
  "test:pypi-wheel": "node scripts/pypi-wheel-integration.mjs",
@@ -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.13",
129
- "@supercov/cli-darwin-x64": "4.29.13",
130
- "@supercov/cli-linux-arm64-gnu": "4.29.13",
131
- "@supercov/cli-linux-arm64-musl": "4.29.13",
132
- "@supercov/cli-linux-x64-gnu": "4.29.13",
133
- "@supercov/cli-linux-x64-musl": "4.29.13",
134
- "@supercov/cli-win32-arm64": "4.29.13",
135
- "@supercov/cli-win32-x64": "4.29.13"
128
+ "@supercov/cli-darwin-arm64": "4.29.15",
129
+ "@supercov/cli-darwin-x64": "4.29.15",
130
+ "@supercov/cli-linux-arm64-gnu": "4.29.15",
131
+ "@supercov/cli-linux-arm64-musl": "4.29.15",
132
+ "@supercov/cli-linux-x64-gnu": "4.29.15",
133
+ "@supercov/cli-linux-x64-musl": "4.29.15",
134
+ "@supercov/cli-win32-arm64": "4.29.15",
135
+ "@supercov/cli-win32-x64": "4.29.15"
136
136
  },
137
137
  "peerDependencies": {
138
138
  "@playwright/test": ">=1.55.0",
@@ -20,7 +20,7 @@ import { inferTestProvenance, testTags } from "./provenance.mjs";
20
20
  import { appendJsonLineDurableSync, appendJsonLineSync } from "./atomic.mjs";
21
21
  import { expandSnapshot, mergeSnapshots, columnarEvents } from "./snapshots.mjs";
22
22
  import { COVERAGE_DOCUMENT_PHASE_COOKIE, COVERAGE_DOCUMENT_PHASE_SITE_COOKIE, COVERAGE_PHASE_HEADER, COVERAGE_PHASE_COOKIE, COVERAGE_PHASE_SITE_COOKIE, COVERAGE_SCOPE_COOKIE, COVERAGE_SCOPE_HEADER, COVERAGE_SCOPE_SITE_COOKIE, COVERAGE_CARRIER_ENV, encodeCoverageCarrier, encodeCoverageScope, serverEvidenceDirectory, serverEvidencePath, startDocumentInPhase, } from "./transport.mjs";
23
- import { PAGE_TIMEOUT_MARKER, activatePageMutant, installCopies, ranInWorker, strongClaim, strongFinish } from "./playwrightStrong.mjs";
23
+ import { PAGE_TIMEOUT_MARKER, activatePageMutant, describeCall, installCopies, keepsWorker, ownDeadline, ranInWorker, stallDetails, stalledOn, strongClaim, strongFinish, watchStall } from "./playwrightStrong.mjs";
24
24
  export * from "@playwright/test";
25
25
  const generatedTargetModule = "__SUPERCOV_PLAYWRIGHT_MODULE__";
26
26
  const targetModule = process.env["SUPERCOV_PLAYWRIGHT_MODULE"] ??
@@ -189,6 +189,10 @@ const ACTION_METHODS = new Set([
189
189
  "type",
190
190
  "uncheck",
191
191
  ]);
192
+ // The calls that open and close a test's browser contexts and pages, as
193
+ // Playwright's own fixtures make them while setting a test up and tearing
194
+ // it down: no wait of the test's, and not where its own time starts.
195
+ const LIFECYCLE = new Set(["Browser.newContext", "Browser.newPage", "BrowserContext.newPage", "BrowserContext.close", "Page.close"]);
192
196
  const REQUEST_METHODS = new Set([
193
197
  "delete",
194
198
  "fetch",
@@ -204,6 +208,26 @@ function isApiRequestContext(value) {
204
208
  typeof candidate["get"] === "function" &&
205
209
  typeof candidate["post"] === "function");
206
210
  }
211
+ /**
212
+ * Where in the test's own code a call was made, for a timeout's reason: the
213
+ * stack through these proxies runs past V8's usual ten frames.
214
+ */
215
+ function testSite() {
216
+ const limit = Error.stackTraceLimit;
217
+ Error.stackTraceLimit = 50;
218
+ const stack = new Error().stack?.split("\n").slice(2) ?? [];
219
+ Error.stackTraceLimit = limit;
220
+ // A strong pass runs the suite in its isolated copy of the project, under
221
+ // `.supercov/`: the test's frame is any outside `node_modules`, said
222
+ // relative to where the suite runs.
223
+ const frame = stack.find((line) => /[/\\]tests?[/\\]|\.(spec|test)\.[cm]?[jt]sx?:/.test(line) && !line.includes("node_modules"));
224
+ if (!frame)
225
+ return undefined;
226
+ const root = process.cwd().replaceAll("\\", "/");
227
+ const place = frame.trim().replace(/^at\s+/, "").replaceAll("\\", "/").replace(`${pathToFileURL(root).href}/`, "").replace(`${root}/`, "");
228
+ // `name (file:line:column)`: the place alone.
229
+ return /\(([^()]+)\)$/.exec(place)?.[1] ?? place;
230
+ }
207
231
  function callerSource() {
208
232
  const stack = new Error().stack?.split("\n").slice(2) ?? [];
209
233
  const candidate = stack.find((line) => /[/\\]tests[/\\]/.test(line) &&
@@ -278,6 +302,16 @@ class CoveragePhaseController {
278
302
  // Set when a worker's evidence could not be read: the test's coverage is
279
303
  // then a lower bound.
280
304
  workerEvidenceMissing = false;
305
+ // A strong attempt's: the test's default timeouts (`watchWaits`), the
306
+ // calls it made on Playwright's objects that have not settled, each with
307
+ // when its own timeout ends it, the newest of them, and since when its
308
+ // pages have sent and answered no request (`stall`).
309
+ waitTimeouts;
310
+ waits = new Set();
311
+ newestWait;
312
+ testCalledAt;
313
+ matcherSite;
314
+ quietSince = Date.now();
281
315
  disposed = false;
282
316
  // Parameter properties are stateful despite the base ESLint rule treating
283
317
  // this as an empty constructor.
@@ -647,10 +681,18 @@ class CoveragePhaseController {
647
681
  void this.registerWorker(worker);
648
682
  };
649
683
  const closed = () => this.closedContexts.add(context);
650
- context.on("page", register);
651
- context.on("serviceworker", registerServiceWorker);
652
- context.on("close", closed);
653
- this.contextListeners.set(context, [["page", register], ["serviceworker", registerServiceWorker], ["close", closed]]);
684
+ const listeners = [["page", register], ["serviceworker", registerServiceWorker], ["close", closed]];
685
+ // A strong attempt's pages are busy while they send or have
686
+ // answered a request: not stalled.
687
+ if (this.waitTimeouts) {
688
+ const busy = () => {
689
+ this.quietSince = Date.now();
690
+ };
691
+ listeners.push(["request", busy], ["requestfinished", busy], ["requestfailed", busy]);
692
+ }
693
+ for (const [event, listener] of listeners)
694
+ context.on(event, listener);
695
+ this.contextListeners.set(context, listeners);
654
696
  for (const worker of context.serviceWorkers())
655
697
  void this.registerWorker(worker);
656
698
  for (const page of context.pages())
@@ -761,6 +803,56 @@ class CoveragePhaseController {
761
803
  requestPhaseId() {
762
804
  return this.activePhaseId;
763
805
  }
806
+ /** Keeps the calls a strong attempt makes, under its test's default timeouts. */
807
+ watchWaits(timeouts) {
808
+ this.waitTimeouts = timeouts;
809
+ }
810
+ /** A call the test made on one of Playwright's objects, until it settles. */
811
+ trackWait(object, method, args, pending, site) {
812
+ if (!this.waitTimeouts || !(pending instanceof Promise))
813
+ return;
814
+ // A locator assertion's `_expect` comes from Playwright's matcher:
815
+ // where the test called the matcher.
816
+ this.keepWait(describeCall(object, method, args), ownDeadline({ method, args, startedAt: Date.now(), request: isApiRequestContext(object), timeouts: this.waitTimeouts }), pending, site ?? this.matcherSite);
817
+ }
818
+ /**
819
+ * An `expect.poll` or a `toPass`, until it settles: it ends by its own
820
+ * timeout, `timeout` where the test gave one, else its config's.
821
+ */
822
+ keepRetries(operation, timeout, polls, pending) {
823
+ if (!this.waitTimeouts || !(pending instanceof Promise))
824
+ return;
825
+ const ms = timeout ?? (polls ? this.waitTimeouts.expect : this.waitTimeouts.toPass);
826
+ this.keepWait(operation, ms > 0 ? Date.now() + ms : Infinity, pending, this.matcherSite);
827
+ }
828
+ keepWait(operation, deadline, pending, at) {
829
+ // Whether it is the test's own (not opening or closing a context or
830
+ // a page, as Playwright's fixtures do); the first such call is where
831
+ // the test's own time starts.
832
+ // Where in the test it was called (`at`), for a timeout's reason.
833
+ const wait = { operation: at ? `${operation} at ${at}` : operation, deadline, fromTest: !LIFECYCLE.has(operation.split(" ")[0]) };
834
+ if (wait.fromTest)
835
+ this.testCalledAt ??= Date.now();
836
+ this.waits.add(wait);
837
+ this.newestWait = wait;
838
+ const settled = () => this.waits.delete(wait);
839
+ pending.then(settled, settled);
840
+ }
841
+ /** A default timeout the test set on a page or a context: the shortest counts. */
842
+ lowerTimeout(method, args) {
843
+ const ms = Number(args[0]);
844
+ if (!this.waitTimeouts || !(ms > 0))
845
+ return;
846
+ const kind = method === "setDefaultTimeout" ? "action" : "navigation";
847
+ const now = this.waitTimeouts[kind];
848
+ this.waitTimeouts[kind] = now > 0 ? Math.min(now, ms) : ms;
849
+ }
850
+ /** What a strong attempt is stalled on before `limitAt`, if it is, and what it waits on now. */
851
+ stall(limitAt) {
852
+ const newest = this.newestWait;
853
+ const stalled = stalledOn({ waits: this.waits, newest, limitAt, quietSince: this.quietSince, now: Date.now() });
854
+ return { stalled: stalled?.operation, waiting: this.waits.has(newest) ? newest.operation : undefined, since: this.testCalledAt };
855
+ }
764
856
  async dispose() {
765
857
  this.disposed = true;
766
858
  await Promise.all([...this.pendingRegistrations]);
@@ -815,6 +907,9 @@ class CoveragePhaseController {
815
907
  const method = String(property);
816
908
  return (...args) => {
817
909
  this.promotePendingAssertion();
910
+ // Where the test made the call, while its frame is
911
+ // still on the stack.
912
+ const site = this.waitTimeouts ? testSite() : undefined;
818
913
  const isRequest = REQUEST_METHODS.has(method) &&
819
914
  isApiRequestContext(object);
820
915
  if (ACTION_METHODS.has(method) || isRequest) {
@@ -822,7 +917,9 @@ class CoveragePhaseController {
822
917
  const operation = `${object.constructor?.name ?? "Playwright"}.${method}`;
823
918
  const phase = await this.beginAction(operation);
824
919
  try {
825
- const result = await Reflect.apply(value, object, isRequest ? this.scopeApiRequest(args) : args);
920
+ const pending = Reflect.apply(value, object, isRequest ? this.scopeApiRequest(args) : args);
921
+ this.trackWait(object, method, args, pending, site);
922
+ const result = await pending;
826
923
  this.finish(phase);
827
924
  return this.prepareResult(result);
828
925
  }
@@ -836,6 +933,9 @@ class CoveragePhaseController {
836
933
  ? this.scopeBrowserContext(args)
837
934
  : args;
838
935
  const result = Reflect.apply(value, object, invokedArgs);
936
+ if (method === "setDefaultTimeout" || method === "setDefaultNavigationTimeout")
937
+ this.lowerTimeout(method, invokedArgs);
938
+ this.trackWait(object, method, invokedArgs, result, site);
839
939
  return this.wrapResult(result, method === "newContext" ? invokedArgs : undefined);
840
940
  };
841
941
  },
@@ -1664,7 +1764,12 @@ function isPlaywrightValue(value) {
1664
1764
  return true;
1665
1765
  }
1666
1766
  }
1667
- function wrapMatchers(matchers, path = "expect", settles = false) {
1767
+ /**
1768
+ * The matchers of an `expect`. `retries` is what an `expect.poll` or a
1769
+ * `toPass` retries under: whether it polls, and the timeout its `expect` was
1770
+ * given (`expect.poll(fn, { timeout })`, `expect.configure({ timeout })`).
1771
+ */
1772
+ function wrapMatchers(matchers, path = "expect", settles = false, retries = { polls: false, timeout: undefined }) {
1668
1773
  return new Proxy(matchers, {
1669
1774
  get(target, property) {
1670
1775
  // Matcher objects and built-ins can expose getters whose internal slots
@@ -1675,11 +1780,15 @@ function wrapMatchers(matchers, path = "expect", settles = false) {
1675
1780
  if (value &&
1676
1781
  typeof value === "object" &&
1677
1782
  (name === "not" || name === "resolves" || name === "rejects"))
1678
- return wrapMatchers(value, `${path}.${name}`, settles && name === "not");
1783
+ return wrapMatchers(value, `${path}.${name}`, settles && name === "not", retries);
1679
1784
  if (typeof value !== "function")
1680
1785
  return value;
1681
1786
  return (...args) => {
1682
1787
  const controller = activeController;
1788
+ // Where the test called the matcher: the calls it makes of
1789
+ // Playwright's objects are named by it.
1790
+ if (controller?.waitTimeouts)
1791
+ controller.matcherSite = testSite();
1683
1792
  const settled = settles && SETTLED_MATCHERS.has(name);
1684
1793
  const phase = bridgedAssertionDepth === 0
1685
1794
  ? controller?.beginAssertion(`${path}.${name}`, undefined, !settled)
@@ -1690,6 +1799,10 @@ function wrapMatchers(matchers, path = "expect", settles = false) {
1690
1799
  controller?.promotePendingAssertion();
1691
1800
  try {
1692
1801
  const result = Reflect.apply(value, target, args);
1802
+ // A poll, or `toPass`, retries until its own timeout,
1803
+ // whatever the calls in it wait on.
1804
+ if (retries.polls || name === "toPass")
1805
+ controller?.keepRetries(`${path}.${name}`, retries.polls ? retries.timeout : args[0]?.timeout ?? retries.timeout, retries.polls, result);
1693
1806
  if (result instanceof Promise) {
1694
1807
  return result.then((resolved) => {
1695
1808
  if (phase && controller)
@@ -1714,21 +1827,22 @@ function wrapMatchers(matchers, path = "expect", settles = false) {
1714
1827
  },
1715
1828
  });
1716
1829
  }
1717
- function wrapExpectCallable(callable, polls = false) {
1830
+ function wrapExpectCallable(callable, polls = false, timeout = undefined) {
1718
1831
  return new Proxy(callable, {
1719
1832
  apply(target, thisArg, argumentsList) {
1720
1833
  const result = Reflect.apply(target, thisArg, argumentsList);
1834
+ // `expect.configure(options)`: an `expect` under its timeout.
1721
1835
  if (typeof result === "function")
1722
- return wrapExpectCallable(result, polls);
1836
+ return wrapExpectCallable(result, polls, argumentsList[0]?.timeout ?? timeout);
1723
1837
  if (result && typeof result === "object")
1724
- return wrapMatchers(result, "expect", !polls && !isPlaywrightValue(argumentsList[0]));
1838
+ return wrapMatchers(result, "expect", !polls && !isPlaywrightValue(argumentsList[0]), { polls, timeout: polls ? argumentsList[1]?.timeout ?? timeout : timeout });
1725
1839
  return result;
1726
1840
  },
1727
1841
  get(target, property, receiver) {
1728
1842
  const value = Reflect.get(target, property, receiver);
1729
1843
  if (typeof value !== "function")
1730
1844
  return value;
1731
- return wrapExpectCallable(value.bind(target), polls || property === "poll");
1845
+ return wrapExpectCallable(value.bind(target), polls || property === "poll", timeout);
1732
1846
  },
1733
1847
  });
1734
1848
  }
@@ -1870,6 +1984,13 @@ const instrumentedFixtures = {
1870
1984
  const configuredHeaders = Object.fromEntries(Object.entries(testInfo.project.use.extraHTTPHeaders ?? {}).map(([name, value]) => [name, String(value)]));
1871
1985
  const setupStarted = performance.now();
1872
1986
  const controller = new CoveragePhaseController(scope, configuredHeaders, testInfo.project.use.baseURL);
1987
+ if (strong?.kind === "mutant")
1988
+ controller.watchWaits({
1989
+ action: testInfo.project.use.actionTimeout ?? 0,
1990
+ navigation: testInfo.project.use.navigationTimeout ?? 0,
1991
+ expect: testInfo.project.expect?.timeout ?? 5_000,
1992
+ toPass: testInfo.project.expect?.toPass?.timeout ?? 0,
1993
+ });
1873
1994
  controllers.set(scope.attemptId, controller);
1874
1995
  activeController = controller;
1875
1996
  directRuntime()?.activateCoverageScope(scope);
@@ -1908,10 +2029,13 @@ const instrumentedFixtures = {
1908
2029
  // A mutant that ran in this worker's own process may have left
1909
2030
  // state in it: the next test gets a new worker.
1910
2031
  let restartWorker = false;
2032
+ // A mutant attempt that stalls ends there, a timeout.
2033
+ const stall = watchStall(testInfo, strong, (limitAt) => controller.stall(limitAt));
1911
2034
  try {
1912
2035
  await use();
1913
2036
  }
1914
2037
  finally {
2038
+ stall?.stop();
1915
2039
  const teardownStarted = performance.now();
1916
2040
  const endedAtMs = Date.now();
1917
2041
  try {
@@ -1946,8 +2070,11 @@ const instrumentedFixtures = {
1946
2070
  appendEvidenceLine(`${JSON.stringify(payload)}\n`);
1947
2071
  }
1948
2072
  finally {
1949
- strongFinish(testInfo, strong, { attemptId: scope.attemptId, pageTimeout: controller.mutantRanAway === true });
1950
- restartWorker = ranInWorker(strong, scope.attemptId) && testInfo.status === "passed";
2073
+ strongFinish(testInfo, strong, { attemptId: scope.attemptId, pageTimeout: controller.mutantRanAway === true, ...stallDetails(stall) });
2074
+ const ranHere = ranInWorker(strong, scope.attemptId);
2075
+ restartWorker = ranHere && testInfo.status === "passed";
2076
+ if (keepsWorker(strong, ranHere, testInfo.status))
2077
+ testInfo.expectedStatus = testInfo.status;
1951
2078
  await timed("controller.dispose", () => controller.dispose());
1952
2079
  timingCount("fixture.testTeardown", performance.now() - teardownStarted);
1953
2080
  timingReport(testInfo.title);
@@ -9,10 +9,11 @@
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. 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
12
+ // mutant, nor after one fails its test (`keepsWorker`). A test's first run
13
+ // in each invocation is a control, with no mutant: the pass's baseline the
14
+ // first time; and after a kill, the test's next run is one too, the check
15
+ // that it still passes without the mutant on the same server, which
16
+ // confirms the kill. A harness may start several
16
17
  // invocations at once, each with a share of the tests; they share the pass's
17
18
  // files and decide the same way.
18
19
  //
@@ -46,6 +47,14 @@
46
47
  // mutant broke ends there; an attempt that ran out of it is a `timeout`,
47
48
  // confirmed as a kill is.
48
49
  //
50
+ // Such an attempt ends sooner where it has stalled (`watchStall`): past every
51
+ // time a run of its test that passed took (its baseline × the factor + 1 s),
52
+ // waiting on a Playwright call that cannot end by its own timeout before the
53
+ // limit (a click with no timeout, an `expect` given 15 s), with its pages
54
+ // quiet (no request sent or answered for a second). Nothing it waits on can
55
+ // make it fail before the limit, and no passing run took that long: the limit
56
+ // would end it as a `timeout` all the same, later.
57
+ //
49
58
  // This module holds what the config, the fixture (playwright.mjs) and the
50
59
  // reporter (playwrightStrongReporter.mjs) share.
51
60
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -54,6 +63,18 @@ import { basename, dirname, resolve, sep } from "node:path";
54
63
 
55
64
  const TIMEOUT_FACTOR = 1.5;
56
65
  const TIMEOUT_CONSTANT_MS = 5_000;
66
+ // Past its baseline × the factor + this, an attempt has outlasted every run
67
+ // of its test that passed: on a large app's suite, 5,831 attempts that passed
68
+ // took at most 0.5 s past their baseline.
69
+ const STALL_CONSTANT_MS = 1_000;
70
+ // How long an attempt's pages must have sent and answered no request.
71
+ const QUIET_MS = 1_000;
72
+ // How often a stalled attempt is looked for.
73
+ const STALL_POLL_MS = 100;
74
+ // Playwright's calls that wait for a navigation, under its navigation timeout.
75
+ const NAVIGATIONS = new Set(["goto", "reload", "goBack", "goForward", "waitForURL", "waitForNavigation", "waitForLoadState"]);
76
+ // An API request's own timeout where nothing sets one (Playwright's default).
77
+ const REQUEST_TIMEOUT_MS = 30_000;
57
78
  const DEFAULT_DURATION_MS = 1_000;
58
79
  // How much likelier to kill a mutant a test is taken to be where its own
59
80
  // evidence infected it than where it only reached it: what orders a mutant's
@@ -187,13 +208,122 @@ export function limitOf(baselineMs, factor) {
187
208
  return Math.ceil(baselineMs * factor + TIMEOUT_CONSTANT_MS);
188
209
  }
189
210
 
190
- /** What a verdict says of an attempt that ran out of its time limit. */
211
+ /** What a verdict says of an attempt that ran out of its time limit, or stalled before it. */
191
212
  function limitReason(attempt) {
192
213
  const seconds = (ms) => `${(ms / 1000).toFixed(1)} s`;
214
+ const waiting = attempt.waitingOn ? `, waiting on ${attempt.waitingOn}` : "";
215
+ if (attempt.stalledAtMs !== undefined)
216
+ return `stopped at ${seconds(attempt.stalledAtMs)} of its ${seconds(attempt.limitMs)} time limit, past every run of the test that passed (${attempt.timeoutFactor} × its ${seconds(attempt.baselineMs)} baseline + ${STALL_CONSTANT_MS / 1000} s), its pages quiet${waiting}, which cannot end before the limit`;
193
217
  const why = attempt.limitMs < limitOf(attempt.baselineMs, attempt.timeoutFactor)
194
218
  ? "the test's own timeout"
195
219
  : `${attempt.timeoutFactor} × its ${seconds(attempt.baselineMs)} baseline + ${TIMEOUT_CONSTANT_MS / 1000} s`;
196
- return `ran past its time limit of ${seconds(attempt.limitMs)} (${why})`;
220
+ return `ran past its time limit of ${seconds(attempt.limitMs)} (${why})${waiting}`;
221
+ }
222
+
223
+ /**
224
+ * When a Playwright call the test made ends by its own timeout, from when it
225
+ * began: `Infinity` where it has none. `method` is the call, `args` what it
226
+ * was given; `request` says it is an API request's; `timeouts` are the test's
227
+ * defaults (`action`, `navigation`; 0 for none). An `expect` on a locator
228
+ * reaches Playwright as `_expect`, with the timeout it runs under.
229
+ */
230
+ export function ownDeadline({ method, args, startedAt, request, timeouts }) {
231
+ const after = (ms) => (ms > 0 ? startedAt + ms : Infinity);
232
+ if (method === "waitForTimeout")
233
+ return startedAt + (Number(args[0]) || 0);
234
+ const options = [...args].reverse().find((arg) => arg !== null && typeof arg === "object" && typeof arg.timeout === "number");
235
+ if (options)
236
+ return after(options.timeout);
237
+ if (request)
238
+ return after(timeouts.action > 0 ? Math.min(timeouts.action, REQUEST_TIMEOUT_MS) : REQUEST_TIMEOUT_MS);
239
+ if (NAVIGATIONS.has(method))
240
+ return after(timeouts.navigation || timeouts.action);
241
+ return after(timeouts.action);
242
+ }
243
+
244
+ /**
245
+ * A Playwright call as a timeout's reason names it (a bundled
246
+ * Playwright's `_Locator` is a `Locator`): `Locator.click (#save)`, `expect(#save) to.be.visible`, `expect to.have.url`,
247
+ * `Page.waitForURL`.
248
+ */
249
+ export function describeCall(object, method, args) {
250
+ const selector = typeof object?._selector === "string" ? object._selector : undefined;
251
+ const said = method === "_expect"
252
+ ? `expect${selector ? `(${selector})` : ""} ${args[0]}`
253
+ : `${(object?.constructor?.name ?? "Playwright").replace(/^_+/, "")}.${method}${selector ? ` (${selector})` : ""}`;
254
+ return said.length > 160 ? `${said.slice(0, 159)}…` : said;
255
+ }
256
+
257
+ /**
258
+ * The call a stalled attempt waits on, or `undefined`: the newest Playwright
259
+ * call, one the test's own code made, has not returned, no call still running can end by its
260
+ * own timeout before `limitAt`, and its pages have been quiet since
261
+ * `quietSince` for a second.
262
+ */
263
+ export function stalledOn({ waits, newest, limitAt, quietSince, now }) {
264
+ // The newest call is the test's own (a fixture's setup, such as a new
265
+ // page, is no wait of the test's).
266
+ if (!newest || !waits.has(newest) || !newest.fromTest)
267
+ return undefined;
268
+ if (now - quietSince < QUIET_MS)
269
+ return undefined;
270
+ for (const wait of waits) {
271
+ if (wait.deadline < limitAt)
272
+ return undefined;
273
+ }
274
+ return newest;
275
+ }
276
+
277
+ /** When, from its start, a mutant attempt has outlasted every passing run of its test. */
278
+ export function stallWindowOf(baselineMs, factor) {
279
+ return Math.ceil(baselineMs * factor + STALL_CONSTANT_MS);
280
+ }
281
+
282
+ /**
283
+ * Ends a mutant attempt as a timeout once it has stalled (`stalledOn`, asked
284
+ * of `look(limitAt)` every tenth of a second from the end of its window, which
285
+ * counts from the first call the test's own code made, `since`):
286
+ * its test's timeout is set to what it has already run. The watch says when
287
+ * it did so and on what (`stalled`), and, where it went on to its limit, what
288
+ * it last waited on (`waiting`). `stop()` ends the watch.
289
+ */
290
+ export function watchStall(testInfo, claimed, look) {
291
+ if (claimed?.kind !== "mutant")
292
+ return undefined;
293
+ const from = claimed.startedAt + stallWindowOf(claimed.baselineMs, claimed.timeoutFactor);
294
+ if (from >= claimed.limitAt)
295
+ return undefined;
296
+ const windowMs = stallWindowOf(claimed.baselineMs, claimed.timeoutFactor);
297
+ const watch = { stalled: undefined, waiting: undefined, timer: undefined };
298
+ const check = () => {
299
+ // A test whose body has ended (it failed, ran out of time, or its
300
+ // fixtures are being torn down: Playwright sets its duration then)
301
+ // waits on nothing of its own: what its teardown closes is not what
302
+ // it waited on.
303
+ if (testInfo.status !== "passed" || testInfo.duration > 0)
304
+ return;
305
+ const { stalled, waiting, since } = look(claimed.limitAt);
306
+ watch.waiting = waiting;
307
+ // The window counts from the test's first call of its own, not from
308
+ // its claim: setting up its page in a new worker on a loaded machine
309
+ // took seconds, which no baseline holds.
310
+ if (stalled && Date.now() >= since + windowMs) {
311
+ watch.stalled = { atMs: Date.now() - claimed.startedAt, waitingOn: stalled };
312
+ testInfo.setTimeout(Math.max(1, Date.now() - claimed.claimedAt));
313
+ return;
314
+ }
315
+ watch.timer = setTimeout(check, STALL_POLL_MS);
316
+ };
317
+ watch.timer = setTimeout(check, Math.max(0, from - Date.now()));
318
+ watch.stop = () => clearTimeout(watch.timer);
319
+ return watch;
320
+ }
321
+
322
+ /** What a stall watch adds to its attempt's end. */
323
+ export function stallDetails(watch) {
324
+ if (watch?.stalled)
325
+ return { stalledAtMs: watch.stalled.atMs, waitingOn: watch.stalled.waitingOn };
326
+ return watch?.waiting ? { waitingOn: watch.waiting } : {};
197
327
  }
198
328
 
199
329
  /**
@@ -316,7 +446,7 @@ function buildPass(pass, root, config) {
316
446
  if (job && job.kind !== "main") {
317
447
  for (const entry of job.mutants) {
318
448
  const all = [...entry.tests, ...(entry.rest ?? [])].filter((id) => tests[id]);
319
- mutants.push({ id: entry.id, mutant: entry.mutant, tests: [...new Set(all)], reason: entry.reason });
449
+ mutants.push({ id: entry.id, mutant: entry.mutant, tests: [...new Set(all)], reason: entry.reason, ...(entry.serverRan ? { serverRan: true } : {}) });
320
450
  }
321
451
  // A serial round runs one test at a time: what it kills, nothing
322
452
  // beside it did.
@@ -397,7 +527,7 @@ function buildPass(pass, root, config) {
397
527
  restarts.push({ id: mutant.id, mutant: switched, tests: ordered, reason: serverWide });
398
528
  continue;
399
529
  }
400
- mutants.push({ id: mutant.id, mutant: switched, tests: ordered, infected, ...(mutant.passedBefore ? { passedBefore: mutant.passedBefore } : {}) });
530
+ mutants.push({ id: mutant.id, mutant: switched, tests: ordered, infected, ...(mutant.passedBefore ? { passedBefore: mutant.passedBefore } : {}), ...(mutant.serverRan ? { serverRan: true } : {}) });
401
531
  }
402
532
  }
403
533
  // What a survivor's verdict says of the candidates it was not run with.
@@ -1412,6 +1542,7 @@ export async function strongClaim(testInfo) {
1412
1542
  else if (configured > 0)
1413
1543
  testInfo.setTimeout(Date.now() - started + configured);
1414
1544
  const { running, beside } = startRunning(pass, testInfo.testId, attempt.mutant);
1545
+ const startedAt = Date.now();
1415
1546
  const claimed = {
1416
1547
  original,
1417
1548
  title: test.title,
@@ -1421,8 +1552,10 @@ export async function strongClaim(testInfo) {
1421
1552
  kind: attempt.kind,
1422
1553
  id: attempt.id,
1423
1554
  mutant: attempt.mutant,
1424
- ...(attempt.kind === "mutant" ? { baselineMs: attempt.baselineMs, limitMs: attempt.limitMs, timeoutFactor: attempt.timeoutFactor, ...(attempt.cold ? { cold: true } : {}) } : {}),
1425
- startedAt: Date.now(),
1555
+ // A mutant's: when its limit ends it, and when its claim began,
1556
+ // which the test's timeout counts from (`watchStall`).
1557
+ ...(attempt.kind === "mutant" ? { baselineMs: attempt.baselineMs, limitMs: attempt.limitMs, timeoutFactor: attempt.timeoutFactor, limitAt: startedAt + attempt.limitMs, claimedAt: started, ...(attempt.cold ? { cold: true } : {}) } : {}),
1558
+ startedAt,
1426
1559
  lock,
1427
1560
  running,
1428
1561
  besideAtStart: beside,
@@ -1480,11 +1613,44 @@ function passedWith(pass, id) {
1480
1613
  return new Set(entries(`${pass.round}/passed/${key(id)}`));
1481
1614
  }
1482
1615
 
1616
+ /**
1617
+ * The mutants an attempt ran on its server, in work one of its requests set
1618
+ * off (`noteRequestHit` in runtime.mjs): their switches, `file#index`.
1619
+ */
1620
+ export function ranByRequests(pass) {
1621
+ const ran = new Set();
1622
+ const path = `${pass.resultsPath}.reached.jsonl`;
1623
+ if (!existsSync(path))
1624
+ return ran;
1625
+ for (const line of readFileSync(path, "utf8").split("\n")) {
1626
+ try {
1627
+ ran.add(JSON.parse(line).mutant);
1628
+ }
1629
+ catch {
1630
+ // A line a process was still writing, or none.
1631
+ }
1632
+ }
1633
+ return ran;
1634
+ }
1635
+
1636
+ /**
1637
+ * Whether a survivor of a shared server is in doubt: its candidates' servers
1638
+ * ran its code when measured, and no attempt of it ran it here. The request
1639
+ * that reached its code did not carry the attempt's mutant (`unreached`): its
1640
+ * verdict is the one it gets alone, with the server started with it.
1641
+ */
1642
+ export function unreached(kind, entry, ran) {
1643
+ return kind !== "alone" && entry.serverRan === true && !ran.has(entry.mutant);
1644
+ }
1645
+
1483
1646
  /** A mutant every candidate test lets live, now that one more passed with it: its verdict. */
1484
1647
  function surviveIfDone(pass, id) {
1485
1648
  if (settled(pass, id) || existsSync(`${pass.round}/confirm/${key(id)}`) || existsSync(`${pass.round}/doubt/${key(id)}`))
1486
1649
  return;
1487
1650
  const entry = mutantOf(pass, id);
1651
+ // The round's judge sends it to run alone.
1652
+ if (unreached(loadWorker(pass).kind, entry, ranByRequests(pass)))
1653
+ return;
1488
1654
  const passed = passedWith(pass, id);
1489
1655
  // Every candidate passed with it: one that failed without it is left to
1490
1656
  // the round's judge, once its controls are all known.
@@ -1503,8 +1669,9 @@ export const WHY = {
1503
1669
  "unfinished": "not every candidate test ran in the shared pass",
1504
1670
  "confirm": "a test killed it beside other mutants' attempts",
1505
1671
  "doubt": "the test that killed it failed without it too, on the same server",
1672
+ "unreached": "its candidates passed on the shared server, yet no attempt of theirs ran it there: the requests that reached its code did not carry their test's mutant",
1506
1673
  };
1507
- export const EVERYWHERE = ["background", "module-level", "by-time"];
1674
+ export const EVERYWHERE = ["background", "module-level", "by-time", "unreached"];
1508
1675
 
1509
1676
  /** What a verdict from a later round says of it. */
1510
1677
  export function reasonOf(kind, reason) {
@@ -1670,6 +1837,25 @@ export function ranInWorker(claimed, attemptId) {
1670
1837
  return Boolean(strong?.requestHits?.get?.(`${attemptId}\0${claimed.mutant}`));
1671
1838
  }
1672
1839
 
1840
+ /**
1841
+ * Whether a mutant attempt that failed or ran out of time keeps its worker
1842
+ * for the next copy: Playwright ends a worker after a test fails, to start
1843
+ * the next test in a new one with a new browser, and on a large app's e2e
1844
+ * suite a failed attempt was one in seven. The failure is the mutant's, in
1845
+ * the app it was switched on in, and the worker's process ran none of it
1846
+ * (`ranInWorker`), so the worker is as before. The attempt is marked as
1847
+ * expected to end so (`expectedStatus`), which Playwright reads after the
1848
+ * test's fixtures are torn down; its verdict is read from its status, as
1849
+ * before. A control that fails (no mutant) still ends its worker, and so
1850
+ * does an attempt whose mutant ran in the worker's own process. A kill is
1851
+ * confirmed by its test's next control on the same server, as before: a
1852
+ * worker the failure did leave unfit fails that control, and puts the kill
1853
+ * in doubt.
1854
+ */
1855
+ export function keepsWorker(claimed, ranHere, status) {
1856
+ return claimed?.kind === "mutant" && !ranHere && (status === "failed" || status === "timedOut");
1857
+ }
1858
+
1673
1859
  /**
1674
1860
  * Switches a document's mutant on before its scripts run: an init script.
1675
1861
  * Every copy of the runtime in the page reads the state from here.
@@ -12,7 +12,7 @@
12
12
  import { appendFileSync, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
13
  import { dirname, join } from "node:path";
14
14
  import { pathToFileURL } from "node:url";
15
- import { attemptPath, baselineOf, entries, invocation, EVERYWHERE, firstWords, giveVerdict, key, loadPass, outcomeOf, placeOf, queuedWork, readJson, reasonOf, serialFile, settleAttempt, strongPass, verdictOf, withoutCopy, writeJson } from "./playwrightStrong.mjs";
15
+ import { attemptPath, baselineOf, entries, invocation, EVERYWHERE, firstWords, giveVerdict, key, loadPass, outcomeOf, placeOf, queuedWork, ranByRequests, readJson, reasonOf, serialFile, settleAttempt, strongPass, unreached, verdictOf, withoutCopy, writeJson } from "./playwrightStrong.mjs";
16
16
 
17
17
  // How often, at most, the status file is written.
18
18
  const STATUS_MS = 1_000;
@@ -40,6 +40,11 @@ function readJsonOr(path) {
40
40
  }
41
41
  }
42
42
 
43
+ /** Ids for a message: the first few, and how many more. */
44
+ function listed(ids) {
45
+ const shown = ids.slice(0, 5).join(", ");
46
+ return ids.length > 5 ? `${shown} and ${ids.length - 5} more` : shown;
47
+ }
43
48
  function readLines(path) {
44
49
  if (!existsSync(path))
45
50
  return [];
@@ -173,12 +178,16 @@ export default class SupercovPlaywrightStrongReporter {
173
178
  const said = {
174
179
  "passed": "lives",
175
180
  "failed": "fails",
176
- "timed-out": `ran out of its ${seconds(attempt.limitMs)} limit (its baseline ${seconds(attempt.baselineMs)})`,
181
+ "timed-out": attempt.stalledAtMs === undefined
182
+ ? `ran out of its ${seconds(attempt.limitMs)} limit (its baseline ${seconds(attempt.baselineMs)})`
183
+ : `stalled before its ${seconds(attempt.limitMs)} limit (its baseline ${seconds(attempt.baselineMs)})`,
177
184
  }[attempt.outcome] ?? attempt.outcome;
185
+ // What a timeout waited on, where the fixture saw it.
186
+ const waiting = attempt.outcome === "timed-out" && attempt.waitingOn ? `, waiting on ${attempt.waitingOn}` : "";
178
187
  // A cold attempt's failure decides nothing: it runs again once a
179
188
  // control has passed on its server.
180
189
  const cold = attempt.cold && (attempt.outcome === "failed" || attempt.outcome === "timed-out") ? ", before any control here: runs again after one" : "";
181
- console.log(`[supercov] ${attempt.id}: ${JSON.stringify(attempt.title)} ${said} (${took}${cold})`);
190
+ console.log(`[supercov] ${attempt.id}: ${JSON.stringify(attempt.title)} ${said}${waiting} (${took}${cold})`);
182
191
  }
183
192
  /**
184
193
  * What this invocation is doing, for the engine's progress line: the
@@ -319,7 +328,7 @@ export default class SupercovPlaywrightStrongReporter {
319
328
  write({ id: entry.id, status: "error", reason: "its candidate tests fail without any mutant", tests: 0, durationMs: 0 });
320
329
  return;
321
330
  }
322
- const job = { id: entry.id, mutant: entry.mutant, tests: runnable, reason };
331
+ const job = { id: entry.id, mutant: entry.mutant, tests: runnable, reason, ...(entry.serverRan ? { serverRan: true } : {}) };
323
332
  // What an alone round left runs alone again, as it was.
324
333
  if (kind === "alone")
325
334
  aloneEach.push({ ...job, reason: entry.reason });
@@ -347,6 +356,9 @@ export default class SupercovPlaywrightStrongReporter {
347
356
  claimedBy.set(taken.id, name.replace(/\.json$/, ""));
348
357
  }
349
358
  const ranInServer = new Set(readLines(`${pass.resultsPath}.everywhere.jsonl`).map((line) => `${line.invocation}\0${line.mutant}`));
359
+ const ranByRequest = ranByRequests(pass);
360
+ // Survivors no attempt ran: they run again alone.
361
+ const notRan = [];
350
362
  for (const [id, entry] of Object.entries(work.entries)) {
351
363
  if (existsSync(`${pass.shared}/verdicts/${key(id)}`)) {
352
364
  decided += 1;
@@ -420,12 +432,28 @@ export default class SupercovPlaywrightStrongReporter {
420
432
  next(entry, "unfinished", left);
421
433
  continue;
422
434
  }
435
+ if (unreached(kind, entry, ranByRequest)) {
436
+ notRan.push(id);
437
+ next(entry, "unreached", runnable);
438
+ continue;
439
+ }
423
440
  verdict(entry.unrun
424
441
  ? { status: "error", reason: `no Playwright test killed it, and ${entry.unrun}` }
425
442
  : { status: "survived", ...(after ? { reason: after } : {}) });
426
443
  }
427
444
  for (const job of work.restarts)
428
445
  next(job, job.reason, job.tests);
446
+ // Said where the pass's output is read: a verdict a server's switch
447
+ // missed is a Supercov fault, and other survivors may share it.
448
+ if (notRan.length)
449
+ console.error(`[supercov] warning: ${notRan.length} mutant(s) lived through every candidate test on the shared server, though no attempt ran them there: the requests that reached their code did not carry their test's mutant. Each runs again alone, with the server started with it switched on: ${listed(notRan)}`);
450
+ if (kind === "alone") {
451
+ const killedAlone = readLines(pass.resultsPath)
452
+ .filter((record) => work.entries[record.id]?.reason === "unreached" && (record.status === "killed" || record.status === "timeout"))
453
+ .map((record) => record.id);
454
+ if (killedAlone.length)
455
+ console.error(`[supercov] warning: ${killedAlone.length} mutant(s) the shared server let live were killed alone, with the server started with them switched on; their verdicts are the kills: ${listed(killedAlone)}`);
456
+ }
429
457
  // What each mutant left open passed: its candidates that ran with it
430
458
  // and passed (before any error outside a test), by the plan's ids. A
431
459
  // later pass, or a later round, resumes there. A round of mutants a
@@ -2214,10 +2214,20 @@ function installNodeRequestPropagation() {
2214
2214
  }
2215
2215
  installNodeRequestPropagation();
2216
2216
 
2217
+ // The context of a request this process is serving, made as it came in
2218
+ // (`owningRequest`): it carries the request's lifetime.
2219
+ function servedRequestContext(context) {
2220
+ return context !== void 0 && context[REQUEST_LIFETIME] !== void 0 ? context : void 0;
2221
+ }
2217
2222
  function withRequestPhase(handler, event) {
2218
2223
  if (!serverPhaseStorage)
2219
2224
  return handler;
2220
- const registeredContext = currentRequestContext();
2225
+ // A handler wrapped while a request was being served -- a route module a
2226
+ // framework loads on its first request, as Next.js does -- belongs to no
2227
+ // test: that request was one attempt's, and every later request naming no
2228
+ // test (a webhook from a mock) ran as that attempt's, in a strong pass with
2229
+ // its mutant rather than the one of the test that set the request off.
2230
+ const registeredContext = servedRequestContext(serverPhaseStorage.getStore()) ? {} : currentRequestContext();
2221
2231
  return function coverageRequestPhase(...args) {
2222
2232
  var _a8, _b, _c, _d;
2223
2233
  const requestContext = args.map((argument) => requestCoverageContext(argument)).find((context2) => context2 !== void 0);
@@ -2227,7 +2237,14 @@ function withRequestPhase(handler, event) {
2227
2237
  const context = __spreadValues(__spreadValues({}, ((_a8 = requestContext == null ? void 0 : requestContext.scope) != null ? _a8 : inheritedContext.scope) ? { scope: (_b = requestContext == null ? void 0 : requestContext.scope) != null ? _b : inheritedContext.scope } : {}), ((_c = requestContext == null ? void 0 : requestContext.phaseId) != null ? _c : inheritedContext.phaseId) ? { phaseId: (_d = requestContext == null ? void 0 : requestContext.phaseId) != null ? _d : inheritedContext.phaseId } : {});
2228
2238
  if (requestContext !== void 0 && !context.scope)
2229
2239
  context.request = nextUnscopedRequest();
2230
- const lifetime = requestContext !== void 0 ? args.map((argument) => argument && typeof argument === "object" ? argument[REQUEST_LIFETIME] : void 0).find((found) => found !== void 0) : void 0;
2240
+ let lifetime = requestContext !== void 0 ? args.map((argument) => argument && typeof argument === "object" ? argument[REQUEST_LIFETIME] : void 0).find((found) => found !== void 0) : void 0;
2241
+ // A framework's own request object -- the web `Request` a Next.js route
2242
+ // handler is given -- carries no lifetime, and work the handler left
2243
+ // running after the answer (`after()`) stayed the request's. The request
2244
+ // being served, whose context the handler is called in, has it.
2245
+ const served = servedRequestContext(serverPhaseStorage.getStore());
2246
+ if (lifetime === void 0 && requestContext !== void 0 && served !== void 0 && (context.scope ? served.scope !== void 0 && served.scope.attemptId === context.scope.attemptId : served.scope === void 0))
2247
+ lifetime = served[REQUEST_LIFETIME];
2231
2248
  if (lifetime !== void 0)
2232
2249
  context[REQUEST_LIFETIME] = lifetime;
2233
2250
  const invoke = () => {
@@ -3098,6 +3115,8 @@ function strongHit() {
3098
3115
  const key = `${attemptId}\0${mutant.key}`;
3099
3116
  const hits = (strong.requestHits.get(key) || 0) + 1;
3100
3117
  strong.requestHits.set(key, hits);
3118
+ if (hits === 1)
3119
+ noteRequestHit(mutant.key, attemptId);
3101
3120
  if (hits > strong.limit) {
3102
3121
  noteMutantTimeout(mutant.file, mutant.index, attemptId);
3103
3122
  throw new MutantTimeoutError(mutant.file, mutant.index, hits);
@@ -3112,6 +3131,22 @@ function strongHit() {
3112
3131
  if (strong.hits === 1)
3113
3132
  noteEverywhereHit(strong);
3114
3133
  }
3134
+ // An attempt's own mutant ran here, in work one of its requests set off: the
3135
+ // pass trusts a survivor of a shared server only where an attempt of it ran
3136
+ // it (playwrightStrongReporter.mjs). A mutant its candidates reached when
3137
+ // measured, which none of its attempts ran, ran where the request's switch
3138
+ // never reached; it runs again alone, with the server started with it.
3139
+ function noteRequestHit(mutant, attemptId) {
3140
+ try {
3141
+ if (isBrowser || typeof process === "undefined" || !process.env)
3142
+ return;
3143
+ const results = process.env["SUPERCOV_STRONG_RESULTS"];
3144
+ const fs = results ? getFs() : void 0;
3145
+ if (fs)
3146
+ fs.appendFileSync(`${results}.reached.jsonl`, JSON.stringify({ attemptId, mutant }) + "\n");
3147
+ } catch (e) {
3148
+ }
3149
+ }
3115
3150
  // A process started with a mutant switched on everywhere, in a round where
3116
3151
  // each Playwright invocation runs one mutant of its own (its runner set
3117
3152
  // SUPERCOV_ACTIVE_MUTANT for the processes it starts, the app's server among
@@ -20,7 +20,11 @@
20
20
  // whose parent was not chosen) runs whole from then on. A kill by a job that
21
21
  // ran other tests than its baseline did is confirmed by running the job's
22
22
  // tests again without the mutant. A job past 3x its baseline and 10 s is
23
- // stopped: a timeout, unless a test had already failed.
23
+ // stopped: a timeout, unless a test had already failed. A baseline ran with
24
+ // the machine to itself, and a job that ran beside others may have spent its
25
+ // time waiting on them (the CPU; Cargo's lock on a build directory, where
26
+ // each job builds Rust compiled to wasm): such a job runs again alone, and
27
+ // only one past its limit there is a timeout.
24
28
  import { fork, spawn } from "node:child_process";
25
29
  import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
26
30
  import { availableParallelism, constants, cpus } from "node:os";
@@ -96,6 +100,49 @@ export function slots(size) {
96
100
  };
97
101
  }
98
102
 
103
+ // Turns at the machine: `shared` work runs beside other shared work, and
104
+ // `alone` work waits until none runs, while no shared work starts. A shared
105
+ // turn learns whether other work ran beside it (`crowded`).
106
+ export function turns() {
107
+ const running = new Set();
108
+ const idle = [];
109
+ let alone;
110
+ return {
111
+ async shared(work) {
112
+ while (alone)
113
+ await alone;
114
+ const turn = { crowded: running.size > 0 };
115
+ for (const other of running)
116
+ other.crowded = true;
117
+ running.add(turn);
118
+ try {
119
+ return await work(turn);
120
+ }
121
+ finally {
122
+ running.delete(turn);
123
+ if (running.size === 0)
124
+ for (const wake of idle.splice(0))
125
+ wake();
126
+ }
127
+ },
128
+ async alone(work) {
129
+ while (alone)
130
+ await alone;
131
+ let end;
132
+ alone = new Promise((done) => { end = done; });
133
+ try {
134
+ if (running.size > 0)
135
+ await new Promise((wake) => idle.push(wake));
136
+ return await work({ crowded: false });
137
+ }
138
+ finally {
139
+ alone = undefined;
140
+ end();
141
+ }
142
+ },
143
+ };
144
+ }
145
+
99
146
  // Every file under `directory`, recursively.
100
147
  function filesUnder(directory) {
101
148
  let entries;
@@ -431,16 +478,19 @@ export async function drive({ command, plan, resultsPath, root = process.cwd(),
431
478
  });
432
479
  return handed ? parallel(work, priority) : result;
433
480
  };
434
- const profile = { jobs: 0, baselines: 0, confirmations: 0, overturned: 0, stopped: 0, jobMs: 0 };
481
+ const profile = { jobs: 0, baselines: 0, confirmations: 0, overturned: 0, stopped: 0, alone: 0, jobMs: 0 };
482
+ const machine = turns();
435
483
  let jobNumber = 0;
436
484
 
437
485
  // One start of the command: `tests` of `file` (null: all of them), with
438
486
  // `mutant` on (null: none), stopped at `limitMs`. A job of a mutant's
439
487
  // later batch (`priority` 1, 2, ...) waits behind every first file's,
440
488
  // so that the kills most mutants get at once come first, and a
441
- // survivor's many files fill what is left.
442
- function job({ mutant, file, tests: chosen, bail, limitMs, priority = 0 }) {
443
- return run(() => new Promise((resolveJob) => {
489
+ // survivor's many files fill what is left. One run `alone` waits for no
490
+ // slot: it has the machine to itself.
491
+ function job({ mutant, file, tests: chosen, bail, limitMs, priority = 0, alone = false }) {
492
+ const start = (work) => (alone ? machine.alone(work) : run(() => machine.shared(work), priority));
493
+ return start((turn) => new Promise((resolveJob) => {
444
494
  const number = ++jobNumber;
445
495
  profile.jobs += 1;
446
496
  const directory = join(work, String(number));
@@ -458,7 +508,7 @@ export async function drive({ command, plan, resultsPath, root = process.cwd(),
458
508
  const statuses = outcomes(evidence);
459
509
  if (environment.SUPERCOV_STRONG_KEEP !== "1")
460
510
  rmSync(directory, { recursive: true, force: true });
461
- return { ...outcome, statuses };
511
+ return { ...outcome, statuses, crowded: turn.crowded };
462
512
  };
463
513
  // A runner's own command, started for this job alone.
464
514
  const spawnJob = () => {
@@ -561,7 +611,7 @@ export async function drive({ command, plan, resultsPath, root = process.cwd(),
561
611
  durationMs: Date.now() - begun,
562
612
  }));
563
613
  });
564
- }), priority);
614
+ }));
565
615
  }
566
616
 
567
617
  // What a file does without a mutant: once with every test a mutant will
@@ -633,9 +683,16 @@ export async function drive({ command, plan, resultsPath, root = process.cwd(),
633
683
  const limitMs = 3 * baseline.durationMs + graceMs;
634
684
  // A test that fails without the mutant must not stop the job.
635
685
  const bail = !whole || [...baseline.statuses.values()].every((status) => status === "passed");
636
- const result = await job({ mutant, file: group.file, tests: chosen, bail, limitMs, priority });
686
+ let result = await job({ mutant, file: group.file, tests: chosen, bail, limitMs, priority });
687
+ const killerIn = (outcome) => [...outcome.statuses].find(([id, status]) => status === "failed" && (chosen === null || chosen.has(id)) && !excluded(id))?.[0];
688
+ // Past its limit beside other jobs, with nothing failed: it may
689
+ // only have waited on them, so it runs again alone.
690
+ if (result.timedOut && result.crowded && !result.mutantTimedOut && killerIn(result) === undefined) {
691
+ profile.alone += 1;
692
+ result = await job({ mutant, file: group.file, tests: chosen, bail, limitMs, alone: true });
693
+ }
637
694
  const ran = [...result.statuses].filter(([id, status]) => status !== "skipped" && (chosen === null || chosen.has(id)));
638
- const killer = ran.find(([id, status]) => status === "failed" && !excluded(id))?.[0];
695
+ const killer = killerIn(result);
639
696
  if (result.mutantTimedOut)
640
697
  return { status: "timeout", reason: "the mutant's evaluations passed its limit", tests: ran.length };
641
698
  if (killer === undefined) {