#6671 · Downstream cancellation leaves HTTP proxy connections open
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
The daemon's loopback HTTP proxy keeps its upstream connection open after its caller goes away. A direct test of the trusted main-branch source reproduces this while awaiting response headers, streaming a response, and uploading a request. Each cancelled local connection is closed, but its origin-side socket remains open for the full one-second observation window. Two completed requests reuse one upstream connection normally. This establishes a connection-lifecycle defect, not the reported machine-wide macOS failure: no network exhaustion or real provider requests were attempted.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Disconnecting during an HTTP response leaves the upstream connection open. | Verified | The streaming-response case fails the socket-release assertion in both clean source checkouts. |
| Cancellation before headers or during a request upload has the same defect. | Verified | Both additional cases fail in each run; upload cancellation waits until the origin receives body bytes. |
| Successful completed requests should retain keepalive reuse. | Verified on baseline | The positive control completes two responses on the same origin socket. |
| Repeated cancellations exhaust macOS network buffers. | Unverified | This run used Linux and small loopback requests. It did not reproduce OS exhaustion, inspect a production daemon, or validate a causal threshold. |
| Specific released packages or a recent provider-client version trigger the accumulation. | Unverified | No installed release, client, provider, or private diagnostic data was used. |
3. Environment
- Repository: public
get-bb/bb; trustedorigin/maincommit9662c45478f4a74f33f11b70187657d97f1e14a7. - Linux x86_64, kernel 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0.
- Two fresh clones, each detached or branched directly from the recorded trusted commit. No linked PR code was checked out or executed.
- The reproduction uses only Node built-ins and the production proxy module. All listeners bind
127.0.0.1on newly allocated ephemeral ports and are closed by test teardown. No app instance, data directory, credentials, authentication service, or provider is needed.
4. Minimal reproduction
- Obtain the trusted source:
git clone https://github.com/get-bb/bb.git bb-proxy-check cd bb-proxy-check git checkout --detach 9662c45478f4a74f33f11b70187657d97f1e14a7
- Save the following self-contained test as
machine-proxy-lifecycle.repro.mtsin that checkout's root. It was authored from the trusted source's lifecycle, not copied from the issue or PR.import assert from "node:assert/strict"; import { once } from "node:events"; import http from "node:http"; import net, { type AddressInfo, type Socket } from "node:net"; import { setTimeout as delay } from "node:timers/promises"; import { test, type TestContext } from "node:test"; import { startMachineAuthProxy } from "./apps/host-daemon/src/machine-auth-proxy.ts"; async function fixture( context: TestContext, handler: http.RequestListener, ) { const connections = new Set<Socket>(); const origin = http.createServer(handler); origin.on("connection", (socket) => { connections.add(socket); socket.on("error", () => {}); }); origin.listen(0, "127.0.0.1"); await once(origin, "listening"); const proxy = await startMachineAuthProxy({ serverUrl: `http://127.0.0.1:${(origin.address() as AddressInfo).port}`, serverHeaders: {}, }); context.after(async () => { for (const socket of connections) socket.destroy(); await proxy.close(); await new Promise<void>((resolve) => origin.close(() => resolve())); }); return new URL(proxy.serverUrl); } for (const phase of ["awaiting headers", "streaming response", "uploading request"] as const) { test(`client cancellation releases upstream while ${phase}`, { timeout: 5_000 }, async (context) => { const observed = Promise.withResolvers<Socket>(); const url = await fixture(context, (request, response) => { request.on("error", () => {}); if (phase === "streaming response") { response.writeHead(200, { "content-type": "text/plain" }); response.write("stream started"); } if (phase === "uploading request") { request.once("data", () => observed.resolve(request.socket)); } else { observed.resolve(request.socket); request.resume(); } }); const client = net.connect(Number(url.port), url.hostname); client.on("error", () => {}); context.after(() => client.destroy()); await once(client, "connect"); const firstBytes = phase === "streaming response" ? once(client, "data") : null; const head = phase === "uploading request" ? `POST /probe HTTP/1.1\r\nHost: ${url.host}\r\nContent-Length: 4096\r\n\r\npartial upload` : `GET /probe HTTP/1.1\r\nHost: ${url.host}\r\n\r\n`; client.write(head); const upstreamSocket = await observed.promise; if (firstBytes !== null) await firstBytes; const clientClosed = once(client, "close"); client.destroy(); await clientClosed; const deadline = Date.now() + 1_000; while (!upstreamSocket.destroyed && Date.now() < deadline) await delay(10); console.log(JSON.stringify({ phase, clientClosed: client.destroyed, upstreamClosed: upstreamSocket.destroyed })); assert.equal(upstreamSocket.destroyed, true, "upstream must close after downstream cancellation"); }); } test("completed responses preserve upstream keepalive reuse", { timeout: 5_000 }, async (context) => { const sockets: Socket[] = []; const url = await fixture(context, (request, response) => { sockets.push(request.socket); response.end("complete"); }); const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); context.after(() => agent.destroy()); for (let requestIndex = 0; requestIndex < 2; requestIndex += 1) { await new Promise<void>((resolve, reject) => { http.get(url, { agent }, (response) => { response.on("error", reject); response.on("end", resolve); response.resume(); }).on("error", reject); }); } assert.equal(sockets.length, 2); assert.equal(sockets[0], sockets[1], "completed requests must reuse the upstream connection"); assert.equal(sockets[0].destroyed, false); console.log(JSON.stringify({ completedRequests: sockets.length, reusedUpstream: sockets[0] === sockets[1] })); }); - Run it without installing any dependencies:
node --experimental-strip-types --test machine-proxy-lifecycle.repro.mts
Expected: all four tests pass; each cancellation prints upstreamClosed: true and the completed-request control prints reusedUpstream: true.
Actual: exit status 1 in each checkout, with three cancellation assertion failures (false !== true) and one passing keepalive control. Selected output, verbatim:
# {"phase":"awaiting headers","clientClosed":true,"upstreamClosed":false}
# {"phase":"streaming response","clientClosed":true,"upstreamClosed":false}
# {"phase":"uploading request","clientClosed":true,"upstreamClosed":false}
# {"completedRequests":2,"reusedUpstream":true}
# tests 4
# pass 1
# fail 3
# cancelled 0
# skipped 0
No screenshot is appropriate for this non-visual transport defect. The complete repeatable test is embedded here; raw logs and temporary checkout paths are deliberately not published.
5. Root cause
The HTTP forwarding handler at the recorded base creates an upstream request, pipes the caller's request into it, and pipes an upstream response back to the caller. Its lifecycle callbacks propagate upstream failures toward the downstream response only:
upstreamResponse.on("error", () => args.response.destroy());
upstreamResponse.on("close", () => {
if (!upstreamResponse.complete) args.response.destroy();
});
upstreamResponse.pipe(args.response);
...
args.request.pipe(upstream);
There is no downstream request-abort listener or downstream response-close listener to destroy the upstream request. A destroyed pipe destination therefore does not cause this handler to cancel its outstanding origin-side work. The three failing cases exercise both sides of that missing lifecycle transition, including the interval before any upstream response exists. The positive control distinguishes abandoned connections from intentionally reusable, fully completed connections.
The test proves sockets remain open beyond the observation interval until its explicit teardown. It does not establish the precise retained-buffer size, indefinite lifetime, or operating-system exhaustion threshold.
6. Proposed fix
Within the existing HTTP forwarding handler, cancel the upstream request when the downstream upload aborts or when the downstream response closes before finishing. Check writableFinished so normal completion preserves keepalive reuse. If an upstream response arrives after the downstream response is destroyed, release it instead of piping it; suppress attempts to write an error response into an already destroyed downstream. Preserve existing header validation and machine-auth behavior. This proposal requires no wire, authentication, schema, packaging, or public API change.
7. PR review
Open PR #6672 declares issue #6671 as a closing reference. Only its GitHub metadata and diff were read as untrusted data. No PR branch, patch, or tests were executed.
The inspected diff adds downstream abort/early-close cancellation, a late-response guard, and a destroyed-downstream error guard in the owning HTTP handler, plus tests for the three disconnect phases and completed keepalive. This is consistent with the root cause established on trusted main. No concrete correctness finding was identified in this bounded static review; runtime correctness of the PR remains unverified. A duplicate fix PR is intentionally not opened.
8. Related issues
No other issue was needed to establish this result. The reproduction reaches the native daemon HTTP proxy directly, without a plugin-route adapter or WebSocket handshake.
9. Verification
The same agent repeated the reproduction in a second newly cloned checkout of 9662c45478f4a74f33f11b70187657d97f1e14a7, confirmed a clean working tree before adding only the newly authored test, and used newly allocated loopback ports. This is a second clean run, not an independent investigation.
node --experimental-strip-types --test machine-proxy-lifecycle.repro.mts
# {"phase":"awaiting headers","clientClosed":true,"upstreamClosed":false}
# {"phase":"streaming response","clientClosed":true,"upstreamClosed":false}
# {"phase":"uploading request","clientClosed":true,"upstreamClosed":false}
# {"completedRequests":2,"reusedUpstream":true}
# tests 4
# pass 1
# fail 3
# cancelled 0
# skipped 0
Both runs agree: three failed cancellation tests and one passing completed-request control. No correction to the reproduction conclusion was required. No fix was applied or claimed as tested.
10. Appendix: checks and trust boundary
The repository's existing HTTP/WebSocket proxy suite passes all 12 tests on unchanged production source, demonstrating that its baseline coverage misses downstream HTTP cancellation:
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run test --filter=@bb/host-daemon -- src/machine-auth-proxy.test.ts pnpm exec turbo run build --filter=@bb/host-daemon
The initial whole-repository build stopped in the GitHub plugin because SDK runtime output was missing in the fresh checkout. The documented SDK bootstrap succeeded, the existing focused suite passed 12/12, and the subsequent targeted host-daemon build passed. The initial broad build was not re-run. This environmental bootstrap issue is separate from the native reproduction, which needs no built packages.
Issue and PR contents were treated solely as untrusted claims. No supplied script or patch was run, no issue-supplied external URL was fetched, and no private runtime data was inspected. Classification: Bug; High priority for resource-lifecycle impact; Low effort for a contained existing-handler correction; area host with perf. Verdict label: confirmed-repro.