@hughescr/stryker-bun-runner 1.3.8 → 1.5.0

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,408 +1,646 @@
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
37
-
38
- ## 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.3.7-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.3.7 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
39
57
 
40
58
  ```bash
41
59
  bun add -D @hughescr/stryker-bun-runner @stryker-mutator/core
42
60
  ```
43
61
 
44
- ## Configuration
45
-
46
- 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:
47
83
 
48
84
  ```javascript
85
+ // @ts-check
86
+ /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */
49
87
  export default {
88
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
50
89
  testRunner: 'bun',
51
- coverageAnalysis: 'perTest',
52
- mutate: ['src/**/*.ts'],
53
- bun: {
54
- // bunPath defaults to 'bun' - only set if using a custom Bun installation
55
- inspectorTimeout: 5000, // Inspector connection timeout in ms (default: 5000)
56
- },
57
90
  };
58
91
  ```
59
92
 
60
- ## How It Works
61
-
62
- The plugin uses Bun's Inspector Protocol (WebSocket) to:
63
-
64
- 1. **Discover tests** - Connects to Bun's test process via WebSocket
65
- 2. **Track execution** - Listens for TestReporter events to correlate test runs with coverage
66
- 3. **Sequential execution** - Uses `--concurrency=1` to ensure reliable coverage correlation
67
- 4. **Build hierarchy** - Reconstructs test names from describe blocks for accurate reporting
68
- 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.
69
-
70
- Oversized covering-test patterns (over 100,000 UTF-8 bytes) fall back to running the full suite, to stay within OS argument-length limits. This approach provides reliable test-to-mutant correlation, even with multiple test files.
71
-
72
- A second full-suite fallback happens at run time: a `--test-name-pattern` that matches zero tests triggers a one-shot full-suite retry (see [Diagnostic warnings worth grepping for in CI](#diagnostic-warnings-worth-grepping-for-in-ci)).
73
-
74
- ## Options
75
-
76
- | Option | Type | Default | Description |
77
- |--------|------|---------|-------------|
78
- | `bun.bunPath` | `string` | `'bun'` | Path to the Bun executable |
79
- | `bun.timeout` | `number` | `10000` | Timeout per test in milliseconds |
80
- | `bun.inspectorTimeout` | `number` | `5000` | Timeout for Inspector WebSocket connection in milliseconds |
81
- | `bun.env` | `object` | `undefined` | Additional environment variables to pass to bun test |
82
- | `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)). |
83
- | `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. |
84
- | `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). |
85
- | `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). |
86
- | `bun.rssCheckIntervalMs` | `number` | `1000` | Poll interval in milliseconds for the `maxChildRss` check. |
87
-
88
- ### Example with all options
89
-
90
- ```javascript
91
- bun: {
92
- bunPath: '/path/to/bun', // Custom bun executable (defaults to 'bun')
93
- timeout: 30000, // 30 second test timeout
94
- inspectorTimeout: 10000, // 10 second connection timeout
95
- env: { DEBUG: 'true' }, // Extra environment variables
96
- bunArgs: ['--only'], // Extra bun test flags (bail flags here are ignored — see Options table)
97
- smol: true, // Smaller JSC heap, some speed cost — see Memory model
98
- maxChildRss: 1_500_000_000, // Kill+report-timeout a child using more than ~1.5GB RSS
99
- rssCheckIntervalMs: 1000, // How often to poll RSS when maxChildRss is set
100
- }
101
- ```
93
+ `appendPlugins` is required: Stryker only loads plugins named `@stryker-mutator/*` by itself, so
94
+ without it `testRunner: 'bun'` is never registered.
102
95
 
103
- ## Running Stryker
96
+ ### 3. Run
104
97
 
105
98
  ```bash
106
99
  bunx stryker run
107
100
  ```
108
101
 
109
- ## How the sandboxed config works
110
-
111
- 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`.
112
-
113
- ## Memory model
114
-
115
- 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.
116
-
117
- What this means for memory planning on a mutation-testing machine:
118
-
119
- - **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.
120
- - **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.
121
- - **Recommended settings for memory-constrained machines:**
122
- - Lower `concurrency` in your `stryker.conf.mjs` first — it has the largest, most direct effect on peak memory (linear multiplier).
123
- - Set `bun.smol: true` to shrink each child's JSC heap ceiling at some speed cost.
124
- - Set `bun.maxChildRss` as a backstop against a single run growing unexpectedly large (see [Memory containment](#memory-containment)).
125
- - 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.
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 BunTestRunner Bun test runner started: bun 1.4.2 at bun; 1 test file(s) from auto-discovery; sanitized bunfig /tmp/stryker-bun-runner-1000-0bfd2cdbbb207a22-0/stryker-bun-runner-bunfig-29463-1791682615998.toml; bail on
108
+ INFO DryRunExecutor Starting initial test run (bun test runner with "perTest" coverage analysis). This may take a while.
109
+ INFO BunTestRunner Bun test runner started: bun 1.4.2 at bun; 1 test file(s) from auto-discovery; sanitized bunfig /tmp/stryker-bun-runner-1000-0bfd2cdbbb207a22-0/stryker-bun-runner-bunfig-29462-1791682616021.toml; bail on
110
+ INFO DryRunExecutor Initial test run succeeded. Ran 2 tests in 0 seconds (net 1 ms, overhead 90 ms).
111
+ [Survived] EqualityOperator
112
+ src/math.ts:6:12
113
+ - return n > 0;
114
+ + return n >= 0;
115
+ Tests ran:
116
+ tests/math.test.ts > isPositive
117
+ ----------|------------------|----------|-----------|------------|----------|----------|
118
+ | % Mutation score | | | | | |
119
+ File | total | covered | # killed | # timeout | # survived | # no cov | # errors |
120
+ ----------|--------|---------|----------|-----------|------------|----------|----------|
121
+ All files | 85.71 | 85.71 | 6 | 0 | 1 | 0 | 0 |
122
+ INFO HtmlReporter Your report can be found at: file:///home/me/demo/reports/mutation/mutation.html
123
+ INFO BunTestRunner Mutant runs on this worker: 3 (killed 2, survived 1, timeout 0, error 0); full-suite fallbacks: 0
124
+ INFO BunTestRunner Mutant runs on this worker: 4 (killed 4, survived 0, timeout 0, error 0); full-suite fallbacks: 0
125
+ ```
126
126
 
127
- ## Memory containment
127
+ - Each Stryker **worker** process logs one `Bun test runner started` line, and one
128
+ `Mutant runs on this worker` line at the end, so you see as many of each as Stryker has workers.
129
+ - **`Initial test run succeeded`** means the [dry run](#terms) passed: your whole suite ran once,
130
+ unmutated, and the runner recorded which tests reach which mutants.
131
+ - **Killed** mutants made a test fail: good. A **Survived** mutant is a change to your code that no
132
+ test noticed; here, no test checks `isPositive(0)`. Add or strengthen a test to kill it.
133
+ - The **mutation score** is the share of mutants your tests detected. The HTML report, at
134
+ `reports/mutation/mutation.html`, shows every mutant in your source.
135
+ - **Full-suite fallbacks** count mutants that had covering tests but had to run the whole suite
136
+ instead (see [Terms](#terms)); a few are normal.
128
137
 
129
- 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:
138
+ If something goes wrong instead, see [Troubleshooting](#troubleshooting).
130
139
 
131
- - **`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.
132
- - **`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.
140
+ ### Optional: skip mutants that do not compile
133
141
 
134
- **Why not a hard, kernel-enforced ceiling (`ulimit -v`, cgroups)?** We looked at this and decided against it:
135
- - `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.
136
- - `RLIMIT_RSS` has been a no-op on Linux since kernel 2.4.30 — the kernel accepts the limit but never enforces it.
137
- - 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.
142
+ Stryker's TypeScript checker type-checks each mutant first and marks the ones that do not compile
143
+ as CompileError instead of running your tests on them. It needs a `tsconfig.json` and `typescript`
144
+ 6 or earlier (see the note under [Install](#1-install)):
138
145
 
139
- `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.
146
+ ```bash
147
+ bun add -D @stryker-mutator/typescript-checker
148
+ ```
140
149
 
141
- ## Orphan prevention
150
+ Then turn it on with `checkers: ['typescript']`. Stryker loads `@stryker-mutator/*` plugins by
151
+ itself, so `appendPlugins` stays as it is. To keep the checker from re-checking your tests too, wrap
152
+ the config in [`withTestFilesExcludedFromTypeCheck`](#keep-tests-out-of-the-typescript-checker):
142
153
 
143
- Each spawned `bun test` child is protected against being left running forever if something goes wrong:
154
+ ```javascript
155
+ // @ts-check
156
+ import { withTestFilesExcludedFromTypeCheck } from '@hughescr/stryker-bun-runner';
144
157
 
145
- - **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.
146
- - **`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.
147
- - **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.
158
+ export default await withTestFilesExcludedFromTypeCheck({
159
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
160
+ testRunner: 'bun',
161
+ checkers: ['typescript'],
162
+ });
163
+ ```
148
164
 
149
- ## `maxTestRunnerReuse` compatibility
165
+ ## Upgrading from 1.4
166
+
167
+ Most projects need no config change, but these differ from 1.4:
168
+
169
+ - **`bun.timeout` now bounds only the dry run** (plus the 30 s drain-handshake allowance). Mutant
170
+ runs use Stryker's per-mutant timeout: `timeoutFactor` × the dry-run time of the tests that
171
+ mutant runs (the whole suite for a static mutant) + `timeoutMS` + the dry run's overhead, less a
172
+ small margin ([Timeouts](#timeouts)). If you raised `bun.timeout` so slow mutant runs would not
173
+ time out, raise `timeoutMS` or `timeoutFactor` instead. `bun.timeout` can now be generous: the
174
+ runner warns above 80% use, and only a hung dry run takes that long to fail.
175
+ - **Mutant runs never randomize.** Covering files run cheapest first (by dry-run time), tests in
176
+ source order. The dry run still follows your bunfig `randomize` and `seed`.
177
+ - **Some verdicts change, toward correctness** ([How results are scored](#how-results-are-scored)).
178
+ A hang that a fast test catches is Killed. An infinite loop stops at Stryker's hit limit and is
179
+ Timeout, reason `Hit limit reached`. A bun crash or failed start with no failing test is Error
180
+ (left out of the score), not Killed. A mutant that stops a test file loading is Killed (1.4
181
+ usually scored it Error). Incremental mode keeps the old verdict of mutants it reuses; run once
182
+ with `--force` to re-score.
183
+ - **The dry run is stricter.** Bun's summary, the inspector's events and the coverage records must
184
+ agree exactly (1.4 tolerated small shortfalls), and missing per-test coverage with
185
+ `coverageAnalysis: 'perTest'` is an Error. See [the dry run fails](#the-dry-run-fails).
186
+ - **Configuration.** Some `bun.bunArgs` flags are now rejected, `--retry` and `--rerun-each`
187
+ among them ([bun.bunArgs](#bunbunargs)). `retry` and `rerunEach` in your bunfig are dropped with
188
+ a warning. `bun.testFiles` entries are exact paths, not substring filters, so a bare name no
189
+ longer matches copies under `dist/` ([Choosing the test files](#choosing-the-test-files)).
190
+ `--config`/`-c` in `bun.bunArgs` names the bunfig the runner reads, and everything outside
191
+ `[test]` in it is kept (1.4 kept only `[install]`): [Your bunfig.toml](#your-bunfigtoml).
192
+ - **Install.** A peer dependency on `typescript` below 7 (see the callout under
193
+ [Install](#1-install)); dependencies are no longer bundled and install normally. Startup now
194
+ requires Bun 1.3.7 or later and stops at once otherwise.
195
+ - **Test ids are unchanged**, so a 1.4 incremental report stays reusable. The one exception is a
196
+ test retried in the dry run (a per-test `{ retry }` option, or `retry` in your bunfig): it had one
197
+ id per attempt (`name [0]`, `name [1]`, ...) and now has the single id `name`.
198
+
199
+ ## Terms
200
+
201
+ - **Mutant**: one small change Stryker makes to your source, such as `>` to `>=`. Each mutant is
202
+ tested on its own and ends up **Killed** (a test failed), **Survived** (no test failed),
203
+ **Timeout**, **NoCoverage** (no test reaches it), **CompileError** (with a checker) or **Error**
204
+ (Stryker shows RuntimeError; left out of the score).
205
+ - **Dry run**: Stryker's first run of your whole suite, without mutants. It must pass. The runner
206
+ uses it to record which tests reach each mutant.
207
+ - **Covering tests**: the tests that reached a mutant in the dry run. A mutant run normally runs
208
+ only these.
209
+ - **Static mutant**: a mutant in code that runs only while a module loads (module-level constants,
210
+ top-level setup), so no single test covers it, and every test has to run for it.
211
+ - **Full-suite fallback**: a mutant that had covering tests but ran the whole suite instead, because
212
+ the list of test names was too long for the command line or matched no test.
213
+ - **killedBy**: the tests Stryker records as having killed a mutant. Incremental mode uses it to
214
+ decide what to re-run.
215
+ - **Bail**: stopping a mutant run at the first failing test, which is enough to kill the mutant.
216
+ - **Hit limit**: Stryker's cap on how many times a mutant may execute in a mutant run (100 times
217
+ its dry-run count). Exceeding it means an infinite loop, scored Timeout.
218
+ - **Sandbox**: the copy of your project Stryker makes under `.stryker-tmp/` and mutates.
219
+ - **Worker**: one of the processes Stryker runs mutants in; Stryker's `concurrency` option sets how
220
+ many.
221
+ - **bunfig**: Bun's configuration file, `bunfig.toml`.
222
+ - **Preload**: a script bun runs before your tests (`[test].preload` in the bunfig). The runner adds
223
+ its own coverage preload, which switches mutants on and records coverage.
224
+ - **Inspector**: Bun's debugging protocol. The runner uses its test events to see each test start
225
+ and finish.
226
+ - **Drain handshake**: at the end of the dry run, the test process waits until the runner confirms
227
+ it has received every test event, so none are lost on a busy machine.
228
+
229
+ ## Requirements and compatibility
230
+
231
+ | Component | Supported | Notes |
232
+ |---|---|---|
233
+ | Bun | 1.3.7 or later | Tested with 1.3.7, 1.3.14 and 1.4.2. Older versions lack the inspector test events the runner needs ([oven-sh/bun#25986](https://github.com/oven-sh/bun/pull/25986)). |
234
+ | `@stryker-mutator/core` | 9.x or 10.x | Peer dependency. Stryker's `testFiles` option needs 9.6 or later. |
235
+ | 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. |
236
+ | `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). |
237
+ | `@stryker-mutator/typescript-checker` (optional) | the same version as `@stryker-mutator/core` | |
238
+ | Operating system | Linux, macOS | |
239
+
240
+ At startup the runner runs `<bunPath> --version` and stops with a clear error if Bun cannot be run
241
+ or is older than 1.3.7. To upgrade Bun, run `bun upgrade`.
150
242
 
151
- 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)).
243
+ ## Configuration
152
244
 
153
- This plugin is designed to tolerate that recycling cleanly:
245
+ Runner options go under `bun` in your Stryker config. Stryker validates them: an unknown key under
246
+ `bun`, a wrong type, or an out-of-range value stops the run with a configuration error.
154
247
 
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. 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.
248
+ | Option | Type | Default | Description |
249
+ |---|---|---|---|
250
+ | `bun.bunPath` | `string` | `'bun'` | Bun executable to run. |
251
+ | `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`. |
252
+ | `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. |
253
+ | `bun.env` | `object` of strings | none | Extra environment variables for every `bun test` process (and for the startup `bun --version` check). |
254
+ | `bun.bunArgs` | `string[]` | none | Extra `bun test` flags. Some are rejected, removed or handled specially; see [bun.bunArgs](#bunbunargs). |
255
+ | `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). |
256
+ | `bun.smol` | `boolean` | `false` | Pass Bun's `--smol` to every process: a smaller JavaScriptCore heap at some cost to speed. |
257
+ | `bun.maxChildRss` | `number` (bytes, >= 0) | none | Soft memory ceiling per `bun test` process. One that exceeds it is killed and that run scored Timeout. |
258
+ | `bun.rssCheckIntervalMs` | `number` (ms, >= 0) | `1000` | How often to check `maxChildRss`. |
259
+ | `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). |
260
+
261
+ ### Example with every option
157
262
 
158
263
  ```javascript
159
- // stryker.conf.mjs
264
+ // @ts-check
265
+ /** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */
160
266
  export default {
267
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
161
268
  testRunner: 'bun',
162
- coverageAnalysis: 'perTest',
163
- mutate: ['src/**/*.ts'],
164
- concurrency: 8, // tune down first on memory-constrained machines
165
- maxTestRunnerReuse: 100, // recycle each Stryker worker after 100 runs
166
269
  bun: {
270
+ bunPath: 'bun', // found on PATH; or an absolute path to a specific Bun
271
+ timeout: 60_000, // the dry run's limit, not a per-test timeout
272
+ inspectorTimeout: 10_000,
273
+ env: { NODE_ENV: 'test' },
274
+ bunArgs: ['--randomize'], // the dry run randomizes; mutant runs never do
275
+ testFiles: ['tests'], // a directory: every test file below it (omit to auto-discover)
167
276
  smol: true,
168
- maxChildRss: 1_500_000_000, // ~1.5GB soft ceiling per bun test child
277
+ maxChildRss: 1_500_000_000, // about 1.5 GB per bun test process
278
+ rssCheckIntervalMs: 1000,
279
+ maxSpawnDepth: 1,
169
280
  },
170
281
  };
171
282
  ```
172
283
 
173
- ## Diagnostic warnings worth grepping for in CI
174
-
175
- The runner logs three warnings that flag when a mutant run's `--test-name-pattern`
176
- couldn't be built or applied with full fidelity. None of them indicate a wrong
177
- mutation-testing verdict by themselves, but they're worth grepping your CI logs for
178
- because they mark where the runner fell back to less-precise behavior:
179
-
180
- - **`--test-name-pattern matched 0 tests`** — the pattern for a mutant's covering
181
- tests matched nothing across the whole run (usually because a mutant changed a
182
- value interpolated into an `it.each` title). The runner retries once with the
183
- full suite rather than reporting a false kill, so the eventual verdict is still
184
- genuine — if the retry itself also matches zero tests (or the zero-match came
185
- from a user-supplied `--test-name-pattern` in `bunArgs`, which is never retried),
186
- the mutant is classified as an infrastructure `Error`, never a kill. Every
187
- occurrence is worth spot-checking that it's explained by an interpolated-title
188
- change, not a real pattern gap.
189
- - **`no exact-name registry available`** — this worker couldn't load the shared
190
- dry-run test-name registry, so every alternative in that mutant's pattern used
191
- the lossy `' > '`-collapsing reconstruction instead of Bun's exact matching
192
- names. Tests whose titles legitimately contain `" > "` may have been silently
193
- excluded from that run.
194
- - **`missing from exact-name registry`** — the registry loaded, but one or more
195
- `testFilter` ids for this mutant weren't in it (falls back to the same lossy
196
- reconstruction for just those ids, listing up to 5 of the missing ids).
197
-
198
- The last two matter because Bun only errors when a pattern matches **zero** tests
199
- across the whole run; a *partial* miss — some alternatives hit, others silently
200
- don't — exits 0 with no error text at all. These two warns are the only signal
201
- that a partial silent drop was possible for a given mutant run, so seeing either
202
- of them in a clean run's logs is worth investigating before trusting the score.
203
-
204
- ### Dry-run failure diagnostics (dry run only)
205
-
206
- - **`Bun exited with code <N> and its console output reported <N> failed test(s), but no failing test could be identified...`**
207
- — the dry run's process-level signals (a non-zero exit code, or a `>0` failed
208
- count parsed from Bun's console recap) say a test failed, but neither the
209
- inspector's per-test data nor the parsed console output identifies which one
210
- — the "empty recap" incident fingerprint: Bun prints e.g. `1 tests failed:`
211
- with no `(fail)` line naming a test. The most likely cause is an unhandled
212
- error firing *between* tests (e.g. a rejected fire-and-forget promise) rather
213
- than inside any single test body, so nothing in bun's own per-test
214
- bookkeeping ever marked a test as failed. What to do: check the trailing
215
- stderr included in the warning for a stack, and look for fire-and-forget
216
- async work (unawaited promises, orphaned timers) anywhere in the suite —
217
- especially in the file that was running when the process exited. This
218
- warning is purely diagnostic and never alters the returned `DryRunResult`
219
- by itself; it's a separate, related change that failed tests' `failureMessage`
220
- in a *Complete* result now has the inspector's `error.stack` appended (when
221
- available) — Stryker core only prints name+failureMessage for initial-run
222
- failures, so that's the only channel this stack reaches the CI log through.
223
-
224
- ### Dry-run completeness gate (dry run only)
225
-
226
- - **`stryker-bun-runner: dry run data-completeness check failed — ...`** — the dry
227
- run otherwise looked healthy (no failed tests) but the runner detected that Bun's
228
- inspector event stream may have been silently truncated mid-run: either the
229
- inspector's execution order fell materially short of what Bun's own console
230
- summary reported (`console reported <N> test(s) ... but the inspector's execution
231
- order contains only <M> non-skipped test(s)`), or a meaningful number of coverage
232
- keys couldn't be paired with any inspector test (`<N> of <M> coverage key(s) ...
233
- could not be paired with any inspector test (orphaned)`) — the signature of one or
234
- more whole test files being dropped from the stream, most often under CI runner
235
- resource contention. When both are present, or the socket also closed
236
- unexpectedly before the runner could finish reading it, the message names all of
237
- them. This is a genuine `DryRunStatus.Error`, not a warning: proceeding on
238
- truncated data would risk silently corrupted coverage attribution (mutants losing
239
- their true killers), so the runner reports the error and does **not** persist the
240
- test registry, rather than let other Stryker workers load a corrupted one. If you
241
- see this, it usually means the CI runner was under heavier contention than usual;
242
- retrying the run (with less concurrent load, or fewer parallel Stryker workers) is
243
- the first thing to try.
244
-
245
- Before this check runs, the bun test child process (during `dryRun` only) holds
246
- itself open past its own natural exit and waits for the runner to prove — via an
247
- inspector-protocol round-trip over the same ordered connection the test events
248
- arrive on — that it has actually received and processed everything the child
249
- sent, before letting the child close its coverage socket and exit. This closes
250
- the specific race that used to cause this gate to fire under CPU-contended CI
251
- runners: previously, nothing synchronized "the runner has drained the inspector
252
- stream" with "the child process is allowed to exit," so a consumer that couldn't
253
- keep up with the event stream under contention would lose whatever hadn't been
254
- processed by the time the child exited.
255
-
256
- The runner's side of this wait is progress-based, not a fixed timer: it keeps
257
- extending as long as the inspector connection is still receiving frames of any
258
- kind, since continued arrivals are proof a backlog is actively draining, and
259
- only gives up once a period of true silence — no frames at all — has elapsed. A
260
- separate, much larger absolute ceiling also exists, but purely as hang
261
- prevention for a connection that never goes silent (or never acks) at all; it
262
- is not the normal way this wait ends. Either way, once the runner gives up (via
263
- silence or the ceiling), it still releases the child immediately rather than
264
- leaving it to time out on its own — the child-side timeout only governs the
265
- case where the sync channel itself is dead or unresponsive. Hitting any of
266
- these bounds still reverts to the original pre-handshake behavior (including
267
- this gate) exactly as before, so the handshake can only reduce how often this
268
- gate fires, never mask a real truncation from it.
269
-
270
- The gate's thresholds — `EXECUTION_SHORTFALL_ABS_FLOOR`, `EXECUTION_SHORTFALL_RATIO_THRESHOLD`,
271
- `ORPHANED_KEY_ABS_FLOOR`, the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS`, and the drain-handshake
272
- bounds (`DRAIN_ACK_SILENCE_TIMEOUT_MS` and `DRAIN_ACK_ABSOLUTE_CEILING_MS`, both in
273
- `src/bun-test-runner.ts`) — are fixed module-level constants. The matching preload-side
274
- ceiling in `src/templates/coverage-preload.ts` is kept above the runner's absolute ceiling,
275
- so it remains the true outermost backstop even though it should now rarely if ever be the
276
- one that actually fires. There is currently no config option to override any of these; if
277
- the defaults produce false positives in your environment (e.g. a CI runner with very
278
- different contention characteristics than the ones this gate was tuned against), a config
279
- knob is a possible follow-up — please open an issue rather than patching the constants
280
- locally. Separately, the dry-run child process's own kill timeout is automatically extended
281
- by the drain ceiling on top of `bun.timeout`, so the drain handshake itself never gets cut
282
- short by that watchdog. That watchdog covers the child's whole lifetime rather than being
283
- phase-specific, though, so as a side effect a dry run whose tests themselves hang (rather
284
- than the drain handshake) is also only detected after `bun.timeout` plus the ceiling — a
285
- one-time cost on the single dry-run child, not the per-mutant hot loop. Mutant runs are
286
- unaffected by any of this and use `bun.timeout` unchanged.
287
-
288
- This handshake only covers the `dryRun` path (where coverage collection and the
289
- completeness gate apply) — individual mutant runs are not held open the same way,
290
- since they run small, `--test-name-pattern`-filtered subsets where the same
291
- backlog-under-contention risk is negligible and the completeness gate does not
292
- apply to them.
293
-
294
- At the default (WARN) log level, dry runs also emit a few lines tracing this
295
- handshake: `Drain-request received`, `Drain handler settled via ...`,
296
- `Post-drain inspector snapshot`, and `Post-drain inspector close/collision
297
- diagnostics`, reporting the round-trip's outcome (`ack`, `silence`,
298
- `ceiling`, or `send-rejected`), the found/start/end event-count deltas
299
- observed during the wait, any found-id gaps, the WebSocket close
300
- code/reason/wasClean (plus how many ms after the last received frame the
301
- close arrived), and raw-vs-unique found-event counts. A separate DEBUG-level
302
- line notes if the inspector socket closed while the run was still thought to
303
- be in progress (including the same close code/reason/wasClean detail) — this
304
- is logged at DEBUG rather than WARN because the child closing its own socket
305
- right after receiving `'drained'` routinely wins the race against the
306
- runner's own close-expectation on a clean run, so on its own it is not
307
- evidence of anything wrong (it is folded into the completeness gate's error
308
- message as corroborating context — now including the captured close
309
- code/reason — only if that gate has already fired for another reason).
310
- Together the WARN-level lines are useful for telling apart two different
311
- failure shapes: residual loss caused by a runner-side bound being hit (a
312
- give-up outcome — `silence` or `ceiling`) versus loss happening inside Bun's
313
- own inspector agent (found-id gaps persisting even though the round-trip
314
- `ack` succeeded). One caveat: gap detection assumes Bun assigns
315
- test-discovery ids densely, which has been observed but is not a guaranteed
316
- contract — and even a dense (0-gap) id range does **not** prove
317
- losslessness: a confirmed Bun TestReporter id-collision bug (two interleaved
318
- `1..N` id sequences when `TestReporter.enable` lands mid-collection) keeps
319
- ids dense while silently merging two distinct tests under one shared id.
320
- That is exactly what the close/collision diagnostics line's
321
- raw/unique/duplicate found counts exist to catch: a **nonzero duplicate
322
- count is direct in-the-wild evidence of that id-collision bug**, and the
323
- close code/reason/wasClean fields confirm or rule out a separate confirmed
324
- Bun bug where `idleTimeout: 0` websockets are force-closed on a ~252-second
325
- ping cycle (`ERR_WEBSOCKET_TIMEOUT`) — an abnormal close landing right on
326
- that cadence points at the ping-cycle bug, while a clean close rules it out.
327
- Finally, a WARN-level `Inspector request unanswered after ...` line fires if
328
- an inspector protocol request (e.g. `TestReporter.enable`) goes unanswered
329
- for more than 2 seconds while other frames are still arriving on the same
330
- connection — a protocol-level stall signature distinct from the
331
- total-silence give-up above.
332
-
333
- ### Coverage-bleed warning (dry run only)
334
-
335
- - **`mutant coverage was recorded between tests, after '<testName>' completed`**
336
- — during the dry run's coverage collection, mutant coverage was recorded in the
337
- gap between one test's `afterEach` and the next test's `beforeEach`, i.e. while
338
- no test was active. The most likely cause is a fire-and-forget promise chain
339
- (or other async work) started by `<testName>` that kept running past that
340
- test's own completion; the warning names the coverage attribution for the
341
- listed mutant IDs as possibly wrong as a result.
342
-
343
- This is diagnostic only — it never changes a dry-run or mutant-run result, and
344
- the runner's normal "static wins" coverage attribution is unaffected. A known
345
- **benign** trigger this warning does not try to filter out: a same-file
346
- describe-level `beforeAll` (or other fixture setup) legitimately running in
347
- that same gap looks identical from this vantage point. If the named test has
348
- no fire-and-forget async work of its own, check for a `beforeAll`/fixture in
349
- the same file before assuming a real leak.
350
-
351
- The real fix, when it is a genuine leak, is in the test itself — `await` the
352
- fire-and-forget work (or otherwise ensure it settles) before the test ends,
353
- rather than in this runner. Warnings are capped at 25 individually, with a
354
- final `...and N more coverage-bleed warning(s) suppressed` line for the rest.
355
-
356
- ## Known Limitations
357
-
358
- - **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.
359
-
360
- - **Inspector-stream drain handshake covers `dryRun` only** — the hold-open-until-drained
361
- handshake described under "Dry-run completeness gate" above only runs for the dry run
362
- (where a `SyncServer` and coverage collection are set up). Individual mutant runs are not
363
- held open the same way: they run small, filtered test subsets where the backlog-under-CPU-
364
- contention risk that motivated the handshake is negligible, and the completeness gate does
365
- not apply to mutant runs in the first place.
366
-
367
- **Upgrade note: duplicate-name test suffixes**
368
-
369
- The runner reconciles how it assigns the `' [N]'` disambiguating suffix to
370
- duplicate-named tests (e.g. two `it('same name')` calls in one `describe`, or
371
- `it.each` on older Bun versions) so that the test registry and mutant coverage
372
- always agree on the same suffix for the same physical test, regardless of Bun's
373
- per-run `--seed` execution-order shuffle. If your suite has duplicate test titles,
374
- upgrading across this change can change which test a given `' [N]'` suffix refers
375
- to, which invalidates
376
- Stryker's incremental-cache correlation for mutants covered by those specific tests.
377
- This is fail-safe, not silently wrong: affected mutants simply re-run once on your
378
- next incremental `stryker mutate` and the cache self-heals from there — no action
379
- needed on your part.
380
-
381
- **Eager-import and `mock.module()` compatibility**
382
-
383
- 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.
384
-
385
- 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.
386
-
387
- 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()`.
388
-
389
- 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.
390
-
391
- ## Concurrent Tests
392
-
393
- This plugin automatically patches `describe.concurrent()`, `test.concurrent()`, and `it.concurrent()` to run sequentially during mutation testing. Your tests will work without modification.
394
-
395
- **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.
396
-
397
- **What this means:**
398
- - ✅ Your `.concurrent()` tests work automatically with Stryker
399
- - ✅ Normal test runs (without Stryker) still use concurrent execution
400
- - ⏱️ Mutation testing runs are slower due to sequential execution
284
+ ### bun.bunArgs
285
+
286
+ The runner owns parts of the `bun test` command line (one test at a time, the per-mutant test
287
+ name pattern, the config file, the inspector, bail and the file list). So:
288
+
289
+ - **Rejected at startup with an error** (rather than silently producing wrong scores):
290
+ `--concurrent`, `--max-concurrency`, `--parallel` and `--test-worker` (break per-test coverage);
291
+ `--shard` and `--changed` (run only part of the suite); `-t`/`--test-name-pattern` (the runner
292
+ builds its own per mutant); `-u`/`--update-snapshots` (snapshot tests could never fail);
293
+ `--pass-with-no-tests` (a selection that matched nothing would be scored Survived); `--watch`
294
+ (never exits); `--coverage`, `--coverage-reporter` and `--coverage-dir` (turn Bun's own coverage
295
+ back on); `--cwd` (moves bun out of the [sandbox](#terms)); `--inspect`, `--inspect-wait` and
296
+ `--inspect-brk` (collide with the runner's inspector); `--retry` and `--rerun-each` (re-run tests,
297
+ which only costs time and repeats test names, so the killing test cannot be identified).
298
+ - **Removed**: [bail](#terms) flags (`--bail`, `--bail=<N>`, `--bail <N>`). Mutant runs bail on the
299
+ first failing test unless you set Stryker's `disableBail`; the dry run never bails.
300
+ - **Dry run only**: `--randomize` and `--seed` (`--seed=<N>` or `--seed <N>`). Mutant runs drop
301
+ them, so a result never depends on a random order.
302
+ - **Used as your bunfig**: `--config=<path>`, `--config <path>` or `-c <path>` is taken out of the
303
+ command line and names the bunfig the runner reads instead of `bunfig.toml` (see
304
+ [Your bunfig.toml](#your-bunfigtoml)). The path is resolved against the project directory (in
305
+ Stryker's sandbox, so check that `ignorePatterns` does not leave the file out), and the file must
306
+ exist. A `--config` or `-c` with no path is rejected.
307
+ - **Fine**: anything else, for example `--only` (only `.only` tests then count as the suite, and
308
+ the dry run fails if none is marked), `--isolate`, `--dots` or a `--reporter`.
309
+
310
+ ### Choosing the test files
311
+
312
+ The runner passes `bun test` an explicit list of test files, from the first of these that is set:
313
+
314
+ 1. **Stryker's `testFiles` option**. Mutant runs stay within that selection too. If
315
+ `bun.testFiles` is also set and differs, the runner warns and uses Stryker's.
316
+ 2. **`bun.testFiles`.** Entries are exact paths, relative to the project directory: a file, or a
317
+ directory to run every test file below it. A bare name fragment is not a filter. Avoid absolute
318
+ paths: under Stryker they point at your original files rather than the sandbox copy, so the
319
+ mutants are never seen (the runner warns about this).
320
+ 3. **Auto-discovery**, following `bun test`'s own rules: files named `*.test.*`, `*_test.*`,
321
+ `*.spec.*` or `*_spec.*` with a JavaScript or TypeScript extension, skipping `node_modules` and
322
+ dot-directories, starting at `[test].root` from your bunfig when it is set.
323
+
324
+ Like `bun test`, discovery searches `dist` and `build`, so compiled copies of your tests run too;
325
+ the runner warns once when it finds any. Details, including the command-line length limit:
326
+ [Choosing the test files](docs/internals.md#choosing-the-test-files).
327
+
328
+ ### Your bunfig.toml
329
+
330
+ `bun test --config` replaces your bunfig rather than adding to it, so the runner hands bun a
331
+ sanitized copy of yours. Everything outside `[test]` is kept. In `[test]`, `preload`, `root`,
332
+ `pathIgnorePatterns`, `timeout`, `smol`, `randomize` and `seed` are kept; `coverage` and
333
+ `onlyFailures` are forced off; `retry` and `rerunEach` are dropped with a warning; anything else is
334
+ dropped. Mutant runs never randomize the test order. Your `[test].preload` files run before the
335
+ runner's own [preload](#terms). Details:
336
+ [the sanitized config](docs/internals.md#your-bunfigtoml-the-sanitized-config).
337
+
338
+ ## How it works
339
+
340
+ 1. **Startup.** Each Stryker worker checks Bun's version, validates `bun.bunArgs`, writes its
341
+ coverage preload and sanitized bunfig to a private temporary directory, and finds the test files.
342
+ 2. **Dry run.** One `bun test` run of the whole suite, one test at a time (`--max-concurrency=1`,
343
+ with `test.concurrent` tests run in turn too), so every mutant reached can be credited to the
344
+ test that reached it. The runner follows each test through Bun's inspector while the preload
345
+ records which mutants each test reached, and how often. Bun's summary, the inspector's events and
346
+ the coverage records must agree exactly, or the dry run fails
347
+ ([the completeness gate](docs/internals.md#the-completeness-gate)).
348
+ 3. **Mutant runs.** A fresh `bun test` process per mutant, with the mutant switched on. It runs only
349
+ the covering tests (`--test-name-pattern`), only in their files, cheapest file first, and bails at
350
+ the first failure unless `disableBail` is set. The hit limit stops infinite loops early.
351
+
352
+ More: [Mutant runs](docs/internals.md#mutant-runs), [the dry run in detail](docs/internals.md#the-dry-run-in-detail).
353
+
354
+ ### How results are scored
355
+
356
+ - **Killed** when a test fails, or when a test file fails to load because of the mutant (bun reports
357
+ a failure count but no failing test).
358
+ - **Survived** when every selected test passes.
359
+ - **Timeout** when the hit limit is exceeded, the time limit is reached, or `bun.maxChildRss` is
360
+ exceeded.
361
+ - **Error** when the run proves nothing either way: the process crashed with no failing test that
362
+ matches a known test, could not be started, exited with an error but no failing test and no failure
363
+ count, or a full-suite fallback ran out of the time Stryker sized for the covering tests.
364
+
365
+ The full table and the reasoning: [How results are scored](docs/internals.md#how-results-are-scored).
366
+
367
+ ### Timeouts
368
+
369
+ Stryker sizes a timeout for every mutant run from the dry-run time of the tests it will run, plus
370
+ `timeoutMS`. The runner kills the `bun test` process a little before that, at Stryker's timeout
371
+ minus the larger of 750 ms and 5% (never more than a quarter of the timeout), and reports the
372
+ Timeout itself; if Stryker's own timer fired first, it would restart the whole worker. `bun.timeout`
373
+ only bounds the dry run. To give mutant runs more time, raise Stryker's `timeoutMS` or
374
+ `timeoutFactor`. Details: [Timeouts](docs/internals.md#timeouts).
375
+
376
+ ## Speeding up runs
377
+
378
+ **What to try first, in order:** keep incremental mode on for local runs; right-size `concurrency`;
379
+ if you use the TypeScript checker, wrap your config in `withTestFilesExcludedFromTypeCheck`; then
380
+ `ignoreStatic`, if you accept what it skips; then TypeScript 7's native checker, if type checking is
381
+ still the slow part.
382
+
383
+ - **Incremental mode.** With Stryker's `incremental: true`, a run reuses the previous results
384
+ (`reports/stryker-incremental.json` by default) and only re-tests mutants whose code or covering
385
+ tests changed. The runner keeps test ids stable across runs, so results stay reusable. Run with
386
+ `--force` only when the cached results look wrong.
387
+ - **`concurrency`.** Stryker runs this many workers, each with one `bun test` process at a time; with
388
+ a checker, Stryker splits it between checker and test-runner processes. More is faster until CPU or
389
+ memory runs out: peak memory is roughly `concurrency` × the memory one run of your suite needs. On a
390
+ memory-constrained machine, lower it first, then consider `bun.smol` and `bun.maxChildRss`
391
+ ([memory](docs/internals.md#memory)).
392
+ - **Bail** is on by default: mutant runs stop at the first failing test. Stryker's
393
+ `disableBail: true` runs every covering test instead, so killedBy lists every test that kills the
394
+ mutant, at a cost in time.
395
+
396
+ ### `ignoreStatic`: faster, but skips module-level code
397
+
398
+ Each [static mutant](#terms) runs your whole suite in a fresh process, so a project with many
399
+ module-level constants or much top-level setup can spend a large part of its time on them.
400
+ Stryker's `ignoreStatic: true` skips them. They are then never tested and not counted in your score,
401
+ so a bug a mutant there would have revealed goes unnoticed. Leave it off if module-level behaviour
402
+ matters to you; turn it on if run time matters more.
401
403
 
402
- ## License
404
+ ```javascript
405
+ export default {
406
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
407
+ testRunner: 'bun',
408
+ ignoreStatic: true,
409
+ };
410
+ ```
411
+
412
+ ### Keep tests out of the TypeScript checker
413
+
414
+ `@stryker-mutator/typescript-checker` type-checks every mutant against the program of its
415
+ `tsconfigFile` (default `tsconfig.json`) and re-checks every file that imports the mutated one. If
416
+ that tsconfig includes your tests, a mutant in a widely imported module re-checks much of your test
417
+ suite too. `withTestFilesExcludedFromTypeCheck`, used in the
418
+ [example above](#optional-skip-mutants-that-do-not-compile), points the checker at the code under
419
+ test only.
420
+
421
+ Each time Stryker loads the config, the helper reads your tsconfig with your project's TypeScript
422
+ (honouring `extends`, `files`, `include` and `exclude`) and writes `tsconfig.stryker-checker.json`
423
+ next to it. That file extends yours and lists everything your tsconfig covers except:
424
+
425
+ - test files, found the way this runner finds them (Bun's naming rules under `[test].root`, plus
426
+ `bun.testFiles` and Stryker's `testFiles`);
427
+ - your bunfig's `[test].preload` scripts;
428
+ - files only those import, such as test helpers, unless a `mutate` pattern covers them or they shape
429
+ the types of other files (a global script with no imports or exports, or a module with a
430
+ `declare global` or `declare module "x"` augmentation).
431
+
432
+ Anything the remaining code imports still comes in through the import, so the program compiles as
433
+ before. As a safety net, the helper type-checks the new program once and compares its errors in
434
+ non-test files with the original's; if leaving the tests out adds an error (a global declared only
435
+ through a test's `/// <reference types>`, say), it warns with the first few and falls back. The
436
+ returned config has `tsconfigFile` pointing at the new file and, if you set `ignorePatterns`, a
437
+ negation for it appended so Stryker copies it into the sandbox. Add `*.stryker-checker.json` to your
438
+ `.gitignore`.
439
+
440
+ It logs one line per call: an info naming the file and how many files it excluded and kept, or a
441
+ warning with the reason it fell back. It falls back, returning your config unchanged, when
442
+ TypeScript cannot be loaded from the project, the tsconfig is missing, has errors or uses project
443
+ references, includes no test files or would be left with none, leaving the tests out adds errors, or
444
+ the file cannot be written or was not generated by the helper. With no `'typescript'` in `checkers`
445
+ it does nothing (logged at info), so list the checker in the config you wrap.
446
+
447
+ The tradeoff: a mutant that only breaks types your tests use, and that no test then fails at run
448
+ time, survives instead of counting as a CompileError.
449
+
450
+ ### TypeScript 7's native checker (experimental)
451
+
452
+ `@stryker-mutator/typescript-checker` 10 can type-check mutants with TypeScript 7's native compiler
453
+ instead of its default mode, which uses your `typescript` package (TypeScript 6 or earlier). The
454
+ native compiler is much faster. Upstream marks this mode experimental: it uses TypeScript 7's
455
+ unstable API, does not support project references, and checks mutants one at a time.
456
+
457
+ **Is it worth it?** Try it when type checking is the slow part of your run (compare a run's time
458
+ with and without `checkers`) and your tsconfig has no project references. Otherwise stay with the
459
+ default mode.
460
+
461
+ To opt in, install TypeScript 7 under the name the checker loads it by, next to your existing
462
+ `typescript` 6 or earlier, and set the option:
403
463
 
404
- Apache-2.0
464
+ ```bash
465
+ bun add -D --exact @typescript/native@npm:typescript@7.0.2
466
+ ```
467
+
468
+ ```javascript
469
+ // @ts-check
470
+ import { withTestFilesExcludedFromTypeCheck } from '@hughescr/stryker-bun-runner';
471
+
472
+ export default await withTestFilesExcludedFromTypeCheck({
473
+ appendPlugins: ['@hughescr/stryker-bun-runner'],
474
+ testRunner: 'bun',
475
+ checkers: ['typescript'],
476
+ typescriptChecker: { experimentalNativePreview: true },
477
+ });
478
+ ```
479
+
480
+ - The checker imports `@typescript/native/unstable/sync`. Its error message suggests a `typescript7`
481
+ alias, but it never looks for one, so use the `@typescript/native` name above.
482
+ - Pin TypeScript 7.0.2 exactly. TypeScript 7.1 renames the `unstable/sync` entry point to `sync`,
483
+ which checker 10.0.0 cannot load.
484
+ - Keep `typescript` 6 or earlier: Stryker and the checker still need it, and so does
485
+ `withTestFilesExcludedFromTypeCheck`. The alias installs a second `tsc` that takes over
486
+ `node_modules/.bin/tsc`, so call TypeScript 6 by its path (`node node_modules/typescript/bin/tsc`)
487
+ where that matters.
488
+
489
+ #### Do you need the checker patch?
490
+
491
+ Only if your tsconfig turns on `noUnusedLocals` or `noUnusedParameters`, or sets
492
+ `allowUnreachableCode: false`. The checker's default mode switches those checks off for mutants,
493
+ since a mutant that leaves a variable unused is not broken. Checker 10.0.0's native mode fails to,
494
+ whenever `tsconfigFile` is a relative path (the default, and what
495
+ `withTestFilesExcludedFromTypeCheck` sets). **Symptom:** the native checker reports more
496
+ CompileErrors than the default mode, with reasons such as
497
+ `error TS6133: 'message' is declared but its value is never read`, and those mutants are never
498
+ tested.
499
+
500
+ The fix is a one-line patch. With Bun:
501
+
502
+ 1. Pin the checker, since the patch is for that exact version:
503
+ `bun add -D --exact @stryker-mutator/typescript-checker@10.0.0`.
504
+ 2. Save this as `patches/@stryker-mutator%2Ftypescript-checker@10.0.0.patch` (the `%2F` is part of
505
+ the file name):
506
+
507
+ ```diff
508
+ diff --git a/dist/src/ts-native/native-typescript-compiler.js b/dist/src/ts-native/native-typescript-compiler.js
509
+ --- a/dist/src/ts-native/native-typescript-compiler.js
510
+ +++ b/dist/src/ts-native/native-typescript-compiler.js
511
+ @@ -43,7 +43,7 @@ export class NativeTypescriptCompiler {
512
+ this.log.debug('Started the native TypeScript compiler on project "%s"', this.tsconfigFile);
513
+ return this.checkSnapshot();
514
+ }
515
+ - async #adjustTSConfigFile(fileName = this.options.tsconfigFile) {
516
+ + async #adjustTSConfigFile(fileName = this.tsconfigFile) {
517
+ const parsedConfig = ts.parseConfigFileTextToJson(toPosixFileName(fileName), await fs.promises.readFile(fileName, 'utf-8'));
518
+ if (parsedConfig.error) {
519
+ return; // let the ts compiler deal with this error
520
+ ```
521
+
522
+ 3. Add it to `package.json` and run `bun install`:
523
+
524
+ ```json
525
+ "patchedDependencies": {
526
+ "@stryker-mutator/typescript-checker@10.0.0": "patches/@stryker-mutator%2Ftypescript-checker@10.0.0.patch"
527
+ }
528
+ ```
529
+
530
+ `patchedDependencies` is a Bun feature. With npm, make the same one-line change in
531
+ `node_modules/@stryker-mutator/typescript-checker/dist/src/ts-native/native-typescript-compiler.js`
532
+ and record it with [patch-package](https://github.com/ds300/patch-package)
533
+ (`npx patch-package @stryker-mutator/typescript-checker`, plus a `"postinstall": "patch-package"`
534
+ script).
535
+
536
+ ## Troubleshooting
537
+
538
+ Run Stryker with `logLevel: 'debug'` (or `--logLevel debug`) for the full detail behind any of
539
+ these. A warning that repeats for many mutants is logged in full once per worker, then at debug,
540
+ with a summary at the end: `<kind>: <N> mutants affected (first: <ids>); see debug log for details`.
541
+ Every log message: [Log output](docs/internals.md#log-output).
542
+
543
+ ### The run stops before the dry run
544
+
545
+ | Message | Cause | Fix |
546
+ |---|---|---|
547
+ | `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)). |
548
+ | `Cannot find TestRunner plugin "bun"` (from Stryker) | The plugin was not loaded. | Add `appendPlugins: ['@hughescr/stryker-bun-runner']`. |
549
+ | `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). |
550
+ | `stryker-bun-runner: could not run "<bunPath>" (<reason>). Install bun >= 1.3.7 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`. |
551
+ | `stryker-bun-runner: bun <version> at "<bunPath>" is too old; version 1.3.7 or newer is required.` | Bun before 1.3.7 lacks the inspector events the runner needs. | `bun upgrade`. |
552
+ | `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). |
553
+ | `has no usable path: write --config=<path>, --config <path> or -c <path>` | A `--config`/`-c` with no file name. | Give the path. |
554
+ | `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`. |
555
+ | `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). |
556
+ | `[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. |
557
+
558
+ ### The dry run fails
559
+
560
+ | Message | Cause | Fix |
561
+ |---|---|---|
562
+ | 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. |
563
+ | `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. |
564
+ | `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. |
565
+ | `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. |
566
+ | `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. |
567
+ | `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. |
568
+ | `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. |
569
+ | `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). |
570
+ | `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. |
571
+ | `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. |
572
+
573
+ ### Warnings during the dry run
574
+
575
+ | Message | Cause | Fix |
576
+ |---|---|---|
577
+ | `The dry run took <N>ms, more than 80% of bun.timeout` | The next, slightly slower dry run may be killed. | Raise `bun.timeout`. |
578
+ | `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`. |
579
+ | `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`. |
580
+ | `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. |
581
+ | `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. |
582
+ | `These bunfig settings were ignored for mutation runs` | `[test].retry` or `[test].rerunEach` in your bunfig. | Remove them to silence the warning. |
583
+ | `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. |
584
+ | `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/`. |
585
+ | `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. |
586
+ | `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`. |
587
+ | `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. |
588
+
589
+ Inspector diagnostics such as `Inspector data looks abnormal` need no action unless the dry run
590
+ also fails; see [Inspector diagnostics](docs/internals.md#inspector-diagnostics).
591
+
592
+ ### Warnings and results during mutant runs
593
+
594
+ | Message or symptom | Cause | Fix |
595
+ |---|---|---|
596
+ | `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`. |
597
+ | `Mutant <id>: could not start bun test: <error>` | Bun could not be started. | Check `bun.bunPath`, `PATH` and system limits. |
598
+ | `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. |
599
+ | `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`. |
600
+ | `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. |
601
+ | `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. |
602
+ | `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. |
603
+ | `bun test child exceeded maxChildRss` | A run went over `bun.maxChildRss`; scored Timeout. | Expected for runaway mutants; raise the limit if many hit it. |
604
+ | 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`. |
605
+ | 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. |
606
+ | 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. |
607
+
608
+ ## Limitations
609
+
610
+ - **One test at a time.** Tests run sequentially, `test.concurrent` included, so per-test coverage
611
+ is exact. Mutation runs are slower than a parallel `bun test`.
612
+ - **`mock.module()` of a mutated file** has no effect when the module was already imported, because
613
+ the dry run imports every mutated file before the tests run. Use dependency injection or spy on
614
+ methods instead. [Details](docs/internals.md#test-names-and-coverage-attribution).
615
+ - **Cross-file order dependence.** Mutant runs order files by cost, not as in the dry run, so a
616
+ global change one test file leaves behind (an unrestored `mock.module()`) can change results.
617
+ - **No randomized order in mutant runs**, and `retry`/`rerunEach` are not supported.
618
+ - **Static mutants** each run the whole suite in a fresh process. See
619
+ [`ignoreStatic`](#ignorestatic-faster-but-skips-module-level-code).
620
+ - **`bun.maxChildRss` is a polled, soft limit**, not a kernel-enforced one.
621
+ - **The dry run's fixed bounds** (the 30 s drain handshake ceiling, the 4 s silence limit) have no
622
+ options.
623
+
624
+ ## Advanced topics
625
+
626
+ [docs/internals.md](docs/internals.md) covers how the runner works in detail:
627
+
628
+ - [Mutant runs](docs/internals.md#mutant-runs): test selection, cheapest-first ordering, fallbacks
629
+ - [How results are scored](docs/internals.md#how-results-are-scored) and
630
+ [the hit limit](docs/internals.md#infinite-loops-the-hit-limit)
631
+ - [The dry run in detail](docs/internals.md#the-dry-run-in-detail): the start and drain handshakes,
632
+ the completeness gate, coverage checks
633
+ - [Log output](docs/internals.md#log-output): start and end summaries, repeated warnings
634
+ - [Temporary files](docs/internals.md#temporary-files): the private per-run directory
635
+ - [Child processes](docs/internals.md#child-processes): process groups, orphan prevention,
636
+ recursion containment
637
+ - [Memory](docs/internals.md#memory) and
638
+ [`maxTestRunnerReuse`](docs/internals.md#maxtestrunnerreuse-compatibility)
405
639
 
406
640
  ## Contributing
407
641
 
408
- Issues and pull requests welcome at [github.com/hughescr/stryker-bun-runner](https://github.com/hughescr/stryker-bun-runner)
642
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
643
+
644
+ ## License
645
+
646
+ Apache-2.0. See [LICENSE.md](LICENSE.md).