From 17e055e0e0e52061708852c5e7bfaa01ea329ea0 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:55:10 +0200 Subject: [PATCH 1/2] fix(hosts): bound host downlink backlog and propagate capacity rejection (fixes #364) --- .../specs/2026-10-31-websocket-link-design.md | 3 +- lib/hosts/hub.test.mjs | 85 ++++++++++++++++++- lib/hosts/hub.ts | 18 ++++ lib/hosts/link-protocol.ts | 7 ++ 4 files changed, 111 insertions(+), 2 deletions(-) diff --git a/docs/specs/2026-10-31-websocket-link-design.md b/docs/specs/2026-10-31-websocket-link-design.md index 2d3374d0a..bba15af13 100644 --- a/docs/specs/2026-10-31-websocket-link-design.md +++ b/docs/specs/2026-10-31-websocket-link-design.md @@ -57,7 +57,8 @@ Non-goals: compression (`perMessageDeflate` stays off), an update-only mode for | Uplink text frame | `LINK_LIMITS.uplinkBytes` 16 MiB (UTF-8 bytes) | the daemon's batch cap; the hub closes **1009** above it | | Single message line | `LINK_LIMITS.maxLineBytes` 8 MiB | unchanged (`encodeLine`/`parseLine`); an over-limit stdout line still becomes `resync` | | Binary frame payload | `LINK_LIMITS.blobBytes` 64 MiB + header | daemon refuses a larger result with `413 result_too_large` (unchanged); the hub's `maxPayloadLength` is `blobBytes + 256`, so Bun closes 1009 above it | -| Hub downlink pacing | one sequenced line in Bun's buffer; the rest waits in the outbox | the hub paces from its outbox: it sends unsent sequenced lines in `seq` order until `send` returns `-1` (queued under backpressure), then sends the rest on the socket's `drain`. So a daemon that stops reading (asleep, stopped, on a slow link) is waited for, not closed, and a resend after a redial is paced the same way. The outbox holds the backlog in memory until the daemon acks it. Unsequenced lines (`welcome`, `ping`, `pong`, `ack`) go at once | +| Hub downlink pacing | one sequenced line in Bun's buffer; the rest waits in the outbox | the hub paces from its outbox: it sends unsent sequenced lines in `seq` order until `send` returns `-1` (queued under backpressure), then sends the rest on the socket's `drain`. So a daemon that stops reading (asleep, stopped, on a slow link) is waited for, not closed, and a resend after a redial is paced the same way. The outbox holds the backlog in memory until the daemon acks it, bounded by the downlink backlog cap below. Unsequenced lines (`welcome`, `ping`, `pong`, `ack`) go at once | +| Hub downlink backlog cap | `LINK_LIMITS.downlinkBacklogBytes` 32 MiB of queued plus unacknowledged bytes per link | `sendDown` rejects a `req` or `stdin` command before recording it when it would take the link's queued (`LinkSender.queuedBytes`) plus unacknowledged (`outboxBytes`) total past the cap, with `LinkLimitError`. A host op reaches its caller as **413** `host_request_too_large`; a channel write reaches its callback as **413** `request_too_large`. The rejected command is never queued, never sent later, and leaves no pending op waiting for a timeout. Acks release capacity, so later commands are accepted once the daemon applies what it has; a redial resends the unacked outbox without counting it twice and the cap still applies. Small control messages (`kill`, `interest`, `host_tools`) bypass the cap so liveness and cleanup keep working on a saturated link. This is the total retained-backlog bound; it is distinct from socket pacing (Bun's buffer) and the unacked send window (512 KiB in flight) above | | Hub send buffer | `backpressureLimit` 16 MiB (`LINK_LIMITS.uplinkBytes`), `closeOnBackpressureLimit: true` | a backstop only: with the pacing above, sequenced lines never reach it. Past it Bun closes the socket instead of buffering on; unacked sequenced messages stay in the outbox and go again after the redial, so a dropped frame is never followed by a later `seq` on the same socket | | Daemon send buffer | 2 pieces (512 KiB) of `bufferedAmount`, and `LINK_LIMITS.unackedBytes` (512 KiB) of frames the hub has not answered | v5 (D7): the daemon hands frames to the socket only while both hold; per-channel backlog still capped at 32 MB with `resync` (unchanged) | | Hub unacked window | `LINK_LIMITS.unackedBytes` (512 KiB) of sequenced lines sent and not acked | v5 (D7): on top of the pacing above | diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 4ee5995d9..d57fd2bd0 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -19,7 +19,7 @@ after(() => { }); const hub = await import("./hub.ts"); -const { encodeBlobFrame, LINK_LIMITS, LINK_PROTOCOL_VERSION } = await import("./link-protocol.ts"); +const { encodeBlobFrame, encodeQueued, LINK_LIMITS, LINK_PROTOCOL_VERSION } = await import("./link-protocol.ts"); const { createHost, revokeHost } = await import("./registry.ts"); const { getRpcSession, startRpcSession } = await import("../rpc-manager.ts"); const { linkHost, listedSession, ompChild, until, upgradeSocket } = await import("./link-driver.test-helper.mjs"); @@ -919,6 +919,7 @@ test("capacity accessors do not create links for unknown or never-linked hosts", for (const id of [unknown, host.id]) { assert.equal(hub.getHostCapacity(id), null); assert.equal(hub.getHostLinkProtocol(id), null); + assert.equal(hub.getHostDownlinkBacklog(id), null); assert.equal(globalThis.__ompHostHub.links.has(id), false); } }); @@ -1083,6 +1084,88 @@ test("the hub answers each uplink frame with one ack; an ack line from the daemo await again.down.cancel(); }); +/** Fill `link`'s downlink backlog to exactly LINK_LIMITS.downlinkBacklogBytes with stdin lines. The last lines stay + * queued (the unacked window is full), so each adds exactly its encoded size. */ +async function fillDownlinkBacklog(link) { + const { req, ch, spawning, result, post } = await spawnOverLink(link); + await post([{ type: "res", seq: 1, id: req.id, ok: true, result }]); + const { transport } = await spawning; + const cap = LINK_LIMITS.downlinkBacklogBytes; + const total = () => { + const seen = hub.getHostDownlinkBacklog(link.id); + return seen.queuedBytes + seen.outboxBytes; + }; + const sizeOf = (line) => Buffer.byteLength(encodeQueued({ type: "stdin", ch, line })); + const write = (line) => new Promise((resolve, reject) => transport.write(line, (error) => error ? reject(error) : resolve())); + const big = "x".repeat(1024 * 1024); + const base = sizeOf(""); + // Big lines first, then one line that leaves exactly 128 KiB of room, then the line that fills it. + while (total() + sizeOf(big) < cap - 256 * 1024) await write(big); + const remainder = cap - total(); + assert.ok(remainder > 128 * 1024 + base, `remainder ${remainder} leaves no room for the final line`); + await write("x".repeat(remainder - 128 * 1024 - base)); + await write("x".repeat(128 * 1024 - base)); + assert.equal(total(), cap); + return { ch, transport }; +} + +test("a downlink backlog past the cap rejects the command with 413 and never delivers it", async () => { + const link = await linkedHost("Backlogged"); + const { transport } = await fillDownlinkBacklog(link); + const seen = hub.getHostDownlinkBacklog(link.id); + assert.ok(seen.outboxBytes > 0, "part of the backlog is sent but unacknowledged"); + assert.ok(seen.queuedBytes > 0, "part of the backlog is still queued"); + // One more command: rejected at once, with nothing recorded for it. + const before = hub.getHostDownlinkBacklog(link.id); + const rejected = await new Promise((resolve) => transport.write("rejected\n", (error) => resolve(error))); + assert.ok(rejected instanceof Error && rejected.status === 413 && rejected.code === "request_too_large", `expected a 413 rejection, got ${rejected}`); + assert.deepEqual(hub.getHostDownlinkBacklog(link.id), before); + // Same for a host op: it rejects instead of waiting for its timeout. + await assert.rejects(link.remote.sessionOps.listSessions(), (error) => error.status === 413 && error.code === "host_request_too_large"); + // Acking what the daemon applied releases capacity, so a later command is accepted. + const frames = () => link.down.socket.frames; + const maxSeq = () => Math.max(0, ...frames().map((sent) => JSON.parse(sent).seq ?? 0)); + frame(link.down.socket, `${JSON.stringify({ type: "ack", ack: maxSeq() })}\n`); + await new Promise((resolve, reject) => transport.write("after-ack\n", (error) => error ? reject(error) : resolve())); + // Drain the whole backlog: the rejected line and op must never appear. + for (let i = 0; i < 200; i++) { + const remaining = hub.getHostDownlinkBacklog(link.id); + if (remaining.queuedBytes === 0 && remaining.outboxBytes === 0) break; + frame(link.down.socket, `${JSON.stringify({ type: "ack", ack: maxSeq() })}\n`); + if (i === 199) assert.fail("the backlog did not drain"); + } + const delivered = frames().map((sent) => JSON.parse(sent)); + assert.equal(delivered.some((message) => message.line === "rejected\n"), false, "the rejected stdin line was delivered after capacity freed"); + assert.equal(delivered.some((message) => message.type === "req" && message.op === "listSessions"), false, "the rejected op was sent after capacity freed"); + await link.down.cancel(); +}); + +test("a redial neither double-counts the downlink backlog nor bypasses the cap", async () => { + const link = await linkedHost("Redialled backlog"); + await fillDownlinkBacklog(link); + const before = hub.getHostDownlinkBacklog(link.id); + await link.down.cancel(); + // The daemon applied nothing (ack 0): its redial resends the unacked outbox without counting it twice. + const again = await openLink(link.token, { ack: 0 }); + assert.deepEqual(hub.getHostDownlinkBacklog(link.id), before, "resending the unacked outbox must not count its bytes twice"); + // The redial closed this test's transport (the child exited with the socket), so the cap is probed with a host op. + await assert.rejects(link.remote.sessionOps.listSessions(), (error) => error.status === 413 && error.code === "host_request_too_large"); + await again.down.cancel(); +}); + +test("the downlink cap is per link: a saturated host does not block another", async () => { + const full = await linkedHost("Full"); + await fillDownlinkBacklog(full); + const other = await linkedHost("Other"); + const { req, ch, spawning, result, post } = await spawnOverLink(other); + await post([{ type: "res", seq: 1, id: req.id, ok: true, result }]); + const { transport } = await spawning; + await new Promise((resolve, reject) => transport.write("other\n", (error) => error ? reject(error) : resolve())); + assert.deepEqual(await other.down.nextReal(), { type: "stdin", seq: 2, ch, line: "other\n" }); + await full.down.cancel(); + await other.down.cancel(); +}); + test("a restarted daemon (hello ack 0) starts a fresh uplink sequence", async () => { const link = await linkedHost("Restarted"); const first = link.remote.sessionOps.listSessions(); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 8b6bb5592..270be3cc6 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -411,6 +411,16 @@ function sendDown(link: Link, body: Unsequenced, key: string): void )) throw new HostOpError(426, "host_upgrade_required", "Update this host before using its application protocol"); const line = encodeQueued(body); const size = Buffer.byteLength(line); + // The downlink backlog is bounded (spec D6): a command that would take the + // queued plus unacknowledged bytes past downlinkBacklogBytes is rejected + // before anything is recorded, so its caller hears it at once instead of + // at the op timeout, and it is never delivered later. Control messages + // (kill, interest, host_tools) are small and keep liveness and cleanup + // working on a saturated link; they bypass the cap. + if ((body.type === "req" || body.type === "stdin") + && link.outboxBytes + link.sender.queuedBytes + size > LINK_LIMITS.downlinkBacklogBytes) { + throw new LinkLimitError(`downlink backlog exceeds ${LINK_LIMITS.downlinkBacklogBytes} bytes`); + } // Ahead of it: what is queued or unacked on this link (counters, no scan); fairness may send it before some of that. const sample = { at: Date.now(), t: performance.now(), bytes: size, bytesAhead: link.outboxBytes + link.sender.queuedBytes, session: sessionOf(link, body) }; link.sender.push(key, { line, size, sample }); @@ -2122,6 +2132,14 @@ export function getHostCapacity(hostId: string): CapacitySnapshot | null { return hub().links.get(hostId)?.capacity ?? null; } +/** Queued plus unacknowledged downlink bytes on `hostId`'s link, or null + * when it has no link. Tests use it to place a backlog exactly on the cap. */ +export function getHostDownlinkBacklog(hostId: string): { queuedBytes: number; outboxBytes: number } | null { + const link = hub().links.get(hostId); + if (!link) return null; + return { queuedBytes: link.sender.queuedBytes, outboxBytes: link.outboxBytes }; +} + export function getHostLinkProtocol(hostId: string): number | null { return hub().links.get(hostId)?.hostVersion ?? null; } diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index dd59a01ac..4add19c83 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -47,6 +47,13 @@ export const LINK_LIMITS = { * link's server side uses it as a cap: its window follows the link below it (lib/browser-link.ts `measure`). */ unackedBytes: 2 * 256 * 1024, uplinkBytes: 16 * 1024 * 1024, + /** Per-link bound on queued plus unacknowledged downlink bytes (spec D6): + * a command that would take the backlog past this is rejected before it is + * recorded, so a slow daemon cannot grow the hub's retained backlog + * without bound. 4x maxLineBytes, so a max-size line is always admittable + * on an empty link; the same order as channelBufferBytes and the daemon's + * per-channel 32 MB resync cap. */ + downlinkBacklogBytes: 32 * 1024 * 1024, blobBytes: 64 * 1024 * 1024, inlineResultBytes: 1024 * 1024, opTimeoutMs: 30_000, From 9dd977e2e72458f045aed718cdbd06faa4f555e0 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:26:28 +0200 Subject: [PATCH 2/2] Fix pacing integration test for the 32 MiB downlink backlog cap (PR #563) The test flooded 48 MiB of stdin while the daemon was stopped, which the new cap correctly rejects past 32 MiB. Send 24 MiB instead: still past the 16 MiB backpressure limit so pacing is exercised, under the cap so every line is admitted. Also assert a further 9 MiB line is rejected at once with 413 and never reaches omp. --- lib/hosts/link-integration.test.mjs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 37f4db113..41eb6a07c 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -590,16 +590,21 @@ test("a request omp opens while the web server stops reaches the next server onc assert.equal(results().length, 1, "one agent tool result"); }); -test("a daemon that stops reading is paced, not closed: the hub sends its outbox as the socket drains, and each line reaches omp once", { skip: process.platform === "win32" && "SIGSTOP is POSIX-only" }, async () => { +test("a daemon that stops reading is paced, not closed: the hub sends its outbox as the socket drains, each line reaches omp once, and a line past the cap is rejected, not queued", { skip: process.platform === "win32" && "SIGSTOP is POSIX-only" }, async () => { const { session } = await startRpcSession("", "", projectDir, undefined, false, null, undefined, hub.getHost(hostId)); assert.equal(sockets.size, 1); const [socket] = sockets; - // 48 MiB of stdin: three times the hub's 16 MiB backpressure limit. + // 24 MiB of stdin: past the hub's 16 MiB backpressure limit, so pacing is + // exercised, but under the 32 MiB downlink backlog cap, so every line is admitted. const count = 8; - const pad = "x".repeat(6 * 1024 * 1024); + const pad = "x".repeat(3 * 1024 * 1024); daemon.kill("SIGSTOP"); try { for (let n = 1; n <= count; n++) session.proc.transport.write(`${JSON.stringify({ t: "cmd", id: n, op: "pad", args: { n, pad } })}\n`, assert.ifError); + // One more line would take the backlog past the 32 MiB cap (24 + 9 MiB): + // it is rejected at once with 413 and never reaches omp. + const over = await new Promise((resolve) => session.proc.transport.write(`${JSON.stringify({ t: "cmd", id: count + 1, op: "pad", args: { n: count + 1, pad: "x".repeat(9 * 1024 * 1024) } })}\n`, (error) => resolve(error))); + assert.ok(over instanceof Error && over.status === 413 && over.code === "request_too_large", `expected a 413 rejection, got ${over}`); // Room for a close at the limit to show up. await sleep(300); assert.deepEqual([...sockets], [socket], "the socket stays open while the daemon reads nothing");