@hughescr/stryker-bun-runner 1.2.1 → 1.3.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
@@ -78,6 +78,9 @@ This approach provides reliable test-to-mutant correlation, even with multiple t
78
78
  | `bun.env` | `object` | `undefined` | Additional environment variables to pass to bun test |
79
79
  | `bun.bunArgs` | `string[]` | `undefined` | Additional bun test flags (e.g., `['--bail']`) |
80
80
  | `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. |
81
+ | `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). |
82
+ | `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). |
83
+ | `bun.rssCheckIntervalMs` | `number` | `1000` | Poll interval in milliseconds for the `maxChildRss` check. |
81
84
 
82
85
  ### Example with all options
83
86
 
@@ -88,6 +91,9 @@ bun: {
88
91
  inspectorTimeout: 10000, // 10 second connection timeout
89
92
  env: { DEBUG: 'true' }, // Extra environment variables
90
93
  bunArgs: ['--bail'], // Stop on first failure
94
+ smol: true, // Smaller JSC heap, some speed cost — see Memory model
95
+ maxChildRss: 1_500_000_000, // Kill+report-timeout a child using more than ~1.5GB RSS
96
+ rssCheckIntervalMs: 1000, // How often to poll RSS when maxChildRss is set
91
97
  }
92
98
  ```
93
99
 
@@ -101,6 +107,66 @@ bunx stryker run
101
107
 
102
108
  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
109
 
110
+ ## Memory model
111
+
112
+ 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.
113
+
114
+ What this means for memory planning on a mutation-testing machine:
115
+
116
+ - **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.
117
+ - **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.
118
+ - **Recommended settings for memory-constrained machines:**
119
+ - Lower `concurrency` in your `stryker.conf.mjs` first — it has the largest, most direct effect on peak memory (linear multiplier).
120
+ - Set `bun.smol: true` to shrink each child's JSC heap ceiling at some speed cost.
121
+ - Set `bun.maxChildRss` as a backstop against a single run growing unexpectedly large (see [Memory containment](#memory-containment)).
122
+ - 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.
123
+
124
+ ## Memory containment
125
+
126
+ 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:
127
+
128
+ - **`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.
129
+ - **`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.
130
+
131
+ **Why not a hard, kernel-enforced ceiling (`ulimit -v`, cgroups)?** We looked at this and decided against it:
132
+ - `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.
133
+ - `RLIMIT_RSS` has been a no-op on Linux since kernel 2.4.30 — the kernel accepts the limit but never enforces it.
134
+ - 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.
135
+
136
+ `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.
137
+
138
+ ## Orphan prevention
139
+
140
+ Each spawned `bun test` child is protected against being left running forever if something goes wrong:
141
+
142
+ - **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.
143
+ - **`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.
144
+ - **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.
145
+
146
+ ## `maxTestRunnerReuse` compatibility
147
+
148
+ 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)).
149
+
150
+ This plugin is designed to tolerate that recycling cleanly:
151
+
152
+ - `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)).
153
+ - 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.
154
+
155
+ ```javascript
156
+ // stryker.conf.mjs
157
+ export default {
158
+ testRunner: 'bun',
159
+ coverageAnalysis: 'perTest',
160
+ mutate: ['src/**/*.ts'],
161
+ concurrency: 8, // tune down first on memory-constrained machines
162
+ maxTestRunnerReuse: 100, // recycle each Stryker worker after 100 runs
163
+ bun: {
164
+ smol: true,
165
+ maxChildRss: 1_500_000_000, // ~1.5GB soft ceiling per bun test child
166
+ },
167
+ };
168
+ ```
169
+
104
170
  ## Known Limitations
105
171
 
106
172
  - **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.
@@ -83,7 +93,12 @@ export declare class BunTestRunner implements TestRunner {
83
93
  */
84
94
  private loadRegistryFile;
85
95
  /**
86
- * Build test results from inspector data
96
+ * Build test results from inspector data.
97
+ *
98
+ * @param inspectorIdToProjectFile - Optional mapping from inspector ID to project file path.
99
+ * When provided, the project file is used for TestResult.id, name, and fileName instead of
100
+ * testInfo.url. This is important for tests defined via helpers (e.g. RuleTester.run()) where
101
+ * Bun's inspector reports a url pointing to node_modules rather than the user's test file.
87
102
  */
88
103
  private buildTestsFromInspector;
89
104
  /**
@@ -204,6 +219,31 @@ export interface BunTestRunnerOptions {
204
219
  * fall back to auto-discovery.
205
220
  */
206
221
  testFiles?: string[];
222
+ /**
223
+ * Pass Bun's `--smol` flag to every `bun test` child, trading some speed for
224
+ * a significantly smaller JavaScriptCore heap footprint. Recommended on
225
+ * memory-constrained machines, especially at higher Stryker `concurrency`,
226
+ * since peak memory during a campaign is roughly
227
+ * `concurrency × per-run suite footprint` (each run is an isolated process
228
+ * that exits when it completes — see README "Memory model").
229
+ * @default false
230
+ */
231
+ smol?: boolean;
232
+ /**
233
+ * Soft memory ceiling, in bytes, for each `bun test` child's resident set
234
+ * size (RSS). When set, the child's RSS is polled periodically; a run that
235
+ * exceeds this ceiling is killed and reported as a clean timeout/error for
236
+ * that one mutant, rather than being left to grow toward system-wide swap
237
+ * exhaustion. This is a polled userspace check, not a kernel-enforced
238
+ * limit — see README "Memory containment" for why a true hard ceiling
239
+ * (rlimit/cgroup) isn't used. Omit to disable.
240
+ */
241
+ maxChildRss?: number;
242
+ /**
243
+ * Poll interval in milliseconds for the {@link maxChildRss} check.
244
+ * @default 1000
245
+ */
246
+ rssCheckIntervalMs?: number;
207
247
  }
208
248
  /**
209
249
  * Extended Stryker options with Bun-specific configuration
@@ -271,6 +311,22 @@ export declare const strykerValidationSchema: {
271
311
  type: string;
272
312
  };
273
313
  };
314
+ smol: {
315
+ type: string;
316
+ description: string;
317
+ default: boolean;
318
+ };
319
+ maxChildRss: {
320
+ type: string;
321
+ minimum: number;
322
+ description: string;
323
+ };
324
+ rssCheckIntervalMs: {
325
+ type: string;
326
+ minimum: number;
327
+ description: string;
328
+ default: number;
329
+ };
274
330
  };
275
331
  additionalProperties: boolean;
276
332
  };
package/dist/index.js CHANGED
@@ -5593,6 +5593,9 @@ function normalizeTestFilePath(url) {
5593
5593
  function normalizeTestName(testName) {
5594
5594
  return testName.replaceAll(/\p{Cc}/gu, "_").trim();
5595
5595
  }
5596
+ function buildProjectFileTestName(filePrefix, fullName) {
5597
+ return normalizeTestName(`${filePrefix} > ${fullName}`);
5598
+ }
5596
5599
  function buildUniqueTestName(fullName, url) {
5597
5600
  const normalizedPath = normalizeTestFilePath(url);
5598
5601
  if (normalizedPath) {
@@ -5604,16 +5607,16 @@ function buildUniqueTestName(fullName, url) {
5604
5607
  // src/coverage/coverage-mapper.ts
5605
5608
  function mapCoverageToInspectorIds(rawCoverage, executionOrder, testHierarchy, logger) {
5606
5609
  if (!rawCoverage?.perTest || Object.keys(rawCoverage.perTest).length === 0) {
5607
- return rawCoverage ?? undefined;
5610
+ return { coverage: rawCoverage ?? undefined, inspectorIdToProjectFile: new Map };
5608
5611
  }
5609
5612
  const firstKey = Object.keys(rawCoverage.perTest)[0];
5610
5613
  if (/@@test-\d+$/.test(firstKey)) {
5611
5614
  return mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger);
5612
5615
  }
5613
5616
  if (/^test-\d+$/.test(firstKey)) {
5614
- return mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger);
5617
+ return { coverage: mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger), inspectorIdToProjectFile: new Map };
5615
5618
  }
5616
- return rawCoverage;
5619
+ return { coverage: rawCoverage, inspectorIdToProjectFile: new Map };
5617
5620
  }
5618
5621
  function countPerTestAppearances(perTestEntries) {
5619
5622
  const appearances = new Map;
@@ -5671,22 +5674,23 @@ function stabilizeCoverage(coverage) {
5671
5674
  const newPerTest = buildFilteredPerTest(perTestEntries, promoteToStatic);
5672
5675
  return { static: newStatic, perTest: newPerTest };
5673
5676
  }
5674
- function buildFileToInspectorIds(executionOrder, testHierarchy) {
5675
- const fileToInspectorIds = new Map;
5676
- for (const inspectorId of executionOrder) {
5677
- const testInfo = testHierarchy.get(inspectorId);
5678
- if (!testInfo) {
5679
- continue;
5680
- }
5681
- const relFile = normalizeTestFilePath(testInfo.url) ?? "";
5682
- const bucket = fileToInspectorIds.get(relFile);
5683
- if (bucket) {
5684
- bucket.push(inspectorId);
5685
- } else {
5686
- fileToInspectorIds.set(relFile, [inspectorId]);
5687
- }
5677
+ function pairKeysWithInspectorIds(globallyOrderedPerTestKeys, executionOrder, testHierarchy, logger) {
5678
+ const nonSkipped = executionOrder.filter((id) => {
5679
+ const status = testHierarchy.get(id)?.status;
5680
+ return status !== "skip" && status !== "todo";
5681
+ });
5682
+ if (globallyOrderedPerTestKeys.length < nonSkipped.length) {
5683
+ logger?.warn("Coverage/execution count mismatch: %s coverage entries vs %s non-skipped executed tests. " + "Performing partial mapping for %s tests.", globallyOrderedPerTestKeys.length, nonSkipped.length, Math.min(globallyOrderedPerTestKeys.length, nonSkipped.length));
5684
+ }
5685
+ const pairCount = Math.min(globallyOrderedPerTestKeys.length, nonSkipped.length);
5686
+ const pairs = [];
5687
+ for (let i = 0;i < pairCount; i++) {
5688
+ const key = globallyOrderedPerTestKeys[i];
5689
+ const sepIdx = key.indexOf("@@");
5690
+ const filePrefix = sepIdx === -1 ? key : key.slice(0, sepIdx);
5691
+ pairs.push({ filePrefix, inspectorId: nonSkipped[i] });
5688
5692
  }
5689
- return fileToInspectorIds;
5693
+ return pairs;
5690
5694
  }
5691
5695
  function resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logger) {
5692
5696
  return counterIds.map((key) => {
@@ -5695,51 +5699,115 @@ function resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logge
5695
5699
  const counterStr = key.slice(sepIdx + 2 + "test-".length);
5696
5700
  const n = Number.parseInt(counterStr, 10);
5697
5701
  const fileIds = fileToInspectorIds.get(filePrefix);
5698
- const inspectorId = fileIds?.[n - 1];
5702
+ const clampedIdx = fileIds ? Math.min(n - 1, fileIds.length - 1) : undefined;
5703
+ const inspectorId = clampedIdx === undefined ? undefined : fileIds?.[clampedIdx];
5699
5704
  const testInfo = inspectorId === undefined ? undefined : testHierarchy.get(inspectorId);
5700
5705
  if (testInfo) {
5701
- return { name: buildUniqueTestName(testInfo.fullName, testInfo.url), testInfo };
5706
+ const testName = buildProjectFileTestName(filePrefix, testInfo.fullName);
5707
+ return { name: testName, testInfo, inspectorId };
5702
5708
  }
5703
5709
  logger?.warn('Coverage key %s: no inspector test found for file "%s" at position %s ' + "(file has %s tests in execution order). Skipping this test in coverage mapping.", key, filePrefix, n, fileToInspectorIds.get(filePrefix)?.length ?? 0);
5704
- return { name: `unknown-${key}`, testInfo: null };
5710
+ return { name: `unknown-${key}`, testInfo: null, inspectorId: undefined };
5705
5711
  });
5706
5712
  }
5707
- function buildRemappedPerTest(counterIds, resolved, rawPerTest) {
5708
- const nameCounts = new Map;
5709
- for (const { name } of resolved) {
5710
- nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);
5713
+ function buildNameInspectorIds(resolved) {
5714
+ const nameInspectorIds = new Map;
5715
+ for (const { name, inspectorId, testInfo } of resolved) {
5716
+ if (!testInfo) {
5717
+ continue;
5718
+ }
5719
+ let ids = nameInspectorIds.get(name);
5720
+ if (!ids) {
5721
+ ids = new Set;
5722
+ nameInspectorIds.set(name, ids);
5723
+ }
5724
+ ids.add(inspectorId);
5711
5725
  }
5726
+ return nameInspectorIds;
5727
+ }
5728
+ function resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes) {
5729
+ const distinctIds = nameInspectorIds.get(baseName);
5730
+ if ((distinctIds?.size ?? 1) <= 1) {
5731
+ return baseName;
5732
+ }
5733
+ const key_ = `${inspectorId}/${baseName}`;
5734
+ const existingIndex = nameIndexes.get(key_);
5735
+ if (existingIndex === undefined) {
5736
+ const nextIndex = nameIndexes.get(baseName) ?? 0;
5737
+ nameIndexes.set(key_, nextIndex);
5738
+ nameIndexes.set(baseName, nextIndex + 1);
5739
+ return `${baseName} [${nextIndex}]`;
5740
+ }
5741
+ return `${baseName} [${existingIndex}]`;
5742
+ }
5743
+ function buildRemappedPerTest(counterIds, resolved, rawPerTest) {
5744
+ const nameInspectorIds = buildNameInspectorIds(resolved);
5712
5745
  const remappedPerTest = {};
5713
5746
  const nameIndexes = new Map;
5714
5747
  for (const [i, key] of counterIds.entries()) {
5715
- const { name: baseName, testInfo } = resolved[i];
5748
+ const { name: baseName, testInfo, inspectorId } = resolved[i];
5716
5749
  if (!testInfo) {
5717
5750
  continue;
5718
5751
  }
5719
- const count = nameCounts.get(baseName) ?? 1;
5720
- let finalName = baseName;
5721
- if (count > 1) {
5722
- const index = nameIndexes.get(baseName) ?? 0;
5723
- finalName = `${baseName} [${index}]`;
5724
- nameIndexes.set(baseName, index + 1);
5752
+ const finalName = resolveEachTestName(baseName, inspectorId, nameInspectorIds, nameIndexes);
5753
+ const incoming = rawPerTest[key];
5754
+ const existing = remappedPerTest[finalName];
5755
+ if (existing) {
5756
+ for (const [mutantId, count_] of Object.entries(incoming)) {
5757
+ existing[mutantId] = (existing[mutantId] ?? 0) + count_;
5758
+ }
5759
+ } else {
5760
+ remappedPerTest[finalName] = { ...incoming };
5725
5761
  }
5726
- remappedPerTest[finalName] = rawPerTest[key];
5727
5762
  }
5728
5763
  return remappedPerTest;
5729
5764
  }
5765
+ function warnInteriorGapIfPresent(pairs, testHierarchy, logger) {
5766
+ const warnedFiles = new Set;
5767
+ for (const { filePrefix, inspectorId } of pairs) {
5768
+ const testUrl = testHierarchy.get(inspectorId)?.url;
5769
+ if (!testUrl) {
5770
+ continue;
5771
+ }
5772
+ const inspectorFile = normalizeTestFilePath(testUrl);
5773
+ if (!inspectorFile || testUrl.includes("node_modules")) {
5774
+ continue;
5775
+ }
5776
+ if (filePrefix !== inspectorFile && !warnedFiles.has(filePrefix)) {
5777
+ warnedFiles.add(filePrefix);
5778
+ logger?.warn('Interior coverage gap detected for "%s": coverage key paired with inspector test from "%s". ' + "Some tests may have been aborted mid-run (e.g. beforeAll failure). Coverage mapping may be inaccurate.", filePrefix, inspectorFile);
5779
+ }
5780
+ }
5781
+ }
5730
5782
  function mapFilePrefixedCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5731
- const fileToInspectorIds = buildFileToInspectorIds(executionOrder, testHierarchy);
5732
- const counterIds = Object.keys(rawCoverage.perTest).toSorted((a, b) => {
5783
+ const globallyOrderedKeys = Object.keys(rawCoverage.perTest);
5784
+ const pairs = pairKeysWithInspectorIds(globallyOrderedKeys, executionOrder, testHierarchy, logger);
5785
+ const fileToInspectorIds = new Map;
5786
+ const inspectorIdToProjectFile = new Map;
5787
+ for (const { filePrefix, inspectorId } of pairs) {
5788
+ const bucket = fileToInspectorIds.get(filePrefix);
5789
+ if (bucket) {
5790
+ bucket.push(inspectorId);
5791
+ } else {
5792
+ fileToInspectorIds.set(filePrefix, [inspectorId]);
5793
+ }
5794
+ inspectorIdToProjectFile.set(inspectorId, filePrefix);
5795
+ }
5796
+ if (globallyOrderedKeys.length === pairs.length) {
5797
+ warnInteriorGapIfPresent(pairs, testHierarchy, logger);
5798
+ }
5799
+ const counterIds = globallyOrderedKeys.toSorted((a, b) => {
5733
5800
  const nA = Number.parseInt(a.split("@@test-")[1] ?? "0", 10);
5734
5801
  const nB = Number.parseInt(b.split("@@test-")[1] ?? "0", 10);
5735
5802
  return nA - nB;
5736
5803
  });
5737
5804
  const resolved = resolveCounterKeys(counterIds, fileToInspectorIds, testHierarchy, logger);
5738
5805
  const remappedPerTest = buildRemappedPerTest(counterIds, resolved, rawCoverage.perTest);
5739
- return stabilizeCoverage({
5806
+ const coverage = stabilizeCoverage({
5740
5807
  static: rawCoverage.static,
5741
5808
  perTest: remappedPerTest
5742
5809
  });
5810
+ return { coverage, inspectorIdToProjectFile };
5743
5811
  }
5744
5812
  function mapLegacyCounterKeys(rawCoverage, executionOrder, testHierarchy, logger) {
5745
5813
  const counterIds = Object.keys(rawCoverage.perTest).toSorted((a, b) => Number.parseInt(a.split("-")[1] ?? "0", 10) - Number.parseInt(b.split("-")[1] ?? "0", 10));
@@ -6189,7 +6257,66 @@ ${stderr}`;
6189
6257
  }
6190
6258
 
6191
6259
  // src/process-runner.ts
6260
+ import { spawn as spawn2 } from "node:child_process";
6261
+
6262
+ // src/utils/process-rss.ts
6192
6263
  import { spawn } from "node:child_process";
6264
+ import { readFile as readFile3 } from "node:fs/promises";
6265
+ async function getProcessRssBytes(pid) {
6266
+ return process.platform === "linux" ? getLinuxRss(pid) : getPsRss(pid);
6267
+ }
6268
+ function parseVmRss(statusContent) {
6269
+ const match = /^VmRSS:\s+(\d+)\s+kB$/m.exec(statusContent);
6270
+ return match ? Number(match[1]) * 1024 : null;
6271
+ }
6272
+ async function getLinuxRss(pid) {
6273
+ try {
6274
+ const status = await readFile3(`/proc/${pid}/status`, "utf8");
6275
+ return parseVmRss(status);
6276
+ } catch {
6277
+ return null;
6278
+ }
6279
+ }
6280
+ function parsePsRssOutput(output) {
6281
+ const trimmed = output.trim();
6282
+ if (trimmed === "") {
6283
+ return null;
6284
+ }
6285
+ const kb = Number(trimmed);
6286
+ return Number.isFinite(kb) ? kb * 1024 : null;
6287
+ }
6288
+ async function getPsRss(pid) {
6289
+ return new Promise((resolve3) => {
6290
+ let child;
6291
+ try {
6292
+ child = spawn("ps", ["-o", "rss=", "-p", String(pid)], { stdio: ["ignore", "pipe", "ignore"] });
6293
+ } catch {
6294
+ resolve3(null);
6295
+ return;
6296
+ }
6297
+ let output = "";
6298
+ child.stdout.on("data", (data) => {
6299
+ output += data.toString();
6300
+ });
6301
+ child.on("close", (code) => {
6302
+ resolve3(code === 0 ? parsePsRssOutput(output) : null);
6303
+ });
6304
+ child.on("error", () => {
6305
+ resolve3(null);
6306
+ });
6307
+ });
6308
+ }
6309
+
6310
+ // src/process-runner.ts
6311
+ var KILL_GRACE_PERIOD_MS = 500;
6312
+ function killWithEscalation(childProcess, isClosed, gracePeriodMs) {
6313
+ childProcess.kill("SIGTERM");
6314
+ setTimeout(() => {
6315
+ if (!isClosed()) {
6316
+ childProcess.kill("SIGKILL");
6317
+ }
6318
+ }, gracePeriodMs);
6319
+ }
6193
6320
  async function runBunTests(options) {
6194
6321
  const args = ["test"];
6195
6322
  if (options.inspectWaitPort) {
@@ -6210,6 +6337,9 @@ async function runBunTests(options) {
6210
6337
  if (options.sequentialMode) {
6211
6338
  args.push("--concurrency=1");
6212
6339
  }
6340
+ if (options.smol) {
6341
+ args.push("--smol");
6342
+ }
6213
6343
  if (options.bunArgs && options.bunArgs.length > 0) {
6214
6344
  args.push(...options.bunArgs);
6215
6345
  }
@@ -6234,8 +6364,11 @@ async function runBunTests(options) {
6234
6364
  const stderrChunks = [];
6235
6365
  let timedOut = false;
6236
6366
  let processKilled = false;
6367
+ let memoryLimitExceeded = false;
6368
+ let hasClosed = false;
6369
+ let rssIntervalHandle;
6237
6370
  if (options.signal?.aborted) {
6238
- resolve3({ stdout: "", stderr: "", exitCode: null, timedOut: true });
6371
+ resolve3({ stdout: "", stderr: "", exitCode: null, timedOut: true, memoryLimitExceeded: false });
6239
6372
  return;
6240
6373
  }
6241
6374
  const spawnOpts = {
@@ -6243,24 +6376,51 @@ async function runBunTests(options) {
6243
6376
  stdio: ["ignore", "pipe", "pipe"],
6244
6377
  cwd: process.cwd()
6245
6378
  };
6246
- const childProcess = spawn(options.bunPath, args, spawnOpts);
6379
+ const childProcess = spawn2(options.bunPath, args, spawnOpts);
6247
6380
  const timeoutHandle = setTimeout(() => {
6248
6381
  timedOut = true;
6249
6382
  processKilled = true;
6250
- childProcess.kill("SIGKILL");
6383
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6251
6384
  }, options.timeout);
6252
6385
  if (options.signal) {
6253
6386
  const onAbort = () => {
6254
6387
  clearTimeout(timeoutHandle);
6255
6388
  processKilled = true;
6256
6389
  timedOut = true;
6257
- childProcess.kill("SIGTERM");
6258
- setTimeout(() => {
6259
- childProcess.kill("SIGKILL");
6260
- }, 500);
6390
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6261
6391
  };
6262
6392
  options.signal.addEventListener("abort", onAbort, { once: true });
6263
6393
  }
6394
+ if (options.maxChildRss !== undefined) {
6395
+ const rssLimit = options.maxChildRss;
6396
+ const checkMemoryCeiling = async () => {
6397
+ if (hasClosed || memoryLimitExceeded) {
6398
+ return;
6399
+ }
6400
+ const pid = childProcess.pid;
6401
+ if (pid === undefined) {
6402
+ return;
6403
+ }
6404
+ const rssBytes = await getProcessRssBytes(pid);
6405
+ if (rssBytes === null || hasClosed) {
6406
+ return;
6407
+ }
6408
+ if (rssBytes > rssLimit) {
6409
+ memoryLimitExceeded = true;
6410
+ timedOut = true;
6411
+ processKilled = true;
6412
+ if (rssIntervalHandle) {
6413
+ clearInterval(rssIntervalHandle);
6414
+ }
6415
+ options.onMemoryLimitExceeded?.(rssBytes);
6416
+ killWithEscalation(childProcess, () => hasClosed, KILL_GRACE_PERIOD_MS);
6417
+ }
6418
+ };
6419
+ rssIntervalHandle = setInterval(() => {
6420
+ checkMemoryCeiling();
6421
+ }, options.rssCheckIntervalMs ?? 1000);
6422
+ rssIntervalHandle.unref();
6423
+ }
6264
6424
  if (childProcess.stdout) {
6265
6425
  childProcess.stdout.on("data", (data) => {
6266
6426
  stdoutChunks.push(data);
@@ -6281,23 +6441,33 @@ async function runBunTests(options) {
6281
6441
  });
6282
6442
  }
6283
6443
  childProcess.on("close", (code) => {
6444
+ hasClosed = true;
6284
6445
  clearTimeout(timeoutHandle);
6446
+ if (rssIntervalHandle) {
6447
+ clearInterval(rssIntervalHandle);
6448
+ }
6285
6449
  resolve3({
6286
6450
  stdout: Buffer.concat(stdoutChunks).toString(),
6287
6451
  stderr: Buffer.concat(stderrChunks).toString(),
6288
6452
  exitCode: processKilled ? null : code,
6289
- timedOut
6453
+ timedOut,
6454
+ memoryLimitExceeded
6290
6455
  });
6291
6456
  });
6292
6457
  childProcess.on("error", (error) => {
6458
+ hasClosed = true;
6293
6459
  clearTimeout(timeoutHandle);
6460
+ if (rssIntervalHandle) {
6461
+ clearInterval(rssIntervalHandle);
6462
+ }
6294
6463
  const stderrOutput = Buffer.concat(stderrChunks).toString();
6295
6464
  resolve3({
6296
6465
  stdout: Buffer.concat(stdoutChunks).toString(),
6297
6466
  stderr: `${stderrOutput}
6298
6467
  Process error: ${error.message}`,
6299
6468
  exitCode: null,
6300
- timedOut
6469
+ timedOut,
6470
+ memoryLimitExceeded
6301
6471
  });
6302
6472
  });
6303
6473
  });
@@ -6421,7 +6591,7 @@ class SyncServer {
6421
6591
  }
6422
6592
  }
6423
6593
  // src/utils/bunfig-sanitizer.ts
6424
- import { readFile as readFile3, unlink as unlink3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
6594
+ import { readFile as readFile4, unlink as unlink3, writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
6425
6595
  import path2 from "node:path";
6426
6596
 
6427
6597
  // node_modules/smol-toml/dist/error.js
@@ -7545,7 +7715,7 @@ async function generateSanitizedBunfig(projectCwd, tmpDir) {
7545
7715
  let rawConfig = {};
7546
7716
  const bunfigPath = path2.join(projectCwd, "bunfig.toml");
7547
7717
  try {
7548
- const content = await readFile3(bunfigPath, "utf8");
7718
+ const content = await readFile4(bunfigPath, "utf8");
7549
7719
  rawConfig = parse(content);
7550
7720
  } catch (err) {
7551
7721
  if (err.code !== "ENOENT") {
@@ -7724,6 +7894,9 @@ class BunTestRunner {
7724
7894
  bunArgs;
7725
7895
  testFilesOverride;
7726
7896
  mutateGlobs;
7897
+ smol;
7898
+ maxChildRss;
7899
+ rssCheckIntervalMs;
7727
7900
  preloadScriptPath;
7728
7901
  coverageFilePath;
7729
7902
  sanitizedBunfigPath;
@@ -7736,6 +7909,7 @@ class BunTestRunner {
7736
7909
  cachedEagerModules;
7737
7910
  cachedEagerModulesCwd;
7738
7911
  lastRegistryTmpPath;
7912
+ currentAbortController;
7739
7913
  constructor(logger, options) {
7740
7914
  this.logger = logger;
7741
7915
  const bunOptions = options.bun ?? {};
@@ -7744,6 +7918,9 @@ class BunTestRunner {
7744
7918
  this.inspectorTimeout = bunOptions.inspectorTimeout ?? 5000;
7745
7919
  this.env = bunOptions.env;
7746
7920
  this.bunArgs = bunOptions.bunArgs;
7921
+ this.smol = bunOptions.smol ?? false;
7922
+ this.maxChildRss = bunOptions.maxChildRss;
7923
+ this.rssCheckIntervalMs = bunOptions.rssCheckIntervalMs;
7747
7924
  if (bunOptions.testFiles?.length === 0) {
7748
7925
  this.logger.warn("bun.testFiles was set to an empty array — treating as undefined and falling back to auto-discovery");
7749
7926
  this.testFilesOverride = undefined;
@@ -7756,7 +7933,10 @@ class BunTestRunner {
7756
7933
  timeout: this.timeout,
7757
7934
  inspectorTimeout: this.inspectorTimeout,
7758
7935
  env: this.env,
7759
- bunArgs: this.bunArgs
7936
+ bunArgs: this.bunArgs,
7937
+ smol: this.smol,
7938
+ maxChildRss: this.maxChildRss,
7939
+ rssCheckIntervalMs: this.rssCheckIntervalMs
7760
7940
  });
7761
7941
  if (this.testFilesOverride?.some((p) => path4.isAbsolute(p))) {
7762
7942
  const isSandbox = process.cwd().includes(".stryker-tmp/sandbox-");
@@ -7870,7 +8050,7 @@ class BunTestRunner {
7870
8050
  }
7871
8051
  }
7872
8052
  }
7873
- buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs) {
8053
+ buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile) {
7874
8054
  if (executionOrder.length === 0) {
7875
8055
  return parsed.tests.map((t) => {
7876
8056
  const normalizedName = normalizeTestName(t.name);
@@ -7914,7 +8094,9 @@ class BunTestRunner {
7914
8094
  timeSpentMs: timePerTest
7915
8095
  };
7916
8096
  }
7917
- const uniqueName = buildUniqueTestName(testInfo.fullName, testInfo.url);
8097
+ const projectFile = inspectorIdToProjectFile?.get(inspectorId);
8098
+ const uniqueName = projectFile ? buildProjectFileTestName(projectFile, testInfo.fullName) : buildUniqueTestName(testInfo.fullName, testInfo.url);
8099
+ const fileName = projectFile ?? normalizeTestFilePath(testInfo.url);
7918
8100
  const status = testInfo.status;
7919
8101
  const elapsed = testInfo.elapsed === undefined ? timePerTest : Math.round(testInfo.elapsed / 1e6);
7920
8102
  const startPosition = testInfo.line === undefined ? undefined : { line: testInfo.line, column: 0 };
@@ -7923,7 +8105,7 @@ class BunTestRunner {
7923
8105
  return {
7924
8106
  id: uniqueName,
7925
8107
  name: uniqueName,
7926
- fileName: normalizeTestFilePath(testInfo.url),
8108
+ fileName,
7927
8109
  startPosition,
7928
8110
  status: TestStatus.Failed,
7929
8111
  failureMessage: parsedTest?.failureMessage ?? testInfo.error?.message ?? "Test failed",
@@ -7934,7 +8116,7 @@ class BunTestRunner {
7934
8116
  return {
7935
8117
  id: uniqueName,
7936
8118
  name: uniqueName,
7937
- fileName: normalizeTestFilePath(testInfo.url),
8119
+ fileName,
7938
8120
  startPosition,
7939
8121
  status: TestStatus.Skipped,
7940
8122
  timeSpentMs: elapsed
@@ -7943,7 +8125,7 @@ class BunTestRunner {
7943
8125
  return {
7944
8126
  id: uniqueName,
7945
8127
  name: uniqueName,
7946
- fileName: normalizeTestFilePath(testInfo.url),
8128
+ fileName,
7947
8129
  startPosition,
7948
8130
  status: TestStatus.Success,
7949
8131
  timeSpentMs: elapsed
@@ -7981,6 +8163,7 @@ class BunTestRunner {
7981
8163
  async dryRun() {
7982
8164
  this.logger.debug("Running dry run with inspector-based coverage collection...");
7983
8165
  const abortController = new AbortController;
8166
+ this.currentAbortController = abortController;
7984
8167
  const inspectPort = await getAvailablePort();
7985
8168
  const syncPort = await getAvailablePort();
7986
8169
  this.logger.debug("Using inspector port: %d, sync port: %d", inspectPort, syncPort);
@@ -8016,6 +8199,12 @@ class BunTestRunner {
8016
8199
  syncPort,
8017
8200
  testFiles,
8018
8201
  signal: abortController.signal,
8202
+ smol: this.smol,
8203
+ maxChildRss: this.maxChildRss,
8204
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
8205
+ onMemoryLimitExceeded: (rssBytes) => {
8206
+ this.logger.warn("bun test child exceeded maxChildRss (%d bytes observed) during dryRun — killing and reporting as a timeout for this run", rssBytes);
8207
+ },
8019
8208
  onInspectorReady: (url) => {
8020
8209
  inspectorUrl = url;
8021
8210
  }
@@ -8073,8 +8262,8 @@ exit=%s timedOut=%s
8073
8262
  if (earlyResult) {
8074
8263
  return earlyResult;
8075
8264
  }
8076
- const mutantCoverage = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8077
- const tests = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs);
8265
+ const { coverage: mutantCoverage, inspectorIdToProjectFile } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8266
+ const tests = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8078
8267
  tests.sort((a, b) => a.name.localeCompare(b.name));
8079
8268
  await this.buildAndPersistTestRegistry(tests);
8080
8269
  return {
@@ -8084,6 +8273,9 @@ exit=%s timedOut=%s
8084
8273
  };
8085
8274
  } finally {
8086
8275
  abortController.abort();
8276
+ if (this.currentAbortController === abortController) {
8277
+ this.currentAbortController = undefined;
8278
+ }
8087
8279
  await syncServer.close();
8088
8280
  }
8089
8281
  }
@@ -8141,19 +8333,35 @@ exit=%s timedOut=%s
8141
8333
  const mutantCwd = process.cwd();
8142
8334
  const bunfigPath = this.sanitizedBunfigPath && this.sanitizedBunfigCwd === mutantCwd ? this.sanitizedBunfigPath : await this.ensureSanitizedBunfig();
8143
8335
  this.cachedTestFiles = await this.getOrDiscoverTestFiles();
8144
- const result = await runBunTests({
8145
- bunPath: this.bunPath,
8146
- timeout: this.timeout,
8147
- env: this.env,
8148
- bunArgs: this.bunArgs,
8149
- bunfigPath,
8150
- activeMutant: options.activeMutant.id,
8151
- bail: true,
8152
- sequentialMode: true,
8153
- preloadScript: this.preloadScriptPath,
8154
- testNamePattern,
8155
- testFiles: this.cachedTestFiles
8156
- });
8336
+ const abortController = new AbortController;
8337
+ this.currentAbortController = abortController;
8338
+ let result;
8339
+ try {
8340
+ result = await runBunTests({
8341
+ bunPath: this.bunPath,
8342
+ timeout: this.timeout,
8343
+ env: this.env,
8344
+ bunArgs: this.bunArgs,
8345
+ bunfigPath,
8346
+ activeMutant: options.activeMutant.id,
8347
+ bail: true,
8348
+ sequentialMode: true,
8349
+ preloadScript: this.preloadScriptPath,
8350
+ testNamePattern,
8351
+ testFiles: this.cachedTestFiles,
8352
+ signal: abortController.signal,
8353
+ smol: this.smol,
8354
+ maxChildRss: this.maxChildRss,
8355
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
8356
+ onMemoryLimitExceeded: (rssBytes) => {
8357
+ 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);
8358
+ }
8359
+ });
8360
+ } finally {
8361
+ if (this.currentAbortController === abortController) {
8362
+ this.currentAbortController = undefined;
8363
+ }
8364
+ }
8157
8365
  if (result.timedOut) {
8158
8366
  this.logger.debug("Mutant run timed out");
8159
8367
  return {
@@ -8229,16 +8437,17 @@ ${result.stderr}`
8229
8437
  return null;
8230
8438
  }
8231
8439
  async collectAndRemapCoverage(testHierarchy, executionOrder) {
8440
+ const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8232
8441
  if (!this.coverageFilePath) {
8233
- return;
8442
+ return { coverage: undefined, inspectorIdToProjectFile: new Map };
8234
8443
  }
8235
8444
  const rawCoverage = await collectCoverage(this.coverageFilePath, this.logger);
8236
8445
  await cleanupCoverageFile(this.coverageFilePath);
8237
8446
  if (!rawCoverage) {
8238
- return;
8447
+ return { coverage: undefined, inspectorIdToProjectFile: new Map };
8239
8448
  }
8240
- const testMap = new Map(testHierarchy.map((t) => [t.id, t]));
8241
- return mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8449
+ const { coverage, inspectorIdToProjectFile } = mapCoverageToInspectorIds(rawCoverage, executionOrder, testMap, this.logger);
8450
+ return { coverage, inspectorIdToProjectFile };
8242
8451
  }
8243
8452
  buildLocalTestFilterIndex(testFilter) {
8244
8453
  const localRegistry = new Set(testFilter);
@@ -8292,6 +8501,11 @@ ${result.stderr}`
8292
8501
  }
8293
8502
  async dispose() {
8294
8503
  this.logger.debug("Disposing BunTestRunner");
8504
+ if (this.currentAbortController) {
8505
+ this.logger.debug("Aborting in-flight bun test child during dispose");
8506
+ this.currentAbortController.abort();
8507
+ this.currentAbortController = undefined;
8508
+ }
8295
8509
  if (this.preloadScriptPath) {
8296
8510
  this.logger.debug("Cleaning up preload script: %s", this.preloadScriptPath);
8297
8511
  await cleanupPreloadScript(this.preloadScriptPath);
@@ -8366,6 +8580,22 @@ var strykerValidationSchema = {
8366
8580
  items: {
8367
8581
  type: "string"
8368
8582
  }
8583
+ },
8584
+ smol: {
8585
+ type: "boolean",
8586
+ description: "Pass Bun's --smol flag to every child (smaller JavaScriptCore heap, some speed cost). Recommended on memory-constrained machines (default: false).",
8587
+ default: false
8588
+ },
8589
+ maxChildRss: {
8590
+ type: "number",
8591
+ minimum: 0,
8592
+ 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."
8593
+ },
8594
+ rssCheckIntervalMs: {
8595
+ type: "number",
8596
+ minimum: 0,
8597
+ description: "Poll interval in milliseconds for the maxChildRss check (default: 1000).",
8598
+ default: 1000
8369
8599
  }
8370
8600
  },
8371
8601
  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.1",
3
+ "version": "1.3.0",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",