Skip to content

fix(responses): while the link WebSocket feature is on, a stalled Remote Link reader no longer makes the Home read 32 MiB ahead, and no turn keeps a second parsed copy of its request - #8622

Merged
lidge-jun merged 18 commits into
devfrom
fix/responses-stalled-reader-memory
Nov 13, 2026

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Nov 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

When a Remote Link Child stops reading a streamed response that the Home relays, the Home holds far more than the bytes in flight (#8601: 66 to 130 MiB per stalled reader, on the HTTP relay and on the link WebSocket). Measuring the pipeline turned up these causes:

  • Read-ahead. It comes from the shared passthrough relay. Bun's fetch is not the source: in a scratch run it stopped at the socket buffers, a few MiB. The inspection tee lets the inspection branch lead the client by 32 MiB plus one chunk (src/server/inspection-tee.ts), and every relay stage after it keeps one chunk queued. With a fake upstream of 1 MiB events and a client that has read nothing, the pipeline had already pulled 36 MiB.
  • Request copies. passthrough-dispatch.ts re-parsed the outbound request body for the undeclared-tool guard and kept that parsed object for the whole stream. For a large request, that is a second full copy. A combo preflight's replay also kept its buffered prefix after the client had read it.

The fix:

  • Paced reads for link turns while the link WebSocket feature is on. A link turn's observer carries pacedReads. The link listener sets it only when the feature is on; link sockets always set it, and they exist only then. Its upstream body is cut into 256 KiB views and marked paced (src/lib/paced-stream.ts). From a paced source, the inspection tee leads by one chunk and the eager relay queues one chunk. Each stage that reads it (block rewrite, failed-tail relay, translator-budget and account-lease wrappers, combo replay) queues nothing ahead and passes the mark on. The stages before the slicer (terminal repair, the web-search bridge, the encrypted-output preflight) keep their default one-chunk queue, as structure/transports/byte-accounting.md documents.
  • No kept copy of the outbound body. The dispatcher still parses the built body once for the undeclared-tool guard, but keeps only its tool scope (outboundToolScope in src/server/responses/outbound-request-body.ts: tools, tool_choice, parallel_tool_calls, and the input items that declare tools). Snapshot repair and the Grok tool scope read nothing else, so they get the same answers from one parse per build. This applies to every passthrough request and changes no output. A block of passthrough-dispatch.ts moved to bare-namespace-aliases.ts, so that file is no longer at the 2,000-line ratchet.
  • Combo replay releases its prefix as each chunk is handed to the client, and all of it on cancel.
  • RSS acceptance fixture. The opt-in acceptance (tests/e2e-style/link-websocket-rss.test.ts) now arms its stall announcement at the idle reading, so a warm-up turn's drain wait cannot announce the load's stall. The WebSocket run no longer waits for the upstream's hold point, because a paced pump stops pulling before it gets there. Without this change the WebSocket diagnostic hung.
  • Link relay lease fixes from the review of fix(link): decode the hold check's body copy only after the request is accepted, under the resolved inbound limit #8613: when traffic accounting throws before dispatch, the relay now decides the hold check's body observation and returns the drain lease. The lease also comes back when ending a broken flow throws, before or after dispatch. A new test covers a request aborted before its headers. A comment explains that the hold check keeps the inbound limit resolved at bind.

Measured on a 4-core Linux VM, four sockets, near-8 MiB create, 16 MiB upstream chunks, one run each, link WebSocket feature on (peak-over-idle RSS per socket, kernel VmHWM; single runs vary by several MiB):

Run dev 2c0a9ef this branch at f05e87f
WebSocket, upstream held 147.8 MiB 111.2 MiB
HTTP relay, upstream held 118.3 MiB 96.2 MiB
WebSocket, free-running upstream 131.8 MiB 115.6 MiB
HTTP relay, free-running upstream 98.9 MiB 89.1 MiB

The later commits only shrink what is kept (the tool scope instead of the outbound text) and were not measured separately. Most of what remains is the request itself: the parsed body kept for the continuation store and the serialized body kept for retries. The rest is allocation peaks while a large create is parsed. The link WebSocket's own extra copies are #8600.

What stays unchanged by default: pacing applies only to a link turn while the link WebSocket feature is on. That needs both switches and the release gate (linkWebsocketTransportReady, still false in this build), so no build paces anything yet. Local HTTP and WebSocket requests, and link requests with the feature off, keep the 32 MiB inspection allowance, the 8 MiB eager queue and every stage's default queue. Tests pin each of those cases. The tool-scope and combo replay changes only drop data nothing reads afterward. Bytes, order, terminals and errors are the same for every request.

Refs #8601

Verification

Red first. Each test failed on the base 2c0a9ef (or on f05e87f, where it pins a regression of that head) for the stated reason, and passes now:

  • tests/responses/stalled-reader-memory.test.ts:
    • Pacing, before the first client read (bound: reads + 1): a relayed link turn, a link socket turn, and a link socket turn on the eager relay (setRelayPlatformForTests("win32")), all with the feature on, pulled 36, 36 and 9 upstream chunks.
    • Small-chunk case: with 16 KiB events and a bound of reads + 2 (the client's chunk plus the one inspection may lead), the test fails when the failed-tail relay, the block rewrite or the translator-budget stage loses the paced mark (mutations recorded).
    • Controls: local requests and a link turn with the feature off keep at least 32 chunks (tee). The eager control keeps 8 to 31, which pins that the platform seam chose the eager relay. Every case delivers the same bytes. The pull counts settle after one event-loop turn, because the fake upstream and every stage advance on promise jobs only.
    • Tool scope: a snapshot-repair turn's rewrite receives exactly the tool scope. On the base it received the whole parsed body with its input.
    • Parse count: one parse of the outbound body per build, streaming and non-streaming. At f05e87f the non-streaming case parsed it 3 times.
  • tests/routing/combo-stream-preflight.test.ts: the replay's buffer slots are empty after each read and after cancel. On the base the slots kept their bytes. These assertions replace an earlier WeakRef and Bun.gc check, which conservative stack scanning could make flaky.
  • tests/server/link-websocket-holds.test.ts:
    • Pacing wiring: the relay marks its turn paced only while the feature is on, and a link socket's observer is paced. Both failed without the wiring.
    • Accounting failures: when traffic accounting throws, the observation is decided and the lease returned. On the base there was no decision. When ending the broken flow also throws, before or after dispatch, the lease is still returned (at f05e87f: not returned).
    • Abort before headers: the request never decodes its copy. This passes on dev and fails against the pre-Link WebSocket holds: the HTTP hold check decodes its body copy outside the inbound budget (fix before the gate opens) #8608 listener with one decode.

Commands (Bun 1.4.4, TMPDIR=/tmp), on head af3d8ea:

  • bun run typecheck: exit 0
  • bun run privacy:scan: exit 0
  • bun run structure:check: exit 0
  • bun scripts/test.ts --parallel=2 over 88 files: exit 0, 2979 pass, 2 skip, 0 fail. The files: the link server tests; the relay, rewrite, failed-tail, snapshot repair, terminal repair, translator-budget, combo preflight, WebSocket endpoint and steering suites; the passthrough suite; tests/responses/responses-core-modules.test.ts; the inbound-body and lab boundary tests; tests/test-layout.test.ts, tests/test-layout-tooling.test.ts, tests/ci-workflows/structure-ssot.test.ts, tests/ci-workflows/file-size-ratchet.test.ts and tests/clients/link-boundary.test.ts.
  • The RSS diagnostics in the table: OCX_LINK_WS_RSS_ACCEPTANCE=1 OCX_LINK_WS_RSS_SOCKETS=4 OCX_LINK_WS_RSS_TRANSPORT=<websocket|http> OCX_LINK_WS_RSS_UPSTREAM=<hold|free>, one at a time.

NOT RUN:

The shared pipeline changes touch src/server/relay.ts, relay-eager.ts, sse-payload-rewrite.ts, inspection-tee.ts, src/lib/translator-budget.ts, core-lifetime.ts, combo-stream-preflight.ts and passthrough-dispatch.ts, so ci:full is advisable.

Review

  • Rounds 1 and 2 (read-only reviewer, gpt-6.1-terra, xhigh): round 1 raised two P2s. The first said the combo replay kept its prefix; I accepted it and fixed it. The second, about snapshot repair keeping the tool catalog, was withdrawn in round 2. Round 2 left one P3, which is fixed.
  • Final review of f05e87f: it blocked on test stability (garbage-collection reachability) and listed P3s. All are addressed here:
    • The two tests now use deterministic seams.
    • The outbound body is parsed once per build and only its tool scope is kept.
    • The lease is returned when ending a broken flow throws.
    • This text says Refs and names the feature condition in the title.
    • The read-ahead source and the acceptance synchronization are documented correctly.
    • The eager control and a per-stage pacing check are added.
    • The stages before the slicer are documented, not marked, because marking them would need the paced decision before the exchange is built.
    • passthrough-dispatch.ts has headroom.
  • Round 3 (same reviewer) on this delta: no P0-P3. The red runs above are the author's.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed (structure/remote-link.md, structure/transports/byte-accounting.md).
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults (no auth or credential path changes; pacing is gated on the link WebSocket feature).

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the bug Something isn't working label Nov 13, 2026
@lidge-jun lidge-jun changed the title fix(responses): a stalled Remote Link reader no longer makes the Home read 32 MiB ahead or hold a second copy of the request fix(responses): while the link WebSocket feature is on, a stalled Remote Link reader no longer makes the Home read 32 MiB ahead, and no turn keeps a second parsed copy of its request Nov 13, 2026
…reader-memory

# Conflicts:
#	tests/fixtures/test-layout-expected.json
@lidge-jun
lidge-jun marked this pull request as ready for review November 13, 2026 03:31
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner November 13, 2026 03:31
@lidge-jun
lidge-jun merged commit f4386e7 into dev Nov 13, 2026
32 checks passed
@lidge-jun
lidge-jun deleted the fix/responses-stalled-reader-memory branch November 13, 2026 03:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T03:33:47.614103Z eab8bb9 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

lidge-jun added a commit that referenced this pull request Nov 13, 2026
… (#8622)

The squash's tree equals the merge of eab8bb9 with dev 9532563, so this commit records the squash as an ancestor without changing any file.
lidge-jun added a commit that referenced this pull request Nov 13, 2026
…e-memory

Brings in dev 9532563 and the squash of the lower slice; no file of this slice is edited (git merge-tree, no conflicts).
lidge-jun added a commit that referenced this pull request Nov 13, 2026
…ance, the Home counts link sockets, and the review nits of #8622 and #8625 (#8647)

* test(responses): pin the combo replay on a paced source, and only the read slots on an unpaced one

* fix(responses): a combo child's required-tool check keeps whether the outbound body denies every tool, not the parsed body

* fix(link): end every relayed request's traffic flow through one guarded helper, so a throwing end never keeps the lease

* fix(link): a throwing stall observer never breaks a relayed body

* test(link): a parsed create stays with its own request when a fallback or recovery builds the next one

* docs(link): note that a link create's parsed body shares its nested input with the frame

* feat(link): the Home counts each link WebSocket in its per-link traffic book with the Child's definition

* test(link): the RSS acceptance announces a stall only after a quiet window, and fails a load that does not settle

* docs(link): only the settled acceptance runs count, and how the quiet window settles them (#8600)

* docs(link): the Home counts link sockets in the Child's units, and says where completeness differs

* docs(link): the traffic counters' comments cover a link socket's message payloads

* docs(responses): the required-tool check keeps its tool declarations as well as whether the body denies every tool

* test(link): a refused or failed link upgrade counts nothing in the Home's traffic book

* style(link): drop the trailing blank line from the gate and the RSS fixture

* docs(link): the quiet window's timers are the only ones that change adds to the RSS fixture

* test(link): the failed-upgrade case proves the gate reached server.upgrade

* test(responses): the workflow ceiling test's hand-made socket carries its WsData, as every upgraded socket does

#8415 added a test that hands sendResponseToWebSocket a socket with no data. Every socket the shared Responses server upgrades carries a WsData object (the Responses socket, the live sideband, the Remote Workspace agent and the link gate all pass data to server.upgrade), and the bridge already reads ws.data on its other paths, so the socket in the test is what was wrong; since the Home counts link socket traffic, sendTextFrame reads ws.data.link on every send and the test threw.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant