@hughescr/stryker-bun-runner 1.3.4 → 1.3.5

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
@@ -242,13 +242,36 @@ of them in a clean run's logs is worth investigating before trusting the score.
242
242
  retrying the run (with less concurrent load, or fewer parallel Stryker workers) is
243
243
  the first thing to try.
244
244
 
245
+ Before this check runs, the bun test child process (during `dryRun` only) holds
246
+ itself open past its own natural exit and waits for the runner to prove — via an
247
+ inspector-protocol round-trip over the same ordered connection the test events
248
+ arrive on — that it has actually received and processed everything the child
249
+ sent, before letting the child close its coverage socket and exit. This closes
250
+ the specific race that used to cause this gate to fire under CPU-contended CI
251
+ runners: previously, nothing synchronized "the runner has drained the inspector
252
+ stream" with "the child process is allowed to exit," so a consumer that couldn't
253
+ keep up with the event stream under contention would lose whatever hadn't been
254
+ processed by the time the child exited. The handshake is bounded on both sides
255
+ (the child gives up and proceeds after a few seconds if it hears nothing back,
256
+ and the runner's own round-trip is bounded independently and more tightly) — if
257
+ either bound is hit, today's original behavior (including this gate) applies
258
+ exactly as before, so the handshake can only reduce how often this gate fires,
259
+ never mask a real truncation from it.
260
+
245
261
  The gate's thresholds — `EXECUTION_SHORTFALL_ABS_FLOOR`, `EXECUTION_SHORTFALL_RATIO_THRESHOLD`,
246
- `ORPHANED_KEY_ABS_FLOOR`, and the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS` it depends on —
247
- are fixed module-level constants in `src/bun-test-runner.ts`. There is currently no config
248
- option to override them; if these defaults produce false positives in your environment
249
- (e.g. a CI runner with very different contention characteristics than the ones this gate
250
- was tuned against), a config knob is a possible follow-up — please open an issue rather
251
- than patching the constants locally.
262
+ `ORPHANED_KEY_ABS_FLOOR`, the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS`, and the drain-handshake
263
+ bounds (`DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS` in `src/bun-test-runner.ts`, and the matching preload-side
264
+ ceiling in `src/templates/coverage-preload.ts`) — are fixed module-level constants. There is
265
+ currently no config option to override them; if these defaults produce false positives in your
266
+ environment (e.g. a CI runner with very different contention characteristics than the ones this
267
+ gate was tuned against), a config knob is a possible follow-up — please open an issue rather than
268
+ patching the constants locally.
269
+
270
+ This handshake only covers the `dryRun` path (where coverage collection and the
271
+ completeness gate apply) — individual mutant runs are not held open the same way,
272
+ since they run small, `--test-name-pattern`-filtered subsets where the same
273
+ backlog-under-contention risk is negligible and the completeness gate does not
274
+ apply to them.
252
275
 
253
276
  ### Coverage-bleed warning (dry run only)
254
277
 
@@ -277,6 +300,13 @@ of them in a clean run's logs is worth investigating before trusting the score.
277
300
 
278
301
  - **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.
279
302
 
303
+ - **Inspector-stream drain handshake covers `dryRun` only** — the hold-open-until-drained
304
+ handshake described under "Dry-run completeness gate" above only runs for the dry run
305
+ (where a `SyncServer` and coverage collection are set up). Individual mutant runs are not
306
+ held open the same way: they run small, filtered test subsets where the backlog-under-CPU-
307
+ contention risk that motivated the handshake is negligible, and the completeness gate does
308
+ not apply to mutant runs in the first place.
309
+
280
310
  **Upgrade note: duplicate-name test suffixes**
281
311
 
282
312
  The runner reconciles how it assigns the `' [N]'` disambiguating suffix to
package/dist/index.js CHANGED
@@ -6657,6 +6657,13 @@ async function getAvailablePort() {
6657
6657
  }
6658
6658
  // src/utils/sync-server.ts
6659
6659
  import { createServer as createServer2 } from "node:http";
6660
+ function rawDataToString(data) {
6661
+ if (Array.isArray(data)) {
6662
+ return Buffer.concat(data).toString("utf8");
6663
+ }
6664
+ return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
6665
+ }
6666
+
6660
6667
  class SyncServer {
6661
6668
  httpServer = null;
6662
6669
  wss = null;
@@ -6666,6 +6673,8 @@ class SyncServer {
6666
6673
  createHttpServer;
6667
6674
  WebSocketServerClass;
6668
6675
  webSocketOpenState;
6676
+ drainHandler = null;
6677
+ drainInFlight = null;
6669
6678
  constructor(options) {
6670
6679
  this.port = options.port;
6671
6680
  this.createHttpServer = options.createHttpServer ?? createServer2;
@@ -6698,7 +6707,11 @@ class SyncServer {
6698
6707
  ws.on("close", () => {
6699
6708
  this.clients.delete(ws);
6700
6709
  });
6701
- ws.on("message", () => {});
6710
+ ws.on("message", (data) => {
6711
+ if (rawDataToString(data) === "drain-request") {
6712
+ this.handleDrainRequest(ws);
6713
+ }
6714
+ });
6702
6715
  });
6703
6716
  this.httpServer.on("error", reject);
6704
6717
  this.httpServer.listen(this.port, () => {
@@ -6719,8 +6732,32 @@ class SyncServer {
6719
6732
  } catch {}
6720
6733
  }
6721
6734
  }
6735
+ setDrainHandler(handler) {
6736
+ this.drainHandler = handler;
6737
+ }
6738
+ handleDrainRequest(ws) {
6739
+ if (!this.drainHandler) {
6740
+ return;
6741
+ }
6742
+ this.drainInFlight ??= this.drainHandler();
6743
+ const inFlight = this.drainInFlight;
6744
+ (async () => {
6745
+ try {
6746
+ await inFlight;
6747
+ } catch {
6748
+ return;
6749
+ }
6750
+ try {
6751
+ if (ws.readyState === this.webSocketOpenState) {
6752
+ ws.send("drained");
6753
+ }
6754
+ } catch {}
6755
+ })();
6756
+ }
6722
6757
  async close() {
6723
6758
  this.readyLatched = false;
6759
+ this.drainHandler = null;
6760
+ this.drainInFlight = null;
6724
6761
  for (const client of this.clients) {
6725
6762
  try {
6726
6763
  client.close();
@@ -8030,6 +8067,15 @@ function sleep(ms) {
8030
8067
  setTimeout(resolve3, ms);
8031
8068
  });
8032
8069
  }
8070
+ function rejectAfterMs(ms, message) {
8071
+ let timer;
8072
+ const promise2 = new Promise((_resolve, reject) => {
8073
+ timer = setTimeout(() => {
8074
+ reject(new Error(message));
8075
+ }, ms);
8076
+ });
8077
+ return { promise: promise2, cancel: () => clearTimeout(timer) };
8078
+ }
8033
8079
  function buildTestNameIndex(tests, bunNames) {
8034
8080
  const testNameIndex = new Map;
8035
8081
  for (const [i, test] of tests.entries()) {
@@ -8047,6 +8093,7 @@ var EXECUTION_SHORTFALL_ABS_FLOOR = 10;
8047
8093
  var EXECUTION_SHORTFALL_RATIO_THRESHOLD = 0.05;
8048
8094
  var ORPHANED_KEY_ABS_FLOOR = 5;
8049
8095
  var INSPECTOR_DRAIN_TIMEOUT_MS = 1000;
8096
+ var DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS = 4000;
8050
8097
 
8051
8098
  class BunTestRunner {
8052
8099
  logger;
@@ -8431,6 +8478,17 @@ exit=%s timedOut=%s
8431
8478
  errorMessage: `Failed to connect to Bun inspector: ${errorMsg}`
8432
8479
  };
8433
8480
  }
8481
+ syncServer.setDrainHandler(async () => {
8482
+ const { promise: timeoutPromise, cancel: cancelTimeout } = rejectAfterMs(DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS, "Inspector drain round-trip timed out");
8483
+ try {
8484
+ await Promise.race([
8485
+ inspector.send("TestReporter.enable", {}),
8486
+ timeoutPromise
8487
+ ]);
8488
+ } finally {
8489
+ cancelTimeout();
8490
+ }
8491
+ });
8434
8492
  syncServer.signalReady();
8435
8493
  this.logger.debug("Signaled preload script to proceed");
8436
8494
  const result = await testProcess;
@@ -79,6 +79,15 @@ const shouldCollectCoverage = shouldCollect(config);
79
79
  // ============================================================================
80
80
  let ws: WebSocket | null = null;
81
81
 
82
+ // Bound on how long the final afterAll (below) waits for the runner's drain
83
+ // acknowledgment before giving up and proceeding as if drained — see
84
+ // "Inspector-stream drain handshake" further down.
85
+ // Deliberately ABOVE the runner-side inspector round-trip timeout
86
+ // (DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS in bun-test-runner.ts) so a stuck
87
+ // round-trip is governed by that shorter ceiling first; this is the outer
88
+ // backstop if the sync channel itself is unresponsive.
89
+ const DRAIN_ACK_TIMEOUT_MS = 5000;
90
+
82
91
  // Per-file test counters for per-test coverage tracking.
83
92
  //
84
93
  // Bun runs multiple test files sequentially inside the same worker process,
@@ -314,7 +323,7 @@ if(shouldCollectCoverage) {
314
323
  strykerGlobal.currentTestId = undefined;
315
324
  });
316
325
 
317
- afterAll(() => {
326
+ afterAll(async () => {
318
327
  // Final gap check, best-effort: catches bleed that has already recorded a
319
328
  // counter delta by the time afterAll runs, with no following beforeEach
320
329
  // left to catch it any other way. This preload's afterAll fires once per
@@ -339,9 +348,76 @@ if(shouldCollectCoverage) {
339
348
  }
340
349
  }
341
350
 
342
- ws?.close();
351
+ // Coverage must be finalized — gap check above, then the write itself —
352
+ // BEFORE the drain-ack wait below, not after. The wait yields this
353
+ // process's event loop for up to DRAIN_ACK_TIMEOUT_MS; if it ran first,
354
+ // any stray timer or promise continuation left behind by the last test
355
+ // could fire during that yield, touch mutantCoverage.static, and leak
356
+ // into the persisted snapshot — reintroducing exactly the class of risk
357
+ // the gap-window bleed check above exists to catch. Writing first means
358
+ // the snapshot is already on disk before that window even opens, so
359
+ // nothing that runs during the wait can affect what was persisted.
343
360
  writeCoverageData();
344
361
  // Clear the accumulator now that it has been written out.
345
362
  lateHits.length = 0;
363
+
364
+ // ====================================================================
365
+ // Inspector-stream drain handshake
366
+ // ====================================================================
367
+ // Block (bounded) on a drain acknowledgment from the runner BEFORE
368
+ // closing this socket / allowing this process to exit. Without this,
369
+ // nothing synchronizes "the runner has received and processed every
370
+ // inspector event" with "this child process is allowed to exit" — a
371
+ // contended CPU (e.g. a 2-core CI box) can leave the runner's
372
+ // InspectorClient with an unprocessed backlog at the moment this
373
+ // process exits, silently truncating the inspector stream that dry
374
+ // run's completeness gate depends on.
375
+ //
376
+ // This IS a single bounded `await`, and an `await` genuinely yields
377
+ // this process's event loop for up to DRAIN_ACK_TIMEOUT_MS — it is not
378
+ // a no-op with respect to timer/microtask starvation, and does not
379
+ // pretend to be. What makes it safe here is ordering, not avoidance:
380
+ // writeCoverageData() above already ran and the coverage snapshot is
381
+ // already on disk by the time this wait starts, so anything that
382
+ // executes during the wait cannot alter what was persisted. This must
383
+ // stay the LAST coverage-adjacent step before ws.close() — no
384
+ // coverage-relevant work should be added after it starts. Separately,
385
+ // it does NOT drain THIS process's own microtask/timer queue on
386
+ // purpose (that risk is documented in the LIMITATION comment above); it
387
+ // only waits on a message sent FROM the parent runner process.
388
+ if(ws && ws.readyState === WebSocket.OPEN) {
389
+ try {
390
+ await new Promise<void>((resolve) => {
391
+ const wsForDrain = ws!;
392
+ const timeout = setTimeout(() => {
393
+ console.warn('[Stryker] Timeout waiting for drain acknowledgment');
394
+ resolve();
395
+ }, DRAIN_ACK_TIMEOUT_MS);
396
+
397
+ wsForDrain.onmessage = (event) => {
398
+ if(event.data === 'drained') {
399
+ clearTimeout(timeout);
400
+ resolve();
401
+ }
402
+ };
403
+
404
+ wsForDrain.onerror = () => {
405
+ clearTimeout(timeout);
406
+ resolve();
407
+ };
408
+
409
+ try {
410
+ wsForDrain.send('drain-request');
411
+ } catch {
412
+ clearTimeout(timeout);
413
+ resolve();
414
+ }
415
+ });
416
+ } catch (error) {
417
+ console.warn('[Stryker] Error during drain handshake:', error);
418
+ }
419
+ }
420
+
421
+ ws?.close();
346
422
  });
347
423
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.3.4",
3
+ "version": "1.3.5",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",