← reports

#5880 · Connect transport continuity after tunnel loss

BugMedium priorityMedium effortremote · connect · partial-reproGitHub issue

2026-10-20 · trusted base bd93d18896bab97c950c4fa3451b621c1e0569c1

Verdict: PARTIALLY REPRODUCED. Root-cause confidence: low for spontaneous idle loss; high for downstream stream teardown.

1. TL;DR

The reported recurring idle disconnects were not reproduced: this investigation cannot attribute them to ATL, TLS termination, Durable Object resets, deployment, or the local network. A real local Workers runtime does reproduce the consequence: when a tunnel closes, Connect immediately closes an established visitor WebSocket, and a replacement tunnel does not revive that socket. Even replacing a still-live tunnel closes the visitor. New visitor connections work after redial, so this demonstrates transport interruption, not logout or loss of authentication. Healthy heartbeat probes succeed, and the existing client heartbeat tests cover both normal idle operation and deliberate termination when acknowledgements are missing.

2. Claims vs findings

ClaimStatusEvidence
Recurring spontaneous idle drops on macOSUnverifiedNo affected Mac, long-duration affected route, or production telemetry was available. Five immediate local idle heartbeat probes pass; that is not a multi-day stability test.
Missing heartbeat acknowledgements can initiate redialVerified mechanism onlyThe existing heartbeat suite passes, including termination after a minute without acknowledgement, stall grace, and wake behavior. It does not explain why acknowledgements were absent in production.
A brief tunnel interruption disrupts the remote connectionVerified at transport boundaryEstablished visitor closes with 1001 on an injected abnormal close and on live replacement, in two clean checkouts. Fresh visitors can exchange messages after redial.
Phone loses an authenticated session or fails to recoverUnverifiedThe fixture bypasses the account gate and uses no phone browser. It tests WebSocket transport only. The app already has a reconnecting socket and subscription replay.
Healthy origin, no sleep, clean network, small payloads rule out local causesUnverifiedThose are reporter observations, not measurements repeated here. Small local round trips and periodic reachability alone do not locate an intermittent transport failure.
ATL edge resets or TLS stalls are the causeUnverifiedNo stored edge records were read. A missing secureConnect milestone and an abnormal WebSocket close do not identify which participant or network hop failed.

3. Environment

4. Minimal reproduction

  1. Save the inline diagnostic test as issue-5880.test.ts and its inline fixture as issue-5880-fixture.ts in a common parent directory, then follow the command transcript. Offline installation assumes the existing package store is populated; otherwise use the same frozen install without --offline.
  2. Open a local tunnel and visitor WebSocket. Exchange a message to prove that the established visitor works. Inject close code 1011 on the tunnel, then reconnect. Repeat separately by opening a replacement without first closing the old tunnel.
  3. Observe that the old visitor closes immediately, while a newly opened visitor on the new tunnel successfully exchanges a message.
git clone https://github.com/get-bb/bb.git bb-5880-first
cd bb-5880-first
git checkout --detach bd93d18896bab97c950c4fa3451b621c1e0569c1
pnpm install --frozen-lockfile --offline --ignore-scripts
pnpm exec turbo run build --filter=@bb/connect --filter=@bb/tunnel-client
cp ../issue-5880.test.ts apps/connect/src/issue-5880.test.ts
cp ../issue-5880-fixture.ts apps/connect/test/issue-5880-fixture.ts
pnpm exec turbo run test --force --filter=@bb/connect -- src/issue-5880.test.ts

git clone https://github.com/get-bb/bb.git ../bb-5880-second
cd ../bb-5880-second
git checkout --detach bd93d18896bab97c950c4fa3451b621c1e0569c1
git status --porcelain
pnpm install --frozen-lockfile --offline --ignore-scripts
cp ../issue-5880.test.ts apps/connect/src/issue-5880.test.ts
cp ../issue-5880-fixture.ts apps/connect/test/issue-5880-fixture.ts
pnpm exec turbo run build --filter=@bb/connect --filter=@bb/tunnel-client
pnpm exec turbo run test --force --filter=@bb/connect -- src/issue-5880.test.ts src/worker.test.ts
pnpm exec turbo run test --filter=@bb/tunnel-client

Continuity expectation requested by the report: a short outage should recover without a visible interruption. Observed current behavior: existing streams close and new transport connections must be opened. The diagnostic asserts the observed behavior to establish the mechanism; it is not a failing regression test for the unexplained idle trigger.

idle control: 5 heartbeat acknowledgements; tunnel OPEN
abnormal-close: established visitor closed 1001 tunnel disconnected
abnormal-close: new tunnel and new visitor exchange messages successfully
live-replacement: established visitor closed 1001 tunnel reconnected
live-replacement: new tunnel and new visitor exchange messages successfully

The injected fault is an explicit local 1011 close, not a spontaneous network 1006 event. The idle control sends five immediate heartbeats rather than simulating hours or days. The fixture uses the real TunnelDO and real workerd sockets, but a minimal routing entry point instead of the authenticated public gate.

Diagnostic test source
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { Miniflare } from "miniflare";
import { afterEach, describe, expect, it } from "vitest";
import {
  HEARTBEAT_REQUEST,
  HEARTBEAT_RESPONSE,
  decodeFrame,
  encodeFrame,
} from "@bb/tunnel-contract";

type ClientWebSocket = NonNullable<
  Awaited<ReturnType<Miniflare["dispatchFetch"]>>["webSocket"]
>;

let runtime: Miniflare | undefined;

afterEach(async () => {
  await runtime?.dispose();
  runtime = undefined;
});

async function startRuntime(): Promise<Miniflare> {
  const bundle = await build({
    entryPoints: [
      fileURLToPath(new URL("../test/issue-5880-fixture.ts", import.meta.url)),
    ],
    bundle: true,
    format: "esm",
    target: "esnext",
    conditions: ["workerd", "worker", "browser"],
    write: false,
  });
  runtime = new Miniflare({
    modules: [
      {
        type: "ESModule",
        path: "/fixture.js",
        contents: bundle.outputFiles[0].text,
      },
    ],
    modulesRoot: "/",
    scriptPath: "/fixture.js",
    compatibilityDate: "2026-06-11",
    compatibilityFlags: ["nodejs_compat"],
    durableObjects: { TUNNEL_DO: "TunnelDO" },
    d1Databases: { DB: "issue-5880-local" },
    analyticsEngineDatasets: { GATE_EVENTS: { dataset: "issue-5880-local" } },
    bindings: {
      BASE_DOMAIN: "relay.test",
      BETTER_AUTH_SECRET: "local-fixture-only",
    },
  });
  await runtime.ready;
  return runtime;
}

async function upgrade(
  runtime: Miniflare,
  path: string,
): Promise<ClientWebSocket> {
  const response = await runtime.dispatchFetch(`https://relay.test${path}`, {
    headers: { Upgrade: "websocket" },
  });
  if (!response.webSocket)
    throw new Error(`upgrade failed: ${response.status}`);
  response.webSocket.accept();
  return response.webSocket;
}

function nextMessage(socket: ClientWebSocket): Promise<string | ArrayBuffer> {
  return new Promise((resolve) => {
    socket.addEventListener("message", (event) => resolve(event.data), {
      once: true,
    });
  });
}

function nextClose(
  socket: ClientWebSocket,
): Promise<{ code: number; reason: string }> {
  return new Promise((resolve) => {
    socket.addEventListener(
      "close",
      (event) => resolve({ code: event.code, reason: event.reason }),
      { once: true },
    );
  });
}

function echoVisitorMessages(tunnel: ClientWebSocket): void {
  tunnel.addEventListener("message", (event) => {
    if (typeof event.data === "string") return;
    const frame = decodeFrame(event.data);
    if (frame.type === "ws-data") tunnel.send(encodeFrame(frame));
  });
}

describe("issue 5880 transport continuity diagnostic", () => {
  it("answers idle heartbeats without closing the tunnel", async () => {
    const runtime = await startRuntime();
    const tunnel = await upgrade(runtime, "/__tunnel?v=1");
    for (let beat = 0; beat < 5; beat += 1) {
      const reply = nextMessage(tunnel);
      tunnel.send(HEARTBEAT_REQUEST);
      expect(await reply).toBe(HEARTBEAT_RESPONSE);
    }
    expect(tunnel.readyState).toBe(1);
    console.log("idle control: 5 heartbeat acknowledgements; tunnel OPEN");
    tunnel.close();
  }, 60_000);

  it.each(["abnormal-close", "live-replacement"] as const)(
    "closes an established visitor on %s and permits a new visitor after redial",
    async (fault) => {
      const runtime = await startRuntime();
      const tunnel = await upgrade(runtime, "/__tunnel?v=1");
      echoVisitorMessages(tunnel);
      const visitor = await upgrade(runtime, "/events");
      const before = nextMessage(visitor);
      visitor.send("before");
      expect(await before).toBe("before");
      const closed = nextClose(visitor);
      let replacement: ClientWebSocket;
      if (fault === "abnormal-close") {
        tunnel.close(1011, "local fault injection");
        const observed = await closed;
        expect(observed).toEqual({ code: 1001, reason: "tunnel disconnected" });
        console.log(
          `${fault}: established visitor closed ${observed.code} ${observed.reason}`,
        );
        replacement = await upgrade(runtime, "/__tunnel?v=1");
      } else {
        replacement = await upgrade(runtime, "/__tunnel?v=1");
        const observed = await closed;
        expect(observed).toEqual({ code: 1001, reason: "tunnel reconnected" });
        console.log(
          `${fault}: established visitor closed ${observed.code} ${observed.reason}`,
        );
      }
      expect(visitor.readyState).not.toBe(1);
      echoVisitorMessages(replacement);
      const freshVisitor = await upgrade(runtime, "/events");
      const after = nextMessage(freshVisitor);
      freshVisitor.send("after");
      expect(await after).toBe("after");
      console.log(
        `${fault}: new tunnel and new visitor exchange messages successfully`,
      );
      freshVisitor.close();
      replacement.close();
    },
    60_000,
  );
});
Minimal routing fixture
export { TunnelDO } from "../src/tunnel-do.js";

interface FixtureEnv {
  TUNNEL_DO: DurableObjectNamespace;
}

export default {
  fetch(request: Request, env: FixtureEnv): Promise<Response> {
    return env.TUNNEL_DO.get(env.TUNNEL_DO.idFromName("issue-5880")).fetch(
      request,
    );
  },
};

5. Root cause

Unknown for the primary reported defect. This evidence does not establish the cause of recurring idle drops. It establishes why an actual tunnel drop is visible downstream: TunnelDO calls abandonStreams on loss, and also during every new tunnel admission, so an already accepted visitor cannot remain attached across redial.

apps/connect/src/tunnel-do.ts:879

  webSocketClose(ws: WebSocket, code: number, reason: string): void {
    const tags = this.state.getTags(ws);
    if (tags.includes(TUNNEL_TAG)) {
      if (this.tunnelSocket() !== null) return;
      const now = Date.now();
      void this.state.storage.put(TUNNEL_CLOSED_AT_KEY, now);
      if (code === CLEAN_CLOSE_CODE) {
        void this.state.storage.delete(TUNNEL_LOST_AT_KEY);
      } else {
        void this.state.storage.put(TUNNEL_LOST_AT_KEY, now);
      }
      if (presenceWritesOnChange(this.env)) void this.markPresence();
      this.abandonStreams(
        "tunnel disconnected mid-request",
        "tunnel disconnected",
      );
      return;

apps/connect/src/tunnel-do.ts:375

    await this.restartIfTunnelVanished();
    const now = Date.now();
    const replacingLive = this.tunnelSocket() !== null;
    if (!replacingLive) {
      await this.recordTunnelGap(new URL(request.url).host, now);
    }
    for (const existing of this.state.getWebSockets(TUNNEL_TAG)) {
      try {
        existing.close(CLEAN_CLOSE_CODE, TUNNEL_REPLACED_CLOSE_REASON);
      } catch {}
    }
    this.abandonStreams("tunnel reconnected mid-request", "tunnel reconnected");

apps/connect/src/tunnel-do.ts:682

  private abandonStreams(httpReason: string, wsReason: string): void {
    for (const streamId of [...this.pendingHttp.keys()]) {
      this.failHttpStream(streamId, 502, httpReason);
    }
    for (const socket of this.state.getWebSockets()) {
      const tags = this.state.getTags(socket);
      if (tags.includes(TUNNEL_TAG)) continue;
      if (tags.some((tag) => tag.startsWith(RELAY_TAG_PREFIX))) {
        this.finishRelay(socket, RELAY_FAILED_CLOSE_CODE, httpReason);
        continue;
      }
      try {
        socket.close(1001, wsReason);
      } catch {}
    }
  }

The local client also destroys its origin-side streams on close. Keeping only a visitor socket open at the gate would therefore not preserve the original end-to-end stream; a continuation design would have to account for both ends.

packages/tunnel-client/src/session.ts:223

    tunnel.on("close", () => this.dispose());
  }

  dispose(): void {
    if (this.heartbeat) clearInterval(this.heartbeat);
    for (const s of this.httpStreams.values()) s.abort.abort();
    for (const s of this.wsStreams.values())
      s.socket.close(1001, "tunnel closed");
    this.refusedOrigins.clear();
    this.httpStreams.clear();
    this.wsStreams.clear();
    this.setRemoteClients(0);
  }

Idle heartbeats are configured through the Workers auto-response API. The client sends every 20 seconds and terminates after the acknowledgement age exceeds 60 seconds; with ordinary timer cadence the first such check occurs at 80 seconds. This is a consequence of lost acknowledgements, not an explanation of why they were lost. Closures with a much fresher acknowledgement cannot be attributed to that normal deadline check alone.

apps/connect/src/tunnel-do.ts:130

    this.nextStreamId = maxSeen + 1;
    this.state.setWebSocketAutoResponse(
      new WebSocketRequestResponsePair(HEARTBEAT_REQUEST, HEARTBEAT_RESPONSE),
    );

packages/tunnel-client/src/session.ts:183

    const monotonicNow = this.options.monotonicNow ?? (() => performance.now());
    this.lastAck = Date.now();
    this.lastReceivedAckAt = null;
    this.lastHeartbeatTickAt = monotonicNow();
    this.heartbeat = setInterval(() => {
      const tickAt = monotonicNow();
      const tickGapMs = tickAt - this.lastHeartbeatTickAt;
      this.lastHeartbeatTickAt = tickAt;
      const now = Date.now();
      if (tickGapMs > HEARTBEAT_LATE_TICK_MS && !this.stallGraceSinceAck) {
        this.options.log.warn(
          `event loop stalled for ${Math.round(tickGapMs / 1000)}s; restarting the tunnel heartbeat deadline`,
        );
        this.lastAck = now;
        this.stallGraceSinceAck = true;
      } else if (now - this.lastAck > HEARTBEAT_DEADLINE_MS) {
        this.options.log.warn("tunnel heartbeat missed; reconnecting");
        tunnel.terminate();
        return;
      }
      this.sendRaw(HEARTBEAT_REQUEST, Buffer.byteLength(HEARTBEAT_REQUEST));
    }, HEARTBEAT_INTERVAL_MS);

Dial diagnostics record cumulative elapsed times from dial start, not separate phase durations. A null tlsMs means no secureConnect milestone was observed; it does not prove an edge TLS defect. Likewise, transportError records an error event if one arrives; its absence is not proof of an edge reset.

plugins/connect/src/tunnel.ts:603

    socket.once("lookup", () => {
      diagnostics.lookupMs = Date.now() - startedAt;
    });
    socket.once("connect", () => {
      diagnostics.connectMs = Date.now() - startedAt;
    });
    socket.once("secureConnect", () => {
      diagnostics.tlsMs = Date.now() - startedAt;
    });

Do not interpret this as absence of client reconnect support: the browser constructs a reconnecting socket with unlimited retries and replays subscriptions on open. This report does not reproduce a failure of that recovery path, an expired session, or a phone logout.

apps/app/src/lib/ws.ts:115

    const socket = new ReconnectingWebSocket(url, undefined, {
      minReconnectionDelay: this.minReconnectionDelay,
      maxReconnectionDelay: 30000,
      reconnectionDelayGrowFactor: 2,
      connectionTimeout: 10000,
      maxRetries: Infinity,
    });
    this.socket = socket;

    socket.onopen = () => {
      const disconnectedAt = this.disconnectedAt;
      this.disconnectedAt = null;
      this.lastServerActivityAt = Date.now();
      const reconnected = this.hasConnected;
      this.hasConnected = true;
      this.setConnectionState("connected");
      this.startPingLoop();
      if (this.subscriptions.size > 0)
        this.sendMessage({
          type: "subscribe",
          targets: [...this.subscriptions.values()].map(
            (subscription) => subscription.target,
          ),
        });
      const event: WebSocketConnectedEvent = reconnected
        ? { reconnected, disconnectedAt: disconnectedAt ?? Date.now() }
        : { reconnected };
      for (const callback of this.connectedCallbacks) {
        callback(event);
      }
    };

    socket.onmessage = (event: MessageEvent) => {

6. Proposed fix / next experiment

No root-cause patch is justified yet. Correlate the reported timestamps and request IDs with stored Workers Logs, Durable Object invocation outcomes, deployment history, and transport/TLS telemetry. Never attach a production real-time tail: that itself resets tunnel objects. Then run a long-duration authenticated staging tunnel with timestamped heartbeat send/ack and event-loop measurements, and a phone browser, to distinguish transport loss from authentication or UI recovery.

If the desired product behavior is transparent recovery, first specify whether to reconnect and restore application state or introduce resumable tunneled streams. The latter changes stream lifecycle and potentially protocol and identity guarantees; it is not a safe contained patch. Existing HTTP redial grace does not imply resumability for already-open WebSockets.

Simple-fix decision: skipped. The spontaneous idle trigger was not reproduced on trusted main, and transport continuation is not a verified sub-500-line repair within the existing contract. No linked open pull request was found in the issue timeline or the numeric PR search. No fix branch or product pull request was created.

7. Verification

The same agent repeated the reproduction in a second clean detached worktree at the exact base commit, with a new frozen install and fresh Miniflare instances. The clean tracked tree was checked before adding the diagnostic. This is a second clean run, not independent verification.

RunCommand / result
Firstpnpm exec turbo run test --filter=@bb/connect -- src/issue-5880.test.ts — 3/3 passed, all observed output above.
Second (cache bypass)pnpm exec turbo run test --force --filter=@bb/connect -- src/issue-5880.test.ts src/worker.test.ts — 156/156 passed: 3 diagnostic cases plus 153 existing gate/DO tests.
Client controlspnpm exec turbo run test --filter=@bb/tunnel-client — 26/26 passed across heartbeat, reconnect, traffic, origin failures/requests, and backpressure.

No report correction was needed: both clean runs produced the same closure codes and successful fresh connections. Verification supports the restricted partial verdict, not the unobserved production cause. The test protects an owner-boundary lifecycle observation using real transport; it adds no production seam and does not duplicate a mock implementing the closure policy.

8. Related issues

9. Appendix

The reports repository permits HTML reports but forbids publishing raw logs and reproduction directories. The complete diagnostic and fixture are therefore embedded above, with copy-paste commands. Raw logs remain in local thread storage. These verbatim excerpts retain the relevant observed stdout and suite totals.

First run

@bb/connect:test: idle control: 5 heartbeat acknowledgements; tunnel OPEN
@bb/connect:test: abnormal-close: established visitor closed 1001 tunnel disconnected
@bb/connect:test: abnormal-close: new tunnel and new visitor exchange messages successfully
@bb/connect:test: live-replacement: established visitor closed 1001 tunnel reconnected
@bb/connect:test: live-replacement: new tunnel and new visitor exchange messages successfully
@bb/connect:test:  ✓ |@bb/connect| src/issue-5880.test.ts (3 tests) 480ms
@bb/connect:test:  Test Files  1 passed (1)
@bb/connect:test:       Tests  3 passed (3)

Second clean run

@bb/connect:test: idle control: 5 heartbeat acknowledgements; tunnel OPEN
@bb/connect:test: abnormal-close: established visitor closed 1001 tunnel disconnected
@bb/connect:test: abnormal-close: new tunnel and new visitor exchange messages successfully
@bb/connect:test: live-replacement: established visitor closed 1001 tunnel reconnected
@bb/connect:test: live-replacement: new tunnel and new visitor exchange messages successfully
@bb/connect:test:  ✓ |@bb/connect| src/issue-5880.test.ts (3 tests) 479ms
@bb/connect:test:  ✓ |@bb/connect:isolated| src/worker.test.ts (153 tests) 762ms
@bb/connect:test:  Test Files  2 passed (2)
@bb/connect:test:       Tests  156 passed (156)

Client controls

@bb/tunnel-client:test:  ✓ test/heartbeat.test.ts (6 tests) 12ms
@bb/tunnel-client:test:  Test Files  6 passed (6)
@bb/tunnel-client:test:       Tests  26 passed (26)

Read-only investigation used repository Type/field/label metadata, all issue comments (none at review time), cross-references, an open-PR numeric search, current main source and history, and the two related issue states. Missing Type, Priority, Effort, remote and connect were filled; none had an existing value to preserve. Medium priority reflects intermittent recoverable remote interruption; Medium effort reflects the unresolved reproduction and several lifecycle paths.

Issue text and logs were treated only as untrusted claims. No issue-provided commands, links, scripts, branches, or patches were executed or fetched. No credentials, user runtime data, production logs, or private repository content were read. No production tunnel was contacted or tailed. Runtime teardown is performed after each test.

> AGENT GENERATED