@hughescr/stryker-bun-runner 1.3.5 → 1.3.7

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
@@ -251,21 +251,39 @@ of them in a clean run's logs is worth investigating before trusting the score.
251
251
  runners: previously, nothing synchronized "the runner has drained the inspector
252
252
  stream" with "the child process is allowed to exit," so a consumer that couldn't
253
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.
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.
260
269
 
261
270
  The gate's thresholds — `EXECUTION_SHORTFALL_ABS_FLOOR`, `EXECUTION_SHORTFALL_RATIO_THRESHOLD`,
262
271
  `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.
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.
269
287
 
270
288
  This handshake only covers the `dryRun` path (where coverage collection and the
271
289
  completeness gate apply) — individual mutant runs are not held open the same way,
@@ -273,6 +291,45 @@ of them in a clean run's logs is worth investigating before trusting the score.
273
291
  backlog-under-contention risk is negligible and the completeness gate does not
274
292
  apply to them.
275
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 ...`,
296
+ `Post-drain inspector snapshot`, and `Post-drain inspector close/collision
297
+ diagnostics`, reporting the round-trip's outcome (`ack`, `silence`,
298
+ `ceiling`, or `send-rejected`), the found/start/end event-count deltas
299
+ observed during the wait, any found-id gaps, the WebSocket close
300
+ code/reason/wasClean (plus how many ms after the last received frame the
301
+ close arrived), and raw-vs-unique found-event counts. A separate DEBUG-level
302
+ line notes if the inspector socket closed while the run was still thought to
303
+ be in progress (including the same close code/reason/wasClean detail) — this
304
+ is logged at DEBUG rather than WARN because the child closing its own socket
305
+ right after receiving `'drained'` routinely wins the race against the
306
+ runner's own close-expectation on a clean run, so on its own it is not
307
+ evidence of anything wrong (it is folded into the completeness gate's error
308
+ message as corroborating context — now including the captured close
309
+ code/reason — only if that gate has already fired for another reason).
310
+ Together the WARN-level lines are useful for telling apart two different
311
+ failure shapes: residual loss caused by a runner-side bound being hit (a
312
+ give-up outcome — `silence` or `ceiling`) versus loss happening inside Bun's
313
+ own inspector agent (found-id gaps persisting even though the round-trip
314
+ `ack` succeeded). One caveat: gap detection assumes Bun assigns
315
+ test-discovery ids densely, which has been observed but is not a guaranteed
316
+ contract — and even a dense (0-gap) id range does **not** prove
317
+ losslessness: a confirmed Bun TestReporter id-collision bug (two interleaved
318
+ `1..N` id sequences when `TestReporter.enable` lands mid-collection) keeps
319
+ ids dense while silently merging two distinct tests under one shared id.
320
+ That is exactly what the close/collision diagnostics line's
321
+ raw/unique/duplicate found counts exist to catch: a **nonzero duplicate
322
+ count is direct in-the-wild evidence of that id-collision bug**, and the
323
+ close code/reason/wasClean fields confirm or rule out a separate confirmed
324
+ Bun bug where `idleTimeout: 0` websockets are force-closed on a ~252-second
325
+ ping cycle (`ERR_WEBSOCKET_TIMEOUT`) — an abnormal close landing right on
326
+ that cadence points at the ping-cycle bug, while a clean close rules it out.
327
+ Finally, a WARN-level `Inspector request unanswered after ...` line fires if
328
+ an inspector protocol request (e.g. `TestReporter.enable`) goes unanswered
329
+ for more than 2 seconds while other frames are still arriving on the same
330
+ connection — a protocol-level stall signature distinct from the
331
+ total-silence give-up above.
332
+
276
333
  ### Coverage-bleed warning (dry run only)
277
334
 
278
335
  - **`mutant coverage was recorded between tests, after '<testName>' completed`**
package/dist/index.js CHANGED
@@ -5972,6 +5972,8 @@ function isTestReporterEndEvent(message) {
5972
5972
  }
5973
5973
 
5974
5974
  // src/inspector/inspector-client.ts
5975
+ var REQUEST_STALL_WARN_MS = 2000;
5976
+
5975
5977
  class InspectorTimeoutError extends Error {
5976
5978
  constructor(message) {
5977
5979
  super(message);
@@ -6000,6 +6002,14 @@ class InspectorClient {
6000
6002
  wsClosed = false;
6001
6003
  _wasClosedUnexpectedly = false;
6002
6004
  closeWaiters = [];
6005
+ lastFrameReceivedAt = Date.now();
6006
+ foundCount = 0;
6007
+ startCount = 0;
6008
+ endCount = 0;
6009
+ closeCode = undefined;
6010
+ closeReason = undefined;
6011
+ closeWasClean = undefined;
6012
+ msFromLastFrameToClose = undefined;
6003
6013
  constructor(options) {
6004
6014
  this.handlers = options.handlers ?? {};
6005
6015
  this.WebSocketClass = options.WebSocketClass ?? wrapper_default;
@@ -6025,6 +6035,7 @@ class InspectorClient {
6025
6035
  this.ws = ws;
6026
6036
  ws.addEventListener("open", () => {
6027
6037
  clearTimeout(timeoutTimer);
6038
+ this.lastFrameReceivedAt = Date.now();
6028
6039
  resolve3();
6029
6040
  });
6030
6041
  ws.addEventListener("error", () => {
@@ -6033,35 +6044,56 @@ class InspectorClient {
6033
6044
  this.handleError(error);
6034
6045
  reject(error);
6035
6046
  });
6036
- ws.addEventListener("close", () => {
6037
- this.handleClose();
6047
+ ws.addEventListener("close", (event) => {
6048
+ this.handleClose(event.code, event.reason, event.wasClean);
6038
6049
  });
6039
6050
  ws.addEventListener("message", (event) => {
6040
6051
  this.handleMessage(event.data);
6041
6052
  });
6042
6053
  });
6043
6054
  }
6044
- async send(method, params) {
6055
+ async send(method, params, timeoutMs) {
6045
6056
  if (!this.ws || this.ws.readyState !== wrapper_default.OPEN) {
6046
6057
  throw new InspectorConnectionError("WebSocket not connected");
6047
6058
  }
6048
6059
  const id = ++this.messageId;
6049
6060
  const message = { id, method, params };
6050
6061
  return new Promise((resolve3, reject) => {
6062
+ const effectiveTimeoutMs = timeoutMs ?? this.state.requestTimeout;
6063
+ const stallTimer = this.handlers.onRequestStall ? setTimeout(() => {
6064
+ if (this.pendingRequests.has(id)) {
6065
+ const msSinceLastFrame = this.getMsSinceLastFrame();
6066
+ if (msSinceLastFrame < REQUEST_STALL_WARN_MS) {
6067
+ this.handlers.onRequestStall({ method, id, msUnanswered: REQUEST_STALL_WARN_MS, msSinceLastFrame });
6068
+ }
6069
+ }
6070
+ }, REQUEST_STALL_WARN_MS) : undefined;
6051
6071
  const timer = setTimeout(() => {
6052
6072
  this.pendingRequests.delete(id);
6053
- reject(new InspectorTimeoutError(`Request timeout after ${this.state.requestTimeout}ms: ${method}`));
6054
- }, this.state.requestTimeout);
6055
- this.pendingRequests.set(id, { resolve: resolve3, reject, timer });
6073
+ if (stallTimer) {
6074
+ clearTimeout(stallTimer);
6075
+ }
6076
+ reject(new InspectorTimeoutError(`Request timeout after ${effectiveTimeoutMs}ms: ${method}`));
6077
+ }, effectiveTimeoutMs);
6078
+ this.pendingRequests.set(id, { resolve: resolve3, reject, timer, stallTimer });
6056
6079
  try {
6057
6080
  this.ws.send(JSON.stringify(message));
6058
6081
  } catch (error) {
6059
6082
  this.pendingRequests.delete(id);
6060
6083
  clearTimeout(timer);
6084
+ if (stallTimer) {
6085
+ clearTimeout(stallTimer);
6086
+ }
6061
6087
  reject(error instanceof Error ? error : new Error(String(error)));
6062
6088
  }
6063
6089
  });
6064
6090
  }
6091
+ clearPendingTimers(pending) {
6092
+ clearTimeout(pending.timer);
6093
+ if (pending.stallTimer) {
6094
+ clearTimeout(pending.stallTimer);
6095
+ }
6096
+ }
6065
6097
  async close() {
6066
6098
  if (this.isClosing || !this.ws) {
6067
6099
  return;
@@ -6069,7 +6101,7 @@ class InspectorClient {
6069
6101
  this.isClosing = true;
6070
6102
  const error = new InspectorConnectionError("Connection closed");
6071
6103
  for (const pending of this.pendingRequests.values()) {
6072
- clearTimeout(pending.timer);
6104
+ this.clearPendingTimers(pending);
6073
6105
  pending.reject(error);
6074
6106
  }
6075
6107
  this.pendingRequests.clear();
@@ -6118,14 +6150,59 @@ class InspectorClient {
6118
6150
  getTest(id) {
6119
6151
  return this.testHierarchy.get(id);
6120
6152
  }
6153
+ getMsSinceLastFrame() {
6154
+ return Date.now() - this.lastFrameReceivedAt;
6155
+ }
6156
+ getEventCounts() {
6157
+ return { found: this.foundCount, start: this.startCount, end: this.endCount };
6158
+ }
6159
+ getCloseInfo() {
6160
+ return {
6161
+ code: this.closeCode,
6162
+ reason: this.closeReason,
6163
+ wasClean: this.closeWasClean,
6164
+ msFromLastFrameToClose: this.msFromLastFrameToClose
6165
+ };
6166
+ }
6167
+ getFoundIdCollisionStats() {
6168
+ const uniqueFoundIdCount = this.testHierarchy.size;
6169
+ return {
6170
+ rawFoundCount: this.foundCount,
6171
+ uniqueFoundIdCount,
6172
+ duplicateFoundIdCount: this.foundCount - uniqueFoundIdCount
6173
+ };
6174
+ }
6175
+ getFoundIdGaps() {
6176
+ if (this.testHierarchy.size === 0) {
6177
+ return [];
6178
+ }
6179
+ let min = Infinity;
6180
+ let max = -Infinity;
6181
+ for (const id of this.testHierarchy.keys()) {
6182
+ if (id < min) {
6183
+ min = id;
6184
+ }
6185
+ if (id > max) {
6186
+ max = id;
6187
+ }
6188
+ }
6189
+ const gaps = [];
6190
+ for (let id = min + 1;id < max; id++) {
6191
+ if (!this.testHierarchy.has(id)) {
6192
+ gaps.push(id);
6193
+ }
6194
+ }
6195
+ return gaps;
6196
+ }
6121
6197
  handleMessage(data) {
6198
+ this.lastFrameReceivedAt = Date.now();
6122
6199
  try {
6123
6200
  const message = JSON.parse(data.toString());
6124
6201
  if (message.id !== undefined) {
6125
6202
  const pending = this.pendingRequests.get(message.id);
6126
6203
  if (pending) {
6127
6204
  this.pendingRequests.delete(message.id);
6128
- clearTimeout(pending.timer);
6205
+ this.clearPendingTimers(pending);
6129
6206
  if (message.error) {
6130
6207
  pending.reject(new Error(`Inspector error: ${message.error.message}`));
6131
6208
  } else {
@@ -6146,6 +6223,7 @@ class InspectorClient {
6146
6223
  }
6147
6224
  }
6148
6225
  handleTestFound(params) {
6226
+ this.foundCount++;
6149
6227
  const { fullName, bunName } = this.buildFullName(params.id, params.name, params.parentId);
6150
6228
  const testInfo = {
6151
6229
  id: params.id,
@@ -6163,6 +6241,7 @@ class InspectorClient {
6163
6241
  }
6164
6242
  }
6165
6243
  handleTestStart(params) {
6244
+ this.startCount++;
6166
6245
  const testInfo = this.testHierarchy.get(params.id);
6167
6246
  if (!testInfo) {
6168
6247
  this.handleError(new Error(`Test start event for unknown test ID: ${params.id}`));
@@ -6176,6 +6255,7 @@ class InspectorClient {
6176
6255
  }
6177
6256
  }
6178
6257
  handleTestEnd(params) {
6258
+ this.endCount++;
6179
6259
  const testInfo = this.testHierarchy.get(params.id);
6180
6260
  if (!testInfo) {
6181
6261
  this.handleError(new Error(`Test end event for unknown test ID: ${params.id}`));
@@ -6212,8 +6292,12 @@ class InspectorClient {
6212
6292
  }
6213
6293
  return { fullName: parts.join(" > "), bunName: parts.join(" ") };
6214
6294
  }
6215
- handleClose() {
6295
+ handleClose(code, reason, wasClean) {
6216
6296
  this.wsClosed = true;
6297
+ this.closeCode = code;
6298
+ this.closeReason = reason;
6299
+ this.closeWasClean = wasClean;
6300
+ this.msFromLastFrameToClose = Date.now() - this.lastFrameReceivedAt;
6217
6301
  const waiters = this.closeWaiters;
6218
6302
  this.closeWaiters = [];
6219
6303
  for (const finish of waiters) {
@@ -6223,9 +6307,20 @@ class InspectorClient {
6223
6307
  return;
6224
6308
  }
6225
6309
  this._wasClosedUnexpectedly = true;
6310
+ if (this.handlers.onUnexpectedClose) {
6311
+ this.handlers.onUnexpectedClose({
6312
+ wsClosed: this.wsClosed,
6313
+ closeExpected: this.closeExpected,
6314
+ isClosing: this.isClosing,
6315
+ closeCode: this.closeCode,
6316
+ closeReason: this.closeReason,
6317
+ closeWasClean: this.closeWasClean,
6318
+ msFromLastFrameToClose: this.msFromLastFrameToClose
6319
+ });
6320
+ }
6226
6321
  const error = new InspectorConnectionError("Connection closed unexpectedly");
6227
6322
  for (const pending of this.pendingRequests.values()) {
6228
- clearTimeout(pending.timer);
6323
+ this.clearPendingTimers(pending);
6229
6324
  pending.reject(error);
6230
6325
  }
6231
6326
  this.pendingRequests.clear();
@@ -8067,14 +8162,46 @@ function sleep(ms) {
8067
8162
  setTimeout(resolve3, ms);
8068
8163
  });
8069
8164
  }
8070
- function rejectAfterMs(ms, message) {
8165
+ var DRAIN_ACK_SILENCE_TIMEOUT_MS = 4000;
8166
+ var DRAIN_ACK_ABSOLUTE_CEILING_MS = 30000;
8167
+ var DRAIN_SILENCE_POLL_INTERVAL_MS = 250;
8168
+ var MAX_GAP_IDS_LISTED = 20;
8169
+
8170
+ class DrainWaitTimeoutError extends Error {
8171
+ reason;
8172
+ constructor(message, reason) {
8173
+ super(message);
8174
+ this.name = "DrainWaitTimeoutError";
8175
+ this.reason = reason;
8176
+ }
8177
+ }
8178
+ function raceAgainstSilence(inspector, silenceMs, absoluteCeilingMs, message) {
8179
+ const startedAt = Date.now();
8071
8180
  let timer;
8072
8181
  const promise2 = new Promise((_resolve, reject) => {
8073
- timer = setTimeout(() => {
8074
- reject(new Error(message));
8075
- }, ms);
8182
+ timer = setInterval(() => {
8183
+ const sinceLastFrame = inspector.getMsSinceLastFrame();
8184
+ const totalElapsed = Date.now() - startedAt;
8185
+ if (totalElapsed >= absoluteCeilingMs) {
8186
+ clearInterval(timer);
8187
+ reject(new DrainWaitTimeoutError(`${message}: ${absoluteCeilingMs}ms absolute ceiling reached`, "ceiling"));
8188
+ } else if (totalElapsed >= silenceMs && sinceLastFrame >= silenceMs) {
8189
+ clearInterval(timer);
8190
+ reject(new DrainWaitTimeoutError(`${message}: ${sinceLastFrame}ms of inspector silence (limit ${silenceMs}ms)`, "silence"));
8191
+ }
8192
+ }, DRAIN_SILENCE_POLL_INTERVAL_MS);
8076
8193
  });
8077
- return { promise: promise2, cancel: () => clearTimeout(timer) };
8194
+ return { promise: promise2, cancel: () => clearInterval(timer) };
8195
+ }
8196
+ function formatGapIdList(gaps) {
8197
+ if (gaps.length === 0) {
8198
+ return "";
8199
+ }
8200
+ const shown = gaps.slice(0, MAX_GAP_IDS_LISTED).join(",");
8201
+ return gaps.length > MAX_GAP_IDS_LISTED ? ` [${shown},…]` : ` [${shown}]`;
8202
+ }
8203
+ function formatDrainSettleReason(reason) {
8204
+ return reason === undefined ? "never requested" : `settled via ${reason}`;
8078
8205
  }
8079
8206
  function buildTestNameIndex(tests, bunNames) {
8080
8207
  const testNameIndex = new Map;
@@ -8093,7 +8220,6 @@ var EXECUTION_SHORTFALL_ABS_FLOOR = 10;
8093
8220
  var EXECUTION_SHORTFALL_RATIO_THRESHOLD = 0.05;
8094
8221
  var ORPHANED_KEY_ABS_FLOOR = 5;
8095
8222
  var INSPECTOR_DRAIN_TIMEOUT_MS = 1000;
8096
- var DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS = 4000;
8097
8223
 
8098
8224
  class BunTestRunner {
8099
8225
  logger;
@@ -8413,7 +8539,7 @@ ${stack}` : baseFailureMessage;
8413
8539
  const testFiles = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
8414
8540
  const testProcess = runBunTests({
8415
8541
  bunPath: this.bunPath,
8416
- timeout: this.timeout,
8542
+ timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
8417
8543
  env: this.env,
8418
8544
  bunArgs: this.bunArgs,
8419
8545
  bunfigPath,
@@ -8461,6 +8587,12 @@ exit=%s timedOut=%s
8461
8587
  handlers: {
8462
8588
  onError: (error) => {
8463
8589
  this.logger.warn("Inspector error: %s", error.message);
8590
+ },
8591
+ onUnexpectedClose: (context) => {
8592
+ this.logger.debug("Inspector WebSocket closed while the run was still thought to be in progress (wsClosed=%s closeExpected=%s isClosing=%s closeCode=%s closeReason=%s closeWasClean=%s msFromLastFrameToClose=%s) — often benign; see checkCompletenessGate", context.wsClosed, context.closeExpected, context.isClosing, String(context.closeCode), String(context.closeReason), String(context.closeWasClean), String(context.msFromLastFrameToClose));
8593
+ },
8594
+ onRequestStall: (info) => {
8595
+ this.logger.warn("Inspector request unanswered after %dms even though other frames are still arriving (last frame %dms ago): %s (id=%d) — possible protocol-level stall distinct from total silence", info.msUnanswered, info.msSinceLastFrame, info.method, info.id);
8464
8596
  }
8465
8597
  }
8466
8598
  });
@@ -8478,15 +8610,30 @@ exit=%s timedOut=%s
8478
8610
  errorMessage: `Failed to connect to Bun inspector: ${errorMsg}`
8479
8611
  };
8480
8612
  }
8613
+ let drainSettleReason;
8481
8614
  syncServer.setDrainHandler(async () => {
8482
- const { promise: timeoutPromise, cancel: cancelTimeout } = rejectAfterMs(DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS, "Inspector drain round-trip timed out");
8615
+ const drainRequestReceivedAt = Date.now();
8616
+ const countsAtRequest = inspector.getEventCounts();
8617
+ const gapsAtRequest = inspector.getFoundIdGaps();
8618
+ 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));
8619
+ const { promise: silencePromise, cancel: cancelSilence } = raceAgainstSilence(inspector, DRAIN_ACK_SILENCE_TIMEOUT_MS, DRAIN_ACK_ABSOLUTE_CEILING_MS, "Inspector drain wait gave up");
8483
8620
  try {
8484
8621
  await Promise.race([
8485
- inspector.send("TestReporter.enable", {}),
8486
- timeoutPromise
8622
+ inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000),
8623
+ silencePromise
8487
8624
  ]);
8625
+ drainSettleReason = "ack";
8626
+ } catch (error) {
8627
+ drainSettleReason = error instanceof DrainWaitTimeoutError ? error.reason : "send-rejected";
8628
+ if (drainSettleReason === "send-rejected") {
8629
+ this.logger.warn("Inspector drain round-trip rejected before any wait bound was hit: %s", error instanceof Error ? error.message : String(error));
8630
+ }
8488
8631
  } finally {
8489
- cancelTimeout();
8632
+ cancelSilence();
8633
+ const elapsedMs = Date.now() - drainRequestReceivedAt;
8634
+ const countsAtSettle = inspector.getEventCounts();
8635
+ const gapsAtSettle = inspector.getFoundIdGaps();
8636
+ 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" : "");
8490
8637
  }
8491
8638
  });
8492
8639
  syncServer.signalReady();
@@ -8500,12 +8647,17 @@ exit=%s timedOut=%s
8500
8647
  const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
8501
8648
  await inspector.close();
8502
8649
  this.logger.debug("Inspector collected %d tests in hierarchy, %d in execution order", testHierarchy.length, executionOrder.length);
8650
+ const finalGaps = inspector.getFoundIdGaps();
8651
+ this.logger.warn("Post-drain inspector snapshot: %d found-id gap(s) remaining%s; drain handshake %s", finalGaps.length, formatGapIdList(finalGaps), formatDrainSettleReason(drainSettleReason));
8652
+ const closeInfo = inspector.getCloseInfo();
8653
+ const collisionStats = inspector.getFoundIdCollisionStats();
8654
+ this.logger.warn("Post-drain inspector close/collision diagnostics: WS close code=%s reason=%s wasClean=%s msFromLastFrameToClose=%s; " + "found events %d raw / %d unique id(s) / %d duplicate id event(s) (nonzero duplicates = direct evidence of the Bun " + "TestReporter id-collision bug; the found-id-gap count above is density-only — it does NOT prove losslessness under collisions)", String(closeInfo.code), String(closeInfo.reason), String(closeInfo.wasClean), String(closeInfo.msFromLastFrameToClose), collisionStats.rawFoundCount, collisionStats.uniqueFoundIdCount, collisionStats.duplicateFoundIdCount);
8503
8655
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
8504
8656
  const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
8505
8657
  if (earlyResult) {
8506
8658
  return earlyResult;
8507
8659
  }
8508
- return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly);
8660
+ return await this.buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly, closeInfo);
8509
8661
  } finally {
8510
8662
  abortController.abort();
8511
8663
  if (this.currentAbortController === abortController) {
@@ -8514,11 +8666,11 @@ exit=%s timedOut=%s
8514
8666
  await syncServer.close();
8515
8667
  }
8516
8668
  }
8517
- async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly) {
8669
+ async buildGatedDryRunResult(result, parsed, testHierarchy, executionOrder, totalElapsedMs, wasClosedUnexpectedly, closeInfo) {
8518
8670
  const { coverage: mutantCoverage, inspectorIdToProjectFile, rawKeyCount, orphanedKeyCount } = await this.collectAndRemapCoverage(testHierarchy, executionOrder);
8519
8671
  const { tests, testNameIndex } = this.buildTestsFromInspector(testHierarchy, executionOrder, parsed, totalElapsedMs, inspectorIdToProjectFile);
8520
8672
  tests.sort((a, b) => a.name.localeCompare(b.name));
8521
- const gateResult = this.checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests);
8673
+ const gateResult = this.checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests, closeInfo);
8522
8674
  if (gateResult) {
8523
8675
  return gateResult;
8524
8676
  }
@@ -8757,7 +8909,7 @@ ${lines.join(`
8757
8909
  %s`, String(result.exitCode), parsed.failed, result.stderr.slice(-500));
8758
8910
  }
8759
8911
  }
8760
- checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests) {
8912
+ checkCompletenessGate(executionOrder, testHierarchy, parsed, rawKeyCount, orphanedKeyCount, wasClosedUnexpectedly, tests, closeInfo) {
8761
8913
  if (tests.some((t) => t.status === TestStatus.Failed)) {
8762
8914
  return null;
8763
8915
  }
@@ -8781,7 +8933,8 @@ ${lines.join(`
8781
8933
  reasons.push(`${orphanedKeyCount} of ${rawKeyCount} coverage key(s) could not be paired with any inspector test (orphaned)`);
8782
8934
  }
8783
8935
  if (wasClosedUnexpectedly) {
8784
- reasons.push("the inspector WebSocket closed unexpectedly before this data could be fully drained");
8936
+ const closeDetail = closeInfo.code === undefined ? "close code/reason not captured" : `close code=${closeInfo.code} reason=${JSON.stringify(closeInfo.reason ?? "")} wasClean=${String(closeInfo.wasClean)}, ${String(closeInfo.msFromLastFrameToClose)}ms after the last received frame`;
8937
+ reasons.push(`the inspector WebSocket closed unexpectedly before this data could be fully drained (${closeDetail})`);
8785
8938
  }
8786
8939
  const errorMessage = "stryker-bun-runner: dry run data-completeness check failed — " + `${reasons.join("; ")}. This indicates the Bun inspector event stream may have been ` + "truncated mid-run; proceeding would risk silently " + "corrupted coverage attribution, so this dry run is being reported as an error instead of " + "Complete, and the test registry has NOT been persisted.";
8787
8940
  this.logger.error("%s", errorMessage);
@@ -82,11 +82,13 @@ let ws: WebSocket | null = null;
82
82
  // Bound on how long the final afterAll (below) waits for the runner's drain
83
83
  // acknowledgment before giving up and proceeding as if drained — see
84
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;
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;
90
92
 
91
93
  // Per-file test counters for per-test coverage tracking.
92
94
  //
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hughescr/stryker-bun-runner",
3
- "version": "1.3.5",
3
+ "version": "1.3.7",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",