← reports

#6724 · Request progress is excluded from the gate deadline

BugMedium priorityLow effortbug · remote · connectGitHub issue2026-10-30

Verdict: REPRODUCED · Root-cause confidence: high

Investigation base 7877c1c7316e6f68dec3bb1f337158e4a55cd9dd; fix base a0e513398f02d47ec5df874b89fec4edfc248894. No connect-next files changed between these commits.

1. TL;DR

The remote-access gate starts one fixed timer before routing, uploading, and waiting for the server's headers. It does not reset that timer when upload bytes arrive or when forwarding finishes. A healthy tunnel therefore cannot save a request that is actively uploading or whose origin needs longer than the initial budget. Real frps and frpc reproduced both failures twice, in separate clean checkouts; fast controls succeeded. A gate-local repair now tracks upload progress, keeps stalled uploads bounded, and adopts the ten-minute connected-tunnel wait policy already present in trusted main's Cloudflare gate.

2. Claims vs findings

ClaimStatusEvidence
A continuously progressing upload can receive a timeout before completion.Verified8 × 2 KiB chunks, 600 ms apart, require about 4.2 s. With a 3 s configured deadline the gate answers 504 at about 3.007 s, after only 5 chunks, while the tunnel remains located here.
A finite slow origin answer fails with the tunnel connected.VerifiedAn origin scheduled to answer after 4 s instead yields the gate's 504 at about 3 s. A 600 ms origin succeeds.
The ordinary and voice budgets are 30 s and 90 s.Verified in codeConstants and path selection at the recorded commit. Reproductions scale the ordinary timer to 3 s; they do not wait 90 s.
Fly streams real public uploads and permits multi-minute quiet responses.Not remeasuredNo public service or production traffic was used. The local HTTP streaming failure is sufficient to establish the gate defect, but is not evidence about Fly's proxy limits.
Cloudflare has a related repaired timeout policy.Verified in trusted mainCommit a0e513398f02d47ec5df874b89fec4edfc248894 introduces a ten-minute maximum wait and removes voice-specific budgeting in apps/connect. This report does not rerun that subsystem.

3. Environment

4. Minimal reproduction

  1. Clone only trusted main and select the recorded base.
    git clone https://github.com/get-bb/bb.git bb-6724
    cd bb-6724
    git checkout --detach 7877c1c7316e6f68dec3bb1f337158e4a55cd9dd
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/connect-next
  2. Save the complete self-authored test patch below as reproduction.patch and apply it. It changes only tests and their origin fixture, not the gate.
    git apply reproduction.patch
    pnpm exec turbo run test --filter=@bb/connect-next -- test/gate.e2e.test.ts -t 'regression:' --silent=false
  3. Expected: fast and progressing uploads both return 200; a finite 4 s answer returns 200; a stalled upload still receives 504 with request-body stage; a never-answering connected origin reaches the 9 s cap. Actual baseline: four expectations fail and two fast controls pass. The cap expectation deliberately specifies the existing main policy selected for the repair; the old implementation returns at 3 s.

Repeatable test patch

This patch is authored from trusted repository fixtures, not copied from issue code. All code needed for this reproduction is inline; raw evidence remains outside the public reports repository, per its publishing policy.

diff --git a/apps/connect-next/test/gate.e2e.test.ts b/apps/connect-next/test/gate.e2e.test.ts
index d29105408..ab2ddad4b 100644
--- a/apps/connect-next/test/gate.e2e.test.ts
+++ b/apps/connect-next/test/gate.e2e.test.ts
@@ -1,4 +1,4 @@
-import type { IncomingMessage } from "node:http";
+import { request as httpRequest, type IncomingMessage } from "node:http";
 import { brotliDecompressSync, gunzipSync } from "node:zlib";
 import { afterAll, beforeAll, describe, expect, it } from "vitest";
 import WebSocket from "ws";
@@ -44,6 +44,7 @@ const DESKTOP = "bb-connect.desktop_session";
 const BEE = `bee.${BASE_DOMAIN}`;
 const GRACE_MS = 2_000;
 const HEAD_MS = 3_000;
+const MAX_WAIT_MS = HEAD_MS * 3;
 
 const fixture: AccountFixture = {
   labels: {
@@ -955,12 +956,143 @@ describe.skipIf(!availability.ok)("connect-next gate end to end", () => {
   });
 
   describe("deadlines and offline", () => {
-    it("answers 504 when the server does not send a response head", async () => {
+    it.each([0, HEAD_MS / 5])(
+      "regression: accepts a progressing upload with %i ms chunk spacing",
+      async (spacingMs) => {
+        const chunkCount = 8;
+        const chunk = Buffer.alloc(2048, "b");
+        const started = Date.now();
+        let sentChunks = 0;
+        const answer = await new Promise<{ status: number; text: string }>(
+          (resolve, reject) => {
+            let timer: NodeJS.Timeout | undefined;
+            const outgoing = httpRequest(
+              {
+                hostname: "127.0.0.1",
+                port: gate.webPort,
+                method: "POST",
+                path: "/echo?deadline-upload",
+                headers: {
+                  ...owner,
+                  host: BEE,
+                  "content-length": String(chunkCount * chunk.length),
+                },
+                agent: false,
+              },
+              (response) => {
+                clearTimeout(timer);
+                const chunks: Buffer[] = [];
+                response.on("data", (data: Buffer) => chunks.push(data));
+                response.on("error", reject);
+                response.on("end", () => {
+                  outgoing.destroy();
+                  resolve({
+                    status: response.statusCode ?? 0,
+                    text: Buffer.concat(chunks).toString(),
+                  });
+                });
+              },
+            );
+            outgoing.on("error", (error) => {
+              clearTimeout(timer);
+              reject(error);
+            });
+            const sendChunk = () => {
+              if (outgoing.destroyed) return;
+              outgoing.write(chunk);
+              sentChunks += 1;
+              if (sentChunks === chunkCount) outgoing.end();
+              else timer = setTimeout(sendChunk, spacingMs);
+            };
+            sendChunk();
+          },
+        );
+        console.log(
+          JSON.stringify({
+            scenario: "upload",
+            spacingMs,
+            elapsedMs: Date.now() - started,
+            sentChunks,
+            totalChunks: chunkCount,
+            tunnel: gate.directory.locate("bee").kind,
+            ...answer,
+          }),
+        );
+        expect(answer.status).toBe(200);
+        expect(sentChunks).toBe(chunkCount);
+        expect(origin.seen.at(-1)?.body.length).toBe(chunkCount * chunk.length);
+      },
+    );
+
+    it.each([HEAD_MS / 5, HEAD_MS + 1000])(
+      "regression: delivers a finite answer delayed %i ms through a connected tunnel",
+      async (waitMs) => {
+        const started = Date.now();
+        const answer = await get(`/deadline-answer?wait=${waitMs}`);
+        console.log(
+          JSON.stringify({
+            scenario: "delayed-answer",
+            elapsedMs: Date.now() - started,
+            originDelayMs: waitMs,
+            tunnel: gate.directory.locate("bee").kind,
+            status: answer.status,
+            text: answer.text,
+          }),
+        );
+        expect(answer.status).toBe(200);
+      },
+    );
+
+    it("regression: bounds waiting for a connected server that never answers", async () => {
       const started = Date.now();
       const answer = await get("/slow");
       expect(answer.status).toBe(504);
       expect(answer.text).toContain("stage: response-head");
+      expect(Date.now() - started).toBeGreaterThanOrEqual(MAX_WAIT_MS - 50);
+      expect(Date.now() - started).toBeLessThan(MAX_WAIT_MS + 1500);
+    });
+
+    it("regression: expires an upload that stops making progress", async () => {
+      const started = Date.now();
+      const answer = await new Promise<{ status: number; text: string }>(
+        (resolve, reject) => {
+          const outgoing = httpRequest(
+            {
+              hostname: "127.0.0.1",
+              port: gate.webPort,
+              path: "/echo?stalled-upload",
+              method: "POST",
+              headers: { ...owner, host: BEE, "content-length": "4096" },
+              agent: false,
+            },
+            (response) => {
+              const chunks: Buffer[] = [];
+              response.on("data", (chunk: Buffer) => chunks.push(chunk));
+              response.on("error", reject);
+              response.on("end", () => {
+                outgoing.destroy();
+                resolve({
+                  status: response.statusCode ?? 0,
+                  text: Buffer.concat(chunks).toString(),
+                });
+              });
+            },
+          );
+          outgoing.on("error", reject);
+          outgoing.write(Buffer.alloc(2048));
+        },
+      );
+      console.log(
+        JSON.stringify({
+          scenario: "stalled-upload",
+          elapsedMs: Date.now() - started,
+          ...answer,
+        }),
+      );
+      expect(answer.status).toBe(504);
+      expect(answer.text).toContain("stage: request-body");
       expect(Date.now() - started).toBeGreaterThanOrEqual(HEAD_MS - 50);
+      expect(Date.now() - started).toBeLessThan(HEAD_MS + 1500);
     });
 
     it("answers 503 for a label with no tunnel", async () => {
diff --git a/apps/connect-next/test/harness.ts b/apps/connect-next/test/harness.ts
index 8b98e2f81..d923b16f8 100644
--- a/apps/connect-next/test/harness.ts
+++ b/apps/connect-next/test/harness.ts
@@ -296,7 +296,12 @@ export async function startOrigin(options: OriginOptions) {
   };
   const server = http.createServer(async (request, response) => {
     const chunks: Buffer[] = [];
-    for await (const chunk of request) chunks.push(chunk as Buffer);
+    try {
+      for await (const chunk of request) chunks.push(chunk as Buffer);
+    } catch (error) {
+      if (request.destroyed && !request.complete) return;
+      throw error;
+    }
     const assertion = await verify(request);
     const entry: SeenRequest = {
       method: request.method ?? "GET",
@@ -316,6 +321,14 @@ export async function startOrigin(options: OriginOptions) {
       return;
     }
     if (path === "/slow") return;
+    if (path === "/deadline-answer") {
+      const delay = Number(
+        new URL(request.url ?? "/", "http://origin.test").searchParams.get(
+          "wait",
+        ),
+      );
+      await new Promise((resolve) => setTimeout(resolve, delay));
+    }
     if (path === "/refuse" || path === "/plain-401") {
       const body = JSON.stringify(
         path === "/refuse"

Actual baseline output, checkout A

@bb/connect-next:test: {"scenario":"upload","spacingMs":0,"elapsedMs":20,"sentChunks":8,"totalChunks":8,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/echo?deadline-upload\"}"}
@bb/connect-next:test: {"scenario":"upload","spacingMs":600,"elapsedMs":3007,"sentChunks":5,"totalChunks":8,"tunnel":"here","status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":608,"originDelayMs":600,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/deadline-answer?wait=600\"}"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":3003,"originDelayMs":4000,"tunnel":"here","status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: {"scenario":"stalled-upload","elapsedMs":3003,"status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
@bb/connect-next:test:  Test Files  1 failed (1)
@bb/connect-next:test:       Tests  4 failed | 2 passed | 39 skipped (45)
@bb/connect-next#test:  ERROR  command (SCRATCH/base/apps/connect-next) /usr/local/bin/pnpm run test test/gate.e2e.test.ts -t regression: --silent=false exited (1)
 Tasks:    2 successful, 3 total
 ERROR  run failed: command  exited (1)

Actual fixed output

@bb/connect-next:test: {"scenario":"upload","spacingMs":0,"elapsedMs":22,"sentChunks":8,"totalChunks":8,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/echo?deadline-upload\"}"}
@bb/connect-next:test: {"scenario":"upload","spacingMs":600,"elapsedMs":4210,"sentChunks":8,"totalChunks":8,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/echo?deadline-upload\"}"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":608,"originDelayMs":600,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/deadline-answer?wait=600\"}"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":4006,"originDelayMs":4000,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/deadline-answer?wait=4000\"}"}
@bb/connect-next:test: {"scenario":"stalled-upload","elapsedMs":3005,"status":504,"text":"bb connect: timed out forwarding the request body (stage: request-body)\n"}
@bb/connect-next:test:  Test Files  1 passed (1)
@bb/connect-next:test:       Tests  6 passed | 39 skipped (45)
 Tasks:    3 successful, 3 total

The final focused run has 6 passing cases. The stalled upload still times out around 3 s; the never-answering origin times out around 9 s. The slow upload completes around 4.2 s and the delayed answer arrives around 4 s, both HTTP 200.

5. Root cause

serve, lines 775–805 enters withDeadline before access resolution and forwarding. withDeadline, lines 676–703 arms exactly one timer and races it against the whole operation:

timer = setTimeout(() => resolve(STALLED), deadlineMs);
const work = run();
const winner = await Promise.race([work, stalled]);

No request-body progress can refresh that deadline. At upstreamFetch, lines 386–400, the stage is set to response-head before body.pipe(outgoing), so an upload timeout is misreported as waiting for the origin's headers. Once the same timer wins, the gate aborts the upstream request and emits its own 504. Tunnel presence is not consulted by the timeout path.

Constants and path selection explain why ordinary requests use 30 s and voice transcription uses 90 s at the baseline. Changing that special case alone cannot distinguish progress from inactivity.

6. Fix and safety

The repair stays in connect-next's existing gate and fixtures, plus its documentation: five files, 262 changed text lines (additions plus deletions). It adds a request-body stage, timestamps incoming body progress, and starts a fresh head budget when the outgoing request finishes forwarding. Only an authenticated, routed HTTP request with a known subdomain may keep waiting beyond the head budget, and only while the directory still locates its tunnel. The timer enforces a ten-minute ceiling even when progress or tunnel presence continues.

The ten-minute ceiling is not a new product decision: trusted main already establishes it for the Cloudflare gate. Routing and WebSocket handshakes retain their original bounded behavior. The voice exception is removed in favor of this same rule. No dependency, lockfile, generated file, migration, persisted data, public protocol, schema, access-control rule, or release mechanism changes.

All 6 focused regressions pass after the repair. Relevant existing suites, build, and typecheck:

@bb/connect-next:test:  Test Files  6 passed (6)
@bb/connect-next:test:       Tests  99 passed (99)
 Tasks:    5 successful, 5 total

Not verified: a Fly staging deployment, real image generation/transcription, production proxy limits, or silent-dead-frp detection timing. The presence check uses frp's existing directory lifecycle, not an independent per-request heartbeat. The hard cap bounds that uncertainty.

7. Verification

The same agent repeated the reproduction in a second clean checkout at 7877c1c7316e6f68dec3bb1f337158e4a55cd9dd, with another frozen install/build and newly allocated ports and temporary directories. This is a repeat check, not independent verification. The unchanged production gate again produced the same two user-visible HTTP failures, the same incorrect upload stage, and the early cap result:

@bb/connect-next:test: {"scenario":"upload","spacingMs":0,"elapsedMs":20,"sentChunks":8,"totalChunks":8,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/echo?deadline-upload\"}"}
@bb/connect-next:test: {"scenario":"upload","spacingMs":600,"elapsedMs":3007,"sentChunks":5,"totalChunks":8,"tunnel":"here","status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":610,"originDelayMs":600,"tunnel":"here","status":200,"text":"{\"ok\":true,\"url\":\"/deadline-answer?wait=600\"}"}
@bb/connect-next:test: {"scenario":"delayed-answer","elapsedMs":3002,"originDelayMs":4000,"tunnel":"here","status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: {"scenario":"stalled-upload","elapsedMs":3004,"status":504,"text":"bb connect: timed out waiting for the tunnel client (stage: response-head)\n"}
@bb/connect-next:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
@bb/connect-next:test:  Test Files  1 failed (1)
@bb/connect-next:test:       Tests  4 failed | 2 passed | 39 skipped (45)
@bb/connect-next#test:  ERROR  command (SCRATCH/verify/apps/connect-next) /usr/local/bin/pnpm run test test/gate.e2e.test.ts -t regression: --silent=false exited (1)
 Tasks:    2 successful, 3 total
 ERROR  run failed: command  exited (1)

Verification command: pnpm exec turbo run test --filter=@bb/connect-next -- test/gate.e2e.test.ts -t 'regression:' --silent=false. Both baseline runs exit 1 because of the intended regression assertions, with no unhandled errors. An initial fixture-only aborted-upload rejection was corrected in the reproduction harness before the final two runs; it is not treated as a gate finding. Trusted main was refreshed before branching; its newer Cloudflare-only change left all reproduced connect-next paths unchanged.

8. Related work

No open pull request linked to issue #6724 was present in its GitHub timeline or the open-PR search at the time of the fix check. Trusted main commit a0e513398f02d47ec5df874b89fec4edfc248894 repairs the sibling Cloudflare gate, not connect-next.

9. Appendix

Normal validation used Turbo to build upstream tasks first. Frozen installation and the scoped build succeeded in both baseline checkouts. The final repair runs:

pnpm exec turbo run test --filter=@bb/connect-next -- test/gate.e2e.test.ts -t 'regression:' --silent=false
pnpm exec turbo run build typecheck test --filter=@bb/connect-next
pnpm exec oxfmt --check apps/connect-next/src/gate.ts apps/connect-next/test/gate.e2e.test.ts apps/connect-next/test/harness.ts apps/connect-next/test/regions.e2e.test.ts docs/connect-next.md
git diff --check
git diff --numstat origin/main

Untrusted-data handling: issue commands, proposed patches, and links were not executed or fetched. Only trusted main, its repository-provided fixtures, and the agent-authored test/fix were run. No workflow or subagent was used.