@hughescr/stryker-bun-runner 1.3.5 → 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
@@ -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,26 @@ 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 ...`, 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.
313
+
276
314
  ### Coverage-bleed warning (dry run only)
277
315
 
278
316
  - **`mutant coverage was recorded between tests, after '<testName>' completed`**
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);
@@ -8067,14 +8108,46 @@ function sleep(ms) {
8067
8108
  setTimeout(resolve3, ms);
8068
8109
  });
8069
8110
  }
8070
- function rejectAfterMs(ms, message) {
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();
8071
8126
  let timer;
8072
8127
  const promise2 = new Promise((_resolve, reject) => {
8073
- timer = setTimeout(() => {
8074
- reject(new Error(message));
8075
- }, ms);
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);
8076
8139
  });
8077
- return { promise: promise2, cancel: () => clearTimeout(timer) };
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}`;
8078
8151
  }
8079
8152
  function buildTestNameIndex(tests, bunNames) {
8080
8153
  const testNameIndex = new Map;
@@ -8093,7 +8166,6 @@ var EXECUTION_SHORTFALL_ABS_FLOOR = 10;
8093
8166
  var EXECUTION_SHORTFALL_RATIO_THRESHOLD = 0.05;
8094
8167
  var ORPHANED_KEY_ABS_FLOOR = 5;
8095
8168
  var INSPECTOR_DRAIN_TIMEOUT_MS = 1000;
8096
- var DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS = 4000;
8097
8169
 
8098
8170
  class BunTestRunner {
8099
8171
  logger;
@@ -8413,7 +8485,7 @@ ${stack}` : baseFailureMessage;
8413
8485
  const testFiles = testFilesCached === null ? await this.getOrDiscoverTestFiles() : testFilesCached;
8414
8486
  const testProcess = runBunTests({
8415
8487
  bunPath: this.bunPath,
8416
- timeout: this.timeout,
8488
+ timeout: this.timeout + DRAIN_ACK_ABSOLUTE_CEILING_MS,
8417
8489
  env: this.env,
8418
8490
  bunArgs: this.bunArgs,
8419
8491
  bunfigPath,
@@ -8461,6 +8533,9 @@ exit=%s timedOut=%s
8461
8533
  handlers: {
8462
8534
  onError: (error) => {
8463
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);
8464
8539
  }
8465
8540
  }
8466
8541
  });
@@ -8478,15 +8553,30 @@ exit=%s timedOut=%s
8478
8553
  errorMessage: `Failed to connect to Bun inspector: ${errorMsg}`
8479
8554
  };
8480
8555
  }
8556
+ let drainSettleReason;
8481
8557
  syncServer.setDrainHandler(async () => {
8482
- const { promise: timeoutPromise, cancel: cancelTimeout } = rejectAfterMs(DRAIN_ACK_ROUND_TRIP_TIMEOUT_MS, "Inspector drain round-trip timed out");
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");
8483
8563
  try {
8484
8564
  await Promise.race([
8485
- inspector.send("TestReporter.enable", {}),
8486
- timeoutPromise
8565
+ inspector.send("TestReporter.enable", {}, DRAIN_ACK_ABSOLUTE_CEILING_MS + 1000),
8566
+ silencePromise
8487
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
+ }
8488
8574
  } finally {
8489
- cancelTimeout();
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" : "");
8490
8580
  }
8491
8581
  });
8492
8582
  syncServer.signalReady();
@@ -8500,6 +8590,8 @@ exit=%s timedOut=%s
8500
8590
  const wasClosedUnexpectedly = inspector.wasClosedUnexpectedly;
8501
8591
  await inspector.close();
8502
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));
8503
8595
  const parsed = parseBunTestOutput(result.stdout, result.stderr);
8504
8596
  const earlyResult = this.checkDryRunProcessResult(result, parsed, testHierarchy);
8505
8597
  if (earlyResult) {
@@ -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.6",
4
4
  "description": "Stryker test runner plugin for Bun with perTest coverage support",
5
5
  "keywords": [
6
6
  "stryker",