@hughescr/stryker-bun-runner 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,6 +69,8 @@ The plugin uses Bun's Inspector Protocol (WebSocket) to:
69
69
 
70
70
  Oversized covering-test patterns (over 100,000 UTF-8 bytes) fall back to running the full suite, to stay within OS argument-length limits. This approach provides reliable test-to-mutant correlation, even with multiple test files.
71
71
 
72
+ A second full-suite fallback happens at run time: a `--test-name-pattern` that matches zero tests triggers a one-shot full-suite retry (see [Diagnostic warnings worth grepping for in CI](#diagnostic-warnings-worth-grepping-for-in-ci)).
73
+
72
74
  ## Options
73
75
 
74
76
  | Option | Type | Default | Description |
@@ -168,10 +170,127 @@ export default {
168
170
  };
169
171
  ```
170
172
 
173
+ ## Diagnostic warnings worth grepping for in CI
174
+
175
+ The runner logs three warnings that flag when a mutant run's `--test-name-pattern`
176
+ couldn't be built or applied with full fidelity. None of them indicate a wrong
177
+ mutation-testing verdict by themselves, but they're worth grepping your CI logs for
178
+ because they mark where the runner fell back to less-precise behavior:
179
+
180
+ - **`--test-name-pattern matched 0 tests`** — the pattern for a mutant's covering
181
+ tests matched nothing across the whole run (usually because a mutant changed a
182
+ value interpolated into an `it.each` title). The runner retries once with the
183
+ full suite rather than reporting a false kill, so the eventual verdict is still
184
+ genuine — if the retry itself also matches zero tests (or the zero-match came
185
+ from a user-supplied `--test-name-pattern` in `bunArgs`, which is never retried),
186
+ the mutant is classified as an infrastructure `Error`, never a kill. Every
187
+ occurrence is worth spot-checking that it's explained by an interpolated-title
188
+ change, not a real pattern gap.
189
+ - **`no exact-name registry available`** — this worker couldn't load the shared
190
+ dry-run test-name registry, so every alternative in that mutant's pattern used
191
+ the lossy `' > '`-collapsing reconstruction instead of Bun's exact matching
192
+ names. Tests whose titles legitimately contain `" > "` may have been silently
193
+ excluded from that run.
194
+ - **`missing from exact-name registry`** — the registry loaded, but one or more
195
+ `testFilter` ids for this mutant weren't in it (falls back to the same lossy
196
+ reconstruction for just those ids, listing up to 5 of the missing ids).
197
+
198
+ The last two matter because Bun only errors when a pattern matches **zero** tests
199
+ across the whole run; a *partial* miss — some alternatives hit, others silently
200
+ don't — exits 0 with no error text at all. These two warns are the only signal
201
+ that a partial silent drop was possible for a given mutant run, so seeing either
202
+ of them in a clean run's logs is worth investigating before trusting the score.
203
+
204
+ ### Dry-run failure diagnostics (dry run only)
205
+
206
+ - **`Bun exited with code <N> and its console output reported <N> failed test(s), but no failing test could be identified...`**
207
+ — the dry run's process-level signals (a non-zero exit code, or a `>0` failed
208
+ count parsed from Bun's console recap) say a test failed, but neither the
209
+ inspector's per-test data nor the parsed console output identifies which one
210
+ — the "empty recap" incident fingerprint: Bun prints e.g. `1 tests failed:`
211
+ with no `(fail)` line naming a test. The most likely cause is an unhandled
212
+ error firing *between* tests (e.g. a rejected fire-and-forget promise) rather
213
+ than inside any single test body, so nothing in bun's own per-test
214
+ bookkeeping ever marked a test as failed. What to do: check the trailing
215
+ stderr included in the warning for a stack, and look for fire-and-forget
216
+ async work (unawaited promises, orphaned timers) anywhere in the suite —
217
+ especially in the file that was running when the process exited. This
218
+ warning is purely diagnostic and never alters the returned `DryRunResult`
219
+ by itself; it's a separate, related change that failed tests' `failureMessage`
220
+ in a *Complete* result now has the inspector's `error.stack` appended (when
221
+ available) — Stryker core only prints name+failureMessage for initial-run
222
+ failures, so that's the only channel this stack reaches the CI log through.
223
+
224
+ ### Dry-run completeness gate (dry run only)
225
+
226
+ - **`stryker-bun-runner: dry run data-completeness check failed — ...`** — the dry
227
+ run otherwise looked healthy (no failed tests) but the runner detected that Bun's
228
+ inspector event stream may have been silently truncated mid-run: either the
229
+ inspector's execution order fell materially short of what Bun's own console
230
+ summary reported (`console reported <N> test(s) ... but the inspector's execution
231
+ order contains only <M> non-skipped test(s)`), or a meaningful number of coverage
232
+ keys couldn't be paired with any inspector test (`<N> of <M> coverage key(s) ...
233
+ could not be paired with any inspector test (orphaned)`) — the signature of one or
234
+ more whole test files being dropped from the stream, most often under CI runner
235
+ resource contention. When both are present, or the socket also closed
236
+ unexpectedly before the runner could finish reading it, the message names all of
237
+ them. This is a genuine `DryRunStatus.Error`, not a warning: proceeding on
238
+ truncated data would risk silently corrupted coverage attribution (mutants losing
239
+ their true killers), so the runner reports the error and does **not** persist the
240
+ test registry, rather than let other Stryker workers load a corrupted one. If you
241
+ see this, it usually means the CI runner was under heavier contention than usual;
242
+ retrying the run (with less concurrent load, or fewer parallel Stryker workers) is
243
+ the first thing to try.
244
+
245
+ The gate's thresholds — `EXECUTION_SHORTFALL_ABS_FLOOR`, `EXECUTION_SHORTFALL_RATIO_THRESHOLD`,
246
+ `ORPHANED_KEY_ABS_FLOOR`, and the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS` it depends on —
247
+ are fixed module-level constants in `src/bun-test-runner.ts`. There is currently no config
248
+ option to override them; if these defaults produce false positives in your environment
249
+ (e.g. a CI runner with very different contention characteristics than the ones this gate
250
+ was tuned against), a config knob is a possible follow-up — please open an issue rather
251
+ than patching the constants locally.
252
+
253
+ ### Coverage-bleed warning (dry run only)
254
+
255
+ - **`mutant coverage was recorded between tests, after '<testName>' completed`**
256
+ — during the dry run's coverage collection, mutant coverage was recorded in the
257
+ gap between one test's `afterEach` and the next test's `beforeEach`, i.e. while
258
+ no test was active. The most likely cause is a fire-and-forget promise chain
259
+ (or other async work) started by `<testName>` that kept running past that
260
+ test's own completion; the warning names the coverage attribution for the
261
+ listed mutant IDs as possibly wrong as a result.
262
+
263
+ This is diagnostic only — it never changes a dry-run or mutant-run result, and
264
+ the runner's normal "static wins" coverage attribution is unaffected. A known
265
+ **benign** trigger this warning does not try to filter out: a same-file
266
+ describe-level `beforeAll` (or other fixture setup) legitimately running in
267
+ that same gap looks identical from this vantage point. If the named test has
268
+ no fire-and-forget async work of its own, check for a `beforeAll`/fixture in
269
+ the same file before assuming a real leak.
270
+
271
+ The real fix, when it is a genuine leak, is in the test itself — `await` the
272
+ fire-and-forget work (or otherwise ensure it settles) before the test ends,
273
+ rather than in this runner. Warnings are capped at 25 individually, with a
274
+ final `...and N more coverage-bleed warning(s) suppressed` line for the rest.
275
+
171
276
  ## Known Limitations
172
277
 
173
278
  - **Sequential execution required** - Tests run with `--concurrency=1` to ensure accurate coverage tracking. This is slower than parallel execution but necessary for correct test-to-mutant correlation.
174
279
 
280
+ **Upgrade note: duplicate-name test suffixes**
281
+
282
+ The runner reconciles how it assigns the `' [N]'` disambiguating suffix to
283
+ duplicate-named tests (e.g. two `it('same name')` calls in one `describe`, or
284
+ `it.each` on older Bun versions) so that the test registry and mutant coverage
285
+ always agree on the same suffix for the same physical test, regardless of Bun's
286
+ per-run `--seed` execution-order shuffle. If your suite has duplicate test titles,
287
+ upgrading across this change can change which test a given `' [N]'` suffix refers
288
+ to, which invalidates
289
+ Stryker's incremental-cache correlation for mutants covered by those specific tests.
290
+ This is fail-safe, not silently wrong: affected mutants simply re-run once on your
291
+ next incremental `stryker mutate` and the cache self-heals from there — no action
292
+ needed on your part.
293
+
175
294
  **Eager-import and `mock.module()` compatibility**
176
295
 
177
296
  During `dryRun`, the plugin eager-imports every mutated source module at preload time in order to produce deterministic per-test coverage. Each mutated module is imported once, before any test file executes.
@@ -22,7 +22,20 @@ function initializeStrykerNamespace(globalObj) {
22
22
  function setActiveMutant(strykerNamespace, activeMutant) {
23
23
  strykerNamespace.activeMutant = activeMutant;
24
24
  }
25
- function formatCoverageData(mutantCoverage, counterToName) {
25
+ function detectGapWindowBleed(staticCountsAtLastBoundary, staticCoverageNow) {
26
+ if (!staticCoverageNow) {
27
+ return [];
28
+ }
29
+ const bledIds = [];
30
+ for (const [id, countNow] of Object.entries(staticCoverageNow)) {
31
+ const countAtBoundary = staticCountsAtLastBoundary.get(id) ?? 0;
32
+ if (countNow > countAtBoundary) {
33
+ bledIds.push(id);
34
+ }
35
+ }
36
+ return bledIds;
37
+ }
38
+ function formatCoverageData(mutantCoverage, counterToName, lateHits = []) {
26
39
  if (!mutantCoverage) {
27
40
  return { perTest: {}, static: [] };
28
41
  }
@@ -34,7 +47,8 @@ function formatCoverageData(mutantCoverage, counterToName) {
34
47
  const staticCoverage = Object.keys(mutantCoverage.static ?? {});
35
48
  return {
36
49
  perTest,
37
- static: staticCoverage
50
+ static: staticCoverage,
51
+ ...lateHits.length > 0 ? { lateHits: [...lateHits] } : {}
38
52
  };
39
53
  }
40
54
  function writeCoverageToFile(coverageFile, data) {
@@ -63,5 +77,6 @@ export {
63
77
  setActiveMutant,
64
78
  initializeStrykerNamespace,
65
79
  getPreloadConfig,
66
- formatCoverageData
80
+ formatCoverageData,
81
+ detectGapWindowBleed
67
82
  };
package/dist/index.d.ts CHANGED
@@ -31,6 +31,7 @@ export declare class BunTestRunner implements TestRunner {
31
31
  private tempDir?;
32
32
  private cachedTestNames?;
33
33
  private baseNameIndex?;
34
+ private testNameIndex?;
34
35
  private cachedTestFiles?;
35
36
  private cachedTestFilesCwd?;
36
37
  private cachedEagerModules?;
@@ -84,17 +85,43 @@ export declare class BunTestRunner implements TestRunner {
84
85
  private ensureSanitizedBunfig;
85
86
  /**
86
87
  * Load the shared dryRun registry written by the one worker that ran dryRun.
87
- * Populates this.cachedTestNames and this.baseNameIndex so that subsequent
88
- * mutantRun calls on this worker can resolve killedBy names correctly, even
89
- * for static-coverage mutants where testFilter is empty.
88
+ * Populates this.cachedTestNames, this.baseNameIndex, and this.testNameIndex
89
+ * so that subsequent mutantRun calls on this worker can resolve killedBy names
90
+ * and build exact --test-name-pattern alternatives, even for static-coverage
91
+ * mutants where testFilter is empty.
90
92
  *
91
- * Failures are non-fatal — the worker falls back to raw console names (current
92
- * behaviour before this fix), and a warning is logged so the issue is visible.
93
+ * Loading is all-or-nothing: a wrong version or a malformed field rejects the
94
+ * whole file (never a half-initialised registry). Failures are non-fatal — the
95
+ * worker falls back to raw console names and the lossy pattern reconstruction,
96
+ * and a warning is logged so the issue is visible.
93
97
  */
94
98
  private loadRegistryFile;
95
99
  /**
100
+ * Build the failureMessage for a single failed test in the Complete-path result.
101
+ *
102
+ * Base message prefers the parsed-console failure message, then the inspector's
103
+ * error.message, then falls back to a generic string. Stryker core's
104
+ * logFailedTestsInInitialRun prints exactly name+failureMessage for each failed
105
+ * test in the ConfigError initial-run path, so the inspector's error.stack (when
106
+ * present and not already part of the base message) is appended — that's what
107
+ * makes that path actionable instead of a bare one-liner.
108
+ *
109
+ * NOTE this is a genuine, intentional change to the content of the returned
110
+ * DryRunResult (a failed test's failureMessage is longer / carries a stack it
111
+ * didn't before) — not a diagnostic-only, log-line-only change like the two
112
+ * warn helpers below. Test statuses, ids, coverage, and mutantRun behavior
113
+ * are all unaffected; only failureMessage content is enriched.
114
+ */
115
+ private buildFailureMessage;
116
+ /**
96
117
  * Build test results from inspector data.
97
118
  *
119
+ * Also returns a testNameIndex mapping each FINAL test id (dedup ' [N]'
120
+ * suffix included) to Bun's exact internal matching name (TestInfo.bunName)
121
+ * for --test-name-pattern generation. Tests without a bunName — console-
122
+ * fallback results and unknown-inspectorId placeholders — get no index entry
123
+ * and stay on the lossy pattern reconstruction path (never worse than before).
124
+ *
98
125
  * @param inspectorIdToProjectFile - Optional mapping from inspector ID to project file path.
99
126
  * When provided, the project file is used for TestResult.id, name, and fileName instead of
100
127
  * testInfo.url. This is important for tests defined via helpers (e.g. RuleTester.run()) where
@@ -106,19 +133,54 @@ export declare class BunTestRunner implements TestRunner {
106
133
  */
107
134
  dryRun(): Promise<DryRunResult>;
108
135
  /**
136
+ * Post-child-exit dry-run pipeline: collect/remap coverage, build tests
137
+ * from inspector data, sort them for incremental-mode determinism, run the
138
+ * completeness gate, and — only if the gate passes — persist the test
139
+ * registry. Returns the gate's Error result when it fires, otherwise the
140
+ * Complete result.
141
+ *
142
+ * Extracted from dryRun() purely to keep dryRun()'s own cyclomatic
143
+ * complexity under the lint threshold; this is a pure code move — same call
144
+ * order and same early-return-on-gate-failure semantics as before.
145
+ */
146
+ private buildGatedDryRunResult;
147
+ /**
109
148
  * Build the in-memory test name cache and base-name index, then atomically
110
- * persist them to a well-known file so other worker processes can lazy-load
111
- * them when handling static-coverage mutants (testFilter is empty for those).
149
+ * persist them — together with the exact-name testNameIndex from
150
+ * buildTestsFromInspector — to a well-known file so other worker processes
151
+ * can lazy-load them when handling static-coverage mutants (testFilter is
152
+ * empty for those) and build exact --test-name-pattern alternatives.
112
153
  *
113
154
  * Writing to a .tmp path then renaming is atomic on POSIX: readers always see
114
155
  * either the previous complete file or the new one — never a partial write.
115
156
  */
116
157
  private buildAndPersistTestRegistry;
117
158
  /**
159
+ * Lossy-visibility warns for a mutant run's --test-name-pattern.
160
+ *
161
+ * Bun exits 0 on a PARTIAL pattern miss (verified live, bun 1.3.14),
162
+ * silently dropping the missed tests — so these warns are the only signal
163
+ * that some covering-test alternatives were built via the lossy
164
+ * ' > '-collapsing reconstruction instead of exact bun names. Must be called
165
+ * AFTER the registry lazy-load so this.testNameIndex reflects reality.
166
+ */
167
+ private warnLossyPatternAlternatives;
168
+ /**
118
169
  * Run tests with an active mutant
119
170
  */
120
171
  mutantRun(options: MutantRunOptions): Promise<MutantRunResult>;
121
172
  /**
173
+ * Spawn bun for a mutant run and interpret the result. Extracted from
174
+ * mutantRun so that a --test-name-pattern which matched 0 tests can retry
175
+ * once with the full suite (testNamePattern undefined) while reusing the
176
+ * SAME localRegistry/localBaseIndex built from the original testFilter for
177
+ * killedBy resolution — avoiding both a false Killed and redundant setup.
178
+ * The retry always recurses with testNamePattern undefined, so the retry
179
+ * gate's first conjunct is false on that call: recursion is bounded to
180
+ * depth 1 by construction, never a retry-of-a-retry.
181
+ */
182
+ private executeMutantRun;
183
+ /**
122
184
  * Build the MutantRunResult for a killed mutant (non-zero exit code).
123
185
  * Handles runtime error detection and killedBy resolution.
124
186
  */
@@ -134,11 +196,112 @@ export declare class BunTestRunner implements TestRunner {
134
196
  */
135
197
  private checkDryRunProcessResult;
136
198
  /**
199
+ * Build a structured summary of failed tests observed via the inspector, for
200
+ * inclusion in checkDryRunProcessResult's error message. Bun's own stdout/stderr
201
+ * recap can be truncated or entirely empty on process failure, so this pulls
202
+ * failure detail straight from the inspector's TestReporter data instead —
203
+ * the same data buildTestsFromInspector would otherwise turn into per-test
204
+ * results, had the process not short-circuited into the error branch first.
205
+ *
206
+ * Returns '' when there are no failed tests in the hierarchy so callers can
207
+ * keep the plain exit-code+stderr message unchanged in that case. Only
208
+ * type === 'test' entries are considered — describe blocks can also carry
209
+ * status 'fail' (propagated from a failing child) and must not masquerade
210
+ * as failed tests here.
211
+ */
212
+ private formatInspectorFailureDetails;
213
+ /**
214
+ * Diagnostic-only check for the Complete dry-run path: bun reported a failure
215
+ * (non-zero exit, or a failed count in its console recap) but nothing in the
216
+ * built test results identifies which test failed. This is the observed
217
+ * incident fingerprint — bun prints e.g. "1 tests failed:" with an empty
218
+ * recap, the inspector shows no TestStatus.Failed entry, and nothing points
219
+ * at a culprit. An unhandled error firing between tests (e.g. a rejected
220
+ * fire-and-forget promise) rather than inside any single test body is a
221
+ * likely cause. Logs a warning only; this check itself never alters test
222
+ * statuses, ids, coverage, or the returned DryRunResult — contrast with
223
+ * buildFailureMessage above, which (elsewhere in this same dry-run path)
224
+ * DOES intentionally change a failed test's failureMessage content.
225
+ */
226
+ private warnOnUnidentifiedDryRunFailure;
227
+ /**
228
+ * Dry-run data-completeness gate.
229
+ *
230
+ * Guards against the inspector event stream silently truncating mid-run
231
+ * (observed under CI runner contention): bun's own child-side coverage file
232
+ * can be complete while the inspector-derived `executionOrder` is cut off at
233
+ * a file boundary, and everything downstream of that (test results, coverage
234
+ * attribution) accepted the truncated data silently — a plausible-looking
235
+ * but corrupted score, not a loud failure.
236
+ *
237
+ * ONLY evaluated when the run otherwise looks GREEN (zero Failed entries in
238
+ * the already-built `tests`): an already-failing dry run is handled by
239
+ * {@link checkDryRunProcessResult} / {@link warnOnUnidentifiedDryRunFailure},
240
+ * and this precondition structurally prevents a failing beforeAll (which
241
+ * marks the rest of its describe/file Failed) from ever reaching Signal A —
242
+ * the incident's own signature was a run that looked completely healthy.
243
+ *
244
+ * Fires (returns a DryRunStatus.Error result) iff EITHER signal is material:
245
+ *
246
+ * - Signal A (execution/console shortfall): `consoleTotal` (bun's SUMMARY
247
+ * pass+fail counts — deliberately NOT the parser's max(per-line, summary)
248
+ * fields, so per-ATTEMPT retry output can never inflate it — see
249
+ * ParsedTestResults.summaryPassed/summaryFailed) compared against the
250
+ * count of ids in `executionOrder` whose status is neither 'skip' nor
251
+ * bun's not-yet-implemented placeholder-test status. Retries do not
252
+ * create a shortfall in this direction: empirically (bun 1.3.14), a
253
+ * retried test fires ONE TestReporter.start per ATTEMPT for the SAME
254
+ * inspector id — so executionOrder, if anything, grows on retries, and
255
+ * bun's summary line counts tests, not attempts, either way. A material
256
+ * shortfall must clear both an absolute floor and a ratio floor.
257
+ *
258
+ * - Signal B (orphaned coverage keys): `orphanedKeyCount` (a whole file's
259
+ * coverage keys unpaired with any inspector test — see coverage-mapper.ts)
260
+ * exceeding a small absolute floor. Deliberately gate-blind for the legacy
261
+ * ("test-N") coverage format, which never populates this count — Signal A
262
+ * still covers that path since it does not depend on coverage format.
263
+ *
264
+ * `wasClosedUnexpectedly` is NEVER a standalone trigger — the WS-vs-child-exit
265
+ * close race can plausibly be true on a nontrivial fraction of healthy runs —
266
+ * it is folded into the Error message only as corroborating context once the
267
+ * gate has already fired via Signal A or B.
268
+ *
269
+ * @returns A DryRunStatus.Error result if the gate fires, otherwise null.
270
+ */
271
+ private checkCompletenessGate;
272
+ /**
137
273
  * Collect coverage from the coverage file and remap counter-based IDs to
138
274
  * full test names using the inspector's execution order.
275
+ *
276
+ * Also collects any cross-test async coverage-bleed observations recorded
277
+ * by the preload (see {@link emitCoverageBleedWarnings}) and warns about
278
+ * them. This method's sole call site is dryRun, so bleed detection is
279
+ * dry-run-only by construction — mutant runs never reach this code.
139
280
  */
140
281
  private collectAndRemapCoverage;
141
282
  /**
283
+ * Warn about cross-test async coverage bleed: mutant coverage that was
284
+ * recorded in the gap between one test's afterEach and the next test's
285
+ * beforeEach, most likely because a fire-and-forget promise chain from the
286
+ * ended test kept running past the test boundary.
287
+ *
288
+ * Diagnostic only: never alters dryRun/mutantRun results or coverage
289
+ * attribution (stabilizeCoverage's "static wins" rule already governs
290
+ * attribution independently of this warning).
291
+ *
292
+ * A known benign trigger this deliberately does NOT try to suppress: a
293
+ * same-file describe-level beforeAll running in the gap looks identical to
294
+ * genuine bleed from this vantage point (both execute while
295
+ * currentTestId is undefined, between two tests). Filtering it out would
296
+ * require tracking beforeAll boundaries explicitly, which is out of scope
297
+ * here — the warning text calls the false-positive out instead.
298
+ *
299
+ * Capped at {@link MAX_COVERAGE_BLEED_WARNINGS} individual warnings, plus a
300
+ * final summary line for the rest, so a suite with many leaking tests
301
+ * doesn't flood the log.
302
+ */
303
+ private emitCoverageBleedWarnings;
304
+ /**
142
305
  * Build local index structures from testFilter for killedBy resolution.
143
306
  *
144
307
  * testFilter carries the full registry IDs Stryker wants us to run, including