diff --git a/src/lib/paced-stream.ts b/src/lib/paced-stream.ts index c3f3166dbf7..3462c4f42e7 100644 --- a/src/lib/paced-stream.ts +++ b/src/lib/paced-stream.ts @@ -32,4 +32,3 @@ export function carryPacedStream>(source: R if (source && paced.has(source)) paced.add(output); return output; } - diff --git a/src/server/index/link-relay-sessions.ts b/src/server/index/link-relay-sessions.ts index 06419e19a67..9d54616e2a1 100644 --- a/src/server/index/link-relay-sessions.ts +++ b/src/server/index/link-relay-sessions.ts @@ -10,6 +10,7 @@ import { linkActivityCounts, type LinkActivity } from "../../link/child-activity import type { LinkSessionGrant, LinkUpgradeOutcome } from "./link-websocket"; import type { LinkTrafficBook } from "../../link/traffic"; import { LINK_HOME_FEATURES_HEADER } from "../../link/request-compression"; +import { linkRelayWaitObserver } from "./link-websocket-limits"; /** A 200 `GET /v1/catalog` whose body the Child read to the end (wp2 catalog freshness). */ export interface LinkCatalogServed { linkId: string | null; keyId: string | null; etag: string } @@ -230,9 +231,14 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) { let ended = false; // A cancel resolves a pending read as done; that end is not a completed body. let cancelled = false; + // Test-only stall signal (link-websocket-limits.ts): set from each chunk handed over until the reader asks again. + const waitObserver = sessionLink !== null ? linkRelayWaitObserver() : null; + let waiting = false; + const stopWaiting = (): void => { if (waiting) { waiting = false; waitObserver?.(false); } }; const finish = () => { if (ended) return; ended = true; + stopWaiting(); req.signal.removeEventListener("abort", aborted); release(); }; @@ -246,10 +252,14 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) { if (req.signal.aborted) aborted(); const body = new ReadableStream({ async pull(controller) { + stopWaiting(); try { const next = await reader.read(); if (next.done) { flow?.end(!cancelled); finish(); controller.close(); if (!cancelled) reportCatalog(); } - else { catalogHash?.update(next.value); flow?.fromHome(next.value.byteLength); controller.enqueue(next.value); } + else { + catalogHash?.update(next.value); flow?.fromHome(next.value.byteLength); controller.enqueue(next.value); + if (waitObserver && !ended) { waiting = true; waitObserver(true); } + } } catch (error) { flow?.end(false); finish(); controller.error(error); } }, cancel, diff --git a/src/server/index/link-websocket-limits.ts b/src/server/index/link-websocket-limits.ts index 05c43baa163..e9a9bb25828 100644 --- a/src/server/index/link-websocket-limits.ts +++ b/src/server/index/link-websocket-limits.ts @@ -121,3 +121,16 @@ export function setLinkPumpWaitObserverForTests(observer: ((waiting: boolean) => pumpWaitObserver = observer; } +/** + * Test-only: told when a relayed HTTP link response has handed its reader a chunk and waits for the next read (true), + * and when that wait ends (false). Bun stops reading a body whose socket does not drain, so a stalled Child reader + * leaves its relay waiting: the HTTP counterpart of the pump wait above (#8600). + */ +let relayWaitObserver: ((waiting: boolean) => void) | null = null; + +export function linkRelayWaitObserver(): ((waiting: boolean) => void) | null { return relayWaitObserver; } + +export function setLinkRelayWaitObserverForTests(observer: ((waiting: boolean) => void) | null): void { + relayWaitObserver = observer; +} + diff --git a/src/server/index/websocket-handler.ts b/src/server/index/websocket-handler.ts index cf07600322f..810c449b3b8 100644 --- a/src/server/index/websocket-handler.ts +++ b/src/server/index/websocket-handler.ts @@ -92,7 +92,7 @@ import { } from "../live"; import type { ServeOptionsContext } from "./serve-options"; import type { RequestMetricsRecorder } from "../request-metrics"; -import { resolveInboundBodyLimitBytes } from "../request-decompress"; +import { attachParsedRequestBody, resolveInboundBodyLimitBytes } from "../request-decompress"; import { responseToolOwnership } from "../responses/response-tool-ownership"; import { runTurnStateCallerScope } from "../turn-state-handles"; import { admitHttpWorkflowTurn, workflowDecisionRefusalResponse } from "../workflow-refusal"; @@ -345,11 +345,16 @@ export function createWebsocketHandler( const baseHeaders = ws.data.headers ?? new Headers(); const fwd = new Headers({ "content-type": "application/json" }); baseHeaders.forEach((value, key) => fwd.set(key, value)); + // A Remote Link socket hands the pipeline the create it parsed (#8600): serializing it into the request and + // parsing it back would hold two more request-sized copies for the turn. Local sockets keep the request body. + const turnBody = { ...payload, stream: true }; + const linkSocket = ws.data.link !== undefined; const req = new Request("http://localhost/v1/responses", { method: "POST", headers: fwd, - body: JSON.stringify({ ...payload, stream: true }), + ...(linkSocket ? {} : { body: JSON.stringify(turnBody) }), }); + if (linkSocket) attachParsedRequestBody(req, turnBody); try { // A socket can be the first ingress for a root. Admit every inference frame, // then keep its workflow lease with the turn until terminal output or cancellation. diff --git a/src/server/request-decompress.ts b/src/server/request-decompress.ts index 87639046a05..0fe9ec16b35 100644 --- a/src/server/request-decompress.ts +++ b/src/server/request-decompress.ts @@ -395,3 +395,31 @@ export function readJsonRequestBody( ): Promise { return readBoundedJsonRequestBody(req, maxBytes, budget); } + +/** + * Admit a body the caller already parsed (a Remote Link WebSocket create, #8600) as if it had been read: its serialized + * size is held to the same limit and observed by the same budget as the parse at the end of the bounded reader. + */ +export function admitParsedJsonRequestBody(body: unknown, maxBytes: number, budget?: TranslatorBudget): unknown { + const parsedBytes = serializedJsonByteLength(body); + if (parsedBytes > maxBytes) throw new DecompressedBodyTooLargeError(parsedBytes, maxBytes, "decoded_exact"); + budget?.observeAcceptedRequestCopy(parsedBytes); + return body; +} + +/** + * A parsed body bound to the one Request it stands for (#8600). It goes with that request alone: a request the pipeline + * builds for a combo child, a recovery or a retry is another Request and reads its own body. Taken once, like a body. + */ +const parsedBodies = new WeakMap(); + +export function attachParsedRequestBody(req: Request, body: unknown): void { + parsedBodies.set(req, body); +} + +export function takeParsedRequestBody(req: Request): { body: unknown } | undefined { + if (!parsedBodies.has(req)) return undefined; + const body = parsedBodies.get(req); + parsedBodies.delete(req); + return { body }; +} diff --git a/src/server/responses/bare-namespace-aliases.ts b/src/server/responses/bare-namespace-aliases.ts index ba7b35e6204..97767cb7a0c 100644 --- a/src/server/responses/bare-namespace-aliases.ts +++ b/src/server/responses/bare-namespace-aliases.ts @@ -16,4 +16,3 @@ export function authorizedBareNamespaceToolAliases(toolNsMap: Iterable<[string, ), ); } - diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index f59a7bdb63c..f87594c6942 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -17,7 +17,7 @@ import { restoreCachedEncryptedAgentTasks, recoverEncryptedAgentTaskWithResult, } from "./agent-task-recovery"; -import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "../request-decompress"; +import { admitParsedJsonRequestBody, readJsonRequestBody, resolveInboundBodyLimitBytes, takeParsedRequestBody } from "../request-decompress"; import { clientCancelledResponse, decodeRequestErrorResponse, @@ -248,7 +248,9 @@ export async function prepareResponsesRequest( const agentTaskRecovery = agentTaskRecoveryConfig(config); let body: unknown; try { - body = await readJsonRequestBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes)); + const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes); + const attached = takeParsedRequestBody(req); + body = attached ? admitParsedJsonRequestBody(attached.body, limit, translatorBudget) : await readJsonRequestBody(req, translatorBudget, limit); } catch (err) { if (options.abortSignal?.aborted || req.signal.aborted) { return clientCancelledResponse(); diff --git a/structure/remote-link.md b/structure/remote-link.md index 87310f8f26a..8622318c6dd 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -207,7 +207,7 @@ A Child compresses a request body with zstd before it crosses the link only when Only a request on a relay session that `src/server/index/link-relay-sessions.ts` has just consumed and verified on the same connection reaches the gate, and only with the exact Codex shape: `GET /v1/responses` without a query, `Upgrade: websocket`, a `Connection` naming upgrade, version 13, a key, and no `Origin`, subprotocol or extension. Any other upgrade, and every upgrade without a session, keeps the 404. One synchronous function then checks the abort signal, the switches and the shutdown drain, requires the upgrade's credential to be the key the proof was made with (401 otherwise), runs the authorization check below, and takes in order a 32 MiB transport reservation from a 768 MiB budget, a slot under the per-link (8) and overall (24) caps, and a slot in the shared 128-socket gate, which may reclaim only an idle link socket (`tryReserveCodexWebSocket({ reclaim: "link" })` in `src/codex/websocket-registry.ts`; below). A refused reservation or cap answers 426 `link_websocket_capacity`. A lease bundle owns the session's drain lease and every reservation: a refusal, abort, throw or failed upgrade releases them once in reverse order, a successful upgrade hands them to the socket, and only its close callback releases them, so last-link `close()` neither hangs on a half-made socket nor misses one. Every cap, budget and interval is a named value in `src/server/index/link-websocket-limits.ts`. -The link listener's websocket handler wraps the shared Responses handler with 8 MiB messages, an 8 MiB backpressure limit that never closes the socket, no idle timeout and no compression. On a link socket the shared SSE pump (`pumpResponsesSseToWebSocket` in `src/server/ws-bridge.ts`) waits for Bun's drain after any send that leaves more than 1 MiB buffered, before the next event of the same upstream chunk, so the send buffer stays under 1 MiB plus one event of at most 4 MiB; it feeds the SSE framer at most 256 KiB of a chunk at a time; a cancel or close ends the wait, and a socket that does not drain for 300 s is closed with 1011. Local sockets keep the single synchronous loop. While the feature is on, every link turn, a link socket's and a relayed `POST /v1/responses` alike, is paced (#8601): its turn observer carries `pacedReads` (`linkTurnPacesReads` in `src/server/link-turn.ts`), and the passthrough relay reads the upstream only as the client drains, one 256 KiB slice ahead (`src/lib/paced-stream.ts`), where every other request lets inspection read 32 MiB past its client. A Child that stops reading therefore holds about one upstream chunk on the Home. Translated adapters, which do not take the passthrough relay, are not paced. A JSON upstream answer turned into Responses events (`sendResponsesJsonAsLinkEvents`) is paced the same way on a link socket: each event waits for send room under the same stall deadline. The turn's cancel (supersession or close) ends that wait, and only a current, uncancelled turn's stall closes the socket. An event larger than the 4 MiB client frame limit, the terminal included, which repeats the whole output, is never sent: the turn ends incomplete with the 502 error frame the SSE pump sends for an oversized upstream frame. Local sockets keep the synchronous JSON delivery. The memory acceptance (design 6.3) is `tests/e2e-style/link-websocket-rss.test.ts`, opt-in with `OCX_LINK_WS_RSS_ACCEPTANCE=1`. The 32 MiB reservation bounds what the WebSocket transport itself adds, so the test runs one stalled load twice, each Home in its own process: 24 link sockets each send a near-maximum create whose reader stalls, upstream chunks run from 1 byte to 16 MiB, each upstream stream is held after 16 MiB, and the sockets are cut in a seeded random order; the second run sends the same load through the HTTP link relay under the same synchronization. It passes when both Homes reported their own stall and the WebSocket run's peak-over-idle RSS minus the HTTP run's is at most 24 reservations (768 MiB). The WebSocket Home reports every link pump waiting for a drain; the HTTP link relay has no such signal (Bun stops pulling its body silently), so its run is synchronized only on the upstream's hold, the two peaks may come from different stages, and the acceptance cannot pass until the relay can report its stall. The peak is Linux `VmHWM`, reset after the idle reading; a sampled peak cannot pass. Only that canonical load can report an acceptance; any other `OCX_LINK_WS_RSS_*` setting (socket count, input size, chunk size, one transport alone, a free-running upstream, a heap breakdown at the stall) runs a diagnostic that prints its numbers and asserts no budget. Measurements on a 4-core Linux VM, peak-over-idle RSS per socket. The diagnostics at four sockets: R1 WebSocket, 1 KiB input, upstream chunks capped at 256 KiB, free-running upstream, 100.6 MiB; R2 the same with the upstream held, 76.0 MiB; R3 as R2 over HTTP, 66.3 MiB; R4 WebSocket, near-8 MiB input, 16 MiB chunks, held, 134.9 MiB; R5 as R4 over HTTP, 129.7 MiB. Five later pairs at the canonical settings and four sockets gave WebSocket-minus-HTTP differences of 31.0, 33.4, 44.2, 45.7 and 47.1 MiB, so R4 minus R5 (5.2 MiB) was a low outlier. The difference follows the request size: 3.5 MiB with a 1 KiB input and 16 MiB chunks, 65.2 MiB with the near-8 MiB input and 256 KiB chunks. The canonical acceptance at 24 sockets measured 117.0 MiB for the WebSocket and 70.2 MiB for HTTP, a difference of 1,123 MiB against 768 MiB (a second run: 117.4 and 65.9 MiB, 1,235 MiB), so it fails: the transport adds about 47 MiB per socket on a near-8 MiB create, above the 32 MiB reservation. The rest is shared by both transports and predates this feature: the passthrough relay read up to 32 MiB ahead of a stalled reader through its inspection tee (R1 against R2; Bun's `fetch` itself stops at the socket buffers, a few MiB), and a large request is copied several times on its way upstream. #8601 paces link turns while the feature is on and drops the kept re-parse of the outbound body. The release gate stays closed whatever the acceptance reports. Every message, of any type, re-runs the authorization check before the shared handler sees it: an uncached, fail-closed `links.json` read still names the link and its key, and the key still has the fingerprint the session was proved with. A failure fences the socket, cancels its turn and closes it with 4401. Native steering and injection are unavailable on a link socket: `response.inject` and `response.steer` get `native_control_unavailable_on_link`, and a create never opens a native channel. +The link listener's websocket handler wraps the shared Responses handler with 8 MiB messages, an 8 MiB backpressure limit that never closes the socket, no idle timeout and no compression. On a link socket the shared SSE pump (`pumpResponsesSseToWebSocket` in `src/server/ws-bridge.ts`) waits for Bun's drain after any send that leaves more than 1 MiB buffered, before the next event of the same upstream chunk, so the send buffer stays under 1 MiB plus one event of at most 4 MiB; it feeds the SSE framer at most 256 KiB of a chunk at a time; a cancel or close ends the wait, and a socket that does not drain for 300 s is closed with 1011. Local sockets keep the single synchronous loop. While the feature is on, every link turn, a link socket's and a relayed `POST /v1/responses` alike, is paced (#8601): its turn observer carries `pacedReads` (`linkTurnPacesReads` in `src/server/link-turn.ts`), and the passthrough relay reads the upstream only as the client drains, one 256 KiB slice ahead (`src/lib/paced-stream.ts`), where every other request lets inspection read 32 MiB past its client. A Child that stops reading therefore holds about one upstream chunk on the Home. Translated adapters, which do not take the passthrough relay, are not paced. A JSON upstream answer turned into Responses events (`sendResponsesJsonAsLinkEvents`) is paced the same way on a link socket: each event waits for send room under the same stall deadline. The turn's cancel (supersession or close) ends that wait, and only a current, uncancelled turn's stall closes the socket. An event larger than the 4 MiB client frame limit, the terminal included, which repeats the whole output, is never sent: the turn ends incomplete with the 502 error frame the SSE pump sends for an oversized upstream frame. Local sockets keep the synchronous JSON delivery. The memory acceptance (design 6.3) is `tests/e2e-style/link-websocket-rss.test.ts`, opt-in with `OCX_LINK_WS_RSS_ACCEPTANCE=1`. The 32 MiB reservation bounds what the WebSocket transport itself adds, so the test runs one stalled load twice, each Home in its own process: 24 link sockets each send a near-maximum create whose reader stalls, upstream chunks run from 1 byte to 16 MiB, each upstream stream is held after 16 MiB, and the sockets are cut in a seeded random order; the second run sends the same load through the HTTP link relay. It passes when both Homes reported their own stall and the WebSocket run's peak-over-idle RSS minus the HTTP run's is at most 24 reservations (768 MiB). The WebSocket Home reports every link pump waiting for a drain; the HTTP Home reports every relayed response waiting for its reader after handing it a chunk (`setLinkRelayWaitObserverForTests` in `src/server/index/link-websocket-limits.ts`, called from `src/server/index/link-relay-sessions.ts` only while a test installed it; Bun stops reading a body whose socket does not drain, so a stalled Child leaves its relay waiting). Either announcement marks the first moment every load reader waits at once, which can come before the load's sustained stall: a paused reader's kernel buffer still takes bytes in flight, so a pump's wait can end without its reader resuming, and a relay also waits in the gap between two chunks. Bun exposes no sustained-backpressure signal and the acceptance uses no quiet period, so a run compares the two loads at their first all-waiting moment; that is why repeated runs differ by hundreds of MiB. The announcement is armed at the idle reading, so the warm-up turn cannot trigger it, and neither run waits for the upstream's hold point: a link turn reads its upstream only as its reader drains (#8601), so a stalled load stops pulling before it. The peak is Linux `VmHWM`, reset after the idle reading; a sampled peak cannot pass. Only that canonical load can report an acceptance; any other `OCX_LINK_WS_RSS_*` setting (socket count, input size, chunk size, one transport alone, a free-running upstream, a heap breakdown at the stall) runs a diagnostic that prints its numbers and asserts no budget. Where a near-8 MiB create was held (#8600, from heap snapshots at the stall and the code path): both transports keep the pipeline's parsed body, which the continuation store needs, and the serialized outbound body, which a retry needs; before #8601 both also kept a re-parse of the outbound body and read 32 MiB ahead of the stalled reader. The WebSocket path added its own copies: the shared handler parsed the frame, serialized it again into a synthetic request (a transient copy), whose body Bun kept for the whole turn (about 8 MiB per socket), and the pipeline read that body back into a second parsed body (about 8 MiB per socket, plus the decoded string while parsing). A link socket now hands the pipeline the create it parsed (`attachParsedRequestBody` in `src/server/request-decompress.ts` binds it to that turn's own request, and preparation takes it once and admits it with `admitParsedJsonRequestBody` under the same limit and budget accounting); a request the pipeline builds from it, a combo child, a recovery or a retry, is another request and reads its own body. A local socket still sends a request body. What remains WebSocket-only is the design's transport buffers (one event of at most 4 MiB waiting for the drain and the socket's own send buffer), the parse of a first create when the handshake carried no thread id, and the HMAC over the canonical input for the hold fingerprint, both transient. Measurements on a 4-core Linux VM, peak-over-idle RSS per socket. Before these changes: the canonical acceptance at 24 sockets measured 117.0 MiB for the WebSocket and 70.2 MiB for HTTP, a difference of 1,123 MiB against 768 MiB (a second run: 1,235 MiB), and four-socket pairs at the canonical settings differed by 31.0 to 47.1 MiB per socket. After #8601 and #8600: four canonical runs measured 62.2, 53.0, 52.4 and 56.9 MiB for the WebSocket and 47.3, 46.6, 51.0 and 49.5 MiB for HTTP, differences of 356, 154, 33 and 179 MiB against 768 MiB; all passed, with each Home reporting its own stall. The reservation, the 768 MiB budget and the 24-socket cap are unchanged. The release gate stays closed whatever the acceptance reports. Every message, of any type, re-runs the authorization check before the shared handler sees it: an uncached, fail-closed `links.json` read still names the link and its key, and the key still has the fingerprint the session was proved with. A failure fences the socket, cancels its turn and closes it with 4401. Native steering and injection are unavailable on a link socket: `response.inject` and `response.steer` get `native_control_unavailable_on_link`, and a create never opens a native channel. DELETE `/api/link/:id`, which `ocx link revoke` calls, closes that link's sockets with 4401 in the same task as its commit, including a socket already upgraded but not yet opened, which closes as soon as Bun opens it, and last-link `close()` refuses further link upgrades and closes every link socket before it drains. Process `stop()` stays forceful. A change made any other way (the API-key routes, a rotation that expires, another process, a hand edit) stops new turns at the next frame and running turns at the sweep, which runs every 30 s only while a link socket exists. Switching either setting off starts a drain on each open link socket, at the first sweep or frame that sees it off. The drain never cancels a running turn: a `response.create` that arrives while a turn runs is dropped and the socket closes with 1000 after that turn; with no turn running, a create is admitted only when it returns a result the socket is waiting for (`returnsPending` in `src/codex/websocket-activity.ts`) and nothing is untracked, so the tool loop that was running continues; any other create, and every create 60 minutes after the drain began, fences and closes the socket. A draining socket that becomes idle closes. Outside a drain, a link socket idle for 10 minutes closes with 1000, and one older than 60 minutes closes at its next idle moment so it re-authenticates; a busy socket is never closed on a timer. When the shared 128-socket gate is full, a link upgrade may reclaim the least recently used idle link socket (`tryReserveCodexWebSocket({ reclaim: "link" })`), never a local one. A link socket counts in the per-link activity book (`beginSocket` in `src/link/child-activity.ts`) while it is busy, that is while a turn runs, a client tool or approval result is pending, results are untracked or it is closing, so activity-gated Child restarts wait for it; the busy-to-idle transition stamps the last data end. A socket that closes while busy ends its count. Coverage: `tests/server/link-websocket-upgrade.test.ts` (a real Home: switched-off characterization, a turn, S2, revocation, same-size and same-mtime edits, native control, close and stop) and `tests/server/link-websocket-gate.test.ts` (each lease transition, caps, budget, no eviction, the sweep on an injected timer, an upgrade racing last-link `close()`), and `tests/server/link-websocket-drain.test.ts` (each drain row, the deadline, idle and age closes, socket activity, link-only reclaim), and `tests/server/link-websocket-pump.test.ts` (the 5 MiB bound with a stalled reader, framing slices, the drain wiring, the stall bound). diff --git a/tests/e2e-style/link-websocket-rss.test.ts b/tests/e2e-style/link-websocket-rss.test.ts index 31d5720bfc4..05400b96acd 100644 --- a/tests/e2e-style/link-websocket-rss.test.ts +++ b/tests/e2e-style/link-websocket-rss.test.ts @@ -15,11 +15,11 @@ import { repoPath } from "../helpers/repo-root"; // upstream chunks run from 1 byte to 16 MiB around near-4 MiB events, each upstream stream is held after 16 MiB, // and the sockets are then cut in a seeded random order. The second run sends the same load through the HTTP link // relay. Accepted when both Homes reported their own stall and the WebSocket run's peak-over-idle RSS minus the HTTP -// run's stays within n reservations (768 MiB at n = 24). The HTTP link relay has no stall signal yet (only the -// upstream's hold is observed), so today the pair is a measurement and the acceptance cannot pass. What both share -// (fetch read-ahead and request copies under a stalled reader) is a separate, pre-existing cost of the pipeline and +// run's stays within n reservations (768 MiB at n = 24). Both Homes report their own stall: every link pump waiting +// for a drain, or every relayed HTTP response waiting for its reader after handing it a chunk (#8600). What both share +// (the pipeline's parsed and serialized request under a stalled reader, #8601) is a cost of the pipeline and // is not part of this bound. -// The definition, the measured numbers (R1 to R5) and how they were taken are in structure/remote-link.md. +// The definition, the measured numbers and how they were taken are in structure/remote-link.md. // The peak is the kernel's high-water mark (VmHWM, reset after the idle reading) on Linux 4.0 or later; // elsewhere the Home samples RSS on its own event loop, may miss a short peak, reports "sampled", and cannot pass. // Any other OCX_LINK_WS_RSS_* setting turns the run into a diagnostic: it prints its numbers and never reports an @@ -58,11 +58,15 @@ function eventsText(count: number): string { } /** - * How a run knew its load had stalled. "home-pumps-waiting": the Home reported every link pump waiting for a drain. - * "upstream-held": only the fake upstream reached its hold point; the HTTP link relay exposes no stall signal of its - * own (Bun stops pulling its body without saying so), so the Home's own stage at that moment is not established. + * How a run knew its load had stalled, always from the Home itself. "home-pumps-waiting": every link pump waits for a + * drain. "home-relays-waiting": every relayed HTTP response waits for its reader (Bun stops reading a body whose socket + * does not drain). Either announcement marks the first moment every load reader waits at once, which can come before + * the load's sustained stall: a paused reader's kernel buffer still takes bytes in flight, so a pump's wait can end + * without its reader resuming, and a relay also waits in the gap between two chunks. Bun exposes no sustained + * backpressure signal and this test uses no quiet period, so a run compares the two loads at their first all-waiting + * moment, and repeated runs vary (structure/remote-link.md). */ -type StallSync = "home-pumps-waiting" | "upstream-held"; +type StallSync = "home-pumps-waiting" | "home-relays-waiting"; interface LoadResult { method: string; idle: number; peak: number; delta: number; sync: StallSync } /** One stalled load against a Home in its own process; prints its numbers and returns the peak reading. */ @@ -71,18 +75,11 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean expect(SOCKETS).toBeLessThanOrEqual(LINK_WS_LIMITS.totalSockets); const root = mkdtempSync(join(tmpdir(), "ocx-link-ws-rss-")); const body = new TextEncoder().encode(eventsText(14)); - // One promise pair per expected upstream request, created up front: no polling for arrivals. + // One promise per expected upstream request, created up front: no polling for arrivals. // Request 0 is a complete warm-up turn, so one-time first-request costs land before "idle". const signals = Array.from({ length: SOCKETS + 1 }, () => { - let stalled!: () => void; let gone!: () => void; - let heldAt!: () => void; - return { - reachedStall: new Promise(resolve => { stalled = resolve; }), - cancelled: new Promise(resolve => { gone = resolve; }), - reachedHold: new Promise(resolve => { heldAt = resolve; }), - stalled: () => stalled(), gone: () => gone(), held: () => heldAt(), - }; + return { cancelled: new Promise(resolve => { gone = resolve; }), gone: () => gone() }; }); let requests = 0; let largestChunk = 0; @@ -102,7 +99,7 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean pull(controller) { if (offset >= body.byteLength) { controller.close(); signal.gone(); return; } // A held stream (not the warm-up) supplies nothing more after the stall point, until it is cancelled. - if (options.hold && stream > 0 && offset >= HOLD_BYTES) { signal.held(); return new Promise(() => {}); } + if (options.hold && stream > 0 && offset >= HOLD_BYTES) return new Promise(() => {}); const size = Math.min(MAX_CHUNK, CHUNK_PLAN[pulls % CHUNK_PLAN.length]!); const chunk = body.subarray(offset, Math.min(body.byteLength, offset + size)); offset += chunk.byteLength; @@ -110,8 +107,6 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean pulls += 1; largestChunk = Math.max(largestChunk, chunk.byteLength); controller.enqueue(chunk); - // By the third chunk the paused reader has an event to stall on (the 16 MiB chunk holds several). - if (pulls === 3) signal.stalled(); }, cancel() { signal.gone(); }, }, { highWaterMark: 0 }), { headers: { "content-type": "text/event-stream" } }); @@ -142,7 +137,7 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean const ask = async (command: string): Promise => { child.stdin.write(command + "\n"); child.stdin.flush(); return Number((await nextLine()).rss); }; const clients: LinkWireClient[] = []; try { - child.stdin.write(JSON.stringify({ upstreamPort: upstream.port, keys, stalls: options.transport === "websocket" ? SOCKETS : Number.MAX_SAFE_INTEGER }) + "\n"); + child.stdin.write(JSON.stringify({ upstreamPort: upstream.port, keys, stalls: SOCKETS }) + "\n"); child.stdin.flush(); const ready = await nextLine(); const linkPort = Number(ready.linkPort); @@ -172,16 +167,13 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean } wire.pause(); } - // The Home itself announces when every link pump is waiting on a drain at once. The HTTP - // diagnostic has no pump to observe and settles for the upstream having enqueued its third chunk. - if (options.transport === "websocket") { - const announced = (async () => { for (;;) if ((await nextLine()).stalled === true) return "stalled" as const; })(); - const finished = Promise.all(signals.slice(1).map(signal => signal.cancelled)).then(() => "finished" as const); - // A load that completes before every pump waits never reached the condition being measured. - expect(await Promise.race([announced, finished])).toBe("stalled"); - } else await Promise.all(signals.slice(1).map(signal => options.hold ? signal.reachedHold : signal.reachedStall)); - // A link turn reads its upstream only as its socket drains (#8601), so a stalled WebSocket pump stops pulling before - // the upstream's hold point: the pumps' own stall is the synchronization, and the upstream is never waited for here. + // The Home itself announces when every link pump, or every relayed HTTP response, waits for its reader at once. + // A link turn reads its upstream only as its reader drains (#8601), so a stalled load stops pulling before the + // upstream's hold point: the Home's own stall is the synchronization, and the upstream is never waited for here. + const announced = (async () => { for (;;) if ((await nextLine()).stalled === true) return "stalled" as const; })(); + const finished = Promise.all(signals.slice(1).map(signal => signal.cancelled)).then(() => "finished" as const); + // A load that completes before every reader stalls never reached the condition being measured. + expect(await Promise.race([announced, finished])).toBe("stalled"); const enqueuedAtStallMiB = delivered.slice(1).map(bytes => Math.round(bytes / MiB)); if (HEAP) { child.stdin.write("heap\n"); child.stdin.flush(); console.log(JSON.stringify(await nextLine())); } // Cut every socket in a seeded random order, at different points of its stalled stream. @@ -199,7 +191,7 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean const delta = peak - idle; const budget = SOCKETS * LINK_WS_LIMITS.socketReservationBytes; console.log(JSON.stringify({ method, transport: options.transport, sockets: SOCKETS, idleMiB: idle / MiB, peakMiB: peak / MiB, deltaMiB: delta / MiB, perSocketMiB: delta / SOCKETS / MiB, budgetMiB: budget / MiB, afterCutMiB: after / MiB, largestUpstreamChunkMiB: largestChunk / MiB, upstreamBodyMiB: Math.round(body.byteLength / MiB), enqueuedAtStallMiB })); - return { method, idle, peak, delta, sync: options.transport === "websocket" ? "home-pumps-waiting" : "upstream-held" }; + return { method, idle, peak, delta, sync: options.transport === "websocket" ? "home-pumps-waiting" : "home-relays-waiting" }; } finally { for (const client of clients) client.destroy(); try { child.stdin.write("stop\n"); child.stdin.flush(); child.stdin.end(); } catch { /* already gone */ } @@ -212,8 +204,8 @@ async function runLoad(options: { transport: "websocket" | "http"; hold: boolean describe.skipIf(!ENABLED)("link WebSocket transport-only RSS acceptance" + (ENABLED ? "" : " [skipped: opt-in with OCX_LINK_WS_RSS_ACCEPTANCE=1; it runs two Homes of several GiB each and is not part of the ordinary suite]"), () => { // Design T4 6.3, as decided after the T5g measurements: the reservation bounds what the link WebSocket transport - // itself adds. Both transports run the same stalled load against a held upstream, each synchronized on the stall it - // can observe (the WebSocket on its pumps, the HTTP relay on the upstream's hold; #8600 gives the relay its own), and + // itself adds. Both transports run the same stalled load against a held upstream, each synchronized on a stall its Home + // reports itself (the WebSocket's pumps waiting for a drain, the HTTP relays waiting for their readers), and // the WebSocket's peak minus the HTTP relay's peak must stay within the sockets' reservations. test.skipIf(!CANONICAL)("acceptance: the WebSocket's peak RSS over the HTTP relay's, under the same held load, stays within the link socket reservations" + (CANONICAL ? "" : " [skipped: diagnostic settings present (" + DIAGNOSTIC_SETTINGS.join(", ") + "); only the canonical load reports an acceptance]"), async () => { @@ -225,9 +217,8 @@ describe.skipIf(!ENABLED)("link WebSocket transport-only RSS acceptance" expect(Number.isFinite(result.peak) && result.peak >= result.idle).toBe(true); } console.log(JSON.stringify({ acceptance: true, sockets: SOCKETS, websocketSync: websocket.sync, httpSync: http.sync, websocketMinusHttpMiB: (websocket.delta - http.delta) / MiB, budgetMiB: SOCKETS * LINK_WS_LIMITS.socketReservationBytes / MiB })); - // The subtraction compares like with like only when both Homes reported their own stall. Until the HTTP relay can - // (follow-up), the pair is a measurement and this acceptance cannot pass, whatever the difference. - expect({ websocket: websocket.sync, http: http.sync }).toEqual({ websocket: "home-pumps-waiting", http: "home-pumps-waiting" }); + // The subtraction compares like with like only when both Homes reported their own stall. + expect({ websocket: websocket.sync, http: http.sync }).toEqual({ websocket: "home-pumps-waiting", http: "home-relays-waiting" }); expect(websocket.delta - http.delta).toBeLessThanOrEqual(SOCKETS * LINK_WS_LIMITS.socketReservationBytes); }); diff --git a/tests/fixtures/link-ws-rss-home.ts b/tests/fixtures/link-ws-rss-home.ts index 9043309f589..06a6d9089ae 100644 --- a/tests/fixtures/link-ws-rss-home.ts +++ b/tests/fixtures/link-ws-rss-home.ts @@ -4,7 +4,8 @@ * stdin as one JSON line; commands follow, one per line: "gc-rss" (collect, then reset the high-water * mark to the current RSS), "peak" (the high-water mark since then), "heap" (a diagnostic breakdown of what * the process holds now: memoryUsage and the largest JSC heap classes by retained size), "stop". When "stalls" link pumps - * are waiting for a drain at the same time, the fixture prints {"stalled":true} once. + * are waiting for a drain, or relayed HTTP responses for their reader, at the same time, the fixture prints + * {"stalled":true} once per idle reading. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -25,7 +26,7 @@ writeFileSync(join(codexHome, "opencodex-catalog.json"), JSON.stringify({ models const { writeLinkStore } = await import("../../src/link/store"); const { linkStorePath } = await import("../../src/link/paths"); const { saveConfig } = await import("../../src/config"); -const { setLinkWebsocketTransportReadyForTests, setLinkPumpWaitObserverForTests } = await import("../../src/server/index/link-websocket-limits"); +const { setLinkWebsocketTransportReadyForTests, setLinkPumpWaitObserverForTests, setLinkRelayWaitObserverForTests } = await import("../../src/server/index/link-websocket-limits"); // Peak RSS. On Linux the kernel keeps the process high-water mark (VmHWM in /proc/self/status), so // a peak that rises and falls inside one synchronous operation is still counted; writing "5" to @@ -55,11 +56,13 @@ const peakAnswer = (): { rss: number | null; method: string } => { let waiting = 0; // Armed by the idle reading ("gc-rss"), so a warm-up turn whose pump waited for a drain cannot announce the load's stall. let announced = true; -setLinkPumpWaitObserverForTests(isWaiting => { +const observeWait = (isWaiting: boolean): void => { waiting += isWaiting ? 1 : -1; sample(); if (!announced && waiting >= setup.stalls) { announced = true; console.log(JSON.stringify({ stalled: true })); } -}); +}; +setLinkPumpWaitObserverForTests(observeWait); +setLinkRelayWaitObserverForTests(observeWait); writeLinkStore(linkStorePath(), { version: 1, diff --git a/tests/responses/stalled-reader-memory.test.ts b/tests/responses/stalled-reader-memory.test.ts index 542c3071ae0..5e1ef55d30a 100644 --- a/tests/responses/stalled-reader-memory.test.ts +++ b/tests/responses/stalled-reader-memory.test.ts @@ -170,5 +170,3 @@ describe("request copies under a stalled reader (#8601)", () => { } finally { parse.mockRestore(); } }); }); - - diff --git a/tests/routing/combo-stream-preflight.test.ts b/tests/routing/combo-stream-preflight.test.ts index 09d25b0b7bd..568e7634374 100644 --- a/tests/routing/combo-stream-preflight.test.ts +++ b/tests/routing/combo-stream-preflight.test.ts @@ -1653,5 +1653,3 @@ describe("combo preflight replay under a stalled reader (#8601)", () => { expect(buffered.map(chunk => chunk.byteLength)).toEqual([0, 0, 0]); }); }); - - diff --git a/tests/server/link-websocket-holds.test.ts b/tests/server/link-websocket-holds.test.ts index 44e7ab6a56f..f1fbcb11aff 100644 --- a/tests/server/link-websocket-holds.test.ts +++ b/tests/server/link-websocket-holds.test.ts @@ -483,4 +483,3 @@ describe("paced reads on the relay (#8601)", () => { expect(s.ws!.data.linkTurnObserver?.(1).pacedReads).toBe(true); }); }); - diff --git a/tests/server/link-websocket-pump.test.ts b/tests/server/link-websocket-pump.test.ts index e98d43b73ff..6431261a111 100644 --- a/tests/server/link-websocket-pump.test.ts +++ b/tests/server/link-websocket-pump.test.ts @@ -2,7 +2,8 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test"; import type { ServerWebSocket } from "bun"; import { pumpResponsesSseToWebSocket, sendResponseToWebSocket, type WsData } from "../../src/server/ws-bridge"; import { BoundedSseFrameBuffer, MAX_CLIENT_SSE_FRAME_BYTES } from "../../src/server/sse-frame-buffer"; -import { LINK_WS_LIMITS, setLinkPumpTimerForTests } from "../../src/server/index/link-websocket-limits"; +import { LINK_WS_LIMITS, setLinkPumpTimerForTests, setLinkRelayWaitObserverForTests } from "../../src/server/index/link-websocket-limits"; +import { chunkedResponse, relayHarness } from "../helpers/link-relay-harness"; import { createLinkWebsocketGate } from "../../src/server/index/link-websocket"; // Lane T5c: the link-only bounded pump of design 6.2. A link socket waits for Bun's drain after any @@ -306,3 +307,43 @@ describe("T5g-R1: a synthesized JSON response on a link socket ends with its tur }); }); + +describe("the HTTP link relay reports when it waits for its reader (#8600)", () => { + afterEach(() => setLinkRelayWaitObserverForTests(null)); + + test("waiting from each chunk it hands over until its reader asks again, and never after the body ends", async () => { + const events: boolean[] = []; + setLinkRelayWaitObserverForTests(waiting => events.push(waiting)); + const h = relayHarness(); + const nonce = await h.session("lnk_aaaaaaaaaaaaaaaa"); + const response = await h.dispatch(h.request("/v1/responses", { method: "POST", nonce, body: "{}" }), async () => chunkedResponse(["a", "b"])); + const reader = response.body!.getReader(); + expect(events).toEqual([]); + expect((await reader.read()).done).toBe(false); + expect(events).toEqual([true]); + expect((await reader.read()).done).toBe(false); + expect(events).toEqual([true, false, true]); + expect((await reader.read()).done).toBe(true); + expect(events).toEqual([true, false, true, false]); + }); + + test("a cancelled reader ends the wait", async () => { + const events: boolean[] = []; + setLinkRelayWaitObserverForTests(waiting => events.push(waiting)); + const h = relayHarness(); + const nonce = await h.session("lnk_aaaaaaaaaaaaaaaa"); + const response = await h.dispatch(h.request("/v1/responses", { method: "POST", nonce, body: "{}" }), async () => chunkedResponse(["a", "b"])); + const reader = response.body!.getReader(); + await reader.read(); + await reader.cancel(); + expect(events).toEqual([true, false]); + }); + + test("without an observer the relay delivers its body as before", async () => { + const h = relayHarness(); + const nonce = await h.session("lnk_aaaaaaaaaaaaaaaa"); + const response = await h.dispatch(h.request("/v1/responses", { method: "POST", nonce, body: "{}" }), async () => chunkedResponse(["a"])); + expect(await response.text()).toBe("a"); + }); +}); + diff --git a/tests/server/link-websocket-upgrade.test.ts b/tests/server/link-websocket-upgrade.test.ts index 15445d29a95..27173289a7b 100644 --- a/tests/server/link-websocket-upgrade.test.ts +++ b/tests/server/link-websocket-upgrade.test.ts @@ -14,6 +14,7 @@ import { LinkWireClient, frameType, type WireMessage } from "../helpers/link-ws- import { setLinkWebsocketTransportReadyForTests } from "../../src/server/index/link-websocket-limits"; import * as nativeControl from "../../src/server/responses/native-response-control"; import * as workflow from "../../src/server/workflow-refusal"; +import * as requestDecompress from "../../src/server/request-decompress"; const originalMode = nativeControl.nativeResponseControlMode; @@ -426,3 +427,43 @@ describe("link Responses WebSocket switched on", () => { expect(["close", "eof"]).toContain(after.type); }); }); + +describe("a link create reaches the pipeline once (#8600)", () => { + test("the pipeline takes the frame the socket parsed instead of reading it back from a request body; a local socket still reads one", async () => { + const port = await startHome(); + const read = spyOn(requestDecompress, "readJsonRequestBody"); + try { + const wire = await openSocket(port); + expect((await runTurn(wire, create("from the link"))).map(frameType)).toContain("response.completed"); + expect(read).not.toHaveBeenCalled(); + const local = new WebSocket(new URL("/v1/responses", server!.url).href.replace("http:", "ws:")); + await new Promise((resolve, reject) => { local.onopen = () => resolve(); local.onerror = () => reject(new Error("local websocket failed")); }); + const done = new Promise(resolve => { local.onmessage = event => { if (String(event.data).includes("response.completed")) resolve(); }; }); + local.send(JSON.stringify(create("from the local socket"))); + await done; + expect(read).toHaveBeenCalledTimes(1); + local.close(); + } finally { read.mockRestore(); } + // Both turns reached the upstream with their own input. + expect(JSON.stringify(upstreamRequests)).toContain("from the link"); + expect(JSON.stringify(upstreamRequests)).toContain("from the local socket"); + }); + + test("a link create through a combo reaches the upstream as the child the combo built, not as the parent's body", async () => { + const port = await startHome({ combos: { free: { strategy: "failover", targets: [{ provider: "fixture", model: "fixture" }] } } } as Partial); + const wire = await openSocket(port); + expect((await runTurn(wire, { ...create("through the combo"), model: "combo/free" })).map(frameType)).toContain("response.completed"); + expect(upstreamRequests).toHaveLength(1); + expect((JSON.parse(upstreamRequests[0]!.body) as Record).model).toBe("fixture"); + }); + + test("a link create past the configured inbound limit is refused as it was when it was read back", async () => { + const port = await startHome({ maxInboundBodyBytes: 1024 * 1024 }); + const wire = await openSocket(port); + wire.sendJson(create("x".repeat(2 * 1024 * 1024))); + const error = await wire.until(message => frameType(message) === "error"); + const frame = JSON.parse(String(error[error.length - 1]!.data)) as Record; + expect({ status: frame.status, code: (frame.error as Record | undefined)?.code }).toEqual({ status: 413, code: "inbound_body_too_large" }); + expect(upstreamRequests).toHaveLength(0); + }); +});