@hughescr/stryker-bun-runner 1.3.2 → 1.3.4

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
@@ -153,7 +153,7 @@ Stryker core's own [`maxTestRunnerReuse`](https://stryker-mutator.io/docs/stryke
153
153
  This plugin is designed to tolerate that recycling cleanly:
154
154
 
155
155
  - `dispose()` cleans up its preload script, coverage file, sanitized bunfig, and registry temp file, and aborts any run still in flight (see [Orphan prevention](#orphan-prevention)).
156
- - A fresh `BunTestRunner` instance that never ran its own `dryRun` (as happens after a recycle) still resolves `killedBy` names correctly: it lazily loads the shared, file-backed dry-run test registry written by whichever instance *did* run `dryRun`, exactly as it already does for any other multi-worker Stryker run.
156
+ - A fresh `BunTestRunner` instance that never ran its own `dryRun` (as happens after a recycle) still resolves `killedBy` names correctly: it lazily loads the shared, file-backed dry-run test registry written by whichever instance *did* run `dryRun`, exactly as it already does for any other multi-worker Stryker run. The registry lives in the OS temp directory, not the project directory, keyed to this Stryker run so it can't collide with another run's registry or a different project's — a recycled instance is still a child of the same Stryker main process, so it derives the same key and finds the same file.
157
157
 
158
158
  ```javascript
159
159
  // stryker.conf.mjs
@@ -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
@@ -47,9 +47,47 @@ export declare class BunTestRunner implements TestRunner {
47
47
  constructor(logger: Logger, options: StrykerOptions);
48
48
  /**
49
49
  * Single source of truth for the registry file name.
50
- * Using getters that read process.cwd() at call time ensures the path
51
- * resolves to Stryker's sandbox directory — which is set by the time these
52
- * are invoked — rather than the orchestrator's cwd at module-load time.
50
+ *
51
+ * Lives in the OS temp directory, not cwd: under Stryker's --inPlace mode
52
+ * cwd IS the user's real project root, and writing there would both
53
+ * pollute the user's project and never get cleaned up (dispose()
54
+ * deliberately never unlinks the registry itself — see its doc comment).
55
+ * The temp directory is OS-managed instead.
56
+ *
57
+ * Keyed by sha256(cwd + ':' + ppid): every worker process Stryker spawns
58
+ * for one run is a direct child of that run's single Stryker main
59
+ * process, so all of them share BOTH process.cwd() (the sandbox
60
+ * directory) AND process.ppid (the main process's pid) — and therefore
61
+ * independently derive this SAME path with no coordination required. A
62
+ * worker recycled mid-run is still a child of the same main process, so
63
+ * it re-derives the same path too (README documents recycled instances
64
+ * lazily loading the registry). This is the entire sharing contract:
65
+ * writer (buildAndPersistTestRegistry) and reader (loadRegistryFile) both
66
+ * go through this one getter rather than reimplementing the formula, so
67
+ * they can never disagree by construction.
68
+ *
69
+ * process.ppid is what makes this safe for this repo's own dogfooding:
70
+ * this plugin's own unit/integration tests run INSIDE a Stryker sandbox as
71
+ * the system under test, as children of the sandbox WORKER process, not
72
+ * of the Stryker main process — so those inner test processes hash a
73
+ * different ppid and land on a different file, and can never clobber the
74
+ * outer run's registry. A worker-unique key (e.g. the STRYKER_MUTATOR_WORKER
75
+ * env var Stryker injects per forked worker) was considered and rejected
76
+ * for the same reason it would break the cross-worker sharing above: it
77
+ * uniquely identifies each worker, not the run.
78
+ *
79
+ * process.cwd() is read directly (not resolved via fs.realpathSync):
80
+ * Stryker's child-process-proxy-worker computes every worker's chdir
81
+ * target via a pure path.resolve() of an identical IPC string, so all
82
+ * workers of a run already get a byte-identical process.cwd() with no
83
+ * symlink divergence to guard against — realpath would only add a
84
+ * syscall (and a new ENOENT failure mode if the sandbox dir is mid-
85
+ * teardown) for no benefit.
86
+ *
87
+ * Using a getter that reads process.cwd()/process.ppid at call time
88
+ * (rather than caching at construction) ensures the path resolves against
89
+ * Stryker's sandbox directory — which is set by the time these are
90
+ * invoked — rather than the orchestrator's cwd at module-load time.
53
91
  */
54
92
  private get registryPath();
55
93
  private get registryTmpPath();
@@ -97,6 +135,23 @@ export declare class BunTestRunner implements TestRunner {
97
135
  */
98
136
  private loadRegistryFile;
99
137
  /**
138
+ * Build the failureMessage for a single failed test in the Complete-path result.
139
+ *
140
+ * Base message prefers the parsed-console failure message, then the inspector's
141
+ * error.message, then falls back to a generic string. Stryker core's
142
+ * logFailedTestsInInitialRun prints exactly name+failureMessage for each failed
143
+ * test in the ConfigError initial-run path, so the inspector's error.stack (when
144
+ * present and not already part of the base message) is appended — that's what
145
+ * makes that path actionable instead of a bare one-liner.
146
+ *
147
+ * NOTE this is a genuine, intentional change to the content of the returned
148
+ * DryRunResult (a failed test's failureMessage is longer / carries a stack it
149
+ * didn't before) — not a diagnostic-only, log-line-only change like the two
150
+ * warn helpers below. Test statuses, ids, coverage, and mutantRun behavior
151
+ * are all unaffected; only failureMessage content is enriched.
152
+ */
153
+ private buildFailureMessage;
154
+ /**
100
155
  * Build test results from inspector data.
101
156
  *
102
157
  * Also returns a testNameIndex mapping each FINAL test id (dedup ' [N]'
@@ -116,6 +171,18 @@ export declare class BunTestRunner implements TestRunner {
116
171
  */
117
172
  dryRun(): Promise<DryRunResult>;
118
173
  /**
174
+ * Post-child-exit dry-run pipeline: collect/remap coverage, build tests
175
+ * from inspector data, sort them for incremental-mode determinism, run the
176
+ * completeness gate, and — only if the gate passes — persist the test
177
+ * registry. Returns the gate's Error result when it fires, otherwise the
178
+ * Complete result.
179
+ *
180
+ * Extracted from dryRun() purely to keep dryRun()'s own cyclomatic
181
+ * complexity under the lint threshold; this is a pure code move — same call
182
+ * order and same early-return-on-gate-failure semantics as before.
183
+ */
184
+ private buildGatedDryRunResult;
185
+ /**
119
186
  * Build the in-memory test name cache and base-name index, then atomically
120
187
  * persist them — together with the exact-name testNameIndex from
121
188
  * buildTestsFromInspector — to a well-known file so other worker processes
@@ -167,11 +234,112 @@ export declare class BunTestRunner implements TestRunner {
167
234
  */
168
235
  private checkDryRunProcessResult;
169
236
  /**
237
+ * Build a structured summary of failed tests observed via the inspector, for
238
+ * inclusion in checkDryRunProcessResult's error message. Bun's own stdout/stderr
239
+ * recap can be truncated or entirely empty on process failure, so this pulls
240
+ * failure detail straight from the inspector's TestReporter data instead —
241
+ * the same data buildTestsFromInspector would otherwise turn into per-test
242
+ * results, had the process not short-circuited into the error branch first.
243
+ *
244
+ * Returns '' when there are no failed tests in the hierarchy so callers can
245
+ * keep the plain exit-code+stderr message unchanged in that case. Only
246
+ * type === 'test' entries are considered — describe blocks can also carry
247
+ * status 'fail' (propagated from a failing child) and must not masquerade
248
+ * as failed tests here.
249
+ */
250
+ private formatInspectorFailureDetails;
251
+ /**
252
+ * Diagnostic-only check for the Complete dry-run path: bun reported a failure
253
+ * (non-zero exit, or a failed count in its console recap) but nothing in the
254
+ * built test results identifies which test failed. This is the observed
255
+ * incident fingerprint — bun prints e.g. "1 tests failed:" with an empty
256
+ * recap, the inspector shows no TestStatus.Failed entry, and nothing points
257
+ * at a culprit. An unhandled error firing between tests (e.g. a rejected
258
+ * fire-and-forget promise) rather than inside any single test body is a
259
+ * likely cause. Logs a warning only; this check itself never alters test
260
+ * statuses, ids, coverage, or the returned DryRunResult — contrast with
261
+ * buildFailureMessage above, which (elsewhere in this same dry-run path)
262
+ * DOES intentionally change a failed test's failureMessage content.
263
+ */
264
+ private warnOnUnidentifiedDryRunFailure;
265
+ /**
266
+ * Dry-run data-completeness gate.
267
+ *
268
+ * Guards against the inspector event stream silently truncating mid-run
269
+ * (observed under CI runner contention): bun's own child-side coverage file
270
+ * can be complete while the inspector-derived `executionOrder` is cut off at
271
+ * a file boundary, and everything downstream of that (test results, coverage
272
+ * attribution) accepted the truncated data silently — a plausible-looking
273
+ * but corrupted score, not a loud failure.
274
+ *
275
+ * ONLY evaluated when the run otherwise looks GREEN (zero Failed entries in
276
+ * the already-built `tests`): an already-failing dry run is handled by
277
+ * {@link checkDryRunProcessResult} / {@link warnOnUnidentifiedDryRunFailure},
278
+ * and this precondition structurally prevents a failing beforeAll (which
279
+ * marks the rest of its describe/file Failed) from ever reaching Signal A —
280
+ * the incident's own signature was a run that looked completely healthy.
281
+ *
282
+ * Fires (returns a DryRunStatus.Error result) iff EITHER signal is material:
283
+ *
284
+ * - Signal A (execution/console shortfall): `consoleTotal` (bun's SUMMARY
285
+ * pass+fail counts — deliberately NOT the parser's max(per-line, summary)
286
+ * fields, so per-ATTEMPT retry output can never inflate it — see
287
+ * ParsedTestResults.summaryPassed/summaryFailed) compared against the
288
+ * count of ids in `executionOrder` whose status is neither 'skip' nor
289
+ * bun's not-yet-implemented placeholder-test status. Retries do not
290
+ * create a shortfall in this direction: empirically (bun 1.3.14), a
291
+ * retried test fires ONE TestReporter.start per ATTEMPT for the SAME
292
+ * inspector id — so executionOrder, if anything, grows on retries, and
293
+ * bun's summary line counts tests, not attempts, either way. A material
294
+ * shortfall must clear both an absolute floor and a ratio floor.
295
+ *
296
+ * - Signal B (orphaned coverage keys): `orphanedKeyCount` (a whole file's
297
+ * coverage keys unpaired with any inspector test — see coverage-mapper.ts)
298
+ * exceeding a small absolute floor. Deliberately gate-blind for the legacy
299
+ * ("test-N") coverage format, which never populates this count — Signal A
300
+ * still covers that path since it does not depend on coverage format.
301
+ *
302
+ * `wasClosedUnexpectedly` is NEVER a standalone trigger — the WS-vs-child-exit
303
+ * close race can plausibly be true on a nontrivial fraction of healthy runs —
304
+ * it is folded into the Error message only as corroborating context once the
305
+ * gate has already fired via Signal A or B.
306
+ *
307
+ * @returns A DryRunStatus.Error result if the gate fires, otherwise null.
308
+ */
309
+ private checkCompletenessGate;
310
+ /**
170
311
  * Collect coverage from the coverage file and remap counter-based IDs to
171
312
  * full test names using the inspector's execution order.
313
+ *
314
+ * Also collects any cross-test async coverage-bleed observations recorded
315
+ * by the preload (see {@link emitCoverageBleedWarnings}) and warns about
316
+ * them. This method's sole call site is dryRun, so bleed detection is
317
+ * dry-run-only by construction — mutant runs never reach this code.
172
318
  */
173
319
  private collectAndRemapCoverage;
174
320
  /**
321
+ * Warn about cross-test async coverage bleed: mutant coverage that was
322
+ * recorded in the gap between one test's afterEach and the next test's
323
+ * beforeEach, most likely because a fire-and-forget promise chain from the
324
+ * ended test kept running past the test boundary.
325
+ *
326
+ * Diagnostic only: never alters dryRun/mutantRun results or coverage
327
+ * attribution (stabilizeCoverage's "static wins" rule already governs
328
+ * attribution independently of this warning).
329
+ *
330
+ * A known benign trigger this deliberately does NOT try to suppress: a
331
+ * same-file describe-level beforeAll running in the gap looks identical to
332
+ * genuine bleed from this vantage point (both execute while
333
+ * currentTestId is undefined, between two tests). Filtering it out would
334
+ * require tracking beforeAll boundaries explicitly, which is out of scope
335
+ * here — the warning text calls the false-positive out instead.
336
+ *
337
+ * Capped at {@link MAX_COVERAGE_BLEED_WARNINGS} individual warnings, plus a
338
+ * final summary line for the rest, so a suite with many leaking tests
339
+ * doesn't flood the log.
340
+ */
341
+ private emitCoverageBleedWarnings;
342
+ /**
175
343
  * Build local index structures from testFilter for killedBy resolution.
176
344
  *
177
345
  * testFilter carries the full registry IDs Stryker wants us to run, including