@hughescr/stryker-bun-runner 1.3.4 → 1.3.6

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,74 @@ 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.
255
+
256
+ The runner's side of this wait is progress-based, not a fixed timer: it keeps
257
+ extending as long as the inspector connection is still receiving frames of any
258
+ kind, since continued arrivals are proof a backlog is actively draining, and
259
+ only gives up once a period of true silence — no frames at all — has elapsed. A
260
+ separate, much larger absolute ceiling also exists, but purely as hang
261
+ prevention for a connection that never goes silent (or never acks) at all; it
262
+ is not the normal way this wait ends. Either way, once the runner gives up (via
263
+ silence or the ceiling), it still releases the child immediately rather than
264
+ leaving it to time out on its own — the child-side timeout only governs the
265
+ case where the sync channel itself is dead or unresponsive. Hitting any of
266
+ these bounds still reverts to the original pre-handshake behavior (including
267
+ this gate) exactly as before, so the handshake can only reduce how often this
268
+ gate fires, never mask a real truncation from it.
269
+
245
270
  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.
271
+ `ORPHANED_KEY_ABS_FLOOR`, the drain wait `INSPECTOR_DRAIN_TIMEOUT_MS`, and the drain-handshake
272
+ bounds (`DRAIN_ACK_SILENCE_TIMEOUT_MS` and `DRAIN_ACK_ABSOLUTE_CEILING_MS`, both in
273
+ `src/bun-test-runner.ts`) — are fixed module-level constants. The matching preload-side
274
+ ceiling in `src/templates/coverage-preload.ts` is kept above the runner's absolute ceiling,
275
+ so it remains the true outermost backstop even though it should now rarely if ever be the
276
+ one that actually fires. There is currently no config option to override any of these; if
277
+ the defaults produce false positives in your environment (e.g. a CI runner with very
278
+ different contention characteristics than the ones this gate was tuned against), a config
279
+ knob is a possible follow-up — please open an issue rather than patching the constants
280
+ locally. Separately, the dry-run child process's own kill timeout is automatically extended
281
+ by the drain ceiling on top of `bun.timeout`, so the drain handshake itself never gets cut
282
+ short by that watchdog. That watchdog covers the child's whole lifetime rather than being
283
+ phase-specific, though, so as a side effect a dry run whose tests themselves hang (rather
284
+ than the drain handshake) is also only detected after `bun.timeout` plus the ceiling — a
285
+ one-time cost on the single dry-run child, not the per-mutant hot loop. Mutant runs are
286
+ unaffected by any of this and use `bun.timeout` unchanged.
287
+
288
+ This handshake only covers the `dryRun` path (where coverage collection and the
289
+ completeness gate apply) — individual mutant runs are not held open the same way,
290
+ since they run small, `--test-name-pattern`-filtered subsets where the same
291
+ backlog-under-contention risk is negligible and the completeness gate does not
292
+ apply to them.
293
+
294
+ At the default (WARN) log level, dry runs also emit a few lines tracing this
295
+ handshake: `Drain-request received`, `Drain handler settled via ...`, and
296
+ `Post-drain inspector snapshot`, reporting the round-trip's outcome (`ack`,
297
+ `silence`, `ceiling`, or `send-rejected`), the found/start/end event-count
298
+ deltas observed during the wait, and any found-id gaps. A separate DEBUG-level
299
+ line notes if the inspector socket closed while the run was still thought to
300
+ be in progress — this is logged at DEBUG rather than WARN because the child
301
+ closing its own socket right after receiving `'drained'` routinely wins the
302
+ race against the runner's own close-expectation on a clean run, so on its own
303
+ it is not evidence of anything wrong (it is folded into the completeness
304
+ gate's error message as corroborating context only if that gate has already
305
+ fired for another reason). Together the WARN-level lines are useful for
306
+ telling apart two different failure shapes: residual loss caused by a
307
+ runner-side bound being hit (a give-up
308
+ outcome — `silence` or `ceiling`) versus loss happening inside Bun's own
309
+ inspector agent (found-id gaps persisting even though the round-trip `ack`
310
+ succeeded). One caveat: gap detection assumes Bun assigns test-discovery ids
311
+ densely, which has been observed but is not a guaranteed contract, so treat
312
+ gap reports as diagnostic rather than definitive.
252
313
 
253
314
  ### Coverage-bleed warning (dry run only)
254
315
 
@@ -277,6 +338,13 @@ of them in a clean run's logs is worth investigating before trusting the score.
277
338
 
278
339
  - **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
340
 
341
+ - **Inspector-stream drain handshake covers `dryRun` only** — the hold-open-until-drained
342
+ handshake described under "Dry-run completeness gate" above only runs for the dry run
343
+ (where a `SyncServer` and coverage collection are set up). Individual mutant runs are not
344
+ held open the same way: they run small, filtered test subsets where the backlog-under-CPU-
345
+ contention risk that motivated the handshake is negligible, and the completeness gate does
346
+ not apply to mutant runs in the first place.
347
+
280
348
  **Upgrade note: duplicate-name test suffixes**
281
349
 
282
350
  The runner reconciles how it assigns the `' [N]'` disambiguating suffix to
package/dist/index.js CHANGED
@@ -6000,6 +6000,10 @@ class InspectorClient {
6000
6000
  wsClosed = false;
6001
6001
  _wasClosedUnexpectedly = false;
6002
6002
  closeWaiters = [];
6003
+ lastFrameReceivedAt = Date.now();
6004
+ foundCount = 0;
6005
+ startCount = 0;
6006
+ endCount = 0;
6003
6007
  constructor(options) {
6004
6008
  this.handlers = options.handlers ?? {};
6005
6009
  this.WebSocketClass = options.WebSocketClass ?? wrapper_default;
@@ -6025,6 +6029,7 @@ class InspectorClient {
6025
6029
  this.ws = ws;
6026
6030
  ws.addEventListener("open", () => {
6027
6031
  clearTimeout(timeoutTimer);
6032
+ this.lastFrameReceivedAt = Date.now();
6028
6033
  resolve3();
6029
6034
  });
6030
6035
  ws.addEventListener("error", () => {
@@ -6041,17 +6046,18 @@ class InspectorClient {
6041
6046
  });
6042
6047
  });
6043
6048
  }
6044
- async send(method, params) {
6049
+ async send(method, params, timeoutMs) {
6045
6050
  if (!this.ws || this.ws.readyState !== wrapper_default.OPEN) {
6046
6051
  throw new InspectorConnectionError("WebSocket not connected");
6047
6052
  }
6048
6053
  const id = ++this.messageId;
6049
6054
  const message = { id, method, params };
6050
6055
  return new Promise((resolve3, reject) => {
6056
+ const effectiveTimeoutMs = timeoutMs ?? this.state.requestTimeout;
6051
6057
  const timer = setTimeout(() => {
6052
6058
  this.pendingRequests.delete(id);
6053
- reject(new InspectorTimeoutError(`Request timeout after ${this.state.requestTimeout}ms: ${method}`));
6054
- }, this.state.requestTimeout);
6059
+ reject(new InspectorTimeoutError(`Request timeout after ${effectiveTimeoutMs}ms: ${method}`));
6060
+ }, effectiveTimeoutMs);
6055
6061
  this.pendingRequests.set(id, { resolve: resolve3, reject, timer });
6056
6062
  try {
6057
6063
  this.ws.send(JSON.stringify(message));
@@ -6118,7 +6124,36 @@ class InspectorClient {
6118
6124
  getTest(id) {
6119
6125
  return this.testHierarchy.get(id);
6120
6126
  }
6127
+ getMsSinceLastFrame() {
6128
+ return Date.now() - this.lastFrameReceivedAt;
6129
+ }
6130
+ getEventCounts() {
6131
+ return { found: this.foundCount, start: this.startCount, end: this.endCount };
6132
+ }
6133
+ getFoundIdGaps() {
6134
+ if (this.testHierarchy.size === 0) {
6135
+ return [];
6136
+ }
6137
+ let min = Infinity;
6138
+ let max = -Infinity;
6139
+ for (const id of this.testHierarchy.keys()) {
6140
+ if (id < min) {
6141
+ min = id;
6142
+ }
6143
+ if (id > max) {
6144
+ max = id;
6145
+ }
6146
+ }
6147
+ const gaps = [];
6148
+ for (let id = min + 1;id < max; id++) {
6149
+ if (!this.testHierarchy.has(id)) {
6150
+ gaps.push(id);
6151
+ }
6152
+ }
6153
+ return gaps;
6154
+ }
6121
6155
  handleMessage(data) {
6156
+ this.lastFrameReceivedAt = Date.now();
6122
6157
  try {
6123
6158
  const message = JSON.parse(data.toString());
6124
6159
  if (message.id !== undefined) {
@@ -6146,6 +6181,7 @@ class InspectorClient {
6146
6181
  }
6147
6182
  }
6148
6183
  handleTestFound(params) {
6184
+ this.foundCount++;
6149
6185
  const { fullName, bunName } = this.buildFullName(params.id, params.name, params.parentId);
6150
6186
  const testInfo = {
6151
6187
  id: params.id,
@@ -6163,6 +6199,7 @@ class InspectorClient {
6163
6199
  }
6164
6200
  }
6165
6201
  handleTestStart(params) {
6202
+ this.startCount++;
6166
6203
  const testInfo = this.testHierarchy.get(params.id);
6167
6204
  if (!testInfo) {
6168
6205
  this.handleError(new Error(`Test start event for unknown test ID: ${params.id}`));
@@ -6176,6 +6213,7 @@ class InspectorClient {
6176
6213
  }
6177
6214
  }
6178
6215
  handleTestEnd(params) {
6216
+ this.endCount++;
6179
6217
  const testInfo = this.testHierarchy.get(params.id);
6180
6218
  if (!testInfo) {
6181
6219
  this.handleError(new Error(`Test end event for unknown test ID: ${params.id}`));
@@ -6223,6 +6261,9 @@ class InspectorClient {
6223
6261
  return;
6224
6262
  }
6225
6263
  this._wasClosedUnexpectedly = true;
6264
+ if (this.handlers.onUnexpectedClose) {
6265
+ this.handlers.onUnexpectedClose({ wsClosed: this.wsClosed, closeExpected: this.closeExpected, isClosing: this.isClosing });
6266
+ }
6226
6267
  const error = new InspectorConnectionError("Connection closed unexpectedly");
6227
6268
  for (const pending of this.pendingRequests.values()) {
6228
6269
  clearTimeout(pending.timer);
@@ -6657,6 +6698,13 @@ async function getAvailablePort() {
6657
6698
  }
6658
6699
  // src/utils/sync-server.ts
6659
6700
  import { createServer as createServer2 } from "node:http";
6701
+ function rawDataToString(data) {
6702
+ if (Array.isArray(data)) {
6703
+ return Buffer.concat(data).toString("utf8");
6704
+ }
6705
+ return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
6706
+ }
6707
+
6660
6708
  class SyncServer {
6661
6709
  httpServer = null;
6662
6710
  wss = null;
@@ -6666,6 +6714,8 @@ class SyncServer {
6666
6714
  createHttpServer;
6667
6715
  WebSocketServerClass;
6668
6716
  webSocketOpenState;
6717
+ drainHandler = null;
6718
+ drainInFlight = null;
6669
6719
  constructor(options) {
6670
6720
  this.port = options.port;
6671
6721
  this.createHttpServer = options.createHttpServer ?? createServer2;
@@ -6698,7 +6748,11 @@ class SyncServer {
6698
6748
  ws.on("close", () => {
6699
6749
  this.clients.delete(ws);
6700
6750
  });
6701
- ws.on("message", () => {});
6751
+ ws.on("message", (data) => {
6752
+ if (rawDataToString(data) === "drain-request") {
6753
+ this.handleDrainRequest(ws);
6754
+ }
6755
+ });
6702
6756
  });
6703
6757
  this.httpServer.on("error", reject);
6704
6758
  this.httpServer.listen(this.port, () => {
@@ -6719,8 +6773,32 @@ class SyncServer {
6719
6773
  } catch {}
6720
6774
  }
6721
6775
  }
6776
+ setDrainHandler(handler) {
6777
+ this.drainHandler = handler;
6778
+ }
6779
+ handleDrainRequest(ws) {
6780
+ if (!this.drainHandler) {
6781
+ return;
6782
+ }
6783
+ this.drainInFlight ??= this.drainHandler();
6784
+ const inFlight = this.drainInFlight;
6785
+ (async () => {
6786
+ try {
6787
+ await inFlight;
6788
+ } catch {
6789
+ return;
6790
+ }
6791
+ try {
6792
+ if (ws.readyState === this.webSocketOpenState) {
6793
+ ws.send("drained");
6794
+ }
6795
+ } catch {}
6796
+ })();
6797
+ }
6722
6798
  async close() {
6723
6799
  this.readyLatched = false;
6800
+ this.drainHandler = null;
6801
+ this.drainInFlight = null;
6724
6802
  for (const client of this.clients) {
6725
6803
  try {
6726
6804
  client.close();
@@ -8030,6 +8108,47 @@ function sleep(ms) {
8030
8108
  setTimeout(resolve3, ms);
8031
8109
  });
8032
8110
  }
8111
+ var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
8112
+ var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
8113
+ var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
8114
+ var MAX_GAP_IDS_LISTED = 20;
8115
+
8116
+ class DrainWaitTimeoutError extends Error {
8117
+ reason;
8118
+ constructor(message, reason) {
8119
+ super(message);
8120
+ this.name = "DrainWaitTimeoutError";
8121
+ this.reason = reason;
8122
+ }
8123
+ }
8124
+ function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs, message) {
8125
+ const startedAt = Date.now();
8126
+ let timer;
8127
+ const promise2 = new Promise((_resolve, reject) => {
8128
+ timer = setInterval(() => {
8129
+ const sinceLastFrame = inspector.getMsSinceLastFrame();
8130
+ const totalElapsed = Date.now() - startedAt;
8131
+ if (totalElapsed >= absoluteCeilingMs) {
8132
+ clearInterval(timer);
8133
+ reject(new DrainWaitTimeoutError(`${message}: ${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
8134
+ } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
8135
+ clearInterval(timer);
8136
+ reject(new DrainWaitTimeoutError(`${message}: ${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
8137
+ }
8138
+ }, DRAIN_SILENCE_POLL_INTERVAL_MS);
8139
+ });
8140
+ return { promise: promise2, cancel: () => clearInterval(timer) };
8141
+ }
8142
+ function formatGapIdList(gaps) {
8143
+ if (gaps.length === 0) {
8144
+ return "";
8145
+ }
8146
+ const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
8147
+ return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
8148
+ }
8149
+ function formatDrainSettleReason(reason) {
8150
+ return reason === undefined ? "never requested" : `settled via ${reason}`;
8151
+ }
8033
8152
  function buildTestNameIndex(tests, bunNames) {
8034
8153
  const testNameIndex = new Map;
8035
8154
  for (const [i, test] of tests.entries()) {
@@ -8366,7 +8485,7 @@ ${stack}` : baseFailureMessage;
8366
8485
  const testFiles = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
8367
8486
  const testProcess = runBunTests({
8368
8487
  bunPath: this.bunPath,
8369
- timeout: this.timeout,
8488
+ timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
8370
8489
  env: this.env,
8371
8490
  bunArgs: this.bunArgs,
8372
8491
  bunfigPath,
@@ -8414,6 +8533,9 @@ exit=%s timedOut=%s
8414
8533
  handlers: {
8415
8534
  onError: (error) => {
8416
8535
  this.logger.warn("Inspector error: %s", error.message);
8536
+ },
8537
+ onUnexpectedClose: (context) => {
8538
+ this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s) — often benign; see checkCompletenessGate", context.wsClosed, context.closeExpected, context.isClosing);
8417
8539
  }
8418
8540
  }
8419
8541
  });
@@ -8431,6 +8553,32 @@ exit=%s timedOut=%s
8431
8553
  errorMessage: `Failed to connect to Bun inspector: ${errorMsg}`
8432
8554
  };
8433
8555
  }
8556
+ let drainSettleReason;
8557
+ syncServer.setDrainHandler(async () => {
8558
+ const drainRequestReceivedAt = Date.now();
8559
+ const countsAtRequest = inspector.getEventCounts();
8560
+ const gapsAtRequest = inspector.getFoundIdGaps();
8561
+ this.logger.warn("Drain-request received: %d/%d/%d found/start/end events received so far; %d found-id gap(s)%s", countsAtRequest.found, countsAtRequest.start, countsAtRequest.end, gapsAtRequest.length, formatGapIdList(gapsAtRequest));
8562
+ const { promise: silencePromise, cancel: cancelSilence } = raceAgainstSilence(inspector, DRAIN_ACK_SILENCE_TIMEOUT_MS, DRAIN_ACK_ABSOLUTE_CEILING_MS, "Inspector drain wait gave up");
8563
+ try {
8564
+ await Promise.race([
8565
+ inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000),
8566
+ silencePromise
8567
+ ]);
8568
+ drainSettleReason = "ack";
8569
+ } catch (error) {
8570
+ drainSettleReason = error instanceof DrainWaitTimeoutError ? error.reason : "send-rejected";
8571
+ if (drainSettleReason === "send-rejected") {
8572
+ this.logger.warn("Inspector drain round-trip rejected before any wait bound was hit: %s", error instanceof Error ? error.message : String(error));
8573
+ }
8574
+ } finally {
8575
+ cancelSilence();
8576
+ const elapsedMs = Date.now() - drainRequestReceivedAt;
8577
+ const countsAtSettle = inspector.getEventCounts();
8578
+ const gapsAtSettle = inspector.getFoundIdGaps();
8579
+ this.logger.warn("Drain handler settled via %s after %dms; events during wait +%d/+%d/+%d found/start/end; found-id gaps %d -> %d%s", drainSettleReason, elapsedMs, countsAtSettle.found - countsAtRequest.found, countsAtSettle.start - countsAtRequest.start, countsAtSettle.end - countsAtRequest.end, gapsAtRequest.length, gapsAtSettle.length, drainSettleReason === "ack" && gapsAtSettle.length > 0 ? " — ack resolved but gaps remain: the ack may under-prove drain" : "");
8580
+ }
8581
+ });
8434
8582
  syncServer.signalReady();
8435
8583
  this.logger.debug("Signaled preload script to proceed");
8436
8584
  const result = await testProcess;
@@ -8442,6 +8590,8 @@ exit=%s timedOut=%s
8442
8590
  const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
8443
8591
  await inspector.close();
8444
8592
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
8593
+ const finalGaps = inspector.getFoundIdGaps();
8594
+ this.logger.warn("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), formatDrainSettleReason(drainSettleReason));
8445
8595
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
8446
8596
  const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
8447
8597
  if (earlyResult) {
@@ -79,6 +79,17 @@ 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
+ // The runner now sends 'drained' once its own wait settles — INCLUDING when
86
+ // it gave up (silence or absolute ceiling) — so this timer only ever governs
87
+ // if the sync channel itself is dead or unresponsive. Deliberately ABOVE the
88
+ // runner-side absolute ceiling (DRAIN_ACK_ABSOLUTE_CEILING_MS in
89
+ // bun-test-runner.ts) so a stuck wait is always governed by that shorter
90
+ // ceiling first.
91
+ const DRAIN_ACK_TIMEOUT_MS = 40_000;
92
+
82
93
  // Per-file test counters for per-test coverage tracking.
83
94
  //
84
95
  // Bun runs multiple test files sequentially inside the same worker process,
@@ -314,7 +325,7 @@ if(shouldCollectCoverage) {
314
325
  strykerGlobal.currentTestId = undefined;
315
326
  });
316
327
 
317
- afterAll(() => {
328
+ afterAll(async () => {
318
329
  // Final gap check, best-effort: catches bleed that has already recorded a
319
330
  // counter delta by the time afterAll runs, with no following beforeEach
320
331
  // left to catch it any other way. This preload's afterAll fires once per
@@ -339,9 +350,76 @@ if(shouldCollectCoverage) {
339
350
  }
340
351
  }
341
352
 
342
- ws?.close();
353
+ // Coverage must be finalized — gap check above, then the write itself —
354
+ // BEFORE the drain-ack wait below, not after. The wait yields this
355
+ // process's event loop for up to DRAIN_ACK_TIMEOUT_MS; if it ran first,
356
+ // any stray timer or promise continuation left behind by the last test
357
+ // could fire during that yield, touch mutantCoverage.static, and leak
358
+ // into the persisted snapshot — reintroducing exactly the class of risk
359
+ // the gap-window bleed check above exists to catch. Writing first means
360
+ // the snapshot is already on disk before that window even opens, so
361
+ // nothing that runs during the wait can affect what was persisted.
343
362
  writeCoverageData();
344
363
  // Clear the accumulator now that it has been written out.
345
364
  lateHits.length = 0;
365
+
366
+ // ====================================================================
367
+ // Inspector-stream drain handshake
368
+ // ====================================================================
369
+ // Block (bounded) on a drain acknowledgment from the runner BEFORE
370
+ // closing this socket / allowing this process to exit. Without this,
371
+ // nothing synchronizes "the runner has received and processed every
372
+ // inspector event" with "this child process is allowed to exit" — a
373
+ // contended CPU (e.g. a 2-core CI box) can leave the runner's
374
+ // InspectorClient with an unprocessed backlog at the moment this
375
+ // process exits, silently truncating the inspector stream that dry
376
+ // run's completeness gate depends on.
377
+ //
378
+ // This IS a single bounded `await`, and an `await` genuinely yields
379
+ // this process's event loop for up to DRAIN_ACK_TIMEOUT_MS — it is not
380
+ // a no-op with respect to timer/microtask starvation, and does not
381
+ // pretend to be. What makes it safe here is ordering, not avoidance:
382
+ // writeCoverageData() above already ran and the coverage snapshot is
383
+ // already on disk by the time this wait starts, so anything that
384
+ // executes during the wait cannot alter what was persisted. This must
385
+ // stay the LAST coverage-adjacent step before ws.close() — no
386
+ // coverage-relevant work should be added after it starts. Separately,
387
+ // it does NOT drain THIS process's own microtask/timer queue on
388
+ // purpose (that risk is documented in the LIMITATION comment above); it
389
+ // only waits on a message sent FROM the parent runner process.
390
+ if(ws && ws.readyState === WebSocket.OPEN) {
391
+ try {
392
+ await new Promise<void>((resolve) => {
393
+ const wsForDrain = ws!;
394
+ const timeout = setTimeout(() => {
395
+ console.warn('[Stryker] Timeout waiting for drain acknowledgment');
396
+ resolve();
397
+ }, DRAIN_ACK_TIMEOUT_MS);
398
+
399
+ wsForDrain.onmessage = (event) => {
400
+ if(event.data === 'drained') {
401
+ clearTimeout(timeout);
402
+ resolve();
403
+ }
404
+ };
405
+
406
+ wsForDrain.onerror = () => {
407
+ clearTimeout(timeout);
408
+ resolve();
409
+ };
410
+
411
+ try {
412
+ wsForDrain.send('drain-request');
413
+ } catch {
414
+ clearTimeout(timeout);
415
+ resolve();
416
+ }
417
+ });
418
+ } catch (error) {
419
+ console.warn('[Stryker] Error during drain handshake:', error);
420
+ }
421
+ }
422
+
423
+ ws?.close();
346
424
  });
347
425
  }
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.6",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",