@hughescr/stryker-bun-runner 1.8.2 → 1.8.3

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
@@ -1156,12 +1156,21 @@ More: [Mutant runs](docs/internals.md#mutant-runs), [the dry run in detail](docs
1156
1156
  - **Killed** when a test fails, or when bun reports an error outside any test (a test file that
1157
1157
  fails to load, a describe body or a hook that throws) with a failure or error count but no
1158
1158
  failing test. `killedBy` lists the failing tests. With no failing test it lists the selected
1159
- tests of each file that failed to load only when bun's summary shows that no test ran at all
1160
- (passing tests are hidden in mutant runs, so nothing else shows whose tests ran), and the error
1161
- was printed right below the header of one of the files the run handed bun; otherwise it is empty
1162
- and the mutant re-runs on every incremental run. Stryker reuses a Killed result while at least
1163
- one test in `killedBy` is unchanged; it does not track a test file's top-level code or its
1164
- imports, so an edit there alone does not make it re-run the mutant. `--force` re-runs everything.
1159
+ tests of each file that failed to load (covering tests the run's `--test-name-pattern` certainly
1160
+ selected, when it had one), when the error was printed right below the header of one of the
1161
+ files the run handed bun and bun's summary shows that no test ran (passing tests are hidden in
1162
+ mutant runs, so nothing else shows whose tests ran). When other tests may have run beside the
1163
+ error (another file's tests passed first, or the whole suite ran without bail), the runner runs
1164
+ that file alone with the same mutant, up to three files per mutant, and then once more alone
1165
+ without the mutant (a control run, made once per file and pattern per worker), and lists its
1166
+ tests only if it fails to load alone with the mutant with no test run and loads alone without
1167
+ it. These runs spend what is left of the mutant's time limit, less the time stopping them can
1168
+ take, so with a per-mutant timeout under about four seconds they are not made; none starts
1169
+ once the runner is being disposed, and none ever changes the result from Killed. Otherwise
1170
+ `killedBy` is empty, the runner warns why, and the mutant re-runs on every incremental run.
1171
+ Stryker reuses a Killed result while at least one test in `killedBy` is unchanged; it does not
1172
+ track a test file's top-level code or its imports, so an edit there alone does not make it
1173
+ re-run the mutant. `--force` re-runs everything.
1165
1174
  - **Survived** when every selected test passes and bun finishes the run (prints its summary).
1166
1175
  - **Timeout** when the hit limit is exceeded, the time limit is reached, or `bun.maxChildRss` is
1167
1176
  exceeded.
@@ -1432,7 +1441,7 @@ also fails; see [Inspector diagnostics](docs/internals.md#inspector-diagnostics)
1432
1441
  | `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`. |
1433
1442
  | `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. |
1434
1443
  | `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 `Failed to write dryRun registry file` warning; re-run. |
1435
- | `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. Either a failing test's name matched no dry-run test, or bun reported an error outside any test and no failing test, and the runner could not tell for certain which file's tests it stopped: another test passed in the same run, or the error was not printed right below the header of one file the run handed bun. | Usually harmless: expected for a mutant that stops one file loading in a run where other files' tests pass, or that makes a describe body or hook throw. |
1444
+ | `could not be resolved to dry-run test ids` or `no killing test identifiable — emitting empty killedBy (<reason>)` | A killed mutant whose killing test is unknown; it re-runs on every incremental run. Either a failing test's name matched no dry-run test, or bun reported an error outside any test and no failing test, and the runner could not tell for certain which file's tests it stopped. The reason in parentheses names the condition: no file list or no test index, an error not printed right below the header of one file the run handed bun, no selected test in that file (or none the run's `--test-name-pattern` certainly selected), or other tests that may have run beside the error, with what the run of that file alone showed instead of a load failure (it passed, a test failed, it was stopped, ...), that the file fails to load alone without the mutant too (its control run), why it was not run alone (too little of the time limit left, the runner being disposed), or that the run alone could not be started. | Usually harmless: expected for a mutant that makes a describe body or hook throw, or that leaves an error behind that surfaces while a later file loads. |
1436
1445
  | `bun test child exceeded maxChildRss` | A run went over `bun.maxChildRss`; scored Timeout. | Expected for runaway mutants; raise the limit if many hit it. |
1437
1446
  | `stryker-bun-runner: <file> was present in bun's module cache in this mutant run (mutant <id>, tests: <tests>) when the mutant first executed, and the dry run neither imported it before the tests nor saw it load.` ..., then Stryker stops with `Unexpected error occurred while running Stryker` and exit code 1 | A test loaded a mutated file that the dry run left out (a package loaded it, say), or replaced it with `mock.module()`. The runner stops the whole Stryker run, which saves no final report and no incremental file. | See [If a mutant run stops the campaign](#if-a-mutant-run-stops-the-campaign). |
1438
1447
  | `A mutant run could not use its watch list (<problem>), so it could not check for files the dry run missed; its result stands.` | The runner could not read the list of mutated files that the dry run left out, so this mutant run could not check whether a test loaded one of them. | Check the temporary directory; re-run if it recurs. |
package/dist/index.d.ts CHANGED
@@ -167,6 +167,17 @@ export declare class BunTestRunner implements TestRunner {
167
167
  */
168
168
  private currentAbortController?;
169
169
  /**
170
+ * Set when dispose() begins, and cleared by init(): from then on no run of a file alone (nor a
171
+ * control run) is started, since dispose() is removing the preload and bunfig they use.
172
+ */
173
+ private disposing;
174
+ /**
175
+ * The control runs' conclusive verdicts (see judgeControlRun and isCacheableControl), for the
176
+ * life of this runner, by controlRunKey: a control run has no mutant, so its outcome for a
177
+ * file and test-name pattern is the same for every mutant, and each costs one spawn per worker.
178
+ */
179
+ private readonly controlVerdicts;
180
+ /**
170
181
  * The drain handshake's silence bound (see src/drain-handshake.ts). Not an
171
182
  * option: a subclass in tests/00-integration/isolate-integration.test.ts
172
183
  * shortens it, to make a real bun child's fallback wait short.
@@ -922,6 +933,46 @@ export declare class BunTestRunner implements TestRunner {
922
933
  * left of the same deadline, because Stryker's timer covers both spawns.
923
934
  */
924
935
  private executeMutantRun;
936
+ /**
937
+ * Spawn one `bun test` child of a mutant run, and wait for it. Every spawn of a mutant run comes
938
+ * through here, so each gets the same environment (its preload variables aside: see
939
+ * buildChildEnv), bun arguments, mutant-run bunfig, preload, sequential mode, bail setting and
940
+ * memory limit, and is killed at its `spawn.timeout` (runBunTests: SIGTERM, then SIGKILL). The
941
+ * child's abort controller is tracked on `this` while it runs, so dispose() kills a child still
942
+ * in flight, as for dryRun().
943
+ */
944
+ private spawnMutantChild;
945
+ /**
946
+ * Run one file of a mutant run alone, with the same mutant and the same test-name pattern as the
947
+ * spawn that printed its error block, and judge whether it failed to load (see judgeSoloRun);
948
+ * when it did, run it alone once more with no mutant (the control run: see runControl) and
949
+ * confirm it only when that run shows the file loading (see withControl). A control verdict
950
+ * already known for the file and pattern is used instead of a control run, and one that says
951
+ * the file fails to load alone without the mutant spares the run alone too.
952
+ *
953
+ * The spawn is the mutant run's own (spawnMutantChild), with the same hit limit, killed by
954
+ * dispose(); it has no witness, which the run itself already passed, so it can add attribution
955
+ * but never change the run's verdict. Its time limit leaves room for its whole termination
956
+ * before the mutant run's deadline (see confirmationTimeout), from one read of the clock, and
957
+ * nothing is spawned when that room is not there or once dispose() has begun. It reports to no
958
+ * profile.
959
+ */
960
+ private runFileAlone;
961
+ /** The run of `candidate`'s file alone with the mutant, judged (see runFileAlone). */
962
+ private spawnAlone;
963
+ /**
964
+ * The control run of `candidate`'s file: alone, with NO mutant active, and otherwise spawned
965
+ * as its run alone was (same pattern, bail setting, bunfig, preload, memory limit; no hit limit,
966
+ * which counts the mutant's hits, and no witness), within the same deadline rule, and never
967
+ * once dispose() has begun. Its verdict (see judgeControlRun) is kept under `key` when it does
968
+ * not depend on this mutant run (isCacheableControl), and dispose() has not begun meanwhile.
969
+ */
970
+ private runControl;
971
+ /**
972
+ * What a control run's outcome depends on besides the runner's fixed settings: the child's
973
+ * working directory, the file, the test-name pattern, and the bail setting.
974
+ */
975
+ private controlRunKey;
925
976
  /**
926
977
  * Count a spawn that had covering tests but no pattern: it runs the whole suite instead of
927
978
  * just those tests, because the pattern was too long for argv or because this is the retry
@@ -1180,6 +1231,7 @@ export declare class BunTestRunner implements TestRunner {
1180
1231
  * test failed (a non-zero exit with a fail or error count: see
1181
1232
  * classifyRunWithoutFailedTest), the tests of the test files bun reported
1182
1233
  * failing to load, when they can be told (see creditFilesThatFailedToLoad).
1234
+ * When killedBy is empty, `refusal` says why.
1183
1235
  */
1184
1236
  private killersOf;
1185
1237
  /**
@@ -1193,19 +1245,40 @@ export declare class BunTestRunner implements TestRunner {
1193
1245
  * file Stryker's testFiles option left out, say) is never credited, and a spawn
1194
1246
  * that handed bun no list credits nothing.
1195
1247
  *
1248
+ * When the summary is all that refused that credit (other tests may have run
1249
+ * beside the blocks: another file's passing tests, or the whole suite without
1250
+ * bail), each such file with selected tests, up to MAX_SOLO_CONFIRMATIONS, is
1251
+ * run alone with the same mutant (runAlone, one child at a time, within the
1252
+ * mutant run's deadline), and a file is credited only when its run alone shows
1253
+ * the same evidence (its own block, and no test that ran: see judgeSoloRun) and
1254
+ * its control run alone with no mutant shows it loading (see judgeControlRun).
1255
+ * A run with no blocks, no file list or no index, or whose blocks' files have no
1256
+ * selected test, spawns nothing more, nor does a credit given directly.
1257
+ *
1196
1258
  * Selected means the mutant's covering tests when it has any (localRegistry),
1197
1259
  * also on a full-suite fallback: that run loaded more files than Stryker planned
1198
1260
  * for, and crediting only the planned tests keeps killedBy within the covering
1199
1261
  * set. Without covering tests (a static mutant, coverageAnalysis 'off' or 'all',
1200
1262
  * a run of Stryker's testFiles) every test of the file that ran in the dry run is
1201
- * selected.
1263
+ * selected. Either way, when the spawn had a --test-name-pattern, only the tests
1264
+ * that pattern certainly selects (loadFailures.selects): a covering test it left
1265
+ * out did not run, so it caught nothing. This holds for the direct credit and for
1266
+ * the credit after a run alone (which has the same pattern) alike.
1202
1267
  *
1203
1268
  * Every id comes from testIdsByFile, so each is a dry-run TestResult.id (see
1204
1269
  * resolveKilledBy for why nothing else may be). When nothing is credited the
1205
- * caller warns as for any other unattributable kill.
1270
+ * caller warns as for any other unattributable kill, with the refusal.
1206
1271
  */
1207
1272
  private creditFilesThatFailedToLoad;
1208
1273
  /**
1274
+ * Run each candidate of `confirmation` alone, one child at a time, and credit the ones whose
1275
+ * run alone confirms that they failed to load (see creditFromSoloRuns). A run alone that throws
1276
+ * or rejects (its spawn, say) confirms nothing, and the mutant run's own result stands. Once
1277
+ * dispose() has begun, no further candidate is run and nothing is credited from this path
1278
+ * (see creditAfterDisposal).
1279
+ */
1280
+ private confirmAlone;
1281
+ /**
1209
1282
  * WARN about failed test names that could not be resolved to dry-run test
1210
1283
  * ids (and are therefore dropped from killedBy by resolveKilledBy). WARN,
1211
1284
  * not debug — the old debug-level log is why the resulting cache poisoning
package/dist/index.js CHANGED
@@ -1603,22 +1603,30 @@ var metaRe = /[.*+?^${}()|[\]\\/]/g;
1603
1603
  function escapeRegex(str) {
1604
1604
  return str.replaceAll(metaRe, String.raw`\$&`);
1605
1605
  }
1606
+ function patternNameOf(id, testNameIndex) {
1607
+ const exact = testNameIndex?.get(id);
1608
+ if (exact !== undefined && exact.length > 0 && !exact.includes("\x00")) {
1609
+ return { name: exact, certain: true };
1610
+ }
1611
+ const firstSepIdx = id.indexOf(" > ");
1612
+ const stripped = firstSepIdx !== -1 && TEST_FILE_SUFFIX_RE.test(id.slice(0, firstSepIdx)) ? id.slice(firstSepIdx + 3) : id;
1613
+ const name = stripped.replace(dedupSuffixRe, "").replaceAll(" > ", " ");
1614
+ return { name, certain: name === stripped };
1615
+ }
1616
+ function testNamePatternSelector(pattern, testNameIndex) {
1617
+ const compiled = new RegExp(pattern);
1618
+ return (id) => {
1619
+ const { name, certain } = patternNameOf(id, testNameIndex);
1620
+ return certain && compiled.test(name);
1621
+ };
1622
+ }
1606
1623
  function buildTestNamePattern(testFilter, testNameIndex) {
1607
1624
  if (testFilter.length === 0) {
1608
1625
  return;
1609
1626
  }
1610
1627
  const alternatives = new Set;
1611
1628
  for (const id of testFilter) {
1612
- const exact = testNameIndex?.get(id);
1613
- if (exact !== undefined && exact.length > 0 && !exact.includes("\x00")) {
1614
- alternatives.add(escapeRegex(exact));
1615
- continue;
1616
- }
1617
- const firstSepIdx = id.indexOf(" > ");
1618
- let name = firstSepIdx !== -1 && TEST_FILE_SUFFIX_RE.test(id.slice(0, firstSepIdx)) ? id.slice(firstSepIdx + 3) : id;
1619
- name = name.replace(dedupSuffixRe, "");
1620
- name = name.replaceAll(" > ", " ");
1621
- name = escapeRegex(name);
1629
+ const name = escapeRegex(patternNameOf(id, testNameIndex).name);
1622
1630
  if (name.length > 0) {
1623
1631
  alternatives.add(name);
1624
1632
  }
@@ -2893,7 +2901,7 @@ class InspectorClient {
2893
2901
  }
2894
2902
  }
2895
2903
  // src/load-failure-killers.ts
2896
- import path9 from "node:path";
2904
+ import path11 from "node:path";
2897
2905
  import { TestStatus as TestStatus2 } from "@stryker-mutator/api/test-runner";
2898
2906
 
2899
2907
  // src/parsers/console-parser.ts
@@ -3099,6 +3107,65 @@ function readBunSummary(output) {
3099
3107
  }
3100
3108
  return summary;
3101
3109
  }
3110
+ var MAX_SUMMARY_LINES = 10;
3111
+ var SUMMARY_LINE_CHARS = 200;
3112
+ var BANNER_LINE = /^\s*bun test v\d/;
3113
+ function summaryLineIndexes(lines) {
3114
+ const lastIndex = lines.length - 1;
3115
+ const lastPass = lastLineMatching(lines, lastIndex, PASS_LINE, false);
3116
+ let ran = lastLineMatching(lines, lastIndex, RAN_LINE, false);
3117
+ if (ran !== undefined && lastPass !== undefined && lastPass.index > ran.index) {
3118
+ ran = undefined;
3119
+ }
3120
+ let block;
3121
+ if (ran === undefined) {
3122
+ block = lastPass === undefined ? [] : Array.from({ length: lines.length - lastPass.index }, (_, offset) => lastPass.index + offset);
3123
+ } else {
3124
+ const after = lines.slice(ran.index + 1);
3125
+ if (after.some((line) => BANNER_LINE.test(line))) {
3126
+ return [];
3127
+ }
3128
+ const ranIndex = ran.index;
3129
+ const start = lastLineMatching(lines, ranIndex - 1, PASS_LINE, true)?.index ?? ranIndex;
3130
+ const bail = after.flatMap((line, offset) => BAIL_LINE.test(line) ? [ranIndex + 1 + offset] : []);
3131
+ block = [...Array.from({ length: ranIndex + 1 - start }, (_, offset) => start + offset), ...bail];
3132
+ }
3133
+ return block.filter((index) => lines[index].trim() !== "");
3134
+ }
3135
+ function shownSummaryIndexes(lines, block) {
3136
+ const ends = block.filter((index) => RAN_LINE.test(lines[index]) || BAIL_LINE.test(lines[index]));
3137
+ const counts = block.filter((index) => COUNT_LINE.test(lines[index]));
3138
+ const rest = block.filter((index) => !ends.includes(index) && !counts.includes(index));
3139
+ return [...new Set([...ends, ...counts, ...rest])].slice(0, MAX_SUMMARY_LINES).toSorted((a, b) => a - b);
3140
+ }
3141
+ function bunSummaryLines(output) {
3142
+ const lines = stripAnsi(output).split(`
3143
+ `);
3144
+ return shownSummaryIndexes(lines, summaryLineIndexes(lines)).map((index) => lines[index].trim().slice(0, SUMMARY_LINE_CHARS));
3145
+ }
3146
+ function headWithSummary(text, limit) {
3147
+ const head = text.slice(0, limit);
3148
+ if (text.length <= limit) {
3149
+ return head;
3150
+ }
3151
+ const lines = text.split(`
3152
+ `);
3153
+ const plain = lines.map((line) => stripAnsi(line));
3154
+ const block = summaryLineIndexes(plain);
3155
+ if (block.length === 0) {
3156
+ return head;
3157
+ }
3158
+ const last = block.at(-1);
3159
+ const blockEnd = lines.slice(0, last + 1).reduce((offset, line) => offset + line.length + 1, 0) - 1;
3160
+ if (blockEnd <= limit) {
3161
+ return head;
3162
+ }
3163
+ const shown = shownSummaryIndexes(plain, block).map((index) => plain[index].trim().slice(0, SUMMARY_LINE_CHARS));
3164
+ return `${head}
3165
+ …
3166
+ ${shown.join(`
3167
+ `)}`;
3168
+ }
3102
3169
  function parseSummaryLines(output) {
3103
3170
  const bun = readBunSummary(output);
3104
3171
  const counts = { passed: bun.pass, failed: bun.fail, skipped: bun.skip };
@@ -3466,111 +3533,6 @@ function layOut(blocks, claims) {
3466
3533
  };
3467
3534
  }
3468
3535
 
3469
- // src/load-failure-killers.ts
3470
- var TEST_ID_FILE_SEPARATOR = " > ";
3471
- var GROUP_PREFIX = "::group::";
3472
- function indexTestIdsByFile(tests) {
3473
- const byFile = new Map;
3474
- const uncertain = new Set;
3475
- for (const test of tests) {
3476
- const file = test.fileName;
3477
- if (file === undefined) {
3478
- continue;
3479
- }
3480
- if (!test.id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`)) {
3481
- uncertain.add(file);
3482
- } else if (test.status !== TestStatus2.Skipped) {
3483
- const ids = byFile.get(file) ?? [];
3484
- ids.push(test.id);
3485
- byFile.set(file, ids);
3486
- }
3487
- }
3488
- for (const file of uncertain) {
3489
- byFile.delete(file);
3490
- }
3491
- return byFile;
3492
- }
3493
- function isTestIdsEntry(entry) {
3494
- return Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && Array.isArray(entry[1]) && entry[1].every((id) => typeof id === "string");
3495
- }
3496
- function parseTestIdsByFile(value, known) {
3497
- if (!Array.isArray(value)) {
3498
- return;
3499
- }
3500
- const byFile = new Map;
3501
- for (const entry of value) {
3502
- if (!isTestIdsEntry(entry) || byFile.has(entry[0])) {
3503
- return;
3504
- }
3505
- const [file, ids] = entry;
3506
- if (!ids.every((id) => known.has(id) && id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`))) {
3507
- return;
3508
- }
3509
- byFile.set(file, ids);
3510
- }
3511
- return byFile;
3512
- }
3513
- function runFileResolver(testFiles, cwd) {
3514
- const files = new Set(testFiles.map((file) => path9.resolve(cwd, file)));
3515
- const keyCounts = new Map;
3516
- for (const file of files) {
3517
- const key = dryRunKey(file, cwd);
3518
- keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1);
3519
- }
3520
- return (line) => {
3521
- if (!line.endsWith(":")) {
3522
- return;
3523
- }
3524
- const printed = line.slice(0, -1);
3525
- const candidates = printed.startsWith(GROUP_PREFIX) ? [printed, printed.slice(GROUP_PREFIX.length)] : [printed];
3526
- const matches = new Set(candidates.filter((candidate) => candidate !== "").map((candidate) => path9.resolve(cwd, candidate)).filter((file) => files.has(file)));
3527
- if (matches.size === 0) {
3528
- return;
3529
- }
3530
- const [file] = matches;
3531
- const key = dryRunKey(file, cwd);
3532
- return matches.size === 1 && keyCounts.get(key) === 1 && path9.resolve(cwd, key) === file ? file : null;
3533
- };
3534
- }
3535
- function dryRunKey(file, cwd) {
3536
- return normalizeTestFilePath(file, cwd) ?? file;
3537
- }
3538
- function noTestRan(output, blockCount) {
3539
- const summary = readBunSummary(output);
3540
- if (summary.bailed !== undefined) {
3541
- return summary.ran === summary.bailed;
3542
- }
3543
- return summary.pass === 0 && summary.ran === summary.skip + summary.todo + summary.fail && summary.fail <= blockCount;
3544
- }
3545
- var NO_CREDIT = { killedBy: [], files: [] };
3546
- function creditLoadFailures(run) {
3547
- const { byFile, testFiles, cwd, covering } = run;
3548
- if (byFile === undefined || testFiles === undefined) {
3549
- return NO_CREDIT;
3550
- }
3551
- const headers = blockHeaderFiles(run.stderr, runFileResolver(testFiles, cwd));
3552
- if (!noTestRan(`${run.stdout}
3553
- ${run.stderr}`, headers.length)) {
3554
- return NO_CREDIT;
3555
- }
3556
- const killedBy = new Set;
3557
- const files = new Set;
3558
- for (const header of headers) {
3559
- if (header === undefined) {
3560
- continue;
3561
- }
3562
- const file = dryRunKey(header, cwd);
3563
- const selected = (byFile.get(file) ?? []).filter((id) => covering.size === 0 || covering.has(id));
3564
- if (selected.length > 0) {
3565
- files.add(file);
3566
- }
3567
- for (const id of selected) {
3568
- killedBy.add(id);
3569
- }
3570
- }
3571
- return { killedBy: [...killedBy], files: [...files] };
3572
- }
3573
-
3574
3536
  // src/process-runner.ts
3575
3537
  import { spawn as spawn3 } from "node:child_process";
3576
3538
 
@@ -3633,13 +3595,13 @@ async function getPsRss(pid) {
3633
3595
  }
3634
3596
 
3635
3597
  // src/utils/project-dir.ts
3636
- import path10 from "node:path";
3598
+ import path9 from "node:path";
3637
3599
  var PROJECT_DIR_ENV = "STRYKER_BUN_RUNNER_PROJECT_DIR";
3638
3600
  var STRYKER_WORKER_ENV = "STRYKER_MUTATOR_WORKER";
3639
3601
  function recordProjectDirectory() {
3640
3602
  const inherited = process.env[PROJECT_DIR_ENV];
3641
3603
  const isWorker = process.env[STRYKER_WORKER_ENV] !== undefined;
3642
- if (isWorker && inherited !== undefined && path10.isAbsolute(inherited)) {
3604
+ if (isWorker && inherited !== undefined && path9.isAbsolute(inherited)) {
3643
3605
  return inherited;
3644
3606
  }
3645
3607
  const here = process.cwd();
@@ -3648,24 +3610,24 @@ function recordProjectDirectory() {
3648
3610
  }
3649
3611
  var projectDirectory = recordProjectDirectory();
3650
3612
  function resolveAgainstProject(file) {
3651
- return path10.resolve(projectDirectory, file);
3613
+ return path9.resolve(projectDirectory, file);
3652
3614
  }
3653
3615
 
3654
3616
  // src/utils/test-file-args.ts
3655
- import path11 from "node:path";
3617
+ import path10 from "node:path";
3656
3618
  var MAX_TEST_FILE_ARGS_BYTES = 131072;
3657
3619
  var ENTRY_OVERHEAD_BYTES = 1 + 8;
3658
3620
  var bytesOf = (args) => args.reduce((sum, arg) => sum + Buffer.byteLength(arg) + ENTRY_OVERHEAD_BYTES, 0);
3659
3621
  function shortestSpelling(absolute, cwd) {
3660
- const relative = path11.relative(cwd, absolute);
3622
+ const relative = path10.relative(cwd, absolute);
3661
3623
  if (relative === "" || relative === "..") {
3662
3624
  return absolute;
3663
3625
  }
3664
- const spelled = relative.startsWith(`..${path11.sep}`) ? relative : `.${path11.sep}${relative}`;
3626
+ const spelled = relative.startsWith(`..${path10.sep}`) ? relative : `.${path10.sep}${relative}`;
3665
3627
  return spelled.length < absolute.length ? spelled : absolute;
3666
3628
  }
3667
3629
  function computeTestFileArgs(files, cwd, budget) {
3668
- const absolute = files.map((file) => path11.resolve(cwd, file));
3630
+ const absolute = files.map((file) => path10.resolve(cwd, file));
3669
3631
  const absoluteBytes = bytesOf(absolute);
3670
3632
  if (absoluteBytes <= budget) {
3671
3633
  return { args: absolute, form: "absolute", bytes: absoluteBytes, fits: true };
@@ -3679,7 +3641,7 @@ function sameEntries(a, b) {
3679
3641
  }
3680
3642
  var lastBuild;
3681
3643
  function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_ARGS_BYTES) {
3682
- if (!path11.isAbsolute(cwd)) {
3644
+ if (!path10.isAbsolute(cwd)) {
3683
3645
  return computeTestFileArgs(files, cwd, budget);
3684
3646
  }
3685
3647
  const cached = lastBuild;
@@ -3694,6 +3656,7 @@ function buildTestFileArgs(files, cwd = process.cwd(), budget = MAX_TEST_FILE_AR
3694
3656
  // src/process-runner.ts
3695
3657
  var KILL_GRACE_PERIOD_MS = 500;
3696
3658
  var STDIO_CLOSE_GRACE_MS = 4 * KILL_GRACE_PERIOD_MS;
3659
+ var TERMINATION_WORST_CASE_MS = KILL_GRACE_PERIOD_MS + STDIO_CLOSE_GRACE_MS;
3697
3660
  var LIFELINE_FD = 3;
3698
3661
  var SPAWN_DEPTH_ENV = "__STRYKER_BUN_RUNNER_DEPTH__";
3699
3662
  var DEFAULT_MAX_SPAWN_DEPTH = 1;
@@ -3820,9 +3783,7 @@ function buildChildEnv(options, spawnDepth) {
3820
3783
  }
3821
3784
  env[SPAWN_DEPTH_ENV] = String(spawnDepth + 1);
3822
3785
  delete env[PROJECT_DIR_ENV];
3823
- if (options.profile) {
3824
- delete env[PROFILE_ENV];
3825
- }
3786
+ delete env[PROFILE_ENV];
3826
3787
  if (options.profile && options.syncPort) {
3827
3788
  env[PRELOAD_TIMINGS_ENV] = "1";
3828
3789
  } else {
@@ -4019,6 +3980,242 @@ Process error: ${error.message}`,
4019
3980
  });
4020
3981
  }
4021
3982
 
3983
+ // src/load-failure-killers.ts
3984
+ var TEST_ID_FILE_SEPARATOR = " > ";
3985
+ var GROUP_PREFIX = "::group::";
3986
+ function indexTestIdsByFile(tests) {
3987
+ const byFile = new Map;
3988
+ const uncertain = new Set;
3989
+ for (const test of tests) {
3990
+ const file = test.fileName;
3991
+ if (file === undefined) {
3992
+ continue;
3993
+ }
3994
+ if (!test.id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`)) {
3995
+ uncertain.add(file);
3996
+ } else if (test.status !== TestStatus2.Skipped) {
3997
+ const ids = byFile.get(file) ?? [];
3998
+ ids.push(test.id);
3999
+ byFile.set(file, ids);
4000
+ }
4001
+ }
4002
+ for (const file of uncertain) {
4003
+ byFile.delete(file);
4004
+ }
4005
+ return byFile;
4006
+ }
4007
+ function isTestIdsEntry(entry) {
4008
+ return Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && Array.isArray(entry[1]) && entry[1].every((id) => typeof id === "string");
4009
+ }
4010
+ function parseTestIdsByFile(value, known) {
4011
+ if (!Array.isArray(value)) {
4012
+ return;
4013
+ }
4014
+ const byFile = new Map;
4015
+ for (const entry of value) {
4016
+ if (!isTestIdsEntry(entry) || byFile.has(entry[0])) {
4017
+ return;
4018
+ }
4019
+ const [file, ids] = entry;
4020
+ if (!ids.every((id) => known.has(id) && id.startsWith(`${file}${TEST_ID_FILE_SEPARATOR}`))) {
4021
+ return;
4022
+ }
4023
+ byFile.set(file, ids);
4024
+ }
4025
+ return byFile;
4026
+ }
4027
+ function runFileResolver(testFiles, cwd) {
4028
+ const files = new Set(testFiles.map((file) => path11.resolve(cwd, file)));
4029
+ const keyCounts = new Map;
4030
+ for (const file of files) {
4031
+ const key = dryRunKey(file, cwd);
4032
+ keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1);
4033
+ }
4034
+ return (line) => {
4035
+ if (!line.endsWith(":")) {
4036
+ return;
4037
+ }
4038
+ const printed = line.slice(0, -1);
4039
+ const candidates = printed.startsWith(GROUP_PREFIX) ? [printed, printed.slice(GROUP_PREFIX.length)] : [printed];
4040
+ const matches = new Set(candidates.filter((candidate) => candidate !== "").map((candidate) => path11.resolve(cwd, candidate)).filter((file) => files.has(file)));
4041
+ if (matches.size === 0) {
4042
+ return;
4043
+ }
4044
+ const [file] = matches;
4045
+ const key = dryRunKey(file, cwd);
4046
+ return matches.size === 1 && keyCounts.get(key) === 1 && path11.resolve(cwd, key) === file ? file : null;
4047
+ };
4048
+ }
4049
+ function dryRunKey(file, cwd) {
4050
+ return normalizeTestFilePath(file, cwd) ?? file;
4051
+ }
4052
+ function noTestRan(output, blockCount) {
4053
+ const summary = readBunSummary(output);
4054
+ if (summary.bailed !== undefined) {
4055
+ return summary.ran === summary.bailed;
4056
+ }
4057
+ return summary.pass === 0 && summary.ran === summary.skip + summary.todo + summary.fail && summary.fail <= blockCount;
4058
+ }
4059
+ var MAX_SOLO_CONFIRMATIONS = 3;
4060
+ function refused(refusal) {
4061
+ return { killedBy: [], files: [], refusal };
4062
+ }
4063
+ function creditOf(candidates) {
4064
+ const killedBy = new Set(candidates.flatMap((candidate) => candidate.selected));
4065
+ return { killedBy: [...killedBy], files: candidates.map((candidate) => candidate.file) };
4066
+ }
4067
+ function summaryShown(output) {
4068
+ return bunSummaryLines(output).join(" / ") || "none";
4069
+ }
4070
+ function creditLoadFailures(run) {
4071
+ const { byFile, testFiles, cwd, covering, selects } = run;
4072
+ if (testFiles === undefined) {
4073
+ return refused("the run handed bun no file list, so which files it ran is not known");
4074
+ }
4075
+ if (byFile === undefined) {
4076
+ return refused("there is no usable dry-run index of test ids by file");
4077
+ }
4078
+ const headers = blockHeaderFiles(run.stderr, runFileResolver(testFiles, cwd));
4079
+ const candidates = new Map;
4080
+ const named = new Set;
4081
+ for (const header of headers) {
4082
+ if (header === undefined) {
4083
+ continue;
4084
+ }
4085
+ const file = dryRunKey(header, cwd);
4086
+ named.add(file);
4087
+ const selected = (byFile.get(file) ?? []).filter((id) => (covering.size === 0 || covering.has(id)) && (selects === undefined || selects(id)));
4088
+ if (selected.length > 0) {
4089
+ candidates.set(file, { path: header, file, selected });
4090
+ }
4091
+ }
4092
+ if (named.size === 0) {
4093
+ return refused("no error block was printed right below the header of exactly one file of the run");
4094
+ }
4095
+ if (candidates.size === 0) {
4096
+ return refused(`no selected test belongs to the file(s) the error blocks name (${[...named].join(", ")})`);
4097
+ }
4098
+ const output = `${run.stdout}
4099
+ ${run.stderr}`;
4100
+ if (noTestRan(output, headers.length)) {
4101
+ return creditOf([...candidates.values()]);
4102
+ }
4103
+ const otherTests = `bun's summary does not show that no other test ran (summary: ${summaryShown(output)})`;
4104
+ if (new Set(testFiles.map((entry) => path11.resolve(cwd, entry))).size === 1) {
4105
+ return refused(`${otherTests}, and the run was that one file alone, so re-running it alone would repeat the run`);
4106
+ }
4107
+ const all = [...candidates.values()];
4108
+ return {
4109
+ ...refused(otherTests),
4110
+ confirm: { candidates: all.slice(0, MAX_SOLO_CONFIRMATIONS), beyondCap: all.slice(MAX_SOLO_CONFIRMATIONS).map((candidate) => candidate.file) }
4111
+ };
4112
+ }
4113
+ function soloNotRun(why) {
4114
+ return { confirmed: false, shown: `was not run: ${why}` };
4115
+ }
4116
+ function judgeSoloRun(candidate, solo, cwd) {
4117
+ const output = `${solo.stdout}
4118
+ ${solo.stderr}`;
4119
+ const not = (shown) => ({ confirmed: false, shown: `${shown} (summary: ${summaryShown(output)})` });
4120
+ if (solo.spawnError !== undefined) {
4121
+ return { confirmed: false, shown: `could not be started (${solo.spawnError})` };
4122
+ }
4123
+ if (solo.timedOut) {
4124
+ return not(solo.memoryLimitExceeded === true ? "exceeded bun.maxChildRss and was stopped" : "was stopped by the runner (the mutant run's time limit, or a dispose)");
4125
+ }
4126
+ if (solo.hitLimitReached) {
4127
+ return not("reached Stryker's hit limit");
4128
+ }
4129
+ if (solo.signal) {
4130
+ return not(`was terminated by ${solo.signal}`);
4131
+ }
4132
+ if (solo.exitCode === 0) {
4133
+ return not("exited 0");
4134
+ }
4135
+ if (solo.failedTests > 0) {
4136
+ return not(`reported ${solo.failedTests} failing test(s)`);
4137
+ }
4138
+ const headers = blockHeaderFiles(solo.stderr, runFileResolver([candidate.path], cwd));
4139
+ if (!headers.includes(candidate.path)) {
4140
+ return not(headers.length === 0 ? "printed no error block" : "printed no error block right below the file's header");
4141
+ }
4142
+ if (!noTestRan(output, headers.length)) {
4143
+ return not("counted tests that ran beside the error block");
4144
+ }
4145
+ return { confirmed: true };
4146
+ }
4147
+ function creditFromSoloRuns(refusal, confirmation, results) {
4148
+ const confirmed = [];
4149
+ const shown = [];
4150
+ for (const { candidate, verdict } of results) {
4151
+ if (verdict.confirmed) {
4152
+ confirmed.push(candidate);
4153
+ } else {
4154
+ shown.push(`${candidate.file} ${verdict.shown}`);
4155
+ }
4156
+ }
4157
+ if (confirmed.length > 0) {
4158
+ return creditOf(confirmed);
4159
+ }
4160
+ return refused(`${refusal}, and re-run alone with the mutant, no file reproduced the load failure: ${shown.join("; ")}${beyondCapText(confirmation)}`);
4161
+ }
4162
+ function beyondCapText(confirmation) {
4163
+ const { beyondCap } = confirmation;
4164
+ return beyondCap.length === 0 ? "" : `; ${beyondCap.length} more file(s) past the cap of ${MAX_SOLO_CONFIRMATIONS} were not re-run (${beyondCap.join(", ")})`;
4165
+ }
4166
+ function creditAfterDisposal(refusal) {
4167
+ return refused(`${refusal}, and the runner was disposed while files were being re-run alone, so nothing is credited from those runs`);
4168
+ }
4169
+ var CONFIRMATION_TERMINATION_MS = TERMINATION_WORST_CASE_MS;
4170
+ var MIN_CONFIRMATION_RUN_MS = KILL_GRACE_PERIOD_MS;
4171
+ function confirmationTimeout(deadline, now) {
4172
+ const left = deadline - now;
4173
+ const timeout = left - CONFIRMATION_TERMINATION_MS;
4174
+ if (timeout < MIN_CONFIRMATION_RUN_MS) {
4175
+ return { notRun: `${Math.max(0, left)} ms of the mutant run's time limit were left, less than the ${MIN_CONFIRMATION_RUN_MS} ms a run alone needs plus the ${CONFIRMATION_TERMINATION_MS} ms stopping it can take` };
4176
+ }
4177
+ return { timeout };
4178
+ }
4179
+ function controlNotRun(why) {
4180
+ return { outcome: "inconclusive", shown: `was not run: ${why}` };
4181
+ }
4182
+ function judgeControlRun(candidate, control, cwd) {
4183
+ const output = `${control.stdout}
4184
+ ${control.stderr}`;
4185
+ const inconclusive = (shown) => ({ outcome: "inconclusive", shown: `${shown} (summary: ${summaryShown(output)})` });
4186
+ if (control.spawnError !== undefined) {
4187
+ return { outcome: "inconclusive", shown: `could not be started (${control.spawnError})` };
4188
+ }
4189
+ if (control.timedOut) {
4190
+ return inconclusive(control.memoryLimitExceeded === true ? "exceeded bun.maxChildRss and was stopped" : "was stopped by the runner (the mutant run's time limit, or a dispose)");
4191
+ }
4192
+ if (control.signal) {
4193
+ return inconclusive(`was terminated by ${control.signal}`);
4194
+ }
4195
+ const headers = blockHeaderFiles(control.stderr, runFileResolver([candidate.path], cwd));
4196
+ if (headers.includes(candidate.path)) {
4197
+ return { outcome: "fails", shown: `printed an error block right below the file's header without the mutant too (summary: ${summaryShown(output)})` };
4198
+ }
4199
+ if (headers.length > 0) {
4200
+ return inconclusive("printed an error block that is not right below the file's header");
4201
+ }
4202
+ const { ran } = readBunSummary(output);
4203
+ if (ran === undefined || ran === 0) {
4204
+ return inconclusive("did not count a test that ran");
4205
+ }
4206
+ return { outcome: "loads" };
4207
+ }
4208
+ function isCacheableControl(verdict) {
4209
+ return verdict.outcome !== "inconclusive";
4210
+ }
4211
+ function withControl(solo, control) {
4212
+ if (!solo.confirmed || control.outcome === "loads") {
4213
+ return solo;
4214
+ }
4215
+ const why = control.outcome === "fails" ? "so the failure is not the mutant's" : "so whether it loads without the mutant is not known";
4216
+ return { confirmed: false, shown: `failed to load alone with the mutant, but its control run alone without the mutant ${control.shown}, ${why}` };
4217
+ }
4218
+
4022
4219
  // src/run-profile.ts
4023
4220
  import { appendFileSync as appendFileSync2 } from "node:fs";
4024
4221
  import path12 from "node:path";
@@ -5505,6 +5702,11 @@ function emptyMutantRunCounts() {
5505
5702
  [MutantRunStatus.Error]: 0
5506
5703
  };
5507
5704
  }
5705
+ function killedFallbackMessage(result, failedNames, killedBy) {
5706
+ const stderr = stripAnsi(result.stderr).trim();
5707
+ const unattributed = failedNames.length === 0 || killedBy.length === 0;
5708
+ return `Tests failed with exit code ${result.exitCode}: ${unattributed ? headWithSummary(stderr, 1000) : stderr.slice(0, 1000)}`;
5709
+ }
5508
5710
  function newHitLimitToken() {
5509
5711
  return randomBytes4(16).toString("hex");
5510
5712
  }
@@ -5587,6 +5789,8 @@ class BunTestRunner {
5587
5789
  campaign;
5588
5790
  warnedWatchListProblem = false;
5589
5791
  currentAbortController;
5792
+ disposing = false;
5793
+ controlVerdicts = new Map;
5590
5794
  drainSilenceMs = DRAIN_ACK_SILENCE_TIMEOUT_MS;
5591
5795
  handOffBudget = HAND_OFF_BUDGET;
5592
5796
  constructor(logger, options) {
@@ -5885,6 +6089,7 @@ class BunTestRunner {
5885
6089
  }
5886
6090
  async init() {
5887
6091
  this.logger.debug("BunTestRunner init starting...");
6092
+ this.disposing = false;
5888
6093
  assertSupportedBunArgs(this.configuredBunArgs);
5889
6094
  if (!this.bunChecked) {
5890
6095
  this.bunVersion = await checkBunVersion(this.bunPath, this.env);
@@ -7229,47 +7434,34 @@ ${preloadLines.join(`
7229
7434
  return exist.every(Boolean) ? entries.toSorted((a, b) => a.localeCompare(b)) : undefined;
7230
7435
  }
7231
7436
  async executeMutantRun(ctx, testNamePattern, coveringTestFiles) {
7232
- const { options, bunfigPath, localRegistry, localBaseIndex } = ctx;
7437
+ const { options, localRegistry, localBaseIndex } = ctx;
7233
7438
  this.countFullSuiteFallback(testNamePattern, ctx.coveringTestCount);
7234
- const abortController = new AbortController;
7235
- this.currentAbortController = abortController;
7236
7439
  const hitLimitToken = newHitLimitToken();
7237
7440
  const guards = this.mutantRunGuards(options);
7238
7441
  const ordered = this.orderForMutantRun(ctx.testFileScope ?? (testNamePattern === undefined ? this.effectiveTestFiles : coveringTestFiles ?? this.effectiveTestFiles), ctx);
7239
7442
  const testFiles = this.fitTestFiles(ordered, ctx.testFileScope === undefined ? this.explicitTestFilesSource(process.cwd()) : "Stryker's testFiles option");
7240
7443
  ctx.profile?.setScope(mutantRunScope(ctx.testFileScope !== undefined, testNamePattern, ctx.coveringTestCount));
7241
- let result;
7242
- try {
7243
- result = await runBunTests({
7244
- bunPath: this.bunPath,
7245
- timeout: Math.max(1, ctx.deadline - Date.now()),
7246
- env: this.env,
7247
- bunArgs: this.mutantBunArgs,
7248
- bunfigPath,
7249
- activeMutant: options.activeMutant.id,
7250
- hitLimit: guards.hitLimit,
7251
- hitLimitToken,
7252
- watchList: guards.watchList,
7253
- bail: !options.disableBail,
7254
- sequentialMode: true,
7255
- preloadScript: this.preloadScriptPath,
7256
- testNamePattern,
7257
- testFiles,
7258
- signal: abortController.signal,
7259
- smol: this.smol,
7260
- maxChildRss: this.maxChildRss,
7261
- rssCheckIntervalMs: this.rssCheckIntervalMs,
7262
- maxSpawnDepth: this.maxSpawnDepth,
7263
- onMemoryLimitExceeded: (rssBytes) => {
7264
- this.mutantWarnings.warn(MUTANT_WARN_KIND.memoryLimit, options.activeMutant.id, "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);
7265
- },
7266
- profile: ctx.profile
7267
- });
7268
- } finally {
7269
- if (this.currentAbortController === abortController) {
7270
- this.currentAbortController = undefined;
7444
+ const result = await this.spawnMutantChild(ctx, {
7445
+ activeMutant: options.activeMutant.id,
7446
+ timeout: Math.max(1, ctx.deadline - Date.now()),
7447
+ testNamePattern,
7448
+ testFiles,
7449
+ hitLimit: guards.hitLimit,
7450
+ hitLimitToken,
7451
+ watchList: guards.watchList,
7452
+ profile: ctx.profile,
7453
+ onMemoryLimitExceeded: (rssBytes) => {
7454
+ this.mutantWarnings.warn(MUTANT_WARN_KIND.memoryLimit, options.activeMutant.id, "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);
7271
7455
  }
7272
- }
7456
+ });
7457
+ let selector;
7458
+ const loadFailures = {
7459
+ runAlone: (candidate) => this.runFileAlone(candidate, ctx, testNamePattern),
7460
+ selects: testNamePattern === undefined ? undefined : (id) => {
7461
+ selector ??= testNamePatternSelector(testNamePattern, this.testNameIndex);
7462
+ return selector(id);
7463
+ }
7464
+ };
7273
7465
  await this.enforceWitness(result.stderr, hitLimitToken, ctx, testNamePattern);
7274
7466
  const runawayResult = this.classifyRunawayMutantRun(result, ctx, testNamePattern, hitLimitToken);
7275
7467
  if (runawayResult) {
@@ -7292,16 +7484,124 @@ ${preloadLines.join(`
7292
7484
  this.mutantWarnings.warn(MUTANT_WARN_KIND.zeroMatchRetry, options.activeMutant.id, "Mutant %s: --test-name-pattern matched 0 tests — usually a runner pattern gap or a mutant that changed an interpolated test title (it.each); retrying once with the full suite", options.activeMutant.id);
7293
7485
  return this.executeMutantRun(ctx, undefined);
7294
7486
  }
7295
- return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id);
7487
+ return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id, loadFailures);
7296
7488
  }
7297
7489
  if (!parsed.summaryPrinted) {
7298
- return this.classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id);
7490
+ return this.classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, options.activeMutant.id, loadFailures);
7299
7491
  }
7300
7492
  return {
7301
7493
  status: MutantRunStatus.Survived,
7302
7494
  nrOfTests: parsed.totalTests
7303
7495
  };
7304
7496
  }
7497
+ async spawnMutantChild(ctx, spawn) {
7498
+ const { options } = ctx;
7499
+ const abortController = new AbortController;
7500
+ this.currentAbortController = abortController;
7501
+ try {
7502
+ return await runBunTests({
7503
+ bunPath: this.bunPath,
7504
+ timeout: spawn.timeout,
7505
+ env: this.env,
7506
+ bunArgs: this.mutantBunArgs,
7507
+ bunfigPath: ctx.bunfigPath,
7508
+ activeMutant: spawn.activeMutant,
7509
+ hitLimit: spawn.hitLimit,
7510
+ hitLimitToken: spawn.hitLimitToken,
7511
+ watchList: spawn.watchList,
7512
+ bail: !options.disableBail,
7513
+ sequentialMode: true,
7514
+ preloadScript: this.preloadScriptPath,
7515
+ testNamePattern: spawn.testNamePattern,
7516
+ testFiles: spawn.testFiles,
7517
+ signal: abortController.signal,
7518
+ smol: this.smol,
7519
+ maxChildRss: this.maxChildRss,
7520
+ rssCheckIntervalMs: this.rssCheckIntervalMs,
7521
+ maxSpawnDepth: this.maxSpawnDepth,
7522
+ onMemoryLimitExceeded: spawn.onMemoryLimitExceeded,
7523
+ profile: spawn.profile
7524
+ });
7525
+ } finally {
7526
+ if (this.currentAbortController === abortController) {
7527
+ this.currentAbortController = undefined;
7528
+ }
7529
+ }
7530
+ }
7531
+ async runFileAlone(candidate, ctx, testNamePattern) {
7532
+ const mutantId = ctx.options.activeMutant.id;
7533
+ const key = this.controlRunKey(candidate, ctx, testNamePattern);
7534
+ const known = this.controlVerdicts.get(key);
7535
+ if (known?.outcome === "fails") {
7536
+ const why = `its control run alone without the mutant, made for an earlier mutant, ${known.shown}, so a load failure alone would not be this mutant's`;
7537
+ this.logger.debug("Mutant %s: not re-run alone, %s: %s", mutantId, candidate.file, why);
7538
+ return soloNotRun(why);
7539
+ }
7540
+ const solo = await this.spawnAlone(candidate, ctx, testNamePattern, mutantId);
7541
+ const control = solo.confirmed ? known ?? await this.runControl(candidate, ctx, testNamePattern, key) : undefined;
7542
+ const verdict = control === undefined ? solo : withControl(solo, control);
7543
+ this.logger.debug("Mutant %s: re-run alone, %s %s", mutantId, candidate.file, verdict.confirmed ? "failed to load and no test ran, and it loads alone without the mutant" : verdict.shown);
7544
+ return verdict;
7545
+ }
7546
+ async spawnAlone(candidate, ctx, testNamePattern, mutantId) {
7547
+ if (this.disposing) {
7548
+ return soloNotRun("the runner is being disposed");
7549
+ }
7550
+ const budget = confirmationTimeout(ctx.deadline, Date.now());
7551
+ if (budget.notRun !== undefined) {
7552
+ return soloNotRun(budget.notRun);
7553
+ }
7554
+ const hitLimitToken = newHitLimitToken();
7555
+ const result = await this.spawnMutantChild(ctx, {
7556
+ activeMutant: mutantId,
7557
+ timeout: budget.timeout,
7558
+ testNamePattern,
7559
+ testFiles: [candidate.path],
7560
+ hitLimit: this.mutantRunGuards(ctx.options).hitLimit,
7561
+ hitLimitToken,
7562
+ watchList: undefined,
7563
+ profile: undefined,
7564
+ onMemoryLimitExceeded: (rssBytes) => {
7565
+ this.logger.debug("Mutant %s: the run of %s alone exceeded maxChildRss (%d bytes observed); killing it", mutantId, candidate.file, rssBytes);
7566
+ }
7567
+ });
7568
+ const parsed = parseBunTestOutput(result.stdout, result.stderr, [candidate.path]);
7569
+ return judgeSoloRun(candidate, {
7570
+ ...result,
7571
+ hitLimitReached: readReportedHitCount(result.stderr, hitLimitToken) !== undefined,
7572
+ failedTests: parsed.tests.filter((test) => test.status === "failed").length
7573
+ }, process.cwd());
7574
+ }
7575
+ async runControl(candidate, ctx, testNamePattern, key) {
7576
+ if (this.disposing) {
7577
+ return controlNotRun("the runner is being disposed");
7578
+ }
7579
+ const budget = confirmationTimeout(ctx.deadline, Date.now());
7580
+ if (budget.notRun !== undefined) {
7581
+ return controlNotRun(budget.notRun);
7582
+ }
7583
+ const result = await this.spawnMutantChild(ctx, {
7584
+ activeMutant: undefined,
7585
+ timeout: budget.timeout,
7586
+ testNamePattern,
7587
+ testFiles: [candidate.path],
7588
+ hitLimit: undefined,
7589
+ hitLimitToken: newHitLimitToken(),
7590
+ watchList: undefined,
7591
+ profile: undefined,
7592
+ onMemoryLimitExceeded: (rssBytes) => {
7593
+ this.logger.debug("The control run of %s alone without a mutant exceeded maxChildRss (%d bytes observed); killing it", candidate.file, rssBytes);
7594
+ }
7595
+ });
7596
+ const verdict = judgeControlRun(candidate, result, process.cwd());
7597
+ if (isCacheableControl(verdict) && !this.disposing) {
7598
+ this.controlVerdicts.set(key, verdict);
7599
+ }
7600
+ return verdict;
7601
+ }
7602
+ controlRunKey(candidate, ctx, testNamePattern) {
7603
+ return JSON.stringify([process.cwd(), candidate.path, testNamePattern ?? null, ctx.options.disableBail === true]);
7604
+ }
7305
7605
  countFullSuiteFallback(testNamePattern, coveringTestCount) {
7306
7606
  if (testNamePattern === undefined && coveringTestCount > 0) {
7307
7607
  this.fullSuiteFallbacks++;
@@ -7329,7 +7629,7 @@ ${preloadLines.join(`
7329
7629
  this.mutantWarnings.warn(MUTANT_WARN_KIND.inconclusiveTimeout, mutantId, "Mutant %s: inconclusive timeout, scoring as Error rather than Timeout: %s", mutantId, errorMessage);
7330
7630
  return { status: MutantRunStatus.Error, errorMessage };
7331
7631
  }
7332
- buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, earlyExit = false) {
7632
+ async buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, loadFailures, earlyExit = false) {
7333
7633
  const rawFailedNames = parsed.tests.filter((test) => test.status === "failed").map((test) => normalizeTestName(test.name));
7334
7634
  if (result.signal && rawFailedNames.length === 0) {
7335
7635
  return this.buildSignalErrorResult(result, mutantId, `bun test terminated by ${result.signal} before any test reported a failure`);
@@ -7340,7 +7640,7 @@ ${preloadLines.join(`
7340
7640
  return noEvidenceResult;
7341
7641
  }
7342
7642
  }
7343
- const killedBy = this.killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId);
7643
+ const { killedBy, refusal } = await this.killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId, loadFailures);
7344
7644
  if (result.signal && killedBy.length === 0) {
7345
7645
  return this.buildSignalErrorResult(result, mutantId, `bun test terminated by ${result.signal}; the ${rawFailedNames.length} failing test(s) reported could not be attributed to a known test`);
7346
7646
  }
@@ -7348,19 +7648,19 @@ ${preloadLines.join(`
7348
7648
  return this.buildEarlyExitErrorResult(result, mutantId, `the ${rawFailedNames.length} failing test(s) it reported could not be attributed to a known test`);
7349
7649
  }
7350
7650
  if (killedBy.length === 0) {
7351
- this.mutantWarnings.warn(MUTANT_WARN_KIND.noKillerIdentified, mutantId, "Mutant %s: no killing test identifiable — emitting empty killedBy; " + `this mutant will re-run on every incremental run
7651
+ this.mutantWarnings.warn(MUTANT_WARN_KIND.noKillerIdentified, mutantId, "Mutant %s: no killing test identifiable — emitting empty killedBy (%s); " + `this mutant will re-run on every incremental run
7352
7652
  ` + `exit=%s
7353
- --- STDOUT (first 600 chars) ---
7653
+ --- STDOUT (first 600 chars, then bun's summary) ---
7354
7654
  %s
7355
- ` + `--- STDERR (first 600 chars) ---
7356
- %s`, mutantId, String(result.exitCode), result.stdout.slice(0, 600) || "(empty)", result.stderr.slice(0, 600) || "(empty)");
7655
+ ` + `--- STDERR (first 600 chars, then bun's summary) ---
7656
+ %s`, mutantId, refusal, String(result.exitCode), headWithSummary(result.stdout, 600) || "(empty)", headWithSummary(result.stderr, 600) || "(empty)");
7357
7657
  }
7358
7658
  return {
7359
7659
  status: MutantRunStatus.Killed,
7360
7660
  killedBy,
7361
7661
  failureMessage: parsed.tests.map((test) => test.failureMessage).filter((msg) => !!msg).join(`
7362
7662
 
7363
- `) || `Tests failed with exit code ${result.exitCode}: ${stripAnsi(result.stderr).trim().slice(0, 1000)}`,
7663
+ `) || killedFallbackMessage(result, rawFailedNames, killedBy),
7364
7664
  nrOfTests: parsed.totalTests || 1
7365
7665
  };
7366
7666
  }
@@ -7392,9 +7692,9 @@ ${preloadLines.join(`
7392
7692
  errorMessage: `bun test exited with code ${result.exitCode} but reported no failing test and no fail/error count, so there is no evidence a test detected this mutant: ${output}`
7393
7693
  };
7394
7694
  }
7395
- classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId) {
7695
+ async classifyEarlyCleanExit(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, loadFailures) {
7396
7696
  if (parsed.tests.some((test) => test.status === "failed")) {
7397
- return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, true);
7697
+ return this.buildMutantKilledResult(result, parsed, localRegistry, localBaseIndex, testFiles, mutantId, loadFailures, true);
7398
7698
  }
7399
7699
  return this.buildEarlyExitErrorResult(result, mutantId, "no test reported a failure");
7400
7700
  }
@@ -7628,22 +7928,54 @@ ${outputLine}`;
7628
7928
  this.warnUnresolvedKilledBy(unresolved, mutantId);
7629
7929
  return [...killedBySet];
7630
7930
  }
7631
- killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId) {
7632
- return rawFailedNames.length === 0 ? this.creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId) : this.resolveKilledBy(rawFailedNames, localRegistry, localBaseIndex, mutantId);
7931
+ async killersOf(rawFailedNames, result, testFiles, localRegistry, localBaseIndex, mutantId, loadFailures) {
7932
+ if (rawFailedNames.length === 0) {
7933
+ return this.creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId, loadFailures);
7934
+ }
7935
+ return {
7936
+ killedBy: this.resolveKilledBy(rawFailedNames, localRegistry, localBaseIndex, mutantId),
7937
+ refusal: `none of the ${rawFailedNames.length} failing test name(s) matched a dry-run test id`
7938
+ };
7633
7939
  }
7634
- creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId) {
7635
- const credit = creditLoadFailures({
7940
+ async creditFilesThatFailedToLoad(result, testFiles, localRegistry, mutantId, loadFailures) {
7941
+ const direct = creditLoadFailures({
7636
7942
  stdout: result.stdout,
7637
7943
  stderr: result.stderr,
7638
7944
  testFiles,
7639
7945
  cwd: process.cwd(),
7640
7946
  byFile: this.testIdsByFile,
7641
- covering: localRegistry
7947
+ covering: localRegistry,
7948
+ selects: loadFailures.selects
7642
7949
  });
7643
- if (credit.killedBy.length > 0) {
7644
- this.logger.debug("Mutant %s: no test ran, and %d test file(s) failed to load (%s); killedBy holds their %d selected test(s)", mutantId, credit.files.length, credit.files.join(", "), credit.killedBy.length);
7950
+ if (direct.refusal === undefined) {
7951
+ this.logger.debug("Mutant %s: no test ran, and %d test file(s) failed to load (%s); killedBy holds their %d selected test(s)", mutantId, direct.files.length, direct.files.join(", "), direct.killedBy.length);
7952
+ return direct;
7953
+ }
7954
+ return direct.confirm === undefined ? direct : this.confirmAlone(direct.refusal, direct.confirm, loadFailures.runAlone, mutantId);
7955
+ }
7956
+ async confirmAlone(refusal, confirmation, runAlone, mutantId) {
7957
+ const results = [];
7958
+ for (const candidate of confirmation.candidates) {
7959
+ if (this.disposing) {
7960
+ break;
7961
+ }
7962
+ let verdict;
7963
+ try {
7964
+ verdict = await runAlone(candidate);
7965
+ } catch (error) {
7966
+ verdict = soloNotRun(`starting it or waiting for it failed (${errorText(error)})`);
7967
+ }
7968
+ results.push({ candidate, verdict });
7969
+ }
7970
+ if (this.disposing) {
7971
+ this.logger.debug("Mutant %s: the runner is being disposed, so no file re-run alone is credited", mutantId);
7972
+ return creditAfterDisposal(refusal);
7973
+ }
7974
+ const credit = creditFromSoloRuns(refusal, confirmation, results);
7975
+ if (credit.refusal === undefined) {
7976
+ this.logger.debug("Mutant %s: other tests may have run, and %d test file(s) failed to load with no test run when re-run alone (%s); killedBy holds their %d selected test(s)%s", mutantId, credit.files.length, credit.files.join(", "), credit.killedBy.length, beyondCapText(confirmation));
7645
7977
  }
7646
- return credit.killedBy;
7978
+ return credit;
7647
7979
  }
7648
7980
  warnUnresolvedKilledBy(unresolved, mutantId) {
7649
7981
  if (unresolved.size === 0) {
@@ -7671,6 +8003,7 @@ ${outputLine}`;
7671
8003
  }
7672
8004
  async dispose() {
7673
8005
  this.logger.debug("Disposing BunTestRunner");
8006
+ this.disposing = true;
7674
8007
  this.logMutantRunSummary();
7675
8008
  this.mutantWarnings.flush();
7676
8009
  this.writeProfileSummary();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.8.2",
3
+ "version": "1.8.3",
4
4
  "description": "Stryker mutation testing test runner plugin for Bun (bun test), with per-test coverage",
5
5
  "keywords": [
6
6
  "stryker",
@@ -43,6 +43,7 @@
43
43
  "lint:fix": "node node_modules/oxlint/bin/oxlint --fix && bun node_modules/eslint/bin/eslint.js -c eslint.package-json.config.mjs --fix package.json",
44
44
  "mutate": "stryker run",
45
45
  "prepublishOnly": "bun run build",
46
+ "release": "bun pm version --no-git-tag-version",
46
47
  "test": "bun test",
47
48
  "typecheck": "node node_modules/typescript/bin/tsc --noEmit && node node_modules/typescript/bin/tsc --noEmit -p scripts",
48
49
  "postversion": "git commit -m \"Bump package version to $npm_package_version\" package.json; git flow release start $npm_package_version; git flow release finish -m $npm_package_version $npm_package_version; git checkout develop; git merge main"