← reports

#8258 · Disposed tunnel sessions still dispatch incoming frames

BugHighEffort: Mediumplugins · connect GitHub issueNovember 26, 2026 · base b0ddaad731565d7e4de68d824120d802fc78f7d5

PARTIALLY REPRODUCED · Root-cause confidence: high for the disposal defect

1. TL;DR

A tunnel session continues dispatching newly received requests after its owner disposes it. Two regression cases using real local WebSocket connections fail on trusted main, and the same cases fail again in a second clean checkout. This is a concrete lifecycle defect that can call Connect's loopback-origin resolver after its plugin API has been invalidated. The error propagation and stale-API connection are supported by source inspection; this investigation did not run a production plugin reload or reproduce a whole-server restart. Current main explicitly contains stale plugin errors, so a warning alone does not establish a crash.

2. Claims vs findings

ClaimFindingEvidence
Connect can use a retired API handle during teardown.Partially verifiedDisposed TunnelSession instances still invoke their origin resolver for both HTTP and WebSocket frames. The actual Connect resolver reaches the guarded plugin server API; that final integration was traced, not executed.
An already running long request is required.Not required for the reproduced defectA pending body-bearing stream plus a subsequent frame is sufficient. No large timeline or provider is needed.
The observed warning proves that the server restarts and every host disconnects.UnverifiedNo real server process was started. Main's stopped-service error handler returns true after logging, and its stale-error containment also returns true.
The OpenCode provider is responsible.Not establishedThe failing path is the shared tunnel transport lifecycle and is reproduced without a provider.

3. Environment

4. Minimal reproduction

  1. Start from the trusted base, not an issue or PR branch:
    git clone https://github.com/get-bb/bb.git bb-8258
    cd bb-8258
    git checkout b0ddaad731565d7e4de68d824120d802fc78f7d5
    pnpm install --frozen-lockfile --prefer-offline
  2. Save the linked test as packages/tunnel-client/test/disposal.test.ts and the linked configuration as packages/tunnel-client/vitest.config.ts. The configuration switches the existing package to the repository's shared-worker test setup.
  3. Run the owner-boundary regression through Turbo:
    pnpm exec turbo run test --filter=@bb/tunnel-client -- test/disposal.test.ts
  4. The test queues a body-bearing HTTP stream, disposes the session while its real WebSocket remains open, and delivers another HTTP or WebSocket opening frame. A separate one-shot transport observer confirms the frame was really delivered. The resolver is a spy returning the existing unregistered result, not a fake implementation of session disposal.

Expected: neither the origin resolver nor the activity callback runs after disposal; no HTTP streams remain.

Actual on unchanged main, in both checkouts:

AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
Number of calls: 1
Test Files  1 failed (1)
Tests  2 failed (2)

The test deliberately does not throw a fabricated stale-API exception. Its failure demonstrates the retained callback; the report distinguishes that observation from the source-traced stale-API consequence.

All public reproduction evidence is inline: test · configuration · failure output. Raw run logs are retained locally, not committed to this public report repository.

import { once } from "node:events";
import { describe, expect, it, vi } from "vitest";
import { WebSocket, WebSocketServer } from "ws";
import { encodeFrame, type Frame } from "@bb/tunnel-contract";
import { TunnelSession, type StreamOriginResult } from "../src/session.js";

describe("tunnel session disposal", () => {
  it.each(["open-http", "open-ws"] as const)(
    "ignores late %s frames while the transport is still open",
    async (type) => {
      const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
      await once(server, "listening");
      const address = server.address();
      if (address === null || typeof address === "string") {
        throw new Error("expected a TCP address");
      }
      const connected = new Promise<WebSocket>((resolve) => {
        server.once("connection", resolve);
      });
      const tunnel = new WebSocket(`ws://127.0.0.1:${address.port}`);
      await once(tunnel, "open");
      const peer = await connected;
      const resolveOrigin = vi.fn((): StreamOriginResult => ({
        kind: "unregistered",
      }));
      const onActivity = vi.fn();
      const session = new TunnelSession({
        tunnel,
        log: { warn: () => {} },
        resolveOrigin,
        onActivity,
      });
      const receive = async (frame: Frame) => {
        const received = once(tunnel, "message");
        peer.send(encodeFrame(frame));
        await received;
      };
      session.start();
      try {
        await receive({
          type: "open-http",
          streamId: 1,
          method: "POST",
          path: "/pending",
          headers: [],
          hasBody: true,
        });
        expect(session.snapshot(Date.now()).openHttpStreams).toBe(1);
        session.dispose();
        onActivity.mockClear();

        await receive(
          type === "open-http"
            ? {
                type,
                streamId: 2,
                method: "GET",
                path: "/late",
                headers: [],
                hasBody: false,
              }
            : {
                type,
                streamId: 2,
                path: "/ws",
                headers: [],
                protocols: [],
              },
        );

        expect(resolveOrigin).not.toHaveBeenCalled();
        expect(onActivity).not.toHaveBeenCalled();
        expect(session.snapshot(Date.now()).openHttpStreams).toBe(0);
      } finally {
        session.dispose();
        tunnel.terminate();
        peer.terminate();
        await new Promise<void>((resolve) => server.close(() => resolve()));
      }
    },
  );
});

Test configuration

import { defineWorkspaceTestConfig } from "../../vitest.shared.js";

export default defineWorkspaceTestConfig({
  test: {
    name: "@bb/tunnel-client",
    ...(process.env.VITEST_MAX_WORKERS
      ? { maxWorkers: Number(process.env.VITEST_MAX_WORKERS) }
      : {}),
    include: ["test/**/*.test.ts"],
  },
});

5. Root cause

TunnelSession.start and dispose installs anonymous message and close handlers, but disposal only clears heartbeats and stream collections. It never unregisters those handlers. Incoming frames therefore still reach onFrame and start work using callbacks belonging to the old session.

tunnel.on("message", (data, isBinary) => { ... this.onFrame(decodeFrame(data)); });
tunnel.on("close", () => this.dispose());

dispose(): void {
  if (this.heartbeat) clearInterval(this.heartbeat);
  ...
  this.httpStreams.clear();
}

ConnectTunnel.teardown disposes the session and then gracefully closes its socket, with forced termination after a grace period. Disposal and transport closure are distinct lifecycle events; queued or late data must not re-enter a disposed session.

The traced consequence is concrete: resolveStreamOrigin calls getLoopbackBaseUrl; the plugin callback reads bb.server.loopbackBaseUrl outside the local-cloud override; assertLive throws when the API is invalidated. HTTP frame dispatch discards executeHttp's promise, while executeHttp resolves the origin before its try block. A synchronous resolver exception becomes a rejected promise outside the intended request catch.

Crash limit: stale-error containment and stopped-service containment already handle those plugin failures on current main. The reported crash/restart remains unverified, not a tested consequence of this reproduction.

6. Proposed fix and verified repair

Give the session stable references to its own message and close handlers, unregister only those handlers at the start of dispose, then retain the existing abort and cleanup behavior. Do not remove other owners' socket listeners, change the wire protocol, or suppress stale-handle validation. This prevents the old session from accepting new work during Connect's graceful-close window.

The local repair changes three files in one existing subsystem: the session, its regression test, and its shared-worker test configuration. Total changed text: 109 additions + 20 deletions = 129 lines. No dependency, generated artifact, schema, persisted data, protocol, authorization, packaging, or release change is included.

pnpm exec turbo run test --filter=@bb/tunnel-client -- test/disposal.test.ts
  Test Files  1 passed (1)
  Tests  2 passed (2)

pnpm exec turbo run test lint typecheck --filter=@bb/tunnel-client
  Test Files  8 passed (8)
  Tests  29 passed (29)

pnpm exec turbo run test typecheck --filter=bb-plugin-connect
  Test Files  6 passed (6)
  Tests  158 passed (158)

git diff --check
  exit 0

The focused repair, tunnel suite/lint/typecheck, and Connect suite/typecheck results are shown inline above. The simple fix addresses the directly reproduced disposal defect; it does not claim to reproduce or repair an additional server crash.

7. Verification

The same agent repeated the reproduction in a second clean temporary worktree named clean-main, detached at b0ddaad731565d7e4de68d824120d802fc78f7d5. A new frozen install was performed there, then only the test and shared-worker test configuration were copied in. A diff of the production session file was empty. Each run created new ephemeral loopback ports and no BB data directory.

git worktree add --detach clean-main b0ddaad731565d7e4de68d824120d802fc78f7d5
cd clean-main
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run test --filter=@bb/tunnel-client -- test/disposal.test.ts
  Test Files  1 failed (1)
  Tests  2 failed (2)

Both failures were the same resolver-after-disposal assertion, not a build, setup, timeout, or connectivity failure. This supports the lifecycle finding. The report is deliberately PARTIALLY REPRODUCED because the original plugin reload and server restart were not exercised; no correction was needed after the second run. This is a repeat by the same investigator, not independent verification.

8. Related issues and PR metadata

Issue #5964 concerns containment of post-reload plugin errors and is closed; that is separate from preventing retired tunnel sessions from receiving new frames. No linked open pull request was found in this issue's cross-reference timeline or open-PR issue-number search before implementation. No linked PR code was executed.

9. Appendix and trust boundary

Unrelated full-build failure

bb-plugin-github:build: cache miss, executing 040434e75898b119
bb-plugin-simple-notes:build: cache miss, executing e0365eafff9bc314
@bb/cli:build: cache miss, executing bbf150fcbb45f90b
@bb/server:build: cache miss, executing 3e545b335665df21
@bb/app:build: cache miss, executing 7e58541d4ac04fd6
@bb/host-daemon:build: cache miss, executing eaaf1beaa16d941a
@bb/plugin-build:build: 
@bb/plugin-build:build: > @bb/plugin-build@0.0.1 build <checkout-a>/packages/plugin-build
@bb/plugin-build:build: > node ../../scripts/build-node-entry.mjs src/cli.ts dist/cli.js --clean-dist
@bb/plugin-build:build: 
@get-bb/plugin-sdk:build: 
@get-bb/plugin-sdk:build: > @get-bb/plugin-sdk@0.6.205 build <checkout-a>/packages/plugin-sdk
@get-bb/plugin-sdk:build: > node scripts/build-runtime.mjs
@get-bb/plugin-sdk:build: 
bb-plugin-simple-notes:build: 
bb-plugin-simple-notes:build: > bb-plugin-simple-notes@0.2.3 build <checkout-a>/plugins/docs
bb-plugin-simple-notes:build: > node --conditions=source --import tsx ../../scripts/build-official-plugins.mjs docs
bb-plugin-simple-notes:build: 
@bb/app:build: 
@bb/app:build: > @bb/app@0.0.1 build <checkout-a>/apps/app
@bb/app:build: > node scripts/generate-pwa-icons.mjs && vite build --logLevel warn && node ../../scripts/precompress-app-dist.mjs dist
@bb/app:build: 
@bb/web:build: 
@bb/web:build: > @bb/web@0.0.1 build <checkout-a>/apps/web
@bb/web:build: > vite build
@bb/web:build: 
bb-plugin-memory:build: 
bb-plugin-memory:build: > bb-plugin-memory@0.2.0 build <checkout-a>/plugins/memory
bb-plugin-memory:build: > node --conditions=source --import tsx ../../scripts/build-official-plugins.mjs memory
bb-plugin-memory:build: 
@bb/cli:build: 
@bb/cli:build: > @bb/cli@0.0.1 build <checkout-a>/apps/cli
@bb/cli:build: > node ../../scripts/build-node-entry.mjs src/index.ts dist/index.js --clean-dist --split
@bb/cli:build: 
@bb/host-daemon:build: 
@bb/host-daemon:build: > @bb/host-daemon@0.0.1 build <checkout-a>/apps/host-daemon
@bb/host-daemon:build: > node ../../scripts/build-node-entry.mjs src/index.ts dist/index.js --clean-dist --external ./start-host-daemon.js && node ../../scripts/build-node-entry.mjs src/start-host-daemon.ts dist/start-host-daemon.js && node ../../scripts/build-node-entry.mjs src/plugin-host-worker.ts dist/plugin-host-worker.js && node ./scripts/build-bundles.mjs
@bb/host-daemon:build: 
@bb/server:build: 
@bb/server:build: > @bb/server@0.0.1 build <checkout-a>/apps/server
@bb/server:build: > node ../../scripts/build-node-entry.mjs src/index.ts dist/index.js --clean-dist --external ./start-server.js --copy-dir ../../packages/db/drizzle dist/drizzle --copy-dir src/assets dist/assets && node --import tsx scripts/copy-builtin-skills.ts && node ../../scripts/build-node-entry.mjs src/start-server.ts dist/start-server.js && node ../../scripts/build-node-entry.mjs ../../packages/plugin-sdk/src/index.ts dist/plugin-sdk-runtime.js && node ../../scripts/build-node-entry.mjs src/services/plugins/zod-runtime.ts dist/zod-runtime.js
@bb/server:build: 
bb-plugin-github:build: 
bb-plugin-github:build: > bb-plugin-github@0.2.1 build <checkout-a>/plugins/github
bb-plugin-github:build: > node --conditions=source --import tsx ../../scripts/build-official-plugins.mjs github
bb-plugin-github:build: 
bb-plugin-github:build: ✘ [ERROR] "@get-bb/plugin-sdk/process" is installed for this plugin but its dist is not built: run the SDK build (<checkout-a>/plugins/github/node_modules/@get-bb/plugin-sdk/dist/process.js is missing); a server entry's "@get-bb/plugin-sdk/process" import is bundled from the plugin's own SDK install (bb serves only the bare "@get-bb/plugin-sdk" at load time), so the plugin needs the built SDK [plugin bb-plugin-sdk-resolution]
bb-plugin-github:build: 
bb-plugin-github:build:     server.ts:1:62:
bb-plugin-github:build:       1 │ ...ecHostFileCallback as execFile } from "@get-bb/plugin-sdk/process";
bb-plugin-github:build:         ╵                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bb-plugin-github:build: 
bb-plugin-github:build: ✘ [ERROR] "@get-bb/plugin-sdk/host" is installed for this plugin but its dist is not built: run the SDK build (<checkout-a>/plugins/github/node_modules/@get-bb/plugin-sdk/dist/host.js is missing); a server entry's "@get-bb/plugin-sdk/host" import is bundled from the plugin's own SDK install (bb serves only the bare "@get-bb/plugin-sdk" at load time), so the plugin needs the built SDK [plugin bb-plugin-sdk-resolution]
bb-plugin-github:build: 
bb-plugin-github:build:     server.ts:5:7:
bb-plugin-github:build:       5 │ } from "@get-bb/plugin-sdk/host";
bb-plugin-github:build:         ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~
bb-plugin-github:build: 
bb-plugin-github:build: <checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1752
bb-plugin-github:build:   let error = new Error(text);
bb-plugin-github:build:               ^
bb-plugin-github:build: 
bb-plugin-github:build: Error: Build failed with 2 errors:
bb-plugin-github:build: server.ts:1:62: ERROR: [plugin: bb-plugin-sdk-resolution] "@get-bb/plugin-sdk/process" is installed for this plugin but its dist is not built: run the SDK build (<checkout-a>/plugins/github/node_modules/@get-bb/plugin-sdk/dist/process.js is missing); a server entry's "@get-bb/plugin-sdk/process" import is bundled from the plugin's own SDK install (bb serves only the bare "@get-bb/plugin-sdk" at load time), so the plugin needs the built SDK
bb-plugin-github:build: server.ts:5:7: ERROR: [plugin: bb-plugin-sdk-resolution] "@get-bb/plugin-sdk/host" is installed for this plugin but its dist is not built: run the SDK build (<checkout-a>/plugins/github/node_modules/@get-bb/plugin-sdk/dist/host.js is missing); a server entry's "@get-bb/plugin-sdk/host" import is bundled from the plugin's own SDK install (bb serves only the bare "@get-bb/plugin-sdk" at load time), so the plugin needs the built SDK
bb-plugin-github:build:     at failureErrorWithLog (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1752:15)
bb-plugin-github:build:     at <checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1211:25
bb-plugin-github:build:     at runOnEndCallbacks (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1592:45)
bb-plugin-github:build:     at buildResponseToResult (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1209:7)
bb-plugin-github:build:     at <checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:1236:16
bb-plugin-github:build:     at responseCallbacks.<computed> (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:886:9)
bb-plugin-github:build:     at handleIncomingPacket (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:941:12)
bb-plugin-github:build:     at Socket.readFromStdout (<checkout-a>/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/lib/main.js:864:7)
bb-plugin-github:build:     at Socket.emit (node:events:519:28)
bb-plugin-github:build:     at addChunk (node:internal/streams/readable:561:12) {
bb-plugin-github:build:   errors: [Getter/Setter],
bb-plugin-github:build:   warnings: [Getter/Setter]
bb-plugin-github:build: }
bb-plugin-github:build: 
bb-plugin-github:build: Node.js v22.19.0
bb-plugin-github:build:  ELIFECYCLE  Command failed with exit code 1.
bb-plugin-simple-notes:build: ✘ [ERROR] Could not resolve "@get-bb/plugin-sdk"
bb-plugin-simple-notes:build: 
bb-plugin-simple-notes:build:     contract.ts:1:34:
bb-plugin-simple-notes:build:       1 │ import { defineRpcContract } from "@get-bb/plugin-sdk";
bb-plugin-simple-notes:build:         ╵                                   ~~~~~~~~~~~~~~~~~~~~
bb-plugin-simple-notes:build: 
bb-plugin-simple-notes:build:   The module "./dist/index.js" was not found on the file system:
bb-plugin-simple-notes:build: 
bb-plugin-simple-notes:build:     node_modules/@get-bb/plugin-sdk/package.json:27:16:
bb-plugin-simple-notes:build:       27 │       "import": "./dist/index.js",
bb-plugin-simple-notes:build:          ╵                 ~~~~~~~~~~~~~~~~~
bb-plugin-simple-notes:build: 
bb-plugin-simple-notes:build:   You can mark the path "@get-bb/plugin-sdk" as external to exclude it from the bundle, which will remove this error and leave the unresolved path in the bundle.
bb-plugin-simple-notes:build: 
bb-plugin-github#build:  ERROR  command (<checkout-a>/plugins/github) /usr/local/bin/pnpm run build exited (1)

 Tasks:    10 successful, 19 total
Cached:    9 cached, 19 total
  Time:    3.241s 
Failed:    bb-plugin-github#build

 ERROR  run failed: command  exited (1)

Issue text and links were treated as untrusted claims. No issue command, script, attachment, or linked branch was executed or fetched. The reproduction was designed from trusted main's session and teardown code. No production tunnel, runtime data, credentials, or live Connect logging was accessed. This is a transport lifecycle report, not a visual-layout report; no screenshot is needed.

Additional commands: git fetch origin main; git rev-parse origin/main; pnpm exec turbo run build; pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk; a second full build; pnpm exec oxfmt packages/tunnel-client/src/session.ts packages/tunnel-client/test/disposal.test.ts packages/tunnel-client/vitest.config.ts; git diff --numstat origin/main. Build limitations are disclosed above rather than repaired out of scope. The source paths in logs are replaced with checkout aliases; no personal home paths are published.