@hughescr/stryker-bun-runner 1.4.0 → 1.5.1

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
@@ -1,434 +1,647 @@
1
1
  # stryker-bun-runner
2
2
 
3
- Stryker test runner plugin for Bun with perTest coverage support.
4
-
5
- [![npm version](https://img.shields.io/npm/v/@hughescr/stryker-bun-runner)](https://www.npmjs.com/package/@hughescr/stryker-bun-runner) [![LICENSE](https://img.shields.io/badge/LICENSE-Apache--2.0-blue)](LICENSE.md) [![Bun](https://img.shields.io/badge/Bun-%3E%3D1.3.7-f9f1e1?logo=bun)](https://bun.sh) [![Stryker](https://img.shields.io/badge/Stryker-Plugin-e74c3c?logo=stryker)](https://stryker-mutator.io) [![Mutation testing badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fhughescr%2Fstryker-bun-runner%2Fmain)](https://dashboard.stryker-mutator.io/reports/github.com/hughescr/stryker-bun-runner/main) [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-3178c6?logo=typescript&logoColor=white)](https://www.typescriptlang.org)
6
-
7
- ## Features
8
-
9
- - **Per-test coverage analysis** - Accurately tracks which tests cover which mutants
10
- - **Inspector Protocol integration** - Uses Bun's WebSocket Inspector API for reliable test discovery and tracking
11
- - **Multi-file support** - Works correctly with multiple test files
12
- - **Incremental mode compatible** - Runs only the tests affected by each mutant
13
-
14
- ## Requirements
15
-
16
- ### Bun Version
17
-
18
- This plugin requires **Bun 1.3.7 or later** for full functionality. Bun 1.3.7 includes the TestReporter WebSocket events (from [PR #25986](https://github.com/oven-sh/bun/pull/25986)) that enable proper test-to-mutant correlation.
19
-
20
- **Important:** Bun versions prior to 1.3.7 will NOT work with this plugin due to missing TestReporter events.
21
-
22
- **To install Bun 1.3.7 or later:**
23
-
24
- ```bash
25
- bun upgrade
26
- ```
27
-
28
- Or install a specific version:
29
-
30
- ```bash
31
- curl -fsSL https://bun.sh/install | bash -s "bun-v1.3.7"
32
- ```
33
-
34
- ### Other Requirements
35
-
36
- - **@stryker-mutator/core** ^9.0.0 || ^10.0.0
37
-
38
- Stryker itself runs on Node (only the test children run on Bun), so the host Node version must satisfy the Stryker major you pick: Stryker 9 needs Node >= 20, Stryker 10 needs Node >= 22.
39
-
40
- ## Installation
3
+ A [Stryker](https://stryker-mutator.io) test runner plugin for [Bun](https://bun.sh). Stryker
4
+ measures how good your tests are by making small changes (mutants) to your code and checking that
5
+ some test fails for each one. This plugin lets Stryker run your `bun test` suite, using per-test
6
+ coverage so that each mutant runs only the tests that reach it.
7
+
8
+ [![npm version](https://img.shields.io/npm/v/@hughescr/stryker-bun-runner)](https://www.npmjs.com/package/@hughescr/stryker-bun-runner) [![LICENSE](https://img.shields.io/badge/LICENSE-Apache--2.0-blue)](LICENSE.md) [![Bun](https://img.shields.io/badge/Bun-%3E%3D1.4.0-f9f1e1?logo=bun)](https://bun.sh) [![Stryker](https://img.shields.io/badge/Stryker-9%20%7C%2010-e74c3c?logo=stryker)](https://stryker-mutator.io) [![Mutation testing badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fhughescr%2Fstryker-bun-runner%2Fmain)](https://dashboard.stryker-mutator.io/reports/github.com/hughescr/stryker-bun-runner/main)
9
+
10
+ - **Per-test coverage**, so each mutant runs only its covering tests, in only their files,
11
+ cheapest file first.
12
+ - **Honest scoring**: a crash or a run that proves nothing is an Error, not a kill; a test file
13
+ that a mutant stops from loading is a kill; an infinite loop is stopped early and scored Timeout.
14
+ - **A strict dry run** that fails loudly rather than hand Stryker incomplete coverage.
15
+ - **Works with** Stryker's incremental mode, `testFiles`, `disableBail`, `ignoreStatic` and the
16
+ TypeScript checker, with a helper that keeps your tests out of the type check.
17
+
18
+ ## Contents
19
+
20
+ - [Quickstart](#quickstart)
21
+ - [Before you start](#before-you-start) · [Install](#1-install) · [Configure](#2-configure) ·
22
+ [Run](#3-run) · [Reading the output](#reading-the-output) ·
23
+ [Optional: skip mutants that do not compile](#optional-skip-mutants-that-do-not-compile)
24
+ - [Upgrading from 1.4](#upgrading-from-14)
25
+ - [Terms](#terms)
26
+ - [Requirements and compatibility](#requirements-and-compatibility)
27
+ - [Configuration](#configuration)
28
+ - [Example with every option](#example-with-every-option) · [bun.bunArgs](#bunbunargs) ·
29
+ [Choosing the test files](#choosing-the-test-files) · [Your bunfig.toml](#your-bunfigtoml)
30
+ - [How it works](#how-it-works)
31
+ - [How results are scored](#how-results-are-scored) · [Timeouts](#timeouts)
32
+ - [Speeding up runs](#speeding-up-runs)
33
+ - [`ignoreStatic`](#ignorestatic-faster-but-skips-module-level-code) ·
34
+ [Keep tests out of the TypeScript checker](#keep-tests-out-of-the-typescript-checker) ·
35
+ [TypeScript 7's native checker](#typescript-7s-native-checker-experimental)
36
+ - [Troubleshooting](#troubleshooting)
37
+ - [Before the dry run](#the-run-stops-before-the-dry-run) ·
38
+ [Dry run fails](#the-dry-run-fails) · [Dry-run warnings](#warnings-during-the-dry-run) ·
39
+ [Mutant runs](#warnings-and-results-during-mutant-runs)
40
+ - [Limitations](#limitations)
41
+ - [Advanced topics](#advanced-topics)
42
+ - [Contributing](#contributing)
43
+ - [License](#license)
44
+
45
+ ## Quickstart
46
+
47
+ ### Before you start
48
+
49
+ - **Bun 1.4.0 or later** (`bun --version`).
50
+ - **Node.js 22 or later** (`node --version`). Stryker itself runs on Node; only your tests run on
51
+ Bun. Stryker 10, which the install below gets you, needs Node 22; Stryker 9 needs Node 20.
52
+ - **A project whose `bun test` passes**, with its source code under `src/` or `lib/` (Stryker's
53
+ default; see `mutate` in [Stryker's options](https://stryker-mutator.io/docs/stryker-js/configuration/)
54
+ otherwise).
55
+
56
+ ### 1. Install
41
57
 
42
58
  ```bash
43
59
  bun add -D @hughescr/stryker-bun-runner @stryker-mutator/core
44
60
  ```
45
61
 
46
- ## Configuration
47
-
48
- Create a `stryker.conf.mjs` file:
62
+ > **Using TypeScript 7? Switch to TypeScript 6 first.** Stryker reads your `tsconfig.json` with the
63
+ > `typescript` package, and TypeScript 7's package cannot do that: `stryker run` stops with
64
+ > `TypeError: ts.parseConfigFileTextToJson is not a function`. A project created with `bun init`
65
+ > gets TypeScript 7. Check with `bun pm ls`, and if it lists `typescript@7`, run:
66
+ >
67
+ > ```bash
68
+ > bun remove typescript && bun add -D typescript@^6
69
+ > ```
70
+ >
71
+ > `bun add -D 'typescript@<7'` on its own is not enough when `typescript` is listed under
72
+ > `peerDependencies` (as `bun init` lists it): it rewrites that entry but leaves TypeScript 7
73
+ > installed.
74
+ >
75
+ > This package declares a peer dependency on `typescript` below 7. With TypeScript 7 present,
76
+ > `bun add` prints `warn: incorrect peer dependency "typescript@7.0.2"` and `npm install` stops
77
+ > with an `ERESOLVE` error. A project without TypeScript gets TypeScript 6 installed as
78
+ > that peer.
79
+
80
+ ### 2. Configure
81
+
82
+ Create `stryker.conf.mjs` in your project root:
49
83
 
50
84
  ```javascript
85
+ // @ts-check
86
+ /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */
51
87
  export default {
88
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
52
89
  testRunner: 'bun',
53
- coverageAnalysis: 'perTest',
54
- mutate: ['src/**/*.ts'],
55
- bun: {
56
- // bunPath defaults to 'bun' - only set if using a custom Bun installation
57
- inspectorTimeout: 5000, // Inspector connection timeout in ms (default: 5000)
58
- },
59
90
  };
60
91
  ```
61
92
 
62
- ## How It Works
63
-
64
- The plugin uses Bun's Inspector Protocol (WebSocket) to:
65
-
66
- 1. **Discover tests** - Connects to Bun's test process via WebSocket
67
- 2. **Track execution** - Listens for TestReporter events to correlate test runs with coverage
68
- 3. **Sequential execution** - Uses `--concurrency=1` to ensure reliable coverage correlation
69
- 4. **Build hierarchy** - Reconstructs test names from describe blocks for accurate reporting
70
- 5. **Targeted mutant runs** - Runs only the tests that covered each mutant (via `--test-name-pattern`); bails after the first failure unless Stryker's `disableBail` option is set (dry runs never bail, since the full suite must run for coverage). Any bail flag in `bun.bunArgs` is ignored — bail is decided solely by the runner.
71
-
72
- 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.
73
-
74
- 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)).
75
-
76
- ## Options
93
+ `appendPlugins` is required: Stryker only loads plugins named `@stryker-mutator/*` by itself, so
94
+ without it `testRunner: 'bun'` is never registered.
77
95
 
78
- | Option | Type | Default | Description |
79
- |--------|------|---------|-------------|
80
- | `bun.bunPath` | `string` | `'bun'` | Path to the Bun executable |
81
- | `bun.timeout` | `number` | `10000` | Timeout per test in milliseconds |
82
- | `bun.inspectorTimeout` | `number` | `5000` | Timeout for Inspector WebSocket connection in milliseconds |
83
- | `bun.env` | `object` | `undefined` | Additional environment variables to pass to bun test |
84
- | `bun.bunArgs` | `string[]` | `undefined` | Additional bun test flags (e.g., `['--only']`). Bail flags (`--bail`, `--bail=<N>`, or a space-separated `--bail <N>`) are ignored here — bail is fully managed by the runner via Stryker's `disableBail` option (see [How It Works](#how-it-works)). |
85
- | `bun.testFiles` | `string[]` | `undefined` | Explicit list of test file paths (absolute or relative to cwd). When provided, skips auto-discovery and uses this list verbatim. Relative paths resolve against the bun subprocess's cwd. Useful for restricting mutation testing to a subset of test files. |
86
- | `bun.smol` | `boolean` | `false` | Pass Bun's `--smol` flag to every child: a smaller JavaScriptCore heap at some cost to speed. Recommended on memory-constrained machines — see [Memory model](#memory-model). |
87
- | `bun.maxChildRss` | `number` | `undefined` | Soft memory ceiling in bytes for each child's RSS. A child that exceeds it is killed and the run reported as a clean timeout for that mutant. See [Memory containment](#memory-containment). |
88
- | `bun.rssCheckIntervalMs` | `number` | `1000` | Poll interval in milliseconds for the `maxChildRss` check. |
89
- | `bun.maxSpawnDepth` | `number` | `1` | Maximum `bun test` spawn nesting depth before the runner refuses to spawn. Guards against runaway recursion — see [Recursion containment](#recursion-containment). Raise to `2` only if your own tests drive this runner. |
90
-
91
- ### Example with all options
92
-
93
- ```javascript
94
- bun: {
95
- bunPath: '/path/to/bun', // Custom bun executable (defaults to 'bun')
96
- timeout: 30000, // 30 second test timeout
97
- inspectorTimeout: 10000, // 10 second connection timeout
98
- env: { DEBUG: 'true' }, // Extra environment variables
99
- bunArgs: ['--only'], // Extra bun test flags (bail flags here are ignored — see Options table)
100
- smol: true, // Smaller JSC heap, some speed cost — see Memory model
101
- maxChildRss: 1_500_000_000, // Kill+report-timeout a child using more than ~1.5GB RSS
102
- rssCheckIntervalMs: 1000, // How often to poll RSS when maxChildRss is set
103
- }
104
- ```
105
-
106
- ## Running Stryker
96
+ ### 3. Run
107
97
 
108
98
  ```bash
109
99
  bunx stryker run
110
100
  ```
111
101
 
112
- ## How the sandboxed config works
113
-
114
- When the plugin initialises it reads your project's `bunfig.toml` (if present) and writes a sanitized copy that is passed to every `bun test` invocation via `--config`. The sanitizer forwards only an explicit allowlist of `[test]` keys; everything else is stripped. The forwarded keys are: `preload`, `root`, `pathIgnorePatterns`, `timeout`, `smol`, `rerunEach`, `retry`, `randomize`, `seed`. The `[install]` table is copied verbatim. Two keys are always forced: `coverage = false` and `onlyFailures = false`. This prevents `coverageThreshold` misses (which cause Bun to exit 1 even when no test actually fails) from being mistaken for mutant kills. If you need additional `[test]` settings forwarded, add their key names to the `SAFE_TEST_KEYS` set in `src/utils/bunfig-sanitizer.ts`.
115
-
116
- ## Memory model
117
-
118
- Every `dryRun` and `mutantRun` spawns a **brand-new `bun test` OS process** and waits for it to fully exit before returning a result — the plugin never reuses a `bun test` child across runs. This is deliberate: it's what makes per-run isolation and coverage correlation reliable, and it means a child process's memory is always fully reclaimed by the OS the moment that one run ends. There is no cross-mutant memory accumulation to "fix" in the spawned child — each mutant gets a clean process.
119
-
120
- What this means for memory planning on a mutation-testing machine:
121
-
122
- - **Peak memory ≈ `concurrency` × per-run suite footprint.** If your test suite loads heavyweight dependencies at module scope (real ML models, native bindings like `sqlite`/`onnxruntime`, PDF/DOCX extractors, etc. across many test files), each individual `bun test` run pays that footprint once — and Stryker runs `concurrency` of them in parallel. 12 concurrent workers × a 2–3GB suite footprint is 24–36GB of *simultaneous* peak usage, not a leak.
123
- - **A mutant that breaks cleanup code (`dispose()`/`close()`/`finally`) still leaks *within* that one run.** Because mutation campaigns exhaustively try every "what if this cleanup were skipped" variant, they will execute every broken-`dispose()` mutant your suite has — and each one runs to completion inside its own process before exiting, so the extra native memory is held only for that run's duration, not across the whole campaign. Well-behaved `afterAll`/`afterEach` cleanup in the tests being mutated is what keeps a single run's peak down; no plugin option can substitute for that.
124
- - **Recommended settings for memory-constrained machines:**
125
- - Lower `concurrency` in your `stryker.conf.mjs` first — it has the largest, most direct effect on peak memory (linear multiplier).
126
- - Set `bun.smol: true` to shrink each child's JSC heap ceiling at some speed cost.
127
- - Set `bun.maxChildRss` as a backstop against a single run growing unexpectedly large (see [Memory containment](#memory-containment)).
128
- - Use Stryker core's [`maxTestRunnerReuse`](#maxtestrunnerreuse-compatibility) to periodically recycle the *Stryker worker* process itself (see below) — this is orthogonal to the spawned `bun test` child and addresses a different, much smaller source of growth.
129
-
130
- ## Recursion containment
131
-
132
- ### Kills reach the whole process tree
133
-
134
- On POSIX systems, every `bun test` child is spawned **detached**, so it leads its own process group, and every kill path (timeout, `AbortSignal`, the `maxChildRss` ceiling) signals that whole group rather than the single child. This matters whenever your test suite itself spawns processes: signalling only the direct child leaves its grandchildren alive and reparented to PID 1, where nothing will ever clean them up. A suite that starts a server, a database, or another `bun` process therefore leaks one of each on every timed-out mutant unless the group is signalled. Platforms without POSIX process-group signalling fall back to terminating the direct child and cannot guarantee descendant cleanup.
135
-
136
- Spawning detached has a consequence worth stating plainly: a detached child is no longer in the terminal's foreground process group, so it does **not** die on its own when you Ctrl-C a run. The runner therefore traps `SIGINT`/`SIGTERM`/`SIGHUP`, kills every live child's group, and re-raises the signal so the default behaviour is preserved. Without that, interrupting a campaign would strand one full `bun test` process per worker.
137
-
138
- ### The runner refuses to nest indefinitely
139
-
140
- Each child carries its spawn depth in `__STRYKER_BUN_RUNNER_DEPTH__`, and a run at or beyond `bun.maxSpawnDepth` fails with a non-zero exit code instead of spawning. The failure mode this prevents is worth spelling out, because it is not hypothetical and it is not survivable:
141
-
142
- - The runner can spawn `bun test` from inside a `bun test` it spawned.
143
- - If a nested run falls back to auto-discovery while its cwd is the project root, it picks up the project's **entire** suite — including the very test that spawned it.
144
- - That test spawns again, and so on. A new generation appears roughly every second.
145
- - Every generation leads its own process group, so killing any one of them does not stop the chain; the survivors keep replicating and are reparented to PID 1. (Group-per-generation is a consequence of the detached spawn above — which is why the depth ceiling, not the group kill, is what actually terminates this.)
146
-
147
- Under mutation testing this is reachable through ordinary mutants — anything that defeats the `bun.testFiles` override puts a nested run back on auto-discovery. The depth ceiling turns that from an unbounded runaway into a single loud failure.
148
-
149
- The default of `1` allows the runner's own `bun test` children and nothing deeper, which is correct for every project whose tests do not themselves drive this runner. If yours do, raise it to `2` — **on the runner instance making the nested call**, since that is where the ceiling is enforced. Setting it in `stryker.conf.mjs` only configures the outer run, which never reaches the ceiling. This plugin's own integration tests are the worked example: they pass `maxSpawnDepth: 2` in their `bun: { … }` literals, because under Stryker the suite is itself a depth-1 run and its own spawns land at depth 2.
150
-
151
- A refused spawn is reported as a failure for that mutant, with the reason on stderr, rather than silently passing.
102
+ ### Reading the output
103
+
104
+ Abridged output from a small project with one test file (your counts will differ):
105
+
106
+ ```text
107
+ INFO DryRunExecutor Starting initial test run (bun test runner with "perTest" coverage analysis). This may take a while.
108
+ INFO DryRunExecutor Initial test run succeeded. Ran 2 tests in 0 seconds (net 1 ms, overhead 90 ms).
109
+ [Survived] EqualityOperator
110
+ src/math.ts:6:12
111
+ - return n > 0;
112
+ + return n >= 0;
113
+ Tests ran:
114
+ tests/math.test.ts > isPositive
115
+ ----------|------------------|----------|-----------|------------|----------|----------|
116
+ | % Mutation score | | | | | |
117
+ File | total | covered | # killed | # timeout | # survived | # no cov | # errors |
118
+ ----------|--------|---------|----------|-----------|------------|----------|----------|
119
+ All files | 85.71 | 85.71 | 6 | 0 | 1 | 0 | 0 |
120
+ INFO HtmlReporter Your report can be found at: file:///home/me/demo/reports/mutation/mutation.html
121
+ INFO BunTestRunner Mutant runs on this worker: 3 (killed 2, survived 1, timeout 0, error 0); full-suite fallbacks: 0
122
+ INFO BunTestRunner Mutant runs on this worker: 4 (killed 4, survived 0, timeout 0, error 0); full-suite fallbacks: 0
123
+ ```
152
124
 
153
- ## Memory containment
125
+ - Each Stryker **worker** process logs one `Mutant runs on this worker` line at the end, so you
126
+ see as many of them as Stryker has workers.
127
+ - Each worker process also logs one `Bun test runner started` line (bun version and path, test
128
+ files, sanitized bunfig), but at `debug`, so it only shows with `--logLevel debug`. These are
129
+ one per worker process, not one per dry run: the dry run itself happens once, on one worker.
130
+ - **`Initial test run succeeded`** means the [dry run](#terms) passed: your whole suite ran once,
131
+ unmutated, and the runner recorded which tests reach which mutants.
132
+ - **Killed** mutants made a test fail: good. A **Survived** mutant is a change to your code that no
133
+ test noticed; here, no test checks `isPositive(0)`. Add or strengthen a test to kill it.
134
+ - The **mutation score** is the share of mutants your tests detected. The HTML report, at
135
+ `reports/mutation/mutation.html`, shows every mutant in your source.
136
+ - **Full-suite fallbacks** count mutants that had covering tests but had to run the whole suite
137
+ instead (see [Terms](#terms)); a few are normal.
154
138
 
155
- Two independent knobs help bound the memory a single `bun test` child can use, on top of the isolation the [memory model](#memory-model) already provides:
139
+ If something goes wrong instead, see [Troubleshooting](#troubleshooting).
156
140
 
157
- - **`bun.smol`** passes Bun's own `--smol` flag, which reduces JavaScriptCore's heap growth at some cost to speed. Cheap to enable, no behavior change beyond memory/speed trade-off.
158
- - **`bun.maxChildRss`** is a *soft, polled userspace* memory ceiling: the plugin periodically reads the child's actual resident set size (RSS) — via `/proc/<pid>/status` on Linux, `ps -o rss=` elsewhere — and if it exceeds the configured byte threshold, kills the child (SIGTERM, escalating to SIGKILL after a grace period) and reports that one run as a clean timeout. This converts "one runaway mutant slowly drags the machine into swap" into "one mutant times out," without corrupting the rest of the campaign.
141
+ ### Optional: skip mutants that do not compile
159
142
 
160
- **Why not a hard, kernel-enforced ceiling (`ulimit -v`, cgroups)?** We looked at this and decided against it:
161
- - `RLIMIT_AS` (what `ulimit -v` sets) caps *virtual address space*, not RSS. Modern JS engines (Bun's JavaScriptCore, V8) reserve large virtual ranges up front — for JIT code, WASM, guard pages — regardless of how much is actually resident. A ceiling tight enough to matter for real RSS would make the engine fail to start, unrelated to any actual leak.
162
- - `RLIMIT_RSS` has been a no-op on Linux since kernel 2.4.30 — the kernel accepts the limit but never enforces it.
163
- - cgroup `memory.max` is the modern, correct mechanism for a true hard ceiling, but requires delegated cgroup access that isn't guaranteed on developer machines, most CI runners, or inside existing containers — wiring it up reliably cross-platform (it doesn't exist at all on macOS) was out of scope for what should be a portable, dependency-free plugin option.
143
+ Stryker's TypeScript checker type-checks each mutant first and marks the ones that do not compile
144
+ as CompileError instead of running your tests on them. It needs a `tsconfig.json` and `typescript`
145
+ 6 or earlier (see the note under [Install](#1-install)):
164
146
 
165
- `bun.maxChildRss` gets you the practical outcome (a runaway run fails cleanly instead of taking down the machine) without those platform landmines. If you need a true hard ceiling, run Stryker itself inside a container/cgroup with a memory limit at the orchestration layer — that composes fine with this plugin.
147
+ ```bash
148
+ bun add -D @stryker-mutator/typescript-checker
149
+ ```
166
150
 
167
- ## Orphan prevention
151
+ Then turn it on with `checkers: ['typescript']`. Stryker loads `@stryker-mutator/*` plugins by
152
+ itself, so `appendPlugins` stays as it is. To keep the checker from re-checking your tests too, wrap
153
+ the config in [`withTestFilesExcludedFromTypeCheck`](#keep-tests-out-of-the-typescript-checker):
168
154
 
169
- Each spawned `bun test` child is protected against being left running forever if something goes wrong:
155
+ ```javascript
156
+ // @ts-check
157
+ import { withTestFilesExcludedFromTypeCheck } from '@hughescr/stryker-bun-runner';
170
158
 
171
- - **Timeouts and aborts escalate gracefully.** When the per-run `bun.timeout` fires, or when the plugin internally aborts a run (e.g. dry-run inspector connection failure), the child receives SIGTERM first; if it hasn't exited after a short grace period, it's escalated to SIGKILL. The same escalation covers `bun.maxChildRss` kills.
172
- - **`dispose()` kills any run still in flight.** If Stryker disposes a `TestRunner` instance while its `dryRun`/`mutantRun` hasn't resolved yet (e.g. tearing down a stuck worker), the in-flight child is aborted using the same escalation path — it isn't left running after the plugin instance that spawned it goes away.
173
- - **A parent-liveness watchdog guards against the parent being killed outright.** If the Stryker worker process itself is killed with SIGKILL, it gets no chance to run any cleanup code at all — `dispose()` never fires. To prevent an orphaned `bun test` process in that case, every child's preload script polls its own `process.ppid` against the value captured at startup. POSIX reparents an orphaned child to the nearest subreaper (commonly PID 1) as soon as its original parent exits, so a changed `ppid` reliably signals "my parent is gone" — no `prctl(PR_SET_PDEATHSIG)` or native addon required, and it works the same on Linux and macOS. On detecting this, the child logs a warning and exits.
159
+ export default await withTestFilesExcludedFromTypeCheck({
160
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
161
+ testRunner: 'bun',
162
+ checkers: ['typescript'],
163
+ });
164
+ ```
174
165
 
175
- ## `maxTestRunnerReuse` compatibility
166
+ ## Upgrading from 1.4
167
+
168
+ Most projects need no config change, but these differ from 1.4:
169
+
170
+ - **`bun.timeout` now bounds only the dry run** (plus the 30 s drain-handshake allowance). Mutant
171
+ runs use Stryker's per-mutant timeout: `timeoutFactor` × the dry-run time of the tests that
172
+ mutant runs (the whole suite for a static mutant) + `timeoutMS` + the dry run's overhead, less a
173
+ small margin ([Timeouts](#timeouts)). If you raised `bun.timeout` so slow mutant runs would not
174
+ time out, raise `timeoutMS` or `timeoutFactor` instead. `bun.timeout` can now be generous: the
175
+ runner warns above 80% use, and only a hung dry run takes that long to fail.
176
+ - **Mutant runs never randomize.** Covering files run cheapest first (by dry-run time), tests in
177
+ source order. The dry run still follows your bunfig `randomize` and `seed`.
178
+ - **Some verdicts change, toward correctness** ([How results are scored](#how-results-are-scored)).
179
+ A hang that a fast test catches is Killed. An infinite loop stops at Stryker's hit limit and is
180
+ Timeout, reason `Hit limit reached`. A bun crash or failed start with no failing test is Error
181
+ (left out of the score), not Killed. A mutant that stops a test file loading is Killed (1.4
182
+ usually scored it Error). Incremental mode keeps the old verdict of mutants it reuses; run once
183
+ with `--force` to re-score.
184
+ - **The dry run is stricter.** Bun's summary, the inspector's events and the coverage records must
185
+ agree exactly (1.4 tolerated small shortfalls), and missing per-test coverage with
186
+ `coverageAnalysis: 'perTest'` is an Error. See [the dry run fails](#the-dry-run-fails).
187
+ - **Configuration.** Some `bun.bunArgs` flags are now rejected, `--retry` and `--rerun-each`
188
+ among them ([bun.bunArgs](#bunbunargs)). `retry` and `rerunEach` in your bunfig are dropped with
189
+ a warning. `bun.testFiles` entries are exact paths, not substring filters, so a bare name no
190
+ longer matches copies under `dist/` ([Choosing the test files](#choosing-the-test-files)).
191
+ `--config`/`-c` in `bun.bunArgs` names the bunfig the runner reads, and everything outside
192
+ `[test]` in it is kept (1.4 kept only `[install]`): [Your bunfig.toml](#your-bunfigtoml).
193
+ - **Install.** A peer dependency on `typescript` below 7 (see the callout under
194
+ [Install](#1-install)); dependencies are no longer bundled and install normally. Startup now
195
+ requires Bun 1.4.0 or later and stops at once otherwise.
196
+ - **Test ids are unchanged**, so a 1.4 incremental report stays reusable. The one exception is a
197
+ test retried in the dry run (a per-test `{ retry }` option, or `retry` in your bunfig): it had one
198
+ id per attempt (`name [0]`, `name [1]`, ...) and now has the single id `name`.
199
+
200
+ ## Terms
201
+
202
+ - **Mutant**: one small change Stryker makes to your source, such as `>` to `>=`. Each mutant is
203
+ tested on its own and ends up **Killed** (a test failed), **Survived** (no test failed),
204
+ **Timeout**, **NoCoverage** (no test reaches it), **CompileError** (with a checker) or **Error**
205
+ (Stryker shows RuntimeError; left out of the score).
206
+ - **Dry run**: Stryker's first run of your whole suite, without mutants. It must pass. The runner
207
+ uses it to record which tests reach each mutant.
208
+ - **Covering tests**: the tests that reached a mutant in the dry run. A mutant run normally runs
209
+ only these.
210
+ - **Static mutant**: a mutant in code that runs only while a module loads (module-level constants,
211
+ top-level setup), so no single test covers it, and every test has to run for it.
212
+ - **Full-suite fallback**: a mutant that had covering tests but ran the whole suite instead, because
213
+ the list of test names was too long for the command line or matched no test.
214
+ - **killedBy**: the tests Stryker records as having killed a mutant. Incremental mode uses it to
215
+ decide what to re-run.
216
+ - **Bail**: stopping a mutant run at the first failing test, which is enough to kill the mutant.
217
+ - **Hit limit**: Stryker's cap on how many times a mutant may execute in a mutant run (100 times
218
+ its dry-run count). Exceeding it means an infinite loop, scored Timeout.
219
+ - **Sandbox**: the copy of your project Stryker makes under `.stryker-tmp/` and mutates.
220
+ - **Worker**: one of the processes Stryker runs mutants in; Stryker's `concurrency` option sets how
221
+ many.
222
+ - **bunfig**: Bun's configuration file, `bunfig.toml`.
223
+ - **Preload**: a script bun runs before your tests (`[test].preload` in the bunfig). The runner adds
224
+ its own coverage preload, which switches mutants on and records coverage.
225
+ - **Inspector**: Bun's debugging protocol. The runner uses its test events to see each test start
226
+ and finish.
227
+ - **Drain handshake**: at the end of the dry run, the test process waits until the runner confirms
228
+ it has received every test event, so none are lost on a busy machine.
229
+
230
+ ## Requirements and compatibility
231
+
232
+ | Component | Supported | Notes |
233
+ |---|---|---|
234
+ | Bun | 1.4.0 or later | Tested with 1.4.0, 1.4.2 and 1.4.3. 1.4.0 is the oldest release the runner's test suite is run against, so older versions are not supported. |
235
+ | `@stryker-mutator/core` | 9.x or 10.x | Peer dependency. Stryker's `testFiles` option needs 9.6 or later. |
236
+ | Node.js | 20 or later with Stryker 9; 22 or later with Stryker 10 | Stryker runs on Node; only the test processes run on Bun. |
237
+ | `typescript` | 6 or earlier, when your project has a `tsconfig.json` | Peer dependency (`<7`): bun warns and npm refuses to install next to TypeScript 7, and a project without TypeScript gets TypeScript 6. Stryker reads `tsconfig.json` with it, with or without a checker, and TypeScript 7's package cannot (see [Install](#1-install)). TypeScript 7 can only be added next to it, for the [native checker](#typescript-7s-native-checker-experimental). |
238
+ | `@stryker-mutator/typescript-checker` (optional) | the same version as `@stryker-mutator/core` | |
239
+ | Operating system | Linux, macOS | |
240
+
241
+ At startup the runner runs `<bunPath> --version` and stops with a clear error if Bun cannot be run
242
+ or is older than 1.4.0. To upgrade Bun, run `bun upgrade`.
176
243
 
177
- Stryker core's own [`maxTestRunnerReuse`](https://stryker-mutator.io/docs/stryker-js/configuration/#maxtestrunnerreuse-number) option periodically disposes and reconstructs the *TestRunner instance* (and, depending on core's process-pooling, the worker process hosting it) after a configured number of runs — this is the right lever for bounding growth in the long-lived Stryker worker itself, as opposed to the already-isolated, per-run `bun test` children this plugin spawns (see [Memory model](#memory-model)).
244
+ ## Configuration
178
245
 
179
- This plugin is designed to tolerate that recycling cleanly:
246
+ Runner options go under `bun` in your Stryker config. Stryker validates them: an unknown key under
247
+ `bun`, a wrong type, or an out-of-range value stops the run with a configuration error.
180
248
 
181
- - `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)).
182
- - 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.
249
+ | Option | Type | Default | Description |
250
+ |---|---|---|---|
251
+ | `bun.bunPath` | `string` | `'bun'` | Bun executable to run. |
252
+ | `bun.timeout` | `number` (ms, >= 0) | `10000` | Wall-clock limit for the **dry run's** `bun test` process, which gets 30 s more for the [drain handshake](#terms). Set it comfortably above your full suite's run time; the runner warns when a dry run uses more than 80% of it. Mutant runs follow Stryker's per-mutant timeout instead (see [Timeouts](#timeouts)). Not the same as Bun's per-test `[test].timeout`. |
253
+ | `bun.inspectorTimeout` | `number` (ms, >= 0) | `5000` | Bound on each step of connecting to Bun's [inspector](#terms) in the dry run: waiting for bun to print its inspector address, connecting, and each request. Raise it if bun is slow to start. |
254
+ | `bun.env` | `object` of strings | none | Extra environment variables for every `bun test` process (and for the startup `bun --version` check). |
255
+ | `bun.bunArgs` | `string[]` | none | Extra `bun test` flags. Some are rejected, removed or handled specially; see [bun.bunArgs](#bunbunargs). |
256
+ | `bun.testFiles` | `string[]` (non-empty) | none | The test files or directories to run, instead of auto-discovery. See [Choosing the test files](#choosing-the-test-files). |
257
+ | `bun.smol` | `boolean` | `false` | Pass Bun's `--smol` to every process: a smaller JavaScriptCore heap at some cost to speed. |
258
+ | `bun.maxChildRss` | `number` (bytes, >= 0) | none | Soft memory ceiling per `bun test` process. One that exceeds it is killed and that run scored Timeout. |
259
+ | `bun.rssCheckIntervalMs` | `number` (ms, >= 0) | `1000` | How often to check `maxChildRss`. |
260
+ | `bun.maxSpawnDepth` | integer (>= 1) | `1` | How deeply `bun test` processes may nest before the runner refuses to start another. Raise it only if your own tests run this runner; see [the troubleshooting entry](#the-dry-run-fails). |
261
+
262
+ ### Example with every option
183
263
 
184
264
  ```javascript
185
- // stryker.conf.mjs
265
+ // @ts-check
266
+ /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */
186
267
  export default {
268
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
187
269
  testRunner: 'bun',
188
- coverageAnalysis: 'perTest',
189
- mutate: ['src/**/*.ts'],
190
- concurrency: 8, // tune down first on memory-constrained machines
191
- maxTestRunnerReuse: 100, // recycle each Stryker worker after 100 runs
192
270
  bun: {
271
+ bunPath: 'bun', // found on PATH; or an absolute path to a specific Bun
272
+ timeout: 60_000, // the dry run's limit, not a per-test timeout
273
+ inspectorTimeout: 10_000,
274
+ env: { NODE_ENV: 'test' },
275
+ bunArgs: ['--randomize'], // the dry run randomizes; mutant runs never do
276
+ testFiles: ['tests'], // a directory: every test file below it (omit to auto-discover)
193
277
  smol: true,
194
- maxChildRss: 1_500_000_000, // ~1.5GB soft ceiling per bun test child
278
+ maxChildRss: 1_500_000_000, // about 1.5 GB per bun test process
279
+ rssCheckIntervalMs: 1000,
280
+ maxSpawnDepth: 1,
195
281
  },
196
282
  };
197
283
  ```
198
284
 
199
- ## Diagnostic warnings worth grepping for in CI
200
-
201
- The runner logs three warnings that flag when a mutant run's `--test-name-pattern`
202
- couldn't be built or applied with full fidelity. None of them indicate a wrong
203
- mutation-testing verdict by themselves, but they're worth grepping your CI logs for
204
- because they mark where the runner fell back to less-precise behavior:
205
-
206
- - **`--test-name-pattern matched 0 tests`** — the pattern for a mutant's covering
207
- tests matched nothing across the whole run (usually because a mutant changed a
208
- value interpolated into an `it.each` title). The runner retries once with the
209
- full suite rather than reporting a false kill, so the eventual verdict is still
210
- genuine — if the retry itself also matches zero tests (or the zero-match came
211
- from a user-supplied `--test-name-pattern` in `bunArgs`, which is never retried),
212
- the mutant is classified as an infrastructure `Error`, never a kill. Every
213
- occurrence is worth spot-checking that it's explained by an interpolated-title
214
- change, not a real pattern gap.
215
- - **`no exact-name registry available`** — this worker couldn't load the shared
216
- dry-run test-name registry, so every alternative in that mutant's pattern used
217
- the lossy `' > '`-collapsing reconstruction instead of Bun's exact matching
218
- names. Tests whose titles legitimately contain `" > "` may have been silently
219
- excluded from that run.
220
- - **`missing from exact-name registry`** — the registry loaded, but one or more
221
- `testFilter` ids for this mutant weren't in it (falls back to the same lossy
222
- reconstruction for just those ids, listing up to 5 of the missing ids).
223
-
224
- The last two matter because Bun only errors when a pattern matches **zero** tests
225
- across the whole run; a *partial* miss — some alternatives hit, others silently
226
- don't — exits 0 with no error text at all. These two warns are the only signal
227
- that a partial silent drop was possible for a given mutant run, so seeing either
228
- of them in a clean run's logs is worth investigating before trusting the score.
229
-
230
- ### Dry-run failure diagnostics (dry run only)
231
-
232
- - **`Bun exited with code <N> and its console output reported <N> failed test(s), but no failing test could be identified...`**
233
- — the dry run's process-level signals (a non-zero exit code, or a `>0` failed
234
- count parsed from Bun's console recap) say a test failed, but neither the
235
- inspector's per-test data nor the parsed console output identifies which one
236
- — the "empty recap" incident fingerprint: Bun prints e.g. `1 tests failed:`
237
- with no `(fail)` line naming a test. The most likely cause is an unhandled
238
- error firing *between* tests (e.g. a rejected fire-and-forget promise) rather
239
- than inside any single test body, so nothing in bun's own per-test
240
- bookkeeping ever marked a test as failed. What to do: check the trailing
241
- stderr included in the warning for a stack, and look for fire-and-forget
242
- async work (unawaited promises, orphaned timers) anywhere in the suite —
243
- especially in the file that was running when the process exited. This
244
- warning is purely diagnostic and never alters the returned `DryRunResult`
245
- by itself; it's a separate, related change that failed tests' `failureMessage`
246
- in a *Complete* result now has the inspector's `error.stack` appended (when
247
- available) — Stryker core only prints name+failureMessage for initial-run
248
- failures, so that's the only channel this stack reaches the CI log through.
249
-
250
- ### Dry-run completeness gate (dry run only)
251
-
252
- - **`stryker-bun-runner: dry run data-completeness check failed — ...`** — the dry
253
- run otherwise looked healthy (no failed tests) but the runner detected that Bun's
254
- inspector event stream may have been silently truncated mid-run: either the
255
- inspector's execution order fell materially short of what Bun's own console
256
- summary reported (`console reported <N> test(s) ... but the inspector's execution
257
- order contains only <M> non-skipped test(s)`), or a meaningful number of coverage
258
- keys couldn't be paired with any inspector test (`<N> of <M> coverage key(s) ...
259
- could not be paired with any inspector test (orphaned)`) — the signature of one or
260
- more whole test files being dropped from the stream, most often under CI runner
261
- resource contention. When both are present, or the socket also closed
262
- unexpectedly before the runner could finish reading it, the message names all of
263
- them. This is a genuine `DryRunStatus.Error`, not a warning: proceeding on
264
- truncated data would risk silently corrupted coverage attribution (mutants losing
265
- their true killers), so the runner reports the error and does **not** persist the
266
- test registry, rather than let other Stryker workers load a corrupted one. If you
267
- see this, it usually means the CI runner was under heavier contention than usual;
268
- retrying the run (with less concurrent load, or fewer parallel Stryker workers) is
269
- the first thing to try.
270
-
271
- Before this check runs, the bun test child process (during `dryRun` only) holds
272
- itself open past its own natural exit and waits for the runner to prove — via an
273
- inspector-protocol round-trip over the same ordered connection the test events
274
- arrive on — that it has actually received and processed everything the child
275
- sent, before letting the child close its coverage socket and exit. This closes
276
- the specific race that used to cause this gate to fire under CPU-contended CI
277
- runners: previously, nothing synchronized "the runner has drained the inspector
278
- stream" with "the child process is allowed to exit," so a consumer that couldn't
279
- keep up with the event stream under contention would lose whatever hadn't been
280
- processed by the time the child exited.
281
-
282
- The runner's side of this wait is progress-based, not a fixed timer: it keeps
283
- extending as long as the inspector connection is still receiving frames of any
284
- kind, since continued arrivals are proof a backlog is actively draining, and
285
- only gives up once a period of true silence — no frames at all — has elapsed. A
286
- separate, much larger absolute ceiling also exists, but purely as hang
287
- prevention for a connection that never goes silent (or never acks) at all; it
288
- is not the normal way this wait ends. Either way, once the runner gives up (via
289
- silence or the ceiling), it still releases the child immediately rather than
290
- leaving it to time out on its own — the child-side timeout only governs the
291
- case where the sync channel itself is dead or unresponsive. Hitting any of
292
- these bounds still reverts to the original pre-handshake behavior (including
293
- this gate) exactly as before, so the handshake can only reduce how often this
294
- gate fires, never mask a real truncation from it.
295
-
296
- The gate's thresholds — `EXECUTION_SHORTFALL_ABS_FLOOR`, `EXECUTION_SHORTFALL_RATIO_THRESHOLD`,
297
- `ORPHANED_KEY_ABS_FLOOR`, the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS`, and the drain-handshake
298
- bounds (`DRAIN_ACK_SILENCE_TIMEOUT_MS` and `DRAIN_ACK_ABSOLUTE_CEILING_MS`, both in
299
- `src/bun-test-runner.ts`) — are fixed module-level constants. The matching preload-side
300
- ceiling in `src/templates/coverage-preload.ts` is kept above the runner's absolute ceiling,
301
- so it remains the true outermost backstop even though it should now rarely if ever be the
302
- one that actually fires. There is currently no config option to override any of these; if
303
- the defaults produce false positives in your environment (e.g. a CI runner with very
304
- different contention characteristics than the ones this gate was tuned against), a config
305
- knob is a possible follow-up — please open an issue rather than patching the constants
306
- locally. Separately, the dry-run child process's own kill timeout is automatically extended
307
- by the drain ceiling on top of `bun.timeout`, so the drain handshake itself never gets cut
308
- short by that watchdog. That watchdog covers the child's whole lifetime rather than being
309
- phase-specific, though, so as a side effect a dry run whose tests themselves hang (rather
310
- than the drain handshake) is also only detected after `bun.timeout` plus the ceiling — a
311
- one-time cost on the single dry-run child, not the per-mutant hot loop. Mutant runs are
312
- unaffected by any of this and use `bun.timeout` unchanged.
313
-
314
- This handshake only covers the `dryRun` path (where coverage collection and the
315
- completeness gate apply) — individual mutant runs are not held open the same way,
316
- since they run small, `--test-name-pattern`-filtered subsets where the same
317
- backlog-under-contention risk is negligible and the completeness gate does not
318
- apply to them.
319
-
320
- At the default (WARN) log level, dry runs also emit a few lines tracing this
321
- handshake: `Drain-request received`, `Drain handler settled via ...`,
322
- `Post-drain inspector snapshot`, and `Post-drain inspector close/collision
323
- diagnostics`, reporting the round-trip's outcome (`ack`, `silence`,
324
- `ceiling`, or `send-rejected`), the found/start/end event-count deltas
325
- observed during the wait, any found-id gaps, the WebSocket close
326
- code/reason/wasClean (plus how many ms after the last received frame the
327
- close arrived), and raw-vs-unique found-event counts. A separate DEBUG-level
328
- line notes if the inspector socket closed while the run was still thought to
329
- be in progress (including the same close code/reason/wasClean detail) — this
330
- is logged at DEBUG rather than WARN because the child closing its own socket
331
- right after receiving `'drained'` routinely wins the race against the
332
- runner's own close-expectation on a clean run, so on its own it is not
333
- evidence of anything wrong (it is folded into the completeness gate's error
334
- message as corroborating context — now including the captured close
335
- code/reason — only if that gate has already fired for another reason).
336
- Together the WARN-level lines are useful for telling apart two different
337
- failure shapes: residual loss caused by a runner-side bound being hit (a
338
- give-up outcome — `silence` or `ceiling`) versus loss happening inside Bun's
339
- own inspector agent (found-id gaps persisting even though the round-trip
340
- `ack` succeeded). One caveat: gap detection assumes Bun assigns
341
- test-discovery ids densely, which has been observed but is not a guaranteed
342
- contract — and even a dense (0-gap) id range does **not** prove
343
- losslessness: a confirmed Bun TestReporter id-collision bug (two interleaved
344
- `1..N` id sequences when `TestReporter.enable` lands mid-collection) keeps
345
- ids dense while silently merging two distinct tests under one shared id.
346
- That is exactly what the close/collision diagnostics line's
347
- raw/unique/duplicate found counts exist to catch: a **nonzero duplicate
348
- count is direct in-the-wild evidence of that id-collision bug**, and the
349
- close code/reason/wasClean fields confirm or rule out a separate confirmed
350
- Bun bug where `idleTimeout: 0` websockets are force-closed on a ~252-second
351
- ping cycle (`ERR_WEBSOCKET_TIMEOUT`) — an abnormal close landing right on
352
- that cadence points at the ping-cycle bug, while a clean close rules it out.
353
- Finally, a WARN-level `Inspector request unanswered after ...` line fires if
354
- an inspector protocol request (e.g. `TestReporter.enable`) goes unanswered
355
- for more than 2 seconds while other frames are still arriving on the same
356
- connection — a protocol-level stall signature distinct from the
357
- total-silence give-up above.
358
-
359
- ### Coverage-bleed warning (dry run only)
360
-
361
- - **`mutant coverage was recorded between tests, after '<testName>' completed`**
362
- — during the dry run's coverage collection, mutant coverage was recorded in the
363
- gap between one test's `afterEach` and the next test's `beforeEach`, i.e. while
364
- no test was active. The most likely cause is a fire-and-forget promise chain
365
- (or other async work) started by `<testName>` that kept running past that
366
- test's own completion; the warning names the coverage attribution for the
367
- listed mutant IDs as possibly wrong as a result.
368
-
369
- This is diagnostic only — it never changes a dry-run or mutant-run result, and
370
- the runner's normal "static wins" coverage attribution is unaffected. A known
371
- **benign** trigger this warning does not try to filter out: a same-file
372
- describe-level `beforeAll` (or other fixture setup) legitimately running in
373
- that same gap looks identical from this vantage point. If the named test has
374
- no fire-and-forget async work of its own, check for a `beforeAll`/fixture in
375
- the same file before assuming a real leak.
376
-
377
- The real fix, when it is a genuine leak, is in the test itself — `await` the
378
- fire-and-forget work (or otherwise ensure it settles) before the test ends,
379
- rather than in this runner. Warnings are capped at 25 individually, with a
380
- final `...and N more coverage-bleed warning(s) suppressed` line for the rest.
381
-
382
- ## Known Limitations
383
-
384
- - **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.
385
-
386
- - **Inspector-stream drain handshake covers `dryRun` only** — the hold-open-until-drained
387
- handshake described under "Dry-run completeness gate" above only runs for the dry run
388
- (where a `SyncServer` and coverage collection are set up). Individual mutant runs are not
389
- held open the same way: they run small, filtered test subsets where the backlog-under-CPU-
390
- contention risk that motivated the handshake is negligible, and the completeness gate does
391
- not apply to mutant runs in the first place.
392
-
393
- **Upgrade note: duplicate-name test suffixes**
394
-
395
- The runner reconciles how it assigns the `' [N]'` disambiguating suffix to
396
- duplicate-named tests (e.g. two `it('same name')` calls in one `describe`, or
397
- `it.each` on older Bun versions) so that the test registry and mutant coverage
398
- always agree on the same suffix for the same physical test, regardless of Bun's
399
- per-run `--seed` execution-order shuffle. If your suite has duplicate test titles,
400
- upgrading across this change can change which test a given `' [N]'` suffix refers
401
- to, which invalidates
402
- Stryker's incremental-cache correlation for mutants covered by those specific tests.
403
- This is fail-safe, not silently wrong: affected mutants simply re-run once on your
404
- next incremental `stryker mutate` and the cache self-heals from there — no action
405
- needed on your part.
406
-
407
- **Eager-import and `mock.module()` compatibility**
408
-
409
- 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.
410
-
411
- Because of this, any `mock.module()` call that runs after a module has already been imported has no effect on the already-resolved module binding. In practice, this means that if a test file calls `mock.module('./some-source-file')` at the top level (or inside a `beforeAll`), and that file is among the mutated modules, the test will see the real module rather than the mock.
412
-
413
- Suggested workarounds: use dependency injection so the real module reference is replaceable at test time; wrap the mocked surface in a test-local helper that the test can control without replacing the module; or use `mock.fn()` on method instances rather than replacing the entire module with `mock.module()`.
414
-
415
- This limitation applies only to mutated source files — the ones listed under `mutate:` in your Stryker config. Pre-import `mock.module()` of non-mutated modules (for example `node:fs`, third-party libraries, or utility files outside the mutation scope) is unaffected.
416
-
417
- ## Concurrent Tests
418
-
419
- This plugin automatically patches `describe.concurrent()`, `test.concurrent()`, and `it.concurrent()` to run sequentially during mutation testing. Your tests will work without modification.
420
-
421
- **Why?** Coverage tracking requires knowing which test exercised which code. With concurrent execution, the `beforeEach` hook assigns test IDs in the order tests *start*, but coverage is recorded in the order tests *complete*. These orders differ with concurrency, causing coverage to be attributed to the wrong tests.
422
-
423
- **What this means:**
424
- - ✅ Your `.concurrent()` tests work automatically with Stryker
425
- - ✅ Normal test runs (without Stryker) still use concurrent execution
426
- - ⏱️ Mutation testing runs are slower due to sequential execution
285
+ ### bun.bunArgs
286
+
287
+ The runner owns parts of the `bun test` command line (one test at a time, the per-mutant test
288
+ name pattern, the config file, the inspector, bail and the file list). So:
289
+
290
+ - **Rejected at startup with an error** (rather than silently producing wrong scores):
291
+ `--concurrent`, `--max-concurrency`, `--parallel` and `--test-worker` (break per-test coverage);
292
+ `--shard` and `--changed` (run only part of the suite); `-t`/`--test-name-pattern` (the runner
293
+ builds its own per mutant); `-u`/`--update-snapshots` (snapshot tests could never fail);
294
+ `--pass-with-no-tests` (a selection that matched nothing would be scored Survived); `--watch`
295
+ (never exits); `--coverage`, `--coverage-reporter` and `--coverage-dir` (turn Bun's own coverage
296
+ back on); `--cwd` (moves bun out of the [sandbox](#terms)); `--inspect`, `--inspect-wait` and
297
+ `--inspect-brk` (collide with the runner's inspector); `--retry` and `--rerun-each` (re-run tests,
298
+ which only costs time and repeats test names, so the killing test cannot be identified).
299
+ - **Removed**: [bail](#terms) flags (`--bail`, `--bail=<N>`, `--bail <N>`). Mutant runs bail on the
300
+ first failing test unless you set Stryker's `disableBail`; the dry run never bails.
301
+ - **Dry run only**: `--randomize` and `--seed` (`--seed=<N>` or `--seed <N>`). Mutant runs drop
302
+ them, so a result never depends on a random order.
303
+ - **Used as your bunfig**: `--config=<path>`, `--config <path>` or `-c <path>` is taken out of the
304
+ command line and names the bunfig the runner reads instead of `bunfig.toml` (see
305
+ [Your bunfig.toml](#your-bunfigtoml)). The path is resolved against the project directory (in
306
+ Stryker's sandbox, so check that `ignorePatterns` does not leave the file out), and the file must
307
+ exist. A `--config` or `-c` with no path is rejected.
308
+ - **Fine**: anything else, for example `--only` (only `.only` tests then count as the suite, and
309
+ the dry run fails if none is marked), `--isolate`, `--dots` or a `--reporter`.
310
+
311
+ ### Choosing the test files
312
+
313
+ The runner passes `bun test` an explicit list of test files, from the first of these that is set:
314
+
315
+ 1. **Stryker's `testFiles` option**. Mutant runs stay within that selection too. If
316
+ `bun.testFiles` is also set and differs, the runner warns and uses Stryker's.
317
+ 2. **`bun.testFiles`.** Entries are exact paths, relative to the project directory: a file, or a
318
+ directory to run every test file below it. A bare name fragment is not a filter. Avoid absolute
319
+ paths: under Stryker they point at your original files rather than the sandbox copy, so the
320
+ mutants are never seen (the runner warns about this).
321
+ 3. **Auto-discovery**, following `bun test`'s own rules: files named `*.test.*`, `*_test.*`,
322
+ `*.spec.*` or `*_spec.*` with a JavaScript or TypeScript extension, skipping `node_modules` and
323
+ dot-directories, starting at `[test].root` from your bunfig when it is set.
324
+
325
+ Like `bun test`, discovery searches `dist` and `build`, so compiled copies of your tests run too;
326
+ the runner warns once when it finds any. Details, including the command-line length limit:
327
+ [Choosing the test files](docs/internals.md#choosing-the-test-files).
328
+
329
+ ### Your bunfig.toml
330
+
331
+ `bun test --config` replaces your bunfig rather than adding to it, so the runner hands bun a
332
+ sanitized copy of yours. Everything outside `[test]` is kept. In `[test]`, `preload`, `root`,
333
+ `pathIgnorePatterns`, `timeout`, `smol`, `randomize` and `seed` are kept; `coverage` and
334
+ `onlyFailures` are forced off; `retry` and `rerunEach` are dropped with a warning; anything else is
335
+ dropped. Mutant runs never randomize the test order. Your `[test].preload` files run before the
336
+ runner's own [preload](#terms). Details:
337
+ [the sanitized config](docs/internals.md#your-bunfigtoml-the-sanitized-config).
338
+
339
+ ## How it works
340
+
341
+ 1. **Startup.** Each Stryker worker checks Bun's version, validates `bun.bunArgs`, writes its
342
+ coverage preload and sanitized bunfig to a private temporary directory, and finds the test files.
343
+ 2. **Dry run.** One `bun test` run of the whole suite, one test at a time (`--max-concurrency=1`,
344
+ with `test.concurrent` tests run in turn too), so every mutant reached can be credited to the
345
+ test that reached it. The runner follows each test through Bun's inspector while the preload
346
+ records which mutants each test reached, and how often. Bun's summary, the inspector's events and
347
+ the coverage records must agree exactly, or the dry run fails
348
+ ([the completeness gate](docs/internals.md#the-completeness-gate)).
349
+ 3. **Mutant runs.** A fresh `bun test` process per mutant, with the mutant switched on. It runs only
350
+ the covering tests (`--test-name-pattern`), only in their files, cheapest file first, and bails at
351
+ the first failure unless `disableBail` is set. The hit limit stops infinite loops early.
352
+
353
+ More: [Mutant runs](docs/internals.md#mutant-runs), [the dry run in detail](docs/internals.md#the-dry-run-in-detail).
354
+
355
+ ### How results are scored
356
+
357
+ - **Killed** when a test fails, or when a test file fails to load because of the mutant (bun reports
358
+ a failure count but no failing test).
359
+ - **Survived** when every selected test passes.
360
+ - **Timeout** when the hit limit is exceeded, the time limit is reached, or `bun.maxChildRss` is
361
+ exceeded.
362
+ - **Error** when the run proves nothing either way: the process crashed with no failing test that
363
+ matches a known test, could not be started, exited with an error but no failing test and no failure
364
+ count, or a full-suite fallback ran out of the time Stryker sized for the covering tests.
365
+
366
+ The full table and the reasoning: [How results are scored](docs/internals.md#how-results-are-scored).
367
+
368
+ ### Timeouts
369
+
370
+ Stryker sizes a timeout for every mutant run from the dry-run time of the tests it will run, plus
371
+ `timeoutMS`. The runner kills the `bun test` process a little before that, at Stryker's timeout
372
+ minus the larger of 750 ms and 5% (never more than a quarter of the timeout), and reports the
373
+ Timeout itself; if Stryker's own timer fired first, it would restart the whole worker. `bun.timeout`
374
+ only bounds the dry run. To give mutant runs more time, raise Stryker's `timeoutMS` or
375
+ `timeoutFactor`. Details: [Timeouts](docs/internals.md#timeouts).
376
+
377
+ ## Speeding up runs
378
+
379
+ **What to try first, in order:** keep incremental mode on for local runs; right-size `concurrency`;
380
+ if you use the TypeScript checker, wrap your config in `withTestFilesExcludedFromTypeCheck`; then
381
+ `ignoreStatic`, if you accept what it skips; then TypeScript 7's native checker, if type checking is
382
+ still the slow part.
383
+
384
+ - **Incremental mode.** With Stryker's `incremental: true`, a run reuses the previous results
385
+ (`reports/stryker-incremental.json` by default) and only re-tests mutants whose code or covering
386
+ tests changed. The runner keeps test ids stable across runs, so results stay reusable. Run with
387
+ `--force` only when the cached results look wrong.
388
+ - **`concurrency`.** Stryker runs this many workers, each with one `bun test` process at a time; with
389
+ a checker, Stryker splits it between checker and test-runner processes. More is faster until CPU or
390
+ memory runs out: peak memory is roughly `concurrency` × the memory one run of your suite needs. On a
391
+ memory-constrained machine, lower it first, then consider `bun.smol` and `bun.maxChildRss`
392
+ ([memory](docs/internals.md#memory)).
393
+ - **Bail** is on by default: mutant runs stop at the first failing test. Stryker's
394
+ `disableBail: true` runs every covering test instead, so killedBy lists every test that kills the
395
+ mutant, at a cost in time.
396
+
397
+ ### `ignoreStatic`: faster, but skips module-level code
398
+
399
+ Each [static mutant](#terms) runs your whole suite in a fresh process, so a project with many
400
+ module-level constants or much top-level setup can spend a large part of its time on them.
401
+ Stryker's `ignoreStatic: true` skips them. They are then never tested and not counted in your score,
402
+ so a bug a mutant there would have revealed goes unnoticed. Leave it off if module-level behaviour
403
+ matters to you; turn it on if run time matters more.
427
404
 
428
- ## License
405
+ ```javascript
406
+ export default {
407
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
408
+ testRunner: 'bun',
409
+ ignoreStatic: true,
410
+ };
411
+ ```
412
+
413
+ ### Keep tests out of the TypeScript checker
414
+
415
+ `@stryker-mutator/typescript-checker` type-checks every mutant against the program of its
416
+ `tsconfigFile` (default `tsconfig.json`) and re-checks every file that imports the mutated one. If
417
+ that tsconfig includes your tests, a mutant in a widely imported module re-checks much of your test
418
+ suite too. `withTestFilesExcludedFromTypeCheck`, used in the
419
+ [example above](#optional-skip-mutants-that-do-not-compile), points the checker at the code under
420
+ test only.
421
+
422
+ Each time Stryker loads the config, the helper reads your tsconfig with your project's TypeScript
423
+ (honouring `extends`, `files`, `include` and `exclude`) and writes `tsconfig.stryker-checker.json`
424
+ next to it. That file extends yours and lists everything your tsconfig covers except:
425
+
426
+ - test files, found the way this runner finds them (Bun's naming rules under `[test].root`, plus
427
+ `bun.testFiles` and Stryker's `testFiles`);
428
+ - your bunfig's `[test].preload` scripts;
429
+ - files only those import, such as test helpers, unless a `mutate` pattern covers them or they shape
430
+ the types of other files (a global script with no imports or exports, or a module with a
431
+ `declare global` or `declare module "x"` augmentation).
432
+
433
+ Anything the remaining code imports still comes in through the import, so the program compiles as
434
+ before. As a safety net, the helper type-checks the new program once and compares its errors in
435
+ non-test files with the original's; if leaving the tests out adds an error (a global declared only
436
+ through a test's `/// <reference types>`, say), it warns with the first few and falls back. The
437
+ returned config has `tsconfigFile` pointing at the new file and, if you set `ignorePatterns`, a
438
+ negation for it appended so Stryker copies it into the sandbox. Add `*.stryker-checker.json` to your
439
+ `.gitignore`.
440
+
441
+ It logs one line per call: an info naming the file and how many files it excluded and kept, or a
442
+ warning with the reason it fell back. It falls back, returning your config unchanged, when
443
+ TypeScript cannot be loaded from the project, the tsconfig is missing, has errors or uses project
444
+ references, includes no test files or would be left with none, leaving the tests out adds errors, or
445
+ the file cannot be written or was not generated by the helper. With no `'typescript'` in `checkers`
446
+ it does nothing (logged at info), so list the checker in the config you wrap.
447
+
448
+ The tradeoff: a mutant that only breaks types your tests use, and that no test then fails at run
449
+ time, survives instead of counting as a CompileError.
450
+
451
+ ### TypeScript 7's native checker (experimental)
452
+
453
+ `@stryker-mutator/typescript-checker` 10 can type-check mutants with TypeScript 7's native compiler
454
+ instead of its default mode, which uses your `typescript` package (TypeScript 6 or earlier). The
455
+ native compiler is much faster. Upstream marks this mode experimental: it uses TypeScript 7's
456
+ unstable API, does not support project references, and checks mutants one at a time.
457
+
458
+ **Is it worth it?** Try it when type checking is the slow part of your run (compare a run's time
459
+ with and without `checkers`) and your tsconfig has no project references. Otherwise stay with the
460
+ default mode.
461
+
462
+ To opt in, install TypeScript 7 under the name the checker loads it by, next to your existing
463
+ `typescript` 6 or earlier, and set the option:
464
+
465
+ ```bash
466
+ bun add -D --exact @typescript/native@npm:typescript@7.0.2
467
+ ```
468
+
469
+ ```javascript
470
+ // @ts-check
471
+ import { withTestFilesExcludedFromTypeCheck } from '@hughescr/stryker-bun-runner';
429
472
 
430
- Apache-2.0
473
+ export default await withTestFilesExcludedFromTypeCheck({
474
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
475
+ testRunner: 'bun',
476
+ checkers: ['typescript'],
477
+ typescriptChecker: { experimentalNativePreview: true },
478
+ });
479
+ ```
480
+
481
+ - The checker imports `@typescript/native/unstable/sync`. Its error message suggests a `typescript7`
482
+ alias, but it never looks for one, so use the `@typescript/native` name above.
483
+ - Pin TypeScript 7.0.2 exactly. TypeScript 7.1 renames the `unstable/sync` entry point to `sync`,
484
+ which checker 10.0.0 cannot load.
485
+ - Keep `typescript` 6 or earlier: Stryker and the checker still need it, and so does
486
+ `withTestFilesExcludedFromTypeCheck`. The alias installs a second `tsc` that takes over
487
+ `node_modules/.bin/tsc`, so call TypeScript 6 by its path (`node node_modules/typescript/bin/tsc`)
488
+ where that matters.
489
+
490
+ #### Do you need the checker patch?
491
+
492
+ Only if your tsconfig turns on `noUnusedLocals` or `noUnusedParameters`, or sets
493
+ `allowUnreachableCode: false`. The checker's default mode switches those checks off for mutants,
494
+ since a mutant that leaves a variable unused is not broken. Checker 10.0.0's native mode fails to,
495
+ whenever `tsconfigFile` is a relative path (the default, and what
496
+ `withTestFilesExcludedFromTypeCheck` sets). **Symptom:** the native checker reports more
497
+ CompileErrors than the default mode, with reasons such as
498
+ `error TS6133: 'message' is declared but its value is never read`, and those mutants are never
499
+ tested.
500
+
501
+ The fix is a one-line patch. With Bun:
502
+
503
+ 1. Pin the checker, since the patch is for that exact version:
504
+ `bun add -D --exact @stryker-mutator/typescript-checker@10.0.0`.
505
+ 2. Save this as `patches/@stryker-mutator%2Ftypescript-checker@10.0.0.patch` (the `%2F` is part of
506
+ the file name):
507
+
508
+ ```diff
509
+ diff --git a/dist/src/ts-native/native-typescript-compiler.js b/dist/src/ts-native/native-typescript-compiler.js
510
+ --- a/dist/src/ts-native/native-typescript-compiler.js
511
+ +++ b/dist/src/ts-native/native-typescript-compiler.js
512
+ @@ -43,7 +43,7 @@ export class NativeTypescriptCompiler {
513
+ this.log.debug('Started the native TypeScript compiler on project "%s"', this.tsconfigFile);
514
+ return this.checkSnapshot();
515
+ }
516
+ - async #adjustTSConfigFile(fileName = this.options.tsconfigFile) {
517
+ + async #adjustTSConfigFile(fileName = this.tsconfigFile) {
518
+ const parsedConfig = ts.parseConfigFileTextToJson(toPosixFileName(fileName), await fs.promises.readFile(fileName, 'utf-8'));
519
+ if (parsedConfig.error) {
520
+ return; // let the ts compiler deal with this error
521
+ ```
522
+
523
+ 3. Add it to `package.json` and run `bun install`:
524
+
525
+ ```json
526
+ "patchedDependencies": {
527
+ "@stryker-mutator/typescript-checker@10.0.0": "patches/@stryker-mutator%2Ftypescript-checker@10.0.0.patch"
528
+ }
529
+ ```
530
+
531
+ `patchedDependencies` is a Bun feature. With npm, make the same one-line change in
532
+ `node_modules/@stryker-mutator/typescript-checker/dist/src/ts-native/native-typescript-compiler.js`
533
+ and record it with [patch-package](https://github.com/ds300/patch-package)
534
+ (`npx patch-package @stryker-mutator/typescript-checker`, plus a `"postinstall": "patch-package"`
535
+ script).
536
+
537
+ ## Troubleshooting
538
+
539
+ Run Stryker with `logLevel: 'debug'` (or `--logLevel debug`) for the full detail behind any of
540
+ these. A warning that repeats for many mutants is logged in full once per worker, then at debug,
541
+ with a summary at the end: `<kind>: <N> mutants affected (first: <ids>); see debug log for details`.
542
+ Every log message: [Log output](docs/internals.md#log-output).
543
+
544
+ ### The run stops before the dry run
545
+
546
+ | Message | Cause | Fix |
547
+ |---|---|---|
548
+ | `TypeError: ts.parseConfigFileTextToJson is not a function` (from Stryker) | TypeScript 7 is installed as `typescript`. | `bun remove typescript && bun add -D typescript@^6` (see [Install](#1-install)). |
549
+ | `Cannot find TestRunner plugin "bun"` (from Stryker) | The plugin was not loaded. | Add `appendPlugins: ['@hughescr/stryker-bun-runner']`. |
550
+ | `Config option "bun" must NOT have additional properties` (from Stryker) | A misspelt or unknown option under `bun`. Stryker does not say which. | Compare each key under `bun` with the [options table](#configuration). |
551
+ | `stryker-bun-runner: could not run "<bunPath>" (<reason>). Install bun >= 1.4.0 or set bun.bunPath in your Stryker config.` | Bun is not installed, not on `PATH`, or `bun.bunPath` is wrong. | Install Bun or set `bun.bunPath`. `bun.env` can set `PATH`. |
552
+ | `stryker-bun-runner: bun <version> at "<bunPath>" is too old; version 1.4.0 or newer is required.` | Bun before 1.4.0, which the runner does not support. | `bun upgrade`. |
553
+ | `stryker-bun-runner: bun.bunArgs contains "<flag>", which <reason>. Remove it.` (or `contains unsupported flags`) | A flag that would corrupt the scores. | Remove it; see [bun.bunArgs](#bunbunargs). |
554
+ | `has no usable path: write --config=<path>, --config <path> or -c <path>` | A `--config`/`-c` with no file name. | Give the path. |
555
+ | `Failed to read bunfig.toml at <path>` or `Failed to read bunfig (named by --config in bun.bunArgs) at <path>` | The bunfig does not parse, or the file named by `--config` is not in the sandbox. | Fix the file, or the path and `ignorePatterns`. |
556
+ | `stryker-bun-runner: refusing to use temporary directory <dir>: <problem>.` | The run's temporary directory, or a directory above it, could be changed by another user. | Delete the directory if it is a stale run directory you trust, or set `TMPDIR` to a directory only you and root control. See [Temporary files](docs/internals.md#temporary-files). |
557
+ | `[Stryker] withTestFilesExcludedFromTypeCheck: not applied: <reason>` (warning) | The helper fell back to your own tsconfig. | Act on the reason; the run continues with the full type check. |
558
+
559
+ ### The dry run fails
560
+
561
+ | Message | Cause | Fix |
562
+ |---|---|---|
563
+ | Stryker lists failing tests | Your suite fails under Stryker, which runs one test at a time. A test that exceeds Bun's `[test].timeout` counts as failed. Each failure message includes the stack from Bun's inspector when Bun reports one. | Run `bun test --max-concurrency=1`. If it fails there too, you have an order-dependent or concurrency-dependent test; fix it. |
564
+ | `Timeout waiting for inspector URL after <N>ms (raise bun.inspectorTimeout if bun is slow to start)` | Bun did not start in time, or exited first; the message ends with bun's last stderr. | Read that stderr (a preload that fails to resolve, say); raise `bun.inspectorTimeout` on a slow machine. |
565
+ | `Failed to connect to Bun inspector: <error>` | Connecting to the inspector did not succeed within `bun.inspectorTimeout`, or bun exited while the runner was connecting; the message ends with bun's last stderr. | If that stderr says why bun exited, fix that; otherwise raise `bun.inspectorTimeout` on a slow or loaded machine, and re-run. |
566
+ | `Failed to start sync server: <error>` | The runner could not open its local socket on `127.0.0.1`. | Re-run; check that loopback networking is available. |
567
+ | `the dry run's sync connection to the runner` ... `before the runner signalled that it is ready to observe the tests` | The test process lost its connection to the runner before the tests started. | Usually follows another error above it; fix that one. |
568
+ | `Dry run timed out: bun.timeout is <N>ms` (and Stryker reports a timeout) | The dry run outgrew `bun.timeout` plus the 30 s drain handshake allowance. | Raise `bun.timeout` above your full suite's run time. |
569
+ | `Bun test process failed with exit code <N>` or `Bun test process terminated by signal <SIGNAL>` | Bun exited abnormally with no failing test (a missing module, a crash). The message includes stderr. | Fix what the stderr shows. |
570
+ | `stryker-bun-runner: dry run data-completeness check failed — <problems>` | Usually something in your suite: a test or hook that calls `process.exit`, or a test file that fails to load (an unresolvable import, say); the problems listed name it. Otherwise test events were lost on a heavily loaded machine. | Fix the cause in your suite; otherwise re-run, and report it if it recurs. See [the completeness gate](docs/internals.md#the-completeness-gate). |
571
+ | `stryker-bun-runner: the dry run produced no mutant coverage data` | The coverage preload never ran, could not write, or the process exited before its final `afterAll` (a test calls `process.exit`). An error with `coverageAnalysis: 'perTest'`, a warning with `'all'`. | Fix the cause the message names, or set `coverageAnalysis` to `'all'` or `'off'` to run without per-test coverage. |
572
+ | `refusing to spawn` ... `at nesting depth` | Your tests themselves run this runner (they run `stryker run` on a fixture, or create a `BunTestRunner`), so `bun test` processes nest. | Give the inner runner `maxSpawnDepth: 2`: in the Stryker config your test runs (`bun: { maxSpawnDepth: 2 }`), or in the options your test passes. Setting it in your own `stryker.conf.mjs` has no effect. |
573
+
574
+ ### Warnings during the dry run
575
+
576
+ | Message | Cause | Fix |
577
+ |---|---|---|
578
+ | `The dry run took <N>ms, more than 80% of bun.timeout` | The next, slightly slower dry run may be killed. | Raise `bun.timeout`. |
579
+ | `Test discovery found <N> test file(s) under a "dist" or "build" directory` | Compiled copies of your tests run too. | Set `[test].root` or `[test].pathIgnorePatterns`, or use `bun.testFiles`. |
580
+ | `discoverTestFiles: no test files found in <dir>; falling back to Bun discovery` | Auto-discovery found nothing under the project (or `[test].root`). | Check `[test].root` and your test file names, or set `bun.testFiles`. |
581
+ | `bun.testFiles contains absolute path(s) and the current working directory appears to be a Stryker sandbox` | Absolute paths point at your original, unmutated files. | Use paths relative to the project. |
582
+ | `Both Stryker's testFiles option and bun.testFiles are set and select different test files` | Two selections disagree; Stryker's wins. | Remove one, or make them agree. |
583
+ | `These bunfig settings were ignored for mutation runs` | `[test].retry` or `[test].rerunEach` in your bunfig. | Remove them to silence the warning. |
584
+ | `The coverage preload reported problems on the dry-run child's stderr` | The preload could not write coverage, for example. | Read the `[Stryker Coverage]` lines it quotes. |
585
+ | `The dry run's coverage data shows no mutant covered by any test` | Every mutant would be NoCoverage. | Check that `mutate` matches the files your tests import, and that tests import sources, not a built copy in `dist/`. |
586
+ | `Bun exited with code <N> and its console output reported <N> failed test(s), but no failing test could be identified` | Usually an unhandled error between tests (a rejected promise nobody awaited). | Look for unawaited async work, especially in the file that ran last. |
587
+ | `mutant coverage was recorded between tests, after '<test>' completed` | Async work from that test kept running after it ended, or a `beforeAll` ran between tests. | `await` the work in the test. Harmless if it is a `beforeAll`. |
588
+ | `Failed to write dryRun registry file` | Other workers cannot read the dry run's test names. | Check the temporary directory; mutants still run, with less precise test selection. |
589
+
590
+ Inspector diagnostics such as `Inspector data looks abnormal` need no action unless the dry run
591
+ also fails; see [Inspector diagnostics](docs/internals.md#inspector-diagnostics).
592
+
593
+ ### Warnings and results during mutant runs
594
+
595
+ | Message or symptom | Cause | Fix |
596
+ |---|---|---|
597
+ | `Mutant <id>: bun test terminated by <SIGNAL>` ... `scoring as Error rather than Killed` | The process crashed (SIGSEGV, an out-of-memory kill) without a failing test. | A few can be a real crash in your suite; many mean memory pressure: lower `concurrency`, set `bun.maxChildRss`. |
598
+ | `Mutant <id>: could not start bun test: <error>` | Bun could not be started. | Check `bun.bunPath`, `PATH` and system limits. |
599
+ | `Mutant <id>: bun test exited with code <N> but reported no failing test and no fail/error count` | Bun failed before running tests (a missing preload, an unreadable bunfig). | Read the output in the warning. |
600
+ | `Mutant <id>: inconclusive timeout, scoring as Error rather than Timeout` | A full-suite fallback did not finish within the time Stryker sized for the covering tests. | Raise Stryker's `timeoutMS` or `timeoutFactor`. |
601
+ | `Mutant <id>: --test-name-pattern matched 0 tests` | The mutant changed a test's name (often an interpolated `it.each` title); the runner retries with the full suite. | Usually nothing; spot-check that the mutant changes a title. |
602
+ | `no exact-name registry available` or `missing from exact-name registry` | A worker could not match test ids to bun's exact names; tests whose titles contain ` > ` may have been skipped in that run. | Check for an earlier registry warning; re-run. |
603
+ | `could not be resolved to dry-run test ids` or `no killing test identifiable — emitting empty killedBy` | A killed mutant whose killing test is unknown; it re-runs on every incremental run. | Usually a test whose output imitates bun's; harmless otherwise. |
604
+ | `bun test child exceeded maxChildRss` | A run went over `bun.maxChildRss`; scored Timeout. | Expected for runaway mutants; raise the limit if many hit it. |
605
+ | Many mutants Timeout | Stryker's timeout is tight for your suite, or many mutants loop forever. Infinite loops stopped by the hit limit carry the reason `Hit limit reached (count/limit)`: open the mutant in the HTML report, or read `statusReason` in Stryker's JSON report. | For the others, raise `timeoutMS` or `timeoutFactor`. |
606
+ | Every mutant runs the whole suite | No per-test coverage: `coverageAnalysis` is not `'perTest'`, or coverage was missing. | Use `'perTest'` and check the dry-run warnings. |
607
+ | The score changed after upgrading this plugin | Scoring has changed over time (for example, a crash without a matching failing test is now Error, and a test file that a mutant stops from loading is Killed). | Expected. See [Upgrading from 1.4](#upgrading-from-14), [How results are scored](#how-results-are-scored), and the [commit history](https://github.com/hughescr/stryker-bun-runner/commits/main) for what changed. |
608
+
609
+ ## Limitations
610
+
611
+ - **One test at a time.** Tests run sequentially, `test.concurrent` included, so per-test coverage
612
+ is exact. Mutation runs are slower than a parallel `bun test`.
613
+ - **`mock.module()` of a mutated file** has no effect when the module was already imported, because
614
+ the dry run imports every mutated file before the tests run. Use dependency injection or spy on
615
+ methods instead. [Details](docs/internals.md#test-names-and-coverage-attribution).
616
+ - **Cross-file order dependence.** Mutant runs order files by cost, not as in the dry run, so a
617
+ global change one test file leaves behind (an unrestored `mock.module()`) can change results.
618
+ - **No randomized order in mutant runs**, and `retry`/`rerunEach` are not supported.
619
+ - **Static mutants** each run the whole suite in a fresh process. See
620
+ [`ignoreStatic`](#ignorestatic-faster-but-skips-module-level-code).
621
+ - **`bun.maxChildRss` is a polled, soft limit**, not a kernel-enforced one.
622
+ - **The dry run's fixed bounds** (the 30 s drain handshake ceiling, the 4 s silence limit) have no
623
+ options.
624
+
625
+ ## Advanced topics
626
+
627
+ [docs/internals.md](docs/internals.md) covers how the runner works in detail:
628
+
629
+ - [Mutant runs](docs/internals.md#mutant-runs): test selection, cheapest-first ordering, fallbacks
630
+ - [How results are scored](docs/internals.md#how-results-are-scored) and
631
+ [the hit limit](docs/internals.md#infinite-loops-the-hit-limit)
632
+ - [The dry run in detail](docs/internals.md#the-dry-run-in-detail): the start and drain handshakes,
633
+ the completeness gate, coverage checks
634
+ - [Log output](docs/internals.md#log-output): start and end summaries, repeated warnings
635
+ - [Temporary files](docs/internals.md#temporary-files): the private per-run directory
636
+ - [Child processes](docs/internals.md#child-processes): process groups, orphan prevention,
637
+ recursion containment
638
+ - [Memory](docs/internals.md#memory) and
639
+ [`maxTestRunnerReuse`](docs/internals.md#maxtestrunnerreuse-compatibility)
431
640
 
432
641
  ## Contributing
433
642
 
434
- Issues and pull requests welcome at [github.com/hughescr/stryker-bun-runner](https://github.com/hughescr/stryker-bun-runner)
643
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
644
+
645
+ ## License
646
+
647
+ Apache-2.0. See [LICENSE.md](LICENSE.md).