@hughescr/stryker-bun-runner 1.3.2 → 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
@@ -201,10 +201,96 @@ don't — exits 0 with no error text at all. These two warns are the only signal
201
201
  that a partial silent drop was possible for a given mutant run, so seeing either
202
202
  of them in a clean run's logs is worth investigating before trusting the score.
203
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
+
204
276
  ## Known Limitations
205
277
 
206
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.
207
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
+
208
294
  **Eager-import and `mock.module()` compatibility**
209
295
 
210
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
@@ -97,6 +97,23 @@ export declare class BunTestRunner implements TestRunner {
97
97
  */
98
98
  private loadRegistryFile;
99
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
+ /**
100
117
  * Build test results from inspector data.
101
118
  *
102
119
  * Also returns a testNameIndex mapping each FINAL test id (dedup ' [N]'
@@ -116,6 +133,18 @@ export declare class BunTestRunner implements TestRunner {
116
133
  */
117
134
  dryRun(): Promise<DryRunResult>;
118
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
+ /**
119
148
  * Build the in-memory test name cache and base-name index, then atomically
120
149
  * persist them — together with the exact-name testNameIndex from
121
150
  * buildTestsFromInspector — to a well-known file so other worker processes
@@ -167,11 +196,112 @@ export declare class BunTestRunner implements TestRunner {
167
196
  */
168
197
  private checkDryRunProcessResult;
169
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
+ /**
170
273
  * Collect coverage from the coverage file and remap counter-based IDs to
171
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.
172
280
  */
173
281
  private collectAndRemapCoverage;
174
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
+ /**
175
305
  * Build local index structures from testFilter for killedBy resolution.
176
306
  *
177
307
  * testFilter carries the full registry IDs Stryker wants us to run, including
package/dist/index.js CHANGED
@@ -5540,7 +5540,7 @@ function mergeCoverageData(dataList) {
5540
5540
  merged.static = [...staticSet];
5541
5541
  return merged;
5542
5542
  }
5543
- async function collectCoverage(coverageFile, logger) {
5543
+ async function readCoverageFileData(coverageFile, logger) {
5544
5544
  try {
5545
5545
  const content = await readFile2(coverageFile, "utf8");
5546
5546
  const trimmed = content.trim();
@@ -5556,6 +5556,14 @@ async function collectCoverage(coverageFile, logger) {
5556
5556
  logger?.warn("[Stryker Coverage] Failed to parse coverage line: %s", errorMsg);
5557
5557
  }
5558
5558
  }
5559
+ return dataList;
5560
+ } catch {
5561
+ return [];
5562
+ }
5563
+ }
5564
+ async function collectCoverage(coverageFile, logger) {
5565
+ try {
5566
+ const dataList = await readCoverageFileData(coverageFile, logger);
5559
5567
  if (dataList.length === 0) {
5560
5568
  return;
5561
5569
  }
@@ -5573,12 +5581,41 @@ async function collectCoverage(coverageFile, logger) {
5573
5581
  return;
5574
5582
  }
5575
5583
  }
5584
+ async function collectLateHits(coverageFile, logger) {
5585
+ const dataList = await readCoverageFileData(coverageFile, logger);
5586
+ return dataList.flatMap((data) => data.lateHits ?? []);
5587
+ }
5576
5588
  async function cleanupCoverageFile(coverageFile) {
5577
5589
  try {
5578
5590
  await unlink2(coverageFile);
5579
5591
  } catch {}
5580
5592
  }
5581
5593
 
5594
+ // src/utils/duplicate-suffix.ts
5595
+ function buildDiscoveryOrderIndex(discoveryOrderedIds) {
5596
+ const index = new Map;
5597
+ let i = 0;
5598
+ for (const id of discoveryOrderedIds) {
5599
+ index.set(id, i);
5600
+ i++;
5601
+ }
5602
+ return index;
5603
+ }
5604
+ function sortDuplicateGroupByLineThenDiscovery(group, getLine, getInspectorId, discoveryOrderIndex) {
5605
+ return group.toSorted((a, b) => {
5606
+ const lineA = getLine(a) ?? Infinity;
5607
+ const lineB = getLine(b) ?? Infinity;
5608
+ if (lineA !== lineB) {
5609
+ return lineA - lineB;
5610
+ }
5611
+ const idA = getInspectorId(a);
5612
+ const idB = getInspectorId(b);
5613
+ const discA = idA === undefined ? Infinity : discoveryOrderIndex.get(idA) ?? Infinity;
5614
+ const discB = idB === undefined ? Infinity : discoveryOrderIndex.get(idB) ?? Infinity;
5615
+ return discA - discB;
5616
+ });
5617
+ }
5618
+
5582
5619
  // src/utils/test-name.ts
5583
5620
  function normalizeTestFilePath(url) {
5584
5621
  if (!url) {
@@ -5607,16 +5644,34 @@ function buildUniqueTestName(fullName, url) {
5607
5644
  // src/coverage/coverage-mapper.ts
5608
5645
  function mapCoverageToInspectorIds(rawCoverage, executionOrder, testHierarchy, logger) {
5609
5646
  if (!rawCoverage?.perTest || Object.keys(rawCoverage.perTest).length === 0) {
5610
- return { coverage: rawCoverage ?? undefined, inspectorIdToProjectFile: new Map };
5647
+ return {
5648
+ coverage: rawCoverage ?? undefined,
5649
+ inspectorIdToProjectFile: new Map,
5650
+ counterKeyToTestName: new Map,
5651
+ rawKeyCount: 0,
5652
+ orphanedKeyCount: 0
5653
+ };
5611
5654
  }
5612
5655
  const firstKey = Object.keys(rawCoverage.perTest)[0];
5613
5656
  if (/@@test-\d+$/.test(firstKey)) {
5614
5657
  return mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger);
5615
5658
  }
5616
5659
  if (/^test-\d+$/.test(firstKey)) {
5617
- return { coverage: mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger), inspectorIdToProjectFile: new Map };
5660
+ return {
5661
+ coverage: mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger),
5662
+ inspectorIdToProjectFile: new Map,
5663
+ counterKeyToTestName: new Map,
5664
+ rawKeyCount: Object.keys(rawCoverage.perTest).length,
5665
+ orphanedKeyCount: 0
5666
+ };
5618
5667
  }
5619
- return { coverage: rawCoverage, inspectorIdToProjectFile: new Map };
5668
+ return {
5669
+ coverage: rawCoverage,
5670
+ inspectorIdToProjectFile: new Map,
5671
+ counterKeyToTestName: new Map,
5672
+ rawKeyCount: Object.keys(rawCoverage.perTest).length,
5673
+ orphanedKeyCount: 0
5674
+ };
5620
5675
  }
5621
5676
  function buildFilteredPerTest(perTestEntries, staticIds) {
5622
5677
  const newPerTest = {};
@@ -5672,7 +5727,7 @@ function resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logge
5672
5727
  const testName = buildProjectFileTestName(filePrefix, testInfo.fullName);
5673
5728
  return { name: testName, testInfo, inspectorId };
5674
5729
  }
5675
- logger?.warn('Coverage key %s: no inspector test found for file "%s" at position %s ' + "(file has %s tests in execution order). Skipping this test in coverage mapping.", key, filePrefix, n, fileToInspectorIds.get(filePrefix)?.length ?? 0);
5730
+ logger?.debug('Coverage key %s: no inspector test found for file "%s" at position %s ' + "(file has %s tests in execution order). Skipping this test in coverage mapping.", key, filePrefix, n, fileToInspectorIds.get(filePrefix)?.length ?? 0);
5676
5731
  return { name: `unknown-${key}`, testInfo: null, inspectorId: undefined };
5677
5732
  });
5678
5733
  }
@@ -5691,31 +5746,40 @@ function buildNameInspectorIds(resolved) {
5691
5746
  }
5692
5747
  return nameInspectorIds;
5693
5748
  }
5694
- function resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes) {
5749
+ function buildDuplicateNameIndex(nameInspectorIds, testHierarchy) {
5750
+ const discoveryOrderIndex = buildDiscoveryOrderIndex(testHierarchy.keys());
5751
+ const indexByKey = new Map;
5752
+ for (const [baseName, ids] of nameInspectorIds) {
5753
+ if (ids.size <= 1) {
5754
+ continue;
5755
+ }
5756
+ const group = [...ids].filter((id) => id !== undefined);
5757
+ const sorted = sortDuplicateGroupByLineThenDiscovery(group, (id) => testHierarchy.get(id)?.line, (id) => id, discoveryOrderIndex);
5758
+ for (const [i, id] of sorted.entries()) {
5759
+ indexByKey.set(`${id}/${baseName}`, i);
5760
+ }
5761
+ }
5762
+ return indexByKey;
5763
+ }
5764
+ function resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateNameIndex) {
5695
5765
  const distinctIds = nameInspectorIds.get(baseName);
5696
5766
  if ((distinctIds?.size ?? 1) <= 1) {
5697
5767
  return baseName;
5698
5768
  }
5699
5769
  const key_ = `${inspectorId}/${baseName}`;
5700
- const existingIndex = nameIndexes.get(key_);
5701
- if (existingIndex === undefined) {
5702
- const nextIndex = nameIndexes.get(baseName) ?? 0;
5703
- nameIndexes.set(key_, nextIndex);
5704
- nameIndexes.set(baseName, nextIndex + 1);
5705
- return `${baseName} [${nextIndex}]`;
5706
- }
5707
- return `${baseName} [${existingIndex}]`;
5770
+ const index = duplicateNameIndex.get(key_) ?? 0;
5771
+ return `${baseName} [${index}]`;
5708
5772
  }
5709
- function buildRemappedPerTest(counterIds, resolved, rawPerTest) {
5773
+ function buildRemappedPerTest(counterIds, resolved, rawPerTest, testHierarchy) {
5710
5774
  const nameInspectorIds = buildNameInspectorIds(resolved);
5775
+ const duplicateNameIndex = buildDuplicateNameIndex(nameInspectorIds, testHierarchy);
5711
5776
  const remappedPerTest = {};
5712
- const nameIndexes = new Map;
5713
5777
  for (const [i, key] of counterIds.entries()) {
5714
5778
  const { name: baseName, testInfo, inspectorId } = resolved[i];
5715
5779
  if (!testInfo) {
5716
5780
  continue;
5717
5781
  }
5718
- const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes);
5782
+ const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, duplicateNameIndex);
5719
5783
  const incoming = rawPerTest[key];
5720
5784
  const existing = remappedPerTest[finalName];
5721
5785
  if (existing) {
@@ -5745,6 +5809,25 @@ function warnInteriorGapIfPresent(pairs, testHierarchy, logger) {
5745
5809
  }
5746
5810
  }
5747
5811
  }
5812
+ function reportOrphanedKeys(resolved, counterIds, logger) {
5813
+ const orphanedIndexes = [];
5814
+ for (const [i, r] of resolved.entries()) {
5815
+ if (!r.testInfo) {
5816
+ orphanedIndexes.push(i);
5817
+ }
5818
+ }
5819
+ const orphanedKeyCount = orphanedIndexes.length;
5820
+ if (orphanedKeyCount > 0) {
5821
+ const orphanedFiles = new Set;
5822
+ for (const i of orphanedIndexes) {
5823
+ const key = counterIds[i];
5824
+ const sepIdx = key.indexOf("@@");
5825
+ orphanedFiles.add(sepIdx === -1 ? key : key.slice(0, sepIdx));
5826
+ }
5827
+ logger?.warn("%s of %s coverage key(s) across %s file(s) could not be paired with any inspector test " + "(orphaned — see per-key detail at debug level). This can indicate the Bun inspector " + "stream was truncated mid-run.", orphanedKeyCount, counterIds.length, orphanedFiles.size);
5828
+ }
5829
+ return orphanedKeyCount;
5830
+ }
5748
5831
  function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5749
5832
  const globallyOrderedKeys = Object.keys(rawCoverage.perTest);
5750
5833
  const pairs = pairKeysWithInspectorIds(globallyOrderedKeys, executionOrder, testHierarchy, logger);
@@ -5768,12 +5851,25 @@ function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy,
5768
5851
  return nA - nB;
5769
5852
  });
5770
5853
  const resolved = resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logger);
5771
- const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest);
5854
+ const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest, testHierarchy);
5855
+ const counterKeyToTestName = new Map;
5856
+ for (const [i, key] of counterIds.entries()) {
5857
+ if (resolved[i].testInfo) {
5858
+ counterKeyToTestName.set(key, resolved[i].name);
5859
+ }
5860
+ }
5861
+ const orphanedKeyCount = reportOrphanedKeys(resolved, counterIds, logger);
5772
5862
  const coverage = stabilizeCoverage({
5773
5863
  static: rawCoverage.static,
5774
5864
  perTest: remappedPerTest
5775
5865
  });
5776
- return { coverage, inspectorIdToProjectFile };
5866
+ return {
5867
+ coverage,
5868
+ inspectorIdToProjectFile,
5869
+ counterKeyToTestName,
5870
+ rawKeyCount: counterIds.length,
5871
+ orphanedKeyCount
5872
+ };
5777
5873
  }
5778
5874
  function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5779
5875
  const counterIds = Object.keys(rawCoverage.perTest).toSorted((a, b) => Number.parseInt(a.split("-")[1] ?? "0", 10) - Number.parseInt(b.split("-")[1] ?? "0", 10));
@@ -5868,6 +5964,10 @@ class InspectorClient {
5868
5964
  state;
5869
5965
  isClosing = false;
5870
5966
  WebSocketClass;
5967
+ closeExpected = false;
5968
+ wsClosed = false;
5969
+ _wasClosedUnexpectedly = false;
5970
+ closeWaiters = [];
5871
5971
  constructor(options) {
5872
5972
  this.handlers = options.handlers ?? {};
5873
5973
  this.WebSocketClass = options.WebSocketClass ?? wrapper_default;
@@ -5946,6 +6046,37 @@ class InspectorClient {
5946
6046
  }
5947
6047
  this.ws = null;
5948
6048
  }
6049
+ expectClose() {
6050
+ this.closeExpected = true;
6051
+ }
6052
+ get wasClosedUnexpectedly() {
6053
+ return this._wasClosedUnexpectedly;
6054
+ }
6055
+ async waitForClose(timeoutMs) {
6056
+ if (this.wsClosed || !this.ws) {
6057
+ return;
6058
+ }
6059
+ return new Promise((resolve3) => {
6060
+ let settled = false;
6061
+ let timer;
6062
+ const finish = () => {
6063
+ if (settled) {
6064
+ return;
6065
+ }
6066
+ settled = true;
6067
+ clearTimeout(timer);
6068
+ const idx = this.closeWaiters.indexOf(finish);
6069
+ if (idx !== -1) {
6070
+ this.closeWaiters.splice(idx, 1);
6071
+ }
6072
+ resolve3();
6073
+ };
6074
+ timer = setTimeout(() => {
6075
+ finish();
6076
+ }, timeoutMs);
6077
+ this.closeWaiters.push(finish);
6078
+ });
6079
+ }
5949
6080
  getTests() {
5950
6081
  return [...this.testHierarchy.values()];
5951
6082
  }
@@ -6050,9 +6181,16 @@ class InspectorClient {
6050
6181
  return { fullName: parts.join(" > "), bunName: parts.join(" ") };
6051
6182
  }
6052
6183
  handleClose() {
6053
- if (this.isClosing) {
6184
+ this.wsClosed = true;
6185
+ const waiters = this.closeWaiters;
6186
+ this.closeWaiters = [];
6187
+ for (const finish of waiters) {
6188
+ finish();
6189
+ }
6190
+ if (this.isClosing || this.closeExpected) {
6054
6191
  return;
6055
6192
  }
6193
+ this._wasClosedUnexpectedly = true;
6056
6194
  const error = new InspectorConnectionError("Connection closed unexpectedly");
6057
6195
  for (const pending of this.pendingRequests.values()) {
6058
6196
  clearTimeout(pending.timer);
@@ -6165,6 +6303,8 @@ function parseSummaryLines(output) {
6165
6303
  if (bailSummary) {
6166
6304
  counts.failed = Math.max(counts.failed, Number.parseInt(bailSummary[1], 10));
6167
6305
  }
6306
+ const genuinePassed = counts.passed;
6307
+ const genuineFailed = counts.failed;
6168
6308
  const ranTestsSummary = /Ran\s+(\d+)\s+tests?/.exec(output);
6169
6309
  if (ranTestsSummary) {
6170
6310
  const totalFromRan = Number.parseInt(ranTestsSummary[1], 10);
@@ -6173,7 +6313,7 @@ function parseSummaryLines(output) {
6173
6313
  counts.passed = totalFromRan;
6174
6314
  }
6175
6315
  }
6176
- return counts;
6316
+ return { ...counts, genuinePassed, genuineFailed };
6177
6317
  }
6178
6318
  function parseBunTestOutput(stdout, stderr) {
6179
6319
  const tests = [];
@@ -6219,7 +6359,10 @@ ${stderr}`;
6219
6359
  totalTests: counters.passed + counters.failed + counters.skipped,
6220
6360
  passed: counters.passed,
6221
6361
  failed: counters.failed,
6222
- skipped: counters.skipped
6362
+ skipped: counters.skipped,
6363
+ summaryPassed: summaryCounts.genuinePassed,
6364
+ summaryFailed: summaryCounts.genuineFailed,
6365
+ summarySkipped: summaryCounts.skipped
6223
6366
  };
6224
6367
  }
6225
6368
 
@@ -6301,7 +6444,7 @@ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
6301
6444
  async function runBunTests(options) {
6302
6445
  const args = ["test"];
6303
6446
  if (options.inspectWaitPort) {
6304
- args.push(`--inspect=${options.inspectWaitPort}`);
6447
+ args.push(`--inspect=127.0.0.1:${options.inspectWaitPort}`);
6305
6448
  }
6306
6449
  if (options.bunfigPath) {
6307
6450
  args.push(`--config=${options.bunfigPath}`);
@@ -7888,6 +8031,12 @@ function buildTestNameIndex(tests, bunNames) {
7888
8031
  return testNameIndex;
7889
8032
  }
7890
8033
  var ZERO_MATCH_TEST_PATTERN_RE = /matched 0 tests\./;
8034
+ var MAX_DRY_RUN_FAILURE_TESTS_LISTED = 20;
8035
+ var MAX_COVERAGE_BLEED_WARNINGS = 25;
8036
+ var EXECUTION_SHORTFALL_ABS_FLOOR = 10;
8037
+ var EXECUTION_SHORTFALL_RATIO_THRESHOLD = 0.05;
8038
+ var ORPHANED_KEY_ABS_FLOOR = 5;
8039
+ var INSPECTOR_DRAIN_TIMEOUT_MS = 1000;
7891
8040
 
7892
8041
  class BunTestRunner {
7893
8042
  logger;
@@ -8061,6 +8210,13 @@ class BunTestRunner {
8061
8210
  }
8062
8211
  }
8063
8212
  }
8213
+ buildFailureMessage(testInfo, parsed) {
8214
+ const parsedTest = parsed.tests.find((t) => t.name.includes(testInfo.name));
8215
+ const baseFailureMessage = parsedTest?.failureMessage ?? testInfo.error?.message ?? "Test failed";
8216
+ const stack = testInfo.error?.stack;
8217
+ return stack && !baseFailureMessage.includes(stack) ? `${baseFailureMessage}
8218
+ ${stack}` : baseFailureMessage;
8219
+ }
8064
8220
  buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile) {
8065
8221
  if (executionOrder.length === 0) {
8066
8222
  const fallbackTests = parsed.tests.map((t) => {
@@ -8114,14 +8270,13 @@ class BunTestRunner {
8114
8270
  const elapsed = testInfo.elapsed === undefined ? timePerTest : Math.round(testInfo.elapsed / 1e6);
8115
8271
  const startPosition = testInfo.line === undefined ? undefined : { line: testInfo.line, column: 0 };
8116
8272
  if (status === "fail") {
8117
- const parsedTest = parsed.tests.find((t) => t.name.includes(testInfo.name));
8118
8273
  return {
8119
8274
  id: uniqueName,
8120
8275
  name: uniqueName,
8121
8276
  fileName,
8122
8277
  startPosition,
8123
8278
  status: TestStatus.Failed,
8124
- failureMessage: parsedTest?.failureMessage ?? testInfo.error?.message ?? "Test failed",
8279
+ failureMessage: this.buildFailureMessage(testInfo, parsed),
8125
8280
  timeSpentMs: elapsed
8126
8281
  };
8127
8282
  }
@@ -8144,28 +8299,26 @@ class BunTestRunner {
8144
8299
  timeSpentMs: elapsed
8145
8300
  };
8146
8301
  });
8302
+ const discoveryOrderIndex = buildDiscoveryOrderIndex(testHierarchy.map((t) => t.id));
8147
8303
  const nameCounts = new Map;
8148
8304
  for (const test of tests) {
8149
8305
  nameCounts.set(test.name, (nameCounts.get(test.name) ?? 0) + 1);
8150
8306
  }
8151
8307
  const nameGroups = new Map;
8152
- for (const test of tests) {
8308
+ for (const [i, test] of tests.entries()) {
8153
8309
  if ((nameCounts.get(test.name) ?? 1) > 1) {
8310
+ const entry = { test, inspectorId: executionOrder[i] };
8154
8311
  const group = nameGroups.get(test.name);
8155
8312
  if (group) {
8156
- group.push(test);
8313
+ group.push(entry);
8157
8314
  } else {
8158
- nameGroups.set(test.name, [test]);
8315
+ nameGroups.set(test.name, [entry]);
8159
8316
  }
8160
8317
  }
8161
8318
  }
8162
8319
  for (const [, group] of nameGroups) {
8163
- group.sort((a, b) => {
8164
- const lineA = "startPosition" in a && a.startPosition ? a.startPosition.line : Infinity;
8165
- const lineB = "startPosition" in b && b.startPosition ? b.startPosition.line : Infinity;
8166
- return lineA - lineB;
8167
- });
8168
- for (const [i, test] of group.entries()) {
8320
+ const sorted = sortDuplicateGroupByLineThenDiscovery(group, (e) => ("startPosition" in e.test) && e.test.startPosition ? e.test.startPosition.line : undefined, (e) => e.inspectorId, discoveryOrderIndex);
8321
+ for (const [i, { test }] of sorted.entries()) {
8169
8322
  const uniqueName = `${test.name} [${i}]`;
8170
8323
  test.id = uniqueName;
8171
8324
  test.name = uniqueName;
@@ -8246,7 +8399,11 @@ exit=%s timedOut=%s
8246
8399
  url: inspectorUrl,
8247
8400
  connectionTimeout: this.inspectorTimeout,
8248
8401
  requestTimeout: this.inspectorTimeout,
8249
- handlers: {}
8402
+ handlers: {
8403
+ onError: (error) => {
8404
+ this.logger.warn("Inspector error: %s", error.message);
8405
+ }
8406
+ }
8250
8407
  });
8251
8408
  try {
8252
8409
  await inspector.connect();
@@ -8266,24 +8423,19 @@ exit=%s timedOut=%s
8266
8423
  this.logger.debug("Signaled preload script to proceed");
8267
8424
  const result = await testProcess;
8268
8425
  const totalElapsedMs = Date.now() - startTime;
8426
+ inspector.expectClose();
8427
+ await inspector.waitForClose(INSPECTOR_DRAIN_TIMEOUT_MS);
8269
8428
  const testHierarchy = inspector.getTests();
8270
8429
  const executionOrder = inspector.getExecutionOrder();
8430
+ const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
8271
8431
  await inspector.close();
8272
8432
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
8273
8433
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
8274
- const earlyResult = this.checkDryRunProcessResult(result, parsed);
8434
+ const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
8275
8435
  if (earlyResult) {
8276
8436
  return earlyResult;
8277
8437
  }
8278
- const { coverage: mutantCoverage, inspectorIdToProjectFile } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8279
- const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8280
- tests.sort((a, b) => a.name.localeCompare(b.name));
8281
- await this.buildAndPersistTestRegistry(tests, testNameIndex);
8282
- return {
8283
- status: DryRunStatus.Complete,
8284
- tests,
8285
- mutantCoverage
8286
- };
8438
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly);
8287
8439
  } finally {
8288
8440
  abortController.abort();
8289
8441
  if (this.currentAbortController === abortController) {
@@ -8292,6 +8444,22 @@ exit=%s timedOut=%s
8292
8444
  await syncServer.close();
8293
8445
  }
8294
8446
  }
8447
+ async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly) {
8448
+ const { coverage: mutantCoverage, inspectorIdToProjectFile, rawKeyCount, orphanedKeyCount } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8449
+ const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8450
+ tests.sort((a, b) => a.name.localeCompare(b.name));
8451
+ const gateResult = this.checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests);
8452
+ if (gateResult) {
8453
+ return gateResult;
8454
+ }
8455
+ await this.buildAndPersistTestRegistry(tests, testNameIndex);
8456
+ this.warnOnUnidentifiedDryRunFailure(result, parsed, tests);
8457
+ return {
8458
+ status: DryRunStatus.Complete,
8459
+ tests,
8460
+ mutantCoverage
8461
+ };
8462
+ }
8295
8463
  async buildAndPersistTestRegistry(tests, testNameIndex) {
8296
8464
  this.cachedTestNames = new Set(tests.map((t) => t.name));
8297
8465
  if (tests.length !== this.cachedTestNames.size) {
@@ -8466,32 +8634,120 @@ exit=%s timedOut=%s
8466
8634
  }
8467
8635
  return null;
8468
8636
  }
8469
- checkDryRunProcessResult(result, parsed) {
8637
+ checkDryRunProcessResult(result, parsed, testHierarchy) {
8470
8638
  if (result.timedOut) {
8471
8639
  this.logger.warn("Dry run timed out");
8472
8640
  return { status: DryRunStatus.Timeout };
8473
8641
  }
8474
8642
  if (result.exitCode !== 0 && parsed.failed === 0) {
8643
+ const failureDetails = this.formatInspectorFailureDetails(testHierarchy);
8644
+ const messageParts = [`Bun test process failed with exit code ${result.exitCode}`];
8645
+ if (failureDetails) {
8646
+ messageParts.push(failureDetails);
8647
+ }
8648
+ messageParts.push(result.stderr);
8475
8649
  return {
8476
8650
  status: DryRunStatus.Error,
8477
- errorMessage: `Bun test process failed with exit code ${result.exitCode}
8478
- ${result.stderr}`
8651
+ errorMessage: messageParts.join(`
8652
+ `)
8479
8653
  };
8480
8654
  }
8481
8655
  return null;
8482
8656
  }
8657
+ formatInspectorFailureDetails(testHierarchy) {
8658
+ const failedTests = testHierarchy.filter((t) => t.type === "test" && t.status === "fail");
8659
+ if (failedTests.length === 0) {
8660
+ return "";
8661
+ }
8662
+ const listed = failedTests.slice(0, MAX_DRY_RUN_FAILURE_TESTS_LISTED);
8663
+ const lines = listed.map((t) => {
8664
+ const message = t.error?.message ?? "no error message captured";
8665
+ let line = ` - ${t.fullName}: ${message}`;
8666
+ if (t.error?.stack) {
8667
+ const indentedStack = t.error.stack.split(`
8668
+ `).map((stackLine) => ` ${stackLine}`).join(`
8669
+ `);
8670
+ line += `
8671
+ ${indentedStack}`;
8672
+ }
8673
+ return line;
8674
+ });
8675
+ const remaining = failedTests.length - listed.length;
8676
+ if (remaining > 0) {
8677
+ lines.push(` ...and ${remaining} more`);
8678
+ }
8679
+ return `${failedTests.length} test(s) reported failed via Bun's inspector (stdout/stderr recap may be truncated or missing):
8680
+ ${lines.join(`
8681
+ `)}`;
8682
+ }
8683
+ warnOnUnidentifiedDryRunFailure(result, parsed, tests) {
8684
+ if ((result.exitCode !== 0 || parsed.failed > 0) && !tests.some((t) => t.status === TestStatus.Failed)) {
8685
+ this.logger.warn("Bun exited with code %s and its console output reported %d failed test(s), " + "but no failing test could be identified from inspector or console data. " + "An unhandled error firing between tests (e.g. a rejected fire-and-forget " + `promise) is a likely cause. Last 500 chars of stderr:
8686
+ %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
8687
+ }
8688
+ }
8689
+ checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests) {
8690
+ if (tests.some((t) => t.status === TestStatus.Failed)) {
8691
+ return null;
8692
+ }
8693
+ const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8694
+ const nonSkippedExecutionCount = executionOrder.filter((id) => {
8695
+ const status = testMap.get(id)?.status;
8696
+ return status !== "skip" && status !== "todo";
8697
+ }).length;
8698
+ const consoleTotal = parsed.summaryPassed + parsed.summaryFailed;
8699
+ const shortfall = consoleTotal - nonSkippedExecutionCount;
8700
+ const signalA = consoleTotal > 0 && shortfall > EXECUTION_SHORTFALL_ABS_FLOOR && shortfall / consoleTotal > EXECUTION_SHORTFALL_RATIO_THRESHOLD;
8701
+ const signalB = orphanedKeyCount > ORPHANED_KEY_ABS_FLOOR;
8702
+ if (!signalA && !signalB) {
8703
+ return null;
8704
+ }
8705
+ const reasons = [];
8706
+ if (signalA) {
8707
+ reasons.push(`console reported ${consoleTotal} test(s) (pass+fail) but the inspector's execution order ` + `contains only ${nonSkippedExecutionCount} non-skipped test(s) (shortfall ${shortfall})`);
8708
+ }
8709
+ if (signalB) {
8710
+ reasons.push(`${orphanedKeyCount} of ${rawKeyCount} coverage key(s) could not be paired with any inspector test (orphaned)`);
8711
+ }
8712
+ if (wasClosedUnexpectedly) {
8713
+ reasons.push("the inspector WebSocket closed unexpectedly before this data could be fully drained");
8714
+ }
8715
+ const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${reasons.join("; ")}. This indicates the Bun inspector event stream may have been ` + "truncated mid-run; proceeding would risk silently " + "corrupted coverage attribution, so this dry run is being reported as an error instead of " + "Complete, and the test registry has NOT been persisted.";
8716
+ this.logger.error("%s", errorMessage);
8717
+ return {
8718
+ status: DryRunStatus.Error,
8719
+ errorMessage
8720
+ };
8721
+ }
8483
8722
  async collectAndRemapCoverage(testHierarchy, executionOrder) {
8484
8723
  const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8485
8724
  if (!this.coverageFilePath) {
8486
- return { coverage: undefined, inspectorIdToProjectFile: new Map };
8725
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, rawKeyCount: 0, orphanedKeyCount: 0 };
8487
8726
  }
8488
- const rawCoverage = await collectCoverage(this.coverageFilePath, this.logger);
8727
+ const [rawCoverage, lateHits] = await Promise.all([
8728
+ collectCoverage(this.coverageFilePath, this.logger),
8729
+ collectLateHits(this.coverageFilePath, this.logger)
8730
+ ]);
8489
8731
  await cleanupCoverageFile(this.coverageFilePath);
8490
8732
  if (!rawCoverage) {
8491
- return { coverage: undefined, inspectorIdToProjectFile: new Map };
8733
+ return { coverage: undefined, inspectorIdToProjectFile: new Map, rawKeyCount: 0, orphanedKeyCount: 0 };
8734
+ }
8735
+ const { coverage, inspectorIdToProjectFile, counterKeyToTestName, rawKeyCount, orphanedKeyCount } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8736
+ if (lateHits.length > 0) {
8737
+ this.emitCoverageBleedWarnings(lateHits, counterKeyToTestName);
8738
+ }
8739
+ return { coverage, inspectorIdToProjectFile, rawKeyCount, orphanedKeyCount };
8740
+ }
8741
+ emitCoverageBleedWarnings(lateHits, counterKeyToTestName) {
8742
+ const listed = lateHits.slice(0, MAX_COVERAGE_BLEED_WARNINGS);
8743
+ for (const { testId, mutantIds } of listed) {
8744
+ const testName = counterKeyToTestName.get(testId) ?? testId;
8745
+ this.logger.warn("mutant coverage was recorded between tests, after '%s' completed — likely fire-and-forget async work " + "leaking past the test boundary (or beforeAll/fixture code running between tests); attribution for %d " + "mutant(s) may be wrong (mutant IDs: %s)", testName, mutantIds.length, mutantIds.join(", "));
8746
+ }
8747
+ const remaining = lateHits.length - listed.length;
8748
+ if (remaining > 0) {
8749
+ this.logger.warn("...and %d more coverage-bleed warning(s) suppressed", remaining);
8492
8750
  }
8493
- const { coverage, inspectorIdToProjectFile } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8494
- return { coverage, inspectorIdToProjectFile };
8495
8751
  }
8496
8752
  buildLocalTestFilterIndex(testFilter) {
8497
8753
  const localRegistry = new Set(testFilter);
@@ -11,9 +11,11 @@ import {
11
11
  initializeStrykerNamespace,
12
12
  setActiveMutant,
13
13
  formatCoverageData,
14
+ detectGapWindowBleed,
14
15
  writeCoverageToFile,
15
16
  startOrphanWatchdog,
16
- type StrykerNamespace
17
+ type StrykerNamespace,
18
+ type LateHitEntry
17
19
  } from '__PRELOAD_LOGIC_PATH__';
18
20
 
19
21
  // ============================================================================
@@ -101,6 +103,24 @@ function extractFilePrefix(bunMain: string): string {
101
103
  return sandboxMatch ? sandboxMatch[1] : bunMain.replace(/^.*\//, '');
102
104
  }
103
105
 
106
+ // ============================================================================
107
+ // Cross-test async coverage-bleed detection (gap-window count-delta)
108
+ // ============================================================================
109
+ // Detects fire-and-forget promise chains (or other async work) that keep
110
+ // recording mutant coverage into the `static` bucket after their originating
111
+ // test's afterEach has fired — i.e. between one test ending and the next
112
+ // test beginning ("the gap window"). Diagnostic only: see
113
+ // emitCoverageBleedWarnings in bun-test-runner.ts for how this surfaces as a
114
+ // warning; it never changes coverage attribution.
115
+ //
116
+ // lastEndedTestId / lastFilePrefix / staticSnapshotAtLastBoundary are updated
117
+ // in afterEach (the start of a gap window) and consumed in the NEXT
118
+ // beforeEach (the end of that gap window) — see both hooks below.
119
+ let lastEndedTestId: string | undefined;
120
+ let lastFilePrefix: string | undefined;
121
+ let staticSnapshotAtLastBoundary = new Map<string, number>();
122
+ const lateHits: LateHitEntry[] = [];
123
+
104
124
  if(syncPort && shouldCollectCoverage) {
105
125
  try {
106
126
  // Install the real 'ready' handler before yielding to the event loop so
@@ -210,7 +230,7 @@ const writeCoverageData = () => {
210
230
  // counterToName is not populated (test names are resolved by coverage-mapper
211
231
  // from the inspector data, not stored here), so pass an empty Map.
212
232
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Placeholder import replaced at runtime
213
- const data = formatCoverageData(strykerGlobal.mutantCoverage, new Map<string, string>());
233
+ const data = formatCoverageData(strykerGlobal.mutantCoverage, new Map<string, string>(), lateHits);
214
234
 
215
235
  try {
216
236
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call -- Placeholder import replaced at runtime
@@ -241,6 +261,29 @@ if(shouldCollectCoverage) {
241
261
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Bun global accessed at runtime
242
262
  const bunMain = String((globalThis as unknown as { Bun?: { main?: string } }).Bun?.main ?? '');
243
263
  const filePrefix = extractFilePrefix(bunMain);
264
+
265
+ // Gap-window bleed check: this beforeEach is the END of the gap window that
266
+ // started when the previous test's afterEach ran (see afterEach below). Diff
267
+ // the static bucket now against the snapshot taken back then; any mutant whose
268
+ // count increased executed while no test was active — i.e. after the previous
269
+ // test ended.
270
+ if(filePrefix !== lastFilePrefix) {
271
+ // FILE-BOUNDARY SKIP: this test starts a new file relative to the last one
272
+ // that ended. A new file's module-level code (imports, describe-level setup)
273
+ // legitimately executes in this gap and would be indistinguishable from real
274
+ // bleed from here, so we deliberately do not diff across a file boundary.
275
+ // This trades missed cross-file leaks for zero file-boundary false positives,
276
+ // which is the safer default for a diagnostic-only warning.
277
+ lastEndedTestId = undefined;
278
+ staticSnapshotAtLastBoundary = new Map();
279
+ } else if(lastEndedTestId !== undefined) {
280
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- Placeholder import replaced at runtime
281
+ const bledMutantIds = detectGapWindowBleed(staticSnapshotAtLastBoundary, mutantCoverage.static);
282
+ if(bledMutantIds.length > 0) {
283
+ lateHits.push({ testId: lastEndedTestId, mutantIds: bledMutantIds });
284
+ }
285
+ }
286
+
244
287
  const prevCount = perFileCounters.get(filePrefix) ?? 0;
245
288
  const nextCount = prevCount + 1;
246
289
  perFileCounters.set(filePrefix, nextCount);
@@ -252,13 +295,53 @@ if(shouldCollectCoverage) {
252
295
  });
253
296
 
254
297
  afterEach(() => {
255
- // Clear currentTestId so any subsequent code records to static
298
+ // Record the gap-window START: which test just ended, and the static bucket's
299
+ // counts at this instant. The NEXT beforeEach (above) diffs against this
300
+ // snapshot to detect any coverage recorded in between — see
301
+ // "Cross-test async coverage-bleed detection" above.
302
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment -- StrykerGlobal from placeholder import
303
+ const endedTestId: string | undefined = strykerGlobal.currentTestId;
304
+ lastEndedTestId = endedTestId;
305
+ if(endedTestId) {
306
+ const sepIdx = endedTestId.indexOf('@@');
307
+ lastFilePrefix = sepIdx === -1 ? endedTestId : endedTestId.slice(0, sepIdx);
308
+ }
309
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- MutantCoverage from placeholder import
310
+ staticSnapshotAtLastBoundary = new Map(Object.entries(mutantCoverage.static));
311
+
312
+ // Clear currentTestId so any subsequent code records to static
256
313
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- StrykerGlobal from placeholder import
257
314
  strykerGlobal.currentTestId = undefined;
258
315
  });
259
316
 
260
317
  afterAll(() => {
318
+ // Final gap check, best-effort: catches bleed that has already recorded a
319
+ // counter delta by the time afterAll runs, with no following beforeEach
320
+ // left to catch it any other way. This preload's afterAll fires once per
321
+ // WORKER PROCESS (empirically verified — Bun runs multiple test files
322
+ // sequentially in one worker sharing this preload module instance), so
323
+ // this is the single final opportunity to detect trailing bleed before
324
+ // coverage is written below.
325
+ //
326
+ // LIMITATION: this only sees hits that execute before afterAll itself
327
+ // runs. A queued timer or promise continuation that is still pending
328
+ // when afterAll fires (and settles afterward, e.g. during process
329
+ // teardown) is never observed — there is no later hook to diff against.
330
+ // Fully catching trailing leaks would need a deliberate strict-drain
331
+ // mode (draining the microtask/timer queue before treating the run as
332
+ // over) — deliberately out of scope here (event-loop starvation risk);
333
+ // see README's "Coverage-bleed warning" section.
334
+ if(lastEndedTestId !== undefined) {
335
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument -- Placeholder import replaced at runtime
336
+ const bledMutantIds = detectGapWindowBleed(staticSnapshotAtLastBoundary, mutantCoverage.static);
337
+ if(bledMutantIds.length > 0) {
338
+ lateHits.push({ testId: lastEndedTestId, mutantIds: bledMutantIds });
339
+ }
340
+ }
341
+
261
342
  ws?.close();
262
343
  writeCoverageData();
344
+ // Clear the accumulator now that it has been written out.
345
+ lateHits.length = 0;
263
346
  });
264
347
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.3.2",
3
+ "version": "1.3.3",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",