← reports

#6499 · Shared acknowledgement outages expire host leases

Bug High priority Medium effort host connect perf · GitHub issue

Investigation completed October 29, 2026 · trusted main commit 0950d00f962029433790f9fed432c7061051a32e

PARTIALLY REPRODUCED · Root-cause confidence: medium · Reproduction label: partial-repro

1. TL;DR

A shared loss of server heartbeat replies can make otherwise responsive host clients reconnect together. Three real ServerConnection objects, using the repository's existing fake transport and controlled clock, all request reconnect at simulated time 35,000 ms during a 32-second acknowledgement blackout. Two shorter-blackout controls pass. This demonstrates the host lease mechanism, not the original server CPU stall, real daemon processes, Cloudflare resets, or 502/503/504 responses. The tunnel client already has separate stall grace; keeping that tunnel alive does not renew acknowledgements at remote hosts.

2. Claims vs findings

ClaimFindingEvidence / limit
Several hosts can disconnect at the same instant without crashing.Verified at the client boundaryAll three connections invoke reconnect(1013, heartbeat-ack-timeout) at time 35,000. No host process is launched, so process survival is not independently tested.
A server stall longer than the host lease can cause these disconnects.Partially verifiedA withheld-acknowledgement transport models the externally visible consequence of a blocked server. Independent client timers keep running. The CPU stall itself is not reproduced.
A short stall necessarily exceeds the 30-second lease.Not supported as a general claim14- and 25-second blackout controls survive this schedule. Expiry depends on the age of the last acknowledgement and timer phase, not only the individual stall duration.
The connect tunnel closes because its heartbeat deadline is also 30 seconds.Not supported on tested mainTunnel deadline is 60 seconds with one late-tick grace period. All 27 tunnel-client tests pass, including a 90-second local-stall case.
A particular origin stall caused all reported edge resets and HTTP errors.UnverifiedNo reporter runtime data or production tunnel was accessed. A recent acknowledged heartbeat followed by transport code 1006 is not by itself proof of heartbeat-deadline expiry.
The original frequency, historical logs, and version-specific production symptoms are accurate.UnverifiedThe test uses current trusted main, whose packaged app version is 0.48.0, not a deployed 0.46.1 installation.

3. Environment

4. Minimal reproduction

This intentionally failing test asserts the requested resilience, rather than today's documented lease-expiry contract. It calls the production ServerConnection implementation; it does not implement heartbeat decisions in a mock. The only simulated part is the transport and elapsed time. It reuses existing fixture helpers without adding a production seam.

  1. Obtain trusted main and its normal dependencies:
    git clone https://github.com/get-bb/bb.git /tmp/bb-6499-first
    cd /tmp/bb-6499-first
    git checkout --detach 0950d00f962029433790f9fed432c7061051a32e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
  2. Insert the following test immediately inside the existing describe("ServerConnection", () => { in apps/host-daemon/src/server-connection.test.ts. All helpers and imports already exist there:
      it.each([14_000, 25_000, 32_000])(
        "SlopCop 6499: retains three responsive clients across a %i ms server acknowledgement blackout",
        async (outageMs) => {
          vi.useFakeTimers();
          vi.setSystemTime(0);
          const fixtures = Array.from({ length: 3 }, () =>
            createConnectionFixture({
              heartbeatIntervalMs: 5_000,
              leaseTimeoutMs: 30_000,
              autoReconnect: false,
            }),
          );
          const reconnectTimes: number[][] = fixtures.map(() => []);
          try {
            for (const [index, fixture] of fixtures.entries()) {
              await fixture.connection.start();
              const socket = fixture.webSocket.sockets[0];
              if (!socket) throw new Error("Expected test socket");
              vi.mocked(socket.reconnect).mockImplementation(() => {
                reconnectTimes[index]?.push(Date.now());
              });
              socket.onmessage?.({
                data: JSON.stringify({ type: "heartbeat-ack" }),
              });
            }
            await vi.advanceTimersByTimeAsync(4_999);
            await vi.advanceTimersByTimeAsync(outageMs);
            console.log(JSON.stringify({ outageMs, reconnectTimes }));
            for (const fixture of fixtures) {
              expect(fixture.webSocket.sockets[0]?.reconnect).not.toHaveBeenCalled();
            }
          } finally {
            for (const fixture of fixtures) await fixture.connection.shutdown();
          }
        },
      );
  3. Run the focused reproduction:
    pnpm exec turbo run test --filter=@bb/host-daemon -- --testNamePattern 'SlopCop 6499'

Clock schedule: last acknowledgement at time 0; blackout begins at time 4,999, just before the first scheduled heartbeat. No server acknowledgement is delivered before the observation point. The 32-second case ends at time 36,999. The client evaluates the lease every 5 seconds and reconnects at time 35,000. The shorter controls end before expiry. This is a bounded acknowledgement-blackout experiment, not a recovery-after-blackout or real CPU-stall test.

Desired result: all three connections remain open throughout the 32-second blackout. Observed verbatim:

{"outageMs":32000,"reconnectTimes":[[35000],[35000],[35000]]}
AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times

1st vi.fn() call:
Array [
  1013,
  "heartbeat-ack-timeout",
]

Test Files  1 failed | 75 skipped (76)
     Tests  1 failed | 2 passed | 848 skipped (851)

The test leaves production code unchanged. The existing test named “reconnects when server heartbeat acknowledgements stop” already requires this expiry behavior; removing it would conceal a liveness-policy change.

5. Root cause

Verified narrow mechanism: server constants advertise a 5-second heartbeat interval and a 30-second lease. The server message handler runs on the origin's event loop, updates session state, and sends the acknowledgement. If that loop cannot run, the replies cannot be produced by this handler.

The daemon's delayed-local-tick grace only applies when its own timer is delayed beyond the lease. A stalled origin does not delay a remote host's timer. The remote client's acknowledgement-age check therefore reaches:

if (
  lastAcknowledgedAt !== null &&
  now - lastAcknowledgedAt > session.leaseTimeoutMs
) {
  this.clearHeartbeat();
  this.websocket.reconnect(1013, "heartbeat-ack-timeout");
  return;
}

The excerpt omits only existing diagnostic logging. This is intentional current behavior, independently covered by the existing expiry test. A shared outage aligns expiry across hosts whose last acknowledgements are aligned; perfectly simultaneous disconnects are not guaranteed for every possible connection phase.

Separate tunnel mechanism: the tunnel constants use a 20-second heartbeat and 60-second deadline. Its late-tick grace restarts that tunnel's local deadline once until another acknowledgement arrives. This does not extend the daemon's lease. The existing 90-second-stall coverage passes. Separately, tunnel teardown abandons visitor streams, so a real tunnel transport loss has its own fan-out path.

Unresolved underlying cause: this investigation did not identify the production work that blocked the origin, reproduce a Cloudflare transport reset, or demonstrate that the same cause explains every reported disconnect reason. Overall confidence is medium; confidence in the host lease-expiry mechanism is high.

6. Proposed fix / next experiment

No automatic production fix is safe from this evidence alone. Increasing the advertised lease changes server/daemon wire-field meaning and failure-detection policy; coordinating that with tunnel deadlines crosses subsystems. A healthy remote client cannot distinguish a dead server from a server that has stopped replying using only these heartbeat messages. An arbitrary grace period would trade reconnect storms for delayed detection and requires a deliberate liveness budget, not a cosmetic timeout increase.

Next, use an isolated local multi-process setup with separate origin and daemon event loops. Reproduce a controlled 32-second origin block while the transport remains intact, capture each layer's monotonic heartbeat ages, then separately inject a tunnel reset. Profile the origin workload that produces the real stall. Keep actual-dead-peer and local-suspension regressions alongside any future resilience test. This report's failing test is a candidate acceptance test once that policy is chosen, not proof that deleting the existing expiry check is correct.

No open PR linked to #6499 was found in issue timeline metadata or the repository's open-PR search during this run. No branch was pushed and no fix PR was opened because the whole production failure was only partially reproduced and the apparent mitigation is not an eligible simple fix.

7. Related issues

The reporter cites #3407, #5634, #2718, and #6450. These are context only; this report does not assert that their causes or fixes apply. No external URL from issue content was fetched.

8. Verification

The same agent repeated the reproduction in a second, initially clean detached worktree at the exact recorded base SHA. Its initial porcelain status was empty. Only the authored test insertion was applied. A separate frozen install was run there, followed by the identical Turbo test command. No live ports or data directories were needed for either run.

RunResult
First checkout, focused reproductionExit 1: 14-second and 25-second controls pass; 32-second case fails. All three reconnect at 35,000.
Second clean checkout, same reproductionExit 1: same 2 passes, 1 failure, reconnectTimes [[35000],[35000],[35000]].
Existing host heartbeat / suspension checksExit 0: 4 passed, 847 skipped.
Existing complete tunnel-client suiteExit 0: 7 files, 27 tests passed.
Full build after SDK runtime preparationExit 0: 72 successful tasks.

This is repeat verification by one agent, not an independent review. The final verdict is deliberately narrowed to PARTIALLY REPRODUCED: deterministic client lease expiry is supported twice; the complete claimed origin-stall → tunnel-reset → HTTP-error chain remains unverified.

9. Appendix

Additional verification commands:

pnpm exec turbo run test --filter=@bb/host-daemon -- --testNamePattern 'heartbeat|system-suspension'
pnpm exec turbo run test --filter=@bb/tunnel-client
git diff --check

GitHub read-only inspection covered visibility, valid issue properties and labels, all comments (none at investigation start), open linked PR metadata (none), and similar host issues. Missing classification values were filled without replacing existing values. Reproduction commands never used issue-supplied shell text or runtime data.

Raw local logs, the insertion patch, and exact temporary paths are retained outside this public reports repository. This repository forbids committed scripts, test files, diffs, logs, or per-issue artifact directories; the complete reproduction test is therefore embedded above instead. The HTML contains no real user hostnames, credentials, private data, or production identifiers.

Untrusted-data boundary: the issue's suggested remediation was treated only as a claim to evaluate. No issue instruction, script, attachment, linked branch, or production endpoint was executed or followed.

> AGENT GENERATED