@hughescr/stryker-bun-runner 1.2.2 → 1.3.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
@@ -65,8 +65,9 @@ The plugin uses Bun's Inspector Protocol (WebSocket) to:
65
65
  2. **Track execution** - Listens for TestReporter events to correlate test runs with coverage
66
66
  3. **Sequential execution** - Uses `--concurrency=1` to ensure reliable coverage correlation
67
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.
68
69
 
69
- This approach provides reliable test-to-mutant correlation, even with multiple test files.
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.
70
71
 
71
72
  ## Options
72
73
 
@@ -76,8 +77,11 @@ This approach provides reliable test-to-mutant correlation, even with multiple t
76
77
  | `bun.timeout` | `number` | `10000` | Timeout per test in milliseconds |
77
78
  | `bun.inspectorTimeout` | `number` | `5000` | Timeout for Inspector WebSocket connection in milliseconds |
78
79
  | `bun.env` | `object` | `undefined` | Additional environment variables to pass to bun test |
79
- | `bun.bunArgs` | `string[]` | `undefined` | Additional bun test flags (e.g., `['--bail']`) |
80
+ | `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)). |
80
81
  | `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. |
82
+ | `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). |
83
+ | `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). |
84
+ | `bun.rssCheckIntervalMs` | `number` | `1000` | Poll interval in milliseconds for the `maxChildRss` check. |
81
85
 
82
86
  ### Example with all options
83
87
 
@@ -87,7 +91,10 @@ bun: {
87
91
  timeout: 30000, // 30 second test timeout
88
92
  inspectorTimeout: 10000, // 10 second connection timeout
89
93
  env: { DEBUG: 'true' }, // Extra environment variables
90
- bunArgs: ['--bail'], // Stop on first failure
94
+ bunArgs: ['--only'], // Extra bun test flags (bail flags here are ignored — see Options table)
95
+ smol: true, // Smaller JSC heap, some speed cost — see Memory model
96
+ maxChildRss: 1_500_000_000, // Kill+report-timeout a child using more than ~1.5GB RSS
97
+ rssCheckIntervalMs: 1000, // How often to poll RSS when maxChildRss is set
91
98
  }
92
99
  ```
93
100
 
@@ -101,6 +108,66 @@ bunx stryker run
101
108
 
102
109
  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`.
103
110
 
111
+ ## Memory model
112
+
113
+ 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.
114
+
115
+ What this means for memory planning on a mutation-testing machine:
116
+
117
+ - **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.
118
+ - **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.
119
+ - **Recommended settings for memory-constrained machines:**
120
+ - Lower `concurrency` in your `stryker.conf.mjs` first — it has the largest, most direct effect on peak memory (linear multiplier).
121
+ - Set `bun.smol: true` to shrink each child's JSC heap ceiling at some speed cost.
122
+ - Set `bun.maxChildRss` as a backstop against a single run growing unexpectedly large (see [Memory containment](#memory-containment)).
123
+ - 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.
124
+
125
+ ## Memory containment
126
+
127
+ 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:
128
+
129
+ - **`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.
130
+ - **`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.
131
+
132
+ **Why not a hard, kernel-enforced ceiling (`ulimit -v`, cgroups)?** We looked at this and decided against it:
133
+ - `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.
134
+ - `RLIMIT_RSS` has been a no-op on Linux since kernel 2.4.30 — the kernel accepts the limit but never enforces it.
135
+ - 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.
136
+
137
+ `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.
138
+
139
+ ## Orphan prevention
140
+
141
+ Each spawned `bun test` child is protected against being left running forever if something goes wrong:
142
+
143
+ - **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.
144
+ - **`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.
145
+ - **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.
146
+
147
+ ## `maxTestRunnerReuse` compatibility
148
+
149
+ 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)).
150
+
151
+ This plugin is designed to tolerate that recycling cleanly:
152
+
153
+ - `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)).
154
+ - 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.
155
+
156
+ ```javascript
157
+ // stryker.conf.mjs
158
+ export default {
159
+ testRunner: 'bun',
160
+ coverageAnalysis: 'perTest',
161
+ mutate: ['src/**/*.ts'],
162
+ concurrency: 8, // tune down first on memory-constrained machines
163
+ maxTestRunnerReuse: 100, // recycle each Stryker worker after 100 runs
164
+ bun: {
165
+ smol: true,
166
+ maxChildRss: 1_500_000_000, // ~1.5GB soft ceiling per bun test child
167
+ },
168
+ };
169
+ ```
170
+
104
171
  ## Known Limitations
105
172
 
106
173
  - **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.
@@ -41,8 +41,24 @@ function writeCoverageToFile(coverageFile, data) {
41
41
  appendFileSync(coverageFile, `${JSON.stringify(data)}
42
42
  `, "utf8");
43
43
  }
44
+ function startOrphanWatchdog(deps) {
45
+ const originalPpid = deps.getPpid();
46
+ let fired = false;
47
+ const intervalId = setInterval(() => {
48
+ if (fired || deps.getPpid() === originalPpid) {
49
+ return;
50
+ }
51
+ fired = true;
52
+ deps.onOrphaned();
53
+ }, deps.intervalMs ?? 1000);
54
+ intervalId.unref();
55
+ return () => {
56
+ clearInterval(intervalId);
57
+ };
58
+ }
44
59
  export {
45
60
  writeCoverageToFile,
61
+ startOrphanWatchdog,
46
62
  shouldCollectCoverage,
47
63
  setActiveMutant,
48
64
  initializeStrykerNamespace,
package/dist/index.d.ts CHANGED
@@ -21,6 +21,9 @@ export declare class BunTestRunner implements TestRunner {
21
21
  private readonly bunArgs?;
22
22
  private readonly testFilesOverride?;
23
23
  private readonly mutateGlobs;
24
+ private readonly smol;
25
+ private readonly maxChildRss?;
26
+ private readonly rssCheckIntervalMs?;
24
27
  private preloadScriptPath?;
25
28
  private coverageFilePath?;
26
29
  private sanitizedBunfigPath?;
@@ -33,6 +36,13 @@ export declare class BunTestRunner implements TestRunner {
33
36
  private cachedEagerModules?;
34
37
  private cachedEagerModulesCwd?;
35
38
  private lastRegistryTmpPath?;
39
+ /**
40
+ * AbortController for whichever `dryRun`/`mutantRun` child process is
41
+ * currently in flight, if any. Lets {@link dispose} kill an orphaned child
42
+ * if Stryker disposes this runner while a run hasn't finished — see README
43
+ * "Orphan prevention".
44
+ */
45
+ private currentAbortController?;
36
46
  constructor(logger: Logger, options: StrykerOptions);
37
47
  /**
38
48
  * Single source of truth for the registry file name.
@@ -186,8 +196,14 @@ export interface BunTestRunnerOptions {
186
196
  */
187
197
  env?: Record<string, string>;
188
198
  /**
189
- * Additional bun test flags to pass
190
- * @example ['--bail', '--only']
199
+ * Additional bun test flags to pass.
200
+ *
201
+ * Bail flags (`--bail`, `--bail=<N>`, or a space-separated `--bail <N>`) are
202
+ * stripped if present — bail is fully managed by the runner based on
203
+ * Stryker's `disableBail` option, so a bail flag configured here would
204
+ * otherwise silently override that decision.
205
+ *
206
+ * @example ['--only', '--verbose']
191
207
  */
192
208
  bunArgs?: string[];
193
209
  /**
@@ -209,6 +225,31 @@ export interface BunTestRunnerOptions {
209
225
  * fall back to auto-discovery.
210
226
  */
211
227
  testFiles?: string[];
228
+ /**
229
+ * Pass Bun's `--smol` flag to every `bun test` child, trading some speed for
230
+ * a significantly smaller JavaScriptCore heap footprint. Recommended on
231
+ * memory-constrained machines, especially at higher Stryker `concurrency`,
232
+ * since peak memory during a campaign is roughly
233
+ * `concurrency × per-run suite footprint` (each run is an isolated process
234
+ * that exits when it completes — see README "Memory model").
235
+ * @default false
236
+ */
237
+ smol?: boolean;
238
+ /**
239
+ * Soft memory ceiling, in bytes, for each `bun test` child's resident set
240
+ * size (RSS). When set, the child's RSS is polled periodically; a run that
241
+ * exceeds this ceiling is killed and reported as a clean timeout/error for
242
+ * that one mutant, rather than being left to grow toward system-wide swap
243
+ * exhaustion. This is a polled userspace check, not a kernel-enforced
244
+ * limit — see README "Memory containment" for why a true hard ceiling
245
+ * (rlimit/cgroup) isn't used. Omit to disable.
246
+ */
247
+ maxChildRss?: number;
248
+ /**
249
+ * Poll interval in milliseconds for the {@link maxChildRss} check.
250
+ * @default 1000
251
+ */
252
+ rssCheckIntervalMs?: number;
212
253
  }
213
254
  /**
214
255
  * Extended Stryker options with Bun-specific configuration
@@ -276,6 +317,22 @@ export declare const strykerValidationSchema: {
276
317
  type: string;
277
318
  };
278
319
  };
320
+ smol: {
321
+ type: string;
322
+ description: string;
323
+ default: boolean;
324
+ };
325
+ maxChildRss: {
326
+ type: string;
327
+ minimum: number;
328
+ description: string;
329
+ };
330
+ rssCheckIntervalMs: {
331
+ type: string;
332
+ minimum: number;
333
+ description: string;
334
+ default: number;
335
+ };
279
336
  };
280
337
  additionalProperties: boolean;
281
338
  };
package/dist/index.js CHANGED
@@ -5618,30 +5618,12 @@ function mapCoverageToInspectorIds(rawCoverage, executionOrder, testHierarchy, l
5618
5618
  }
5619
5619
  return { coverage: rawCoverage, inspectorIdToProjectFile: new Map };
5620
5620
  }
5621
- function countPerTestAppearances(perTestEntries) {
5622
- const appearances = new Map;
5623
- for (const [, counts] of perTestEntries) {
5624
- for (const mutantId of Object.keys(counts)) {
5625
- appearances.set(mutantId, (appearances.get(mutantId) ?? 0) + 1);
5626
- }
5627
- }
5628
- return appearances;
5629
- }
5630
- function buildPromoteToStaticSet(existingStaticKeys, perTestAppearances) {
5631
- const promoteToStatic = new Set(existingStaticKeys);
5632
- for (const [mutantId, count] of perTestAppearances) {
5633
- if (count > 1) {
5634
- promoteToStatic.add(mutantId);
5635
- }
5636
- }
5637
- return promoteToStatic;
5638
- }
5639
- function buildFilteredPerTest(perTestEntries, promoteToStatic) {
5621
+ function buildFilteredPerTest(perTestEntries, staticIds) {
5640
5622
  const newPerTest = {};
5641
5623
  for (const [testId, counts] of perTestEntries) {
5642
5624
  const filteredCounts = {};
5643
5625
  for (const [mutantId, hitCount] of Object.entries(counts)) {
5644
- if (!promoteToStatic.has(mutantId)) {
5626
+ if (!staticIds.has(mutantId)) {
5645
5627
  filteredCounts[mutantId] = hitCount;
5646
5628
  }
5647
5629
  }
@@ -5652,27 +5634,11 @@ function buildFilteredPerTest(perTestEntries, promoteToStatic) {
5652
5634
  return newPerTest;
5653
5635
  }
5654
5636
  function stabilizeCoverage(coverage) {
5655
- const perTestEntries = Object.entries(coverage.perTest);
5656
- if (perTestEntries.length === 0) {
5657
- return coverage;
5658
- }
5659
- const existingStaticKeys = Object.keys(coverage.static);
5660
- const perTestAppearances = countPerTestAppearances(perTestEntries);
5661
- const promoteToStatic = buildPromoteToStaticSet(existingStaticKeys, perTestAppearances);
5662
- const existingStatic = new Set(existingStaticKeys);
5663
- const hasNewPromotions = [...promoteToStatic].some((id) => !existingStatic.has(id));
5664
- const hasPerTestContamination = perTestEntries.some(([, counts]) => Object.keys(counts).some((id) => promoteToStatic.has(id)));
5665
- if (!hasNewPromotions && !hasPerTestContamination) {
5666
- return coverage;
5667
- }
5668
- const newStatic = { ...coverage.static };
5669
- for (const mutantId of promoteToStatic) {
5670
- if (!(mutantId in newStatic)) {
5671
- newStatic[mutantId] = 1;
5672
- }
5673
- }
5674
- const newPerTest = buildFilteredPerTest(perTestEntries, promoteToStatic);
5675
- return { static: newStatic, perTest: newPerTest };
5637
+ const staticIds = new Set(Object.keys(coverage.static));
5638
+ return {
5639
+ static: coverage.static,
5640
+ perTest: buildFilteredPerTest(Object.entries(coverage.perTest), staticIds)
5641
+ };
5676
5642
  }
5677
5643
  function pairKeysWithInspectorIds(globallyOrderedPerTestKeys, executionOrder, testHierarchy, logger) {
5678
5644
  const nonSkipped = executionOrder.filter((id) => {
@@ -6257,7 +6223,80 @@ ${stderr}`;
6257
6223
  }
6258
6224
 
6259
6225
  // src/process-runner.ts
6226
+ import { spawn as spawn2 } from "node:child_process";
6227
+
6228
+ // src/utils/process-rss.ts
6260
6229
  import { spawn } from "node:child_process";
6230
+ import { readFile as readFile3 } from "node:fs/promises";
6231
+ async function getProcessRssBytes(pid) {
6232
+ return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
6233
+ }
6234
+ function parseVmRss(statusContent) {
6235
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
6236
+ return match ? Number(match[1]) * 1024 : null;
6237
+ }
6238
+ async function getLinuxRss(pid) {
6239
+ try {
6240
+ const status = await readFile3(`/proc/${pid}/status`, "utf8");
6241
+ return parseVmRss(status);
6242
+ } catch {
6243
+ return null;
6244
+ }
6245
+ }
6246
+ function parsePsRssOutput(output) {
6247
+ const trimmed = output.trim();
6248
+ if (trimmed === "") {
6249
+ return null;
6250
+ }
6251
+ const kb = Number(trimmed);
6252
+ return Number.isFinite(kb) ? kb * 1024 : null;
6253
+ }
6254
+ async function getPsRss(pid) {
6255
+ return new Promise((resolve3) => {
6256
+ let child;
6257
+ try {
6258
+ child = spawn("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
6259
+ } catch {
6260
+ resolve3(null);
6261
+ return;
6262
+ }
6263
+ let output = "";
6264
+ child.stdout.on("data", (data) => {
6265
+ output += data.toString();
6266
+ });
6267
+ child.on("close", (code) => {
6268
+ resolve3(code === 0 ? parsePsRssOutput(output) : null);
6269
+ });
6270
+ child.on("error", () => {
6271
+ resolve3(null);
6272
+ });
6273
+ });
6274
+ }
6275
+
6276
+ // src/process-runner.ts
6277
+ var KILL_GRACE_PERIOD_MS = 500;
6278
+ function stripBailArgs(bunArgs) {
6279
+ const sanitized = [];
6280
+ for (let i = 0;i < bunArgs.length; i++) {
6281
+ const arg = bunArgs[i];
6282
+ if (arg === "--bail" || arg.startsWith("--bail=")) {
6283
+ if (arg === "--bail" && /^\d+$/.test(bunArgs[i + 1])) {
6284
+ i += 1;
6285
+ }
6286
+ continue;
6287
+ }
6288
+ sanitized.push(arg);
6289
+ }
6290
+ return sanitized;
6291
+ }
6292
+ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
6293
+ childProcess.kill("SIGTERM");
6294
+ setTimeout(() => {
6295
+ if (!isClosed()) {
6296
+ childProcess.kill("SIGKILL");
6297
+ }
6298
+ }, gracePeriodMs);
6299
+ }
6261
6300
  async function runBunTests(options) {
6262
6301
  const args = ["test"];
6263
6302
  if (options.inspectWaitPort) {
@@ -6278,8 +6317,11 @@ async function runBunTests(options) {
6278
6317
  if (options.sequentialMode) {
6279
6318
  args.push("--concurrency=1");
6280
6319
  }
6320
+ if (options.smol) {
6321
+ args.push("--smol");
6322
+ }
6281
6323
  if (options.bunArgs && options.bunArgs.length > 0) {
6282
- args.push(...options.bunArgs);
6324
+ args.push(...stripBailArgs(options.bunArgs));
6283
6325
  }
6284
6326
  if (options.testFiles && options.testFiles.length > 0) {
6285
6327
  args.push(...options.testFiles);
@@ -6302,8 +6344,11 @@ async function runBunTests(options) {
6302
6344
  const stderrChunks = [];
6303
6345
  let timedOut = false;
6304
6346
  let processKilled = false;
6347
+ let memoryLimitExceeded = false;
6348
+ let hasClosed = false;
6349
+ let rssIntervalHandle;
6305
6350
  if (options.signal?.aborted) {
6306
- resolve3({ stdout: "", stderr: "", exitCode: null, timedOut: true });
6351
+ resolve3({ stdout: "", stderr: "", exitCode: null, timedOut: true, memoryLimitExceeded: false });
6307
6352
  return;
6308
6353
  }
6309
6354
  const spawnOpts = {
@@ -6311,24 +6356,51 @@ async function runBunTests(options) {
6311
6356
  stdio: ["ignore", "pipe", "pipe"],
6312
6357
  cwd: process.cwd()
6313
6358
  };
6314
- const childProcess = spawn(options.bunPath, args, spawnOpts);
6359
+ const childProcess = spawn2(options.bunPath, args, spawnOpts);
6315
6360
  const timeoutHandle = setTimeout(() => {
6316
6361
  timedOut = true;
6317
6362
  processKilled = true;
6318
- childProcess.kill("SIGKILL");
6363
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6319
6364
  }, options.timeout);
6320
6365
  if (options.signal) {
6321
6366
  const onAbort = () => {
6322
6367
  clearTimeout(timeoutHandle);
6323
6368
  processKilled = true;
6324
6369
  timedOut = true;
6325
- childProcess.kill("SIGTERM");
6326
- setTimeout(() => {
6327
- childProcess.kill("SIGKILL");
6328
- }, 500);
6370
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6329
6371
  };
6330
6372
  options.signal.addEventListener("abort", onAbort, { once: true });
6331
6373
  }
6374
+ if (options.maxChildRss !== undefined) {
6375
+ const rssLimit = options.maxChildRss;
6376
+ const checkMemoryCeiling = async () => {
6377
+ if (hasClosed || memoryLimitExceeded) {
6378
+ return;
6379
+ }
6380
+ const pid = childProcess.pid;
6381
+ if (pid === undefined) {
6382
+ return;
6383
+ }
6384
+ const rssBytes = await getProcessRssBytes(pid);
6385
+ if (rssBytes === null || hasClosed) {
6386
+ return;
6387
+ }
6388
+ if (rssBytes > rssLimit) {
6389
+ memoryLimitExceeded = true;
6390
+ timedOut = true;
6391
+ processKilled = true;
6392
+ if (rssIntervalHandle) {
6393
+ clearInterval(rssIntervalHandle);
6394
+ }
6395
+ options.onMemoryLimitExceeded?.(rssBytes);
6396
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6397
+ }
6398
+ };
6399
+ rssIntervalHandle = setInterval(() => {
6400
+ checkMemoryCeiling();
6401
+ }, options.rssCheckIntervalMs ?? 1000);
6402
+ rssIntervalHandle.unref();
6403
+ }
6332
6404
  if (childProcess.stdout) {
6333
6405
  childProcess.stdout.on("data", (data) => {
6334
6406
  stdoutChunks.push(data);
@@ -6349,23 +6421,33 @@ async function runBunTests(options) {
6349
6421
  });
6350
6422
  }
6351
6423
  childProcess.on("close", (code) => {
6424
+ hasClosed = true;
6352
6425
  clearTimeout(timeoutHandle);
6426
+ if (rssIntervalHandle) {
6427
+ clearInterval(rssIntervalHandle);
6428
+ }
6353
6429
  resolve3({
6354
6430
  stdout: Buffer.concat(stdoutChunks).toString(),
6355
6431
  stderr: Buffer.concat(stderrChunks).toString(),
6356
6432
  exitCode: processKilled ? null : code,
6357
- timedOut
6433
+ timedOut,
6434
+ memoryLimitExceeded
6358
6435
  });
6359
6436
  });
6360
6437
  childProcess.on("error", (error) => {
6438
+ hasClosed = true;
6361
6439
  clearTimeout(timeoutHandle);
6440
+ if (rssIntervalHandle) {
6441
+ clearInterval(rssIntervalHandle);
6442
+ }
6362
6443
  const stderrOutput = Buffer.concat(stderrChunks).toString();
6363
6444
  resolve3({
6364
6445
  stdout: Buffer.concat(stdoutChunks).toString(),
6365
6446
  stderr: `${stderrOutput}
6366
6447
  Process error: ${error.message}`,
6367
6448
  exitCode: null,
6368
- timedOut
6449
+ timedOut,
6450
+ memoryLimitExceeded
6369
6451
  });
6370
6452
  });
6371
6453
  });
@@ -6489,7 +6571,7 @@ class SyncServer {
6489
6571
  }
6490
6572
  }
6491
6573
  // src/utils/bunfig-sanitizer.ts
6492
- import { readFile as readFile3, unlink as unlink3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
6574
+ import { readFile as readFile4, unlink as unlink3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
6493
6575
  import path2 from "node:path";
6494
6576
 
6495
6577
  // node_modules/smol-toml/dist/error.js
@@ -7613,7 +7695,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir) {
7613
7695
  let rawConfig = {};
7614
7696
  const bunfigPath = path2.join(projectCwd, "bunfig.toml");
7615
7697
  try {
7616
- const content = await readFile3(bunfigPath, "utf8");
7698
+ const content = await readFile4(bunfigPath, "utf8");
7617
7699
  rawConfig = parse(content);
7618
7700
  } catch (err) {
7619
7701
  if (err.code !== "ENOENT") {
@@ -7649,6 +7731,7 @@ async function cleanupSanitizedBunfig(filePath) {
7649
7731
  }
7650
7732
  }
7651
7733
  // src/utils/test-name-pattern.ts
7734
+ var MAX_TEST_NAME_PATTERN_LENGTH = 1e5;
7652
7735
  function buildTestNamePattern(testFilter) {
7653
7736
  if (testFilter.length === 0) {
7654
7737
  return;
@@ -7670,7 +7753,11 @@ function buildTestNamePattern(testFilter) {
7670
7753
  if (alternatives.size === 0) {
7671
7754
  return;
7672
7755
  }
7673
- return `^(?:${[...alternatives].join("|")})$`;
7756
+ const pattern = `^(?:${[...alternatives].join("|")})$`;
7757
+ if (Buffer.byteLength(pattern) > MAX_TEST_NAME_PATTERN_LENGTH) {
7758
+ return;
7759
+ }
7760
+ return pattern;
7674
7761
  }
7675
7762
  // src/utils/test-file-discovery.ts
7676
7763
  import * as fsPromises from "node:fs/promises";
@@ -7792,6 +7879,9 @@ class BunTestRunner {
7792
7879
  bunArgs;
7793
7880
  testFilesOverride;
7794
7881
  mutateGlobs;
7882
+ smol;
7883
+ maxChildRss;
7884
+ rssCheckIntervalMs;
7795
7885
  preloadScriptPath;
7796
7886
  coverageFilePath;
7797
7887
  sanitizedBunfigPath;
@@ -7804,6 +7894,7 @@ class BunTestRunner {
7804
7894
  cachedEagerModules;
7805
7895
  cachedEagerModulesCwd;
7806
7896
  lastRegistryTmpPath;
7897
+ currentAbortController;
7807
7898
  constructor(logger, options) {
7808
7899
  this.logger = logger;
7809
7900
  const bunOptions = options.bun ?? {};
@@ -7812,6 +7903,9 @@ class BunTestRunner {
7812
7903
  this.inspectorTimeout = bunOptions.inspectorTimeout ?? 5000;
7813
7904
  this.env = bunOptions.env;
7814
7905
  this.bunArgs = bunOptions.bunArgs;
7906
+ this.smol = bunOptions.smol ?? false;
7907
+ this.maxChildRss = bunOptions.maxChildRss;
7908
+ this.rssCheckIntervalMs = bunOptions.rssCheckIntervalMs;
7815
7909
  if (bunOptions.testFiles?.length === 0) {
7816
7910
  this.logger.warn("bun.testFiles was set to an empty array — treating as undefined and falling back to auto-discovery");
7817
7911
  this.testFilesOverride = undefined;
@@ -7824,7 +7918,10 @@ class BunTestRunner {
7824
7918
  timeout: this.timeout,
7825
7919
  inspectorTimeout: this.inspectorTimeout,
7826
7920
  env: this.env,
7827
- bunArgs: this.bunArgs
7921
+ bunArgs: this.bunArgs,
7922
+ smol: this.smol,
7923
+ maxChildRss: this.maxChildRss,
7924
+ rssCheckIntervalMs: this.rssCheckIntervalMs
7828
7925
  });
7829
7926
  if (this.testFilesOverride?.some((p) => path4.isAbsolute(p))) {
7830
7927
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
@@ -8051,6 +8148,7 @@ class BunTestRunner {
8051
8148
  async dryRun() {
8052
8149
  this.logger.debug("Running dry run with inspector-based coverage collection...");
8053
8150
  const abortController = new AbortController;
8151
+ this.currentAbortController = abortController;
8054
8152
  const inspectPort = await getAvailablePort();
8055
8153
  const syncPort = await getAvailablePort();
8056
8154
  this.logger.debug("Using inspector port: %d, sync port: %d", inspectPort, syncPort);
@@ -8086,6 +8184,12 @@ class BunTestRunner {
8086
8184
  syncPort,
8087
8185
  testFiles,
8088
8186
  signal: abortController.signal,
8187
+ smol: this.smol,
8188
+ maxChildRss: this.maxChildRss,
8189
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
8190
+ onMemoryLimitExceeded: (rssBytes) => {
8191
+ this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during dryRun — killing and reporting as a timeout for this run", rssBytes);
8192
+ },
8089
8193
  onInspectorReady: (url) => {
8090
8194
  inspectorUrl = url;
8091
8195
  }
@@ -8154,6 +8258,9 @@ exit=%s timedOut=%s
8154
8258
  };
8155
8259
  } finally {
8156
8260
  abortController.abort();
8261
+ if (this.currentAbortController === abortController) {
8262
+ this.currentAbortController = undefined;
8263
+ }
8157
8264
  await syncServer.close();
8158
8265
  }
8159
8266
  }
@@ -8211,19 +8318,35 @@ exit=%s timedOut=%s
8211
8318
  const mutantCwd = process.cwd();
8212
8319
  const bunfigPath = this.sanitizedBunfigPath && this.sanitizedBunfigCwd === mutantCwd ? this.sanitizedBunfigPath : await this.ensureSanitizedBunfig();
8213
8320
  this.cachedTestFiles = await this.getOrDiscoverTestFiles();
8214
- const result = await runBunTests({
8215
- bunPath: this.bunPath,
8216
- timeout: this.timeout,
8217
- env: this.env,
8218
- bunArgs: this.bunArgs,
8219
- bunfigPath,
8220
- activeMutant: options.activeMutant.id,
8221
- bail: true,
8222
- sequentialMode: true,
8223
- preloadScript: this.preloadScriptPath,
8224
- testNamePattern,
8225
- testFiles: this.cachedTestFiles
8226
- });
8321
+ const abortController = new AbortController;
8322
+ this.currentAbortController = abortController;
8323
+ let result;
8324
+ try {
8325
+ result = await runBunTests({
8326
+ bunPath: this.bunPath,
8327
+ timeout: this.timeout,
8328
+ env: this.env,
8329
+ bunArgs: this.bunArgs,
8330
+ bunfigPath,
8331
+ activeMutant: options.activeMutant.id,
8332
+ bail: !options.disableBail,
8333
+ sequentialMode: true,
8334
+ preloadScript: this.preloadScriptPath,
8335
+ testNamePattern,
8336
+ testFiles: this.cachedTestFiles,
8337
+ signal: abortController.signal,
8338
+ smol: this.smol,
8339
+ maxChildRss: this.maxChildRss,
8340
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
8341
+ onMemoryLimitExceeded: (rssBytes) => {
8342
+ this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during mutant run %s — killing and reporting as a timeout for this mutant", rssBytes, options.activeMutant.id);
8343
+ }
8344
+ });
8345
+ } finally {
8346
+ if (this.currentAbortController === abortController) {
8347
+ this.currentAbortController = undefined;
8348
+ }
8349
+ }
8227
8350
  if (result.timedOut) {
8228
8351
  this.logger.debug("Mutant run timed out");
8229
8352
  return {
@@ -8363,6 +8486,11 @@ ${result.stderr}`
8363
8486
  }
8364
8487
  async dispose() {
8365
8488
  this.logger.debug("Disposing BunTestRunner");
8489
+ if (this.currentAbortController) {
8490
+ this.logger.debug("Aborting in-flight bun test child during dispose");
8491
+ this.currentAbortController.abort();
8492
+ this.currentAbortController = undefined;
8493
+ }
8366
8494
  if (this.preloadScriptPath) {
8367
8495
  this.logger.debug("Cleaning up preload script: %s", this.preloadScriptPath);
8368
8496
  await cleanupPreloadScript(this.preloadScriptPath);
@@ -8437,6 +8565,22 @@ var strykerValidationSchema = {
8437
8565
  items: {
8438
8566
  type: "string"
8439
8567
  }
8568
+ },
8569
+ smol: {
8570
+ type: "boolean",
8571
+ description: "Pass Bun's --smol flag to every child (smaller JavaScriptCore heap, some speed cost). Recommended on memory-constrained machines (default: false).",
8572
+ default: false
8573
+ },
8574
+ maxChildRss: {
8575
+ type: "number",
8576
+ minimum: 0,
8577
+ description: "Soft memory ceiling in bytes for each bun test child's RSS. A child exceeding this is killed and the run reported as a clean timeout for that mutant. Polled userspace check, not a kernel-enforced limit. Omit to disable."
8578
+ },
8579
+ rssCheckIntervalMs: {
8580
+ type: "number",
8581
+ minimum: 0,
8582
+ description: "Poll interval in milliseconds for the maxChildRss check (default: 1000).",
8583
+ default: 1000
8440
8584
  }
8441
8585
  },
8442
8586
  additionalProperties: false
@@ -12,9 +12,31 @@ import {
12
12
  setActiveMutant,
13
13
  formatCoverageData,
14
14
  writeCoverageToFile,
15
+ startOrphanWatchdog,
15
16
  type StrykerNamespace
16
17
  } from '__PRELOAD_LOGIC_PATH__';
17
18
 
19
+ // ============================================================================
20
+ // Section 0: Orphan prevention
21
+ // ============================================================================
22
+ // Every bun test child loads this preload script (dryRun AND mutant runs), so
23
+ // this watchdog runs unconditionally, regardless of coverage collection.
24
+ // If the Stryker worker that spawned this process dies (including via
25
+ // SIGKILL, which gives it no chance to kill its children), this process would
26
+ // otherwise run forever, or until its own --timeout is reached — see README
27
+ // "Orphan prevention".
28
+ const stopOrphanWatchdog = startOrphanWatchdog({
29
+ getPpid: () => process.ppid,
30
+ onOrphaned: () => {
31
+ console.warn('[Stryker] Parent process is no longer running — terminating to avoid an orphaned bun test process');
32
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit -- deliberate self-termination once orphaned; nothing else can stop this process from running forever
33
+ process.exit(1);
34
+ },
35
+ });
36
+ afterAll(() => {
37
+ stopOrphanWatchdog();
38
+ });
39
+
18
40
  // Patch .concurrent() to be regular sequential execution
19
41
  // This ensures accurate coverage tracking during mutation testing
20
42
  // Users can still use .concurrent() for faster normal test runs
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.2.2",
3
+ "version": "1.3.1",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",