diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index e60c8a4c9c..d3d9aad387 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -125,6 +125,7 @@ Legend: โœ… fully automated ยท ๐Ÿ”ถ partially automated ยท โ›” manual-only (no s | [navigation](../suites/navigation.md) | `NAV-B12` (the logic half): a read TanStack Query cancels when a navigation unmounts its page rejects as an `AbortError` that never flags the backend unreachable, so the offline overlay stays down; an event whose thrown value is an `AbortError` โ€” also in the SDK's `AbortError: โ€ฆ` and stringified `Error: AbortError: โ€ฆ` shapes โ€” is dropped before it is sent, while a failure merely caused by one is kept | ๐Ÿ”ถ unit + component | `app/lib/backend/api-client.test.ts`, `app/components/connectivity/online-gate.test.tsx` (a real `QueryClient` read cancelled by an unmount, under the real connection state), `app/lib/sentry-normalize.test.ts`, `lib/utils/abort-error.test.ts`; the throttled real-browser round with a live DSN stays manual | | [navigation](../suites/navigation.md) | `NAV-B14`: the error displays' **contact support** link follows `TALE_CONTACT_SUPPORT_URL` from the environment through `window.__ENV__` and the app-root `SupportUrlProvider` to the rendered link, which opens in a new tab with the organization as `organizationId` (replacing one the URL carries). The web tier hands the page the value only as an absolute http(s) URL, verbatim and script-safe, and leaves anything else out with a warning, so the link keeps `https://tale.dev/contact`; a display's own `supportUrl` wins over the provider | โœ… e2e + component + server | `tests/e2e/specs/navigation.spec.ts` (*the contact-support link opens the operator's page*), `packages/ui/src/components/error-boundaries/core/support-url.test.tsx`, `packages/ui/src/components/error-boundaries/displays/error-display-compact.test.tsx`, `packages/ui/src/components/error-boundaries/displays/global-error-display.test.tsx`, `lib/contact-support-url.test.ts`, `lib/utils/inline-script.test.ts`, `vite-plugins/inject-env.test.ts`, `server.test.ts` | | [settings](../suites/settings.md) | Foreground egress proxy boots, stops gracefully and restarts with read-only `/tmp` | โœ… automated | `tests/integration/container-smoke-test.ts` and `compose.test.yml` (real proxy health, refused temporary-file creation, shutdown exit/log and same-container restart) | +| [settings](../suites/settings.md) | Sandbox memory lifetime: completed commands release request/consumer data while a sibling remains active; held-open stdin refuses whole lines above its 8 MiB pending queue and accepts again after draining; HTTP intake and device tunnel completion detach their listeners | ๐Ÿ”ถ unit + real processes + HTTP | `services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts` (bundled manager under Node), `exec-manager.test.ts`, `http-body.test.ts`, `main.test.ts`; `services/sandbox/src/devices/tunnel.test.ts`; production workload memory profiling remains operational | | [settings](../suites/settings.md) | The egress proxy serves `SANDBOX_EGRESS_MAX_CLIENTS` connections at once (2000 by default) for the whole fleet, keeps its 600 s tunnel timeout, refuses to start on a value that is no whole number above 0, raises its soft open-file limit to two descriptors per connection as far as the hard limit allows (a Kubernetes Pod sets none) and leaves a limit that already holds them alone, and warns when even the hard limit cannot hold them; both compose pipelines pass the same default and size the container's pids and open-file limits for it | โœ… automated | `services/sandbox/src/egress-proxy-config.test.ts` (the real entrypoint and template), `tools/cli/src/lib/compose/services/compose-parity.test.ts` (`egress connection capacity parity`) | | [settings](../suites/settings.md) | Explicit native configuration recovery retains the superseded plan and verified writes; rejects unrelated edits, omitted resources and wrong organizations; replays interrupted replacement through managed provisioning | โœ… automated | `tools/cli/src/lib/config/platform-apply.test.ts` | | [settings](../suites/settings.md) | Managed Compose failures identify validation or startup and preserve pending runtime receipts without exposing private inputs | โœ… automated | `tools/cli/src/lib/deployment/runtime-command.test.ts` (exit/exception paths, safe fallback and failure propagation through the real runtime orchestration with injected Docker responses) | diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 8ac5d4d622..461eded4d2 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -33,6 +33,12 @@ which the history present at attachment has been delivered. Session idle and TTL cleanup atomically checks the current work generation and activity clock before freezing compute; see the [session contract](../sandbox/docs/sessions.md). +Completed commands release their request and consumer data even while another +command keeps the session active. Process cleanup retains only the ownership +and liveness data it still needs. Held-open stdin has an 8 MiB pending-write +ceiling: a nonreading command refuses further lines with `WRITE_FAILED` until +its pipe drains, without partially accepting the refused line. + File staging streams each URL into a temporary file beside its destination and replaces the destination only after a complete, bounded download. Cancelling or failing a download preserves the previous file. At most two stage requests diff --git a/services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts b/services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts new file mode 100644 index 0000000000..632517fee3 --- /dev/null +++ b/services/sandbox-runtime/daemon/src/exec-manager.memory.test.ts @@ -0,0 +1,234 @@ +// Production Node owns child-process buffers and closure lifetimes. Run the +// bundled manager there so Bun's different stream implementation cannot hide +// retained requests or an unbounded held-stdin queue. +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; + +const roots: string[] = []; +afterAll(() => { + for (const root of roots) rmSync(root, { recursive: true, force: true }); +}); + +async function runInNode(body: string, withHttpServer = false): Promise { + const root = realpathSync(mkdtempSync(`${tmpdir()}/runnerd-memory-`)); + roots.push(root); + writeFileSync( + `${root}/entry.ts`, + `import assert from 'node:assert/strict'; +import { writeFileSync } from 'node:fs'; +import { ExecManager } from ${JSON.stringify(`${import.meta.dir}/exec-manager.ts`)}; +import { EnvStore } from ${JSON.stringify(`${import.meta.dir}/env-store.ts`)}; +import { RUNNERD_MAX_REQUEST_BODY_BYTES } from ${JSON.stringify(`${import.meta.dir}/protocol.ts`)}; +process.env.TALE_WORKSPACE_ROOT = ${JSON.stringify(root)}; +const root = ${JSON.stringify(root)}; +const base = { timeoutMs: 30000, stdoutMaxBytes: 0, stderrMaxBytes: 0 }; +const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); +${body}`, + ); + const built = await Bun.build({ + // Keep main separate so its entry-file check does not listen on import. + entrypoints: [ + `${root}/entry.ts`, + ...(withHttpServer ? [`${import.meta.dir}/main.ts`] : []), + ], + outdir: `${root}/dist`, + target: 'node', + naming: '[name].js', + }); + expect(built.success).toBe(true); + const result = spawnSync('node', ['--expose-gc', `${root}/dist/entry.js`], { + encoding: 'utf8', + timeout: 15_000, + }); + expect({ + status: result.status, + error: result.error, + stderr: result.stderr, + }).toEqual({ + status: 0, + error: undefined, + stderr: '', + }); +} + +describe('ExecManager memory under Node', () => { + for (const consumerMode of ['exec', 'attach'] as const) { + test(`a disconnected HTTP ${consumerMode} consumer is collected while its exec keeps running`, async () => { + await runInNode( + String.raw` +const consumerMode = ${JSON.stringify(consumerMode)}; +process.env.TALE_RUNNERD_TOKEN = ''; +const { request } = await import('node:http'); +const mainUrl = new URL('./main.js', import.meta.url); +const { server } = await import(mainUrl.href); +const refs = []; +server.prependListener('request', (req, res) => { + if (refs.length === 0 && (consumerMode === 'exec' ? req.method === 'POST' && req.url === '/execs' : req.url === '/execs/http-consumer/attach')) { + refs.push(new WeakRef(req), new WeakRef(res)); + // Keep replay waiting on its real Node drain/abort promise until the + // client disconnects, even when loopback would otherwise drain at once. + if (consumerMode === 'attach') Object.defineProperty(res, 'writableNeedDrain', { value: true }); + } +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const url = 'http://127.0.0.1:' + server.address().port; +const execId = 'http-consumer'; +async function disconnect() { + await new Promise((resolve, reject) => { + const payload = JSON.stringify({ + ...base, execId, + command: [process.execPath, '-e', "process.stdin.resume(); process.stdin.on('end', () => { process.stdout.write('ready\\n'); setTimeout(() => {}, 30000); })"], + stdinBase64: Buffer.alloc(1024 * 1024, 120).toString('base64'), + }); + const client = request(url + '/execs', { + method: 'POST', agent: false, + headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) }, + }); + client.once('error', reject); + client.once('response', response => { + let received = ''; + response.setEncoding('utf8'); + response.on('data', chunk => { + received += chunk; + if (!received.includes('"t":"stdout"')) return; + response.removeAllListeners('data'); + response.destroy(); + client.destroy(); + resolve(); + }); + }); + client.end(payload); + }); +} +async function disconnectReplay() { + await new Promise((resolve, reject) => { + const client = request(url + '/execs/' + execId + '/attach', { agent: false }); + client.once('error', reject); + client.once('response', response => { + response.once('data', () => { + assert(refs[1].deref()?.listenerCount('drain') > 0, 'replay must be waiting for drain before disconnect'); + response.destroy(); + client.destroy(); + resolve(); + }); + }); + client.end(); + }); +} +const status = async () => (await fetch(url + '/execs/' + execId)).json(); +try { + await disconnect(); + if (consumerMode === 'attach') await disconnectReplay(); + assert.equal(refs.length, 2); + let retained = refs.length; + for (let round = 0; round < 30; round++) { + // A dereference roots its target until this job ends: await BEFORE GC. + await wait(10); + global.gc(); + retained = refs.filter(ref => ref.deref() !== undefined).length; + if (retained === 0) break; + } + assert.equal(retained, 0, 'detached request/response must not survive through the abort reason stack'); + assert.equal((await status()).state, 'running'); + const health = await (await fetch(url + '/healthz')).json(); + assert.equal(health.activity.activeOperations, 0); + // Only the first attach is stalled; the next consumer must replay normally. + const response = await fetch(url + '/execs/' + execId + '/attach'); + assert.equal(response.status, 200); + const output = response.text(); + const cancellation = await (await fetch(url + '/execs/' + execId + '/cancel', { method: 'POST' })).json(); + assert.equal(cancellation.killed, true); + const events = (await output).trim().split('\n').map(line => JSON.parse(line)); + assert(events.some(event => event.t === 'stdout' && Buffer.from(event.b64, 'base64').toString().includes('ready'))); + assert(events.some(event => event.t === 'exit' && event.cancelled)); + assert.equal((await status()).state, 'exited'); +} finally { + await fetch(url + '/execs/' + execId + '/cancel', { method: 'POST' }).then(response => response.json()); + server.closeAllConnections(); + await new Promise(resolve => server.close(resolve)); +} +`, + true, + ); + }, 20_000); + } + + test('completed requests and consumers are released while sibling and shim pipes remain live', async () => { + await runInNode(String.raw` +const shim = root + '/shim'; +writeFileSync(shim, '#!/bin/sh\nshift\nprintf "pid %s\\n" "$$" >&3\n"$@"\ncode=$?\nprintf "exit %s\\n" "$code" >&3\nif [ "$TALE_EXEC_ID" = background ]; then printf partial >&3; sleep 30; fi\nexit "$code"\n', { mode: 0o755 }); +const manager = new ExecManager(new EnvStore(), () => {}, undefined, {}, { execShim: shim }); +const running = manager.run({ ...base, execId: 'sibling', command: ['sleep', '30'] }, () => {}); +const refs = []; +let shimPid; +async function complete(execId) { + const request = { ...base, execId, command: ['/bin/sh', '-c', 'cat >/dev/null; echo "$PPID"'], stdinBase64: Buffer.alloc(1024 * 1024, 120).toString('base64') }; + const emit = event => { + if (execId === 'background' && event.t === 'stdout') shimPid = Number(Buffer.from(event.b64, 'base64').toString().trim()); + }; + refs.push(new WeakRef(request), new WeakRef(emit)); + await manager.run(request, emit); +} +try { + // Exceed the recent replay window; the completed shim targets stay deferred. + for (let i = 0; i < 20; i++) await complete('done-' + i); + await complete('background'); + assert.equal(manager.liveCount(), 1); + assert.equal(manager.leftoverCount(), 21); + assert.equal(manager.canAttach('done-0'), false); + process.kill(shimPid, 0); + let retained = refs.length; + for (let i = 0; i < 20; i++) { + await wait(10); + global.gc(); + retained = refs.filter(ref => ref.deref() !== undefined).length; + if (retained === 0) break; + } + assert.equal(retained, 0, 'completed requests/consumers must not be retained by leftovers or open pipes'); +} finally { + if (shimPid > 1) process.kill(-shimPid, 'SIGKILL'); + manager.cancel('sibling'); + await running; + manager[Symbol.dispose](); +} +`); + }, 20_000); + + test('held stdin refuses excess input before queuing it and accepts again after draining', async () => { + await runInNode(String.raw` +const manager = new ExecManager(new EnvStore(), () => {}); +const ready = root + '/ready'; +let outputBytes = 0; +const running = manager.run({ ...base, execId: 'input', stdinMode: 'hold', command: ['/bin/sh', '-c', 'while [ ! -f "$1" ]; do sleep 0.01; done; exec cat', 'sh', ready] }, event => { + if (event.t === 'stdout') outputBytes += Buffer.from(event.b64, 'base64').length; +}); +try { + const line = JSON.stringify({ message: 'x'.repeat(60000) }) + '\n'; + const b64 = Buffer.from(line).toString('base64'); + let accepted = 0; + for (let i = 0; i < 1000; i++) { + const response = manager.writeStdin('input', { b64 }); + if (response.ok) accepted++; + else assert.equal(response.reason, 'WRITE_FAILED'); + } + assert(accepted > 0); + assert(accepted <= Math.ceil(RUNNERD_MAX_REQUEST_BODY_BYTES / Buffer.byteLength(line)) + 1, 'stdin accepted an unbounded queue'); + assert.deepEqual(manager.writeStdin('input', { b64, eof: true }), { ok: false, reason: 'WRITE_FAILED' }); + writeFileSync(ready, 'ready'); + const expected = accepted * Buffer.byteLength(line); + for (let i = 0; i < 500 && outputBytes !== expected; i++) await wait(10); + assert.equal(outputBytes, expected, 'refused bytes must not enter the pipe'); + const tail = Buffer.from('{"tail":true}\n'); + assert.deepEqual(manager.writeStdin('input', { b64: tail.toString('base64'), eof: true }), { ok: true }); + await running; + assert.equal(outputBytes, expected + tail.length); +} finally { + manager.cancel('input'); + await running; + manager[Symbol.dispose](); +} +`); + }, 20_000); +}); diff --git a/services/sandbox-runtime/daemon/src/exec-manager.test.ts b/services/sandbox-runtime/daemon/src/exec-manager.test.ts index 6d58eda749..37b351db08 100644 --- a/services/sandbox-runtime/daemon/src/exec-manager.test.ts +++ b/services/sandbox-runtime/daemon/src/exec-manager.test.ts @@ -1043,6 +1043,61 @@ describe('ExecManager', () => { } }, 30_000); + test('the primary consumer detaches without stopping the exec or its other subscribers', async () => { + using mgr = new ExecManager(new EnvStore(), () => {}); + const primary = collect(); + const controller = new AbortController(); + const done = mgr.run( + { + ...base, + execId: 'primary-drop', + command: ['cat'], + cwd: ROOT, + stdinMode: 'hold', + }, + primary.emit, + controller.signal, + ); + const follower = collect(); + const attached = mgr.attach('primary-drop', follower.emit); + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1); + controller.abort(); + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0); + const before = primary.events.length; + expect(mgr.status('primary-drop')?.state).toBe('running'); + expect( + mgr.writeStdin('primary-drop', { + b64: Buffer.from('{"after":"disconnect"}\n').toString('base64'), + eof: true, + }), + ).toEqual({ ok: true }); + await done; + await attached; + expect(primary.events).toHaveLength(before); + expect(decode(follower.events, 'stdout')).toBe('{"after":"disconnect"}\n'); + expect(follower.events.at(-1)?.t).toBe('exit'); + const replay = collect(); + await mgr.attach('primary-drop', replay.emit); + // The journal's catch-up marker records a different boundary for an + // attach during execution versus one after exit. Recorded events match. + expect(replay.events.filter((event) => event.seq !== undefined)).toEqual( + follower.events.filter((event) => event.seq !== undefined), + ); + }); + + test('primary consumer abort listeners are removed on exit and spawn failure', async () => { + using mgr = new ExecManager(new EnvStore(), () => {}); + for (const command of [['true'], [`${ROOT}/missing-command`]]) { + const controller = new AbortController(); + await mgr.run( + { ...base, execId: 'primary-cleanup', command, cwd: ROOT }, + () => {}, + controller.signal, + ); + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0); + } + }); + test('a consumer that goes away stops following and settles its attach at once', async () => { using mgr = new ExecManager(new EnvStore(), () => {}); const { emit } = collect(); diff --git a/services/sandbox-runtime/daemon/src/exec-manager.ts b/services/sandbox-runtime/daemon/src/exec-manager.ts index ec5b926138..d566124dc6 100644 --- a/services/sandbox-runtime/daemon/src/exec-manager.ts +++ b/services/sandbox-runtime/daemon/src/exec-manager.ts @@ -34,6 +34,7 @@ import { import { ID_ALPHABET_RE, RUNNERD_RING_BUFFER_BYTES, + RUNNERD_MAX_REQUEST_BODY_BYTES, RUNNERD_STDIN_MAX_BYTES, WORKSPACE_ROOT, type RunnerdExecEvent, @@ -60,6 +61,7 @@ const LEFTOVER_PRUNE_AT = 256; const HOLD_MAX_MS = 10 * 60_000; type ExecSubscriber = (event: RunnerdExecEvent) => void | Promise; +const discardEvent: ExecSubscriber = () => {}; /** A reaping target, with whether its leader is still running: while it is, * its pid โ€” the group's number โ€” cannot have been reused, so the delayed @@ -114,14 +116,13 @@ interface LiveExec { * when the daemon goes down. Once per exec. */ terminate: () => void; terminated: boolean; - /** The child itself exited (its 'exit' fired). */ - leaderExited: boolean; + /** Only these small liveness flags outlive the exec while a delayed reap + * or a deferred descendant waits. Never capture the full record there: + * it owns replay data and callbacks into the child and HTTP consumer. */ + processState: { leaderExited: boolean; rootExited: boolean }; /** The exec's subreaper shim, when it runs under one: every process it * started is the shim's descendant. */ rootPid: number | undefined; - /** The shim exited: no descendant of it is left, and its pid may name - * another process now. */ - rootExited: boolean; /** The shim has yet to name the command's group on its status pipe. */ groupPending: boolean; /** What waits for the shim to name the command's group: a cancel that @@ -306,6 +307,7 @@ export class ExecManager { async run( req: RunnerdExecRequest, emit: (event: RunnerdExecEvent) => void, + consumerSignal?: AbortSignal, ): Promise { if (this.disposed) { emit({ @@ -315,12 +317,16 @@ export class ExecManager { }); return; } - if (!ID_ALPHABET_RE.test(req.execId)) { + // Child callbacks outlive the command when a background descendant holds + // its output pipe. Capture only their small inputs, not the initial stdin + // or environment carried by the request. + const { execId, stdoutMaxBytes, stderrMaxBytes } = req; + if (!ID_ALPHABET_RE.test(execId)) { emit({ t: 'fail', code: 'BAD_REQUEST', message: 'invalid execId' }); return; } - if (this.live.has(req.execId)) { - emit({ t: 'fail', code: 'DUPLICATE_EXEC', message: req.execId }); + if (this.live.has(execId)) { + emit({ t: 'fail', code: 'DUPLICATE_EXEC', message: execId }); return; } // Capture into consts so the type narrows without re-reading req.* (which @@ -351,7 +357,7 @@ export class ExecManager { const env: NodeJS.ProcessEnv = { ...process.env, ...this.envStore.resolve(req.env), - [EXEC_TAG_ENV]: req.execId, + [EXEC_TAG_ENV]: execId, }; const cmd = hasShell ? 'bash' : (command?.[0] ?? ''); @@ -423,7 +429,7 @@ export class ExecManager { // Under the shim the group is the command's, named on the status pipe. groupId: shim !== null ? undefined : child.pid, rootPid: shim !== null ? child.pid : undefined, - rootExited: false, + processState: { leaderExited: false, rootExited: false }, groupPending: shim !== null, awaitingGroup: [], exitCode: null, @@ -436,18 +442,25 @@ export class ExecManager { timedOut: false, stdin: null, terminated: false, - leaderExited: false, handedOver: false, deferred: null, terminate: () => { if (record.terminated) return; record.terminated = true; this.withGroup(record, () => { - void this.reap([this.liveTarget(req.execId, record)]); + void this.reap([this.liveTarget(execId, record)]); }); }, }; - this.live.set(req.execId, record); + this.live.set(execId, record); + + const detach = () => { + consumerSignal?.removeEventListener('abort', detach); + consumerSignal = undefined; + emit = discardEvent; + }; + if (consumerSignal?.aborted) detach(); + else consumerSignal?.addEventListener('abort', detach, { once: true }); const ringEmit = (event: RunnerdExecEvent, persist = true) => { // Stamp a monotonic seq so a reconnecting /attach?sinceSeq= can replay @@ -476,7 +489,7 @@ export class ExecManager { } }; - ringEmit({ t: 'start', execId: req.execId, startedAtMs }); + ringEmit({ t: 'start', execId, startedAtMs }); if (req.stdinMode === 'hold') { // Held-open stdin: the initial payload is written but NOT ended; later @@ -527,16 +540,16 @@ export class ExecManager { // handling below). Keeps the start..stdout..exit order the platform // adapters depend on and never mutates the already-retained ring. if (settled) return; - // stdoutMaxBytes <= 0 โ‡’ UNLIMITED: never truncate (the ring + per-consumer - // buffer ceiling bound memory). Long-lived streaming execs pass 0 so their - // live output is never silently cut off mid-run. - if (req.stdoutMaxBytes > 0) { - const remaining = req.stdoutMaxBytes - stdoutBytes; + // stdoutMaxBytes <= 0 disables truncation. The ring and consumer queues + // bound memory; the journal's storage budget fails explicitly instead + // of silently cutting off a long-lived command's output. + if (stdoutMaxBytes > 0) { + const remaining = stdoutMaxBytes - stdoutBytes; if (remaining <= 0) { if (!stdoutTruncLogged) { stdoutTruncLogged = true; console.warn( - `[runnerd] exec ${req.execId} stdout hit cap ${req.stdoutMaxBytes}B โ€” further stdout dropped (truncated)`, + `[runnerd] exec ${execId} stdout hit cap ${stdoutMaxBytes}B โ€” further stdout dropped (truncated)`, ); } stdoutTrunc = true; @@ -559,13 +572,13 @@ export class ExecManager { }); child.stderr.on('data', (chunk: Buffer) => { if (settled) return; - if (req.stderrMaxBytes > 0) { - const remaining = req.stderrMaxBytes - stderrBytes; + if (stderrMaxBytes > 0) { + const remaining = stderrMaxBytes - stderrBytes; if (remaining <= 0) { if (!stderrTruncLogged) { stderrTruncLogged = true; console.warn( - `[runnerd] exec ${req.execId} stderr hit cap ${req.stderrMaxBytes}B โ€” further stderr dropped (truncated)`, + `[runnerd] exec ${execId} stderr hit cap ${stderrMaxBytes}B โ€” further stderr dropped (truncated)`, ); } stderrTrunc = true; @@ -653,8 +666,13 @@ export class ExecManager { journalFailed ? { ...terminal, exitCode: -1 } : terminal, false, ); - this.dropLive(req.execId); - this.retainRecent(req.execId, record.ring, journal, record.exitCode); + this.dropLive(execId); + this.retainRecent(execId, record.ring, journal, record.exitCode); + // Deferred descendants may keep these pipe callbacks alive after the + // recent diagnostic history is evicted. Transfer its sole ownership. + record.ring = []; + record.ringBytes = 0; + detach(); resolve(); }; // The command could not be executed: nothing of it is left to end. @@ -663,6 +681,8 @@ export class ExecManager { if (settled) return; settled = true; couldNotRun = true; + record.stdin = null; + child.stdin.destroy(); if (record.timer) clearTimeout(record.timer); if (drainTimer) clearTimeout(drainTimer); ringEmit({ @@ -670,8 +690,11 @@ export class ExecManager { code: 'BAD_REQUEST', message: `spawn failed: ${message}`, }); - this.dropLive(req.execId); - this.retainRecent(req.execId, record.ring, journal, null); + this.dropLive(execId); + this.retainRecent(execId, record.ring, journal, null); + record.ring = []; + record.ringBytes = 0; + detach(); resolve(); }; child.on('error', (err) => { @@ -687,7 +710,11 @@ export class ExecManager { // 128 + signal number is the conventional shell exit for a signal. exitCode = code ?? (signal ? 128 + (SIGNAL_NUMBERS[signal] ?? 15) : -1); exited = true; - record.leaderExited = true; + record.processState.leaderExited = true; + // No later steer can reach the finished command. A shim or descendant + // may still hold fd 0 open, so release any queued input explicitly. + record.stdin = null; + child.stdin.destroy(); // The exec is over: whatever it left running (a `cmd &`, a `nohup` // worker, a browser) ends with it instead of holding memory and pids // in a session that reads idle โ€” at once when no other exec of the @@ -701,13 +728,11 @@ export class ExecManager { if (!record.terminated) { record.terminated = true; const self: Reaping = { - execId: req.execId, + execId, groupId: record.groupId, ...this.rootOf(record), }; - const othersLive = [...this.live.keys()].some( - (id) => id !== req.execId, - ); + const othersLive = [...this.live.keys()].some((id) => id !== execId); this.liftHolds(record.ordinal); if (othersLive) { // Under the shim its descendants are the proof; without it, a @@ -715,7 +740,7 @@ export class ExecManager { const waiting: Leftover = { ...self, ...(record.rootPid === undefined - ? { members: this.recordGroup(req.execId, record.groupId) } + ? { members: this.recordGroup(execId, record.groupId) } : {}), }; record.deferred = waiting; @@ -799,7 +824,7 @@ export class ExecManager { } child.on('exit', (code, signal) => { // The shim waits until nothing it adopted is left. - record.rootExited = true; + record.processState.rootExited = true; shimExit = { code, signal }; shimOver(); }); @@ -875,7 +900,8 @@ export class ExecManager { held.groupId = group; signalGroup(group, 'SIGTERM', this.reaper); setTimeout(() => { - if (!rec.leaderExited) signalGroup(group, 'SIGKILL', this.reaper); + if (!rec.processState.leaderExited) + signalGroup(group, 'SIGKILL', this.reaper); }, SIGKILL_GRACE_MS).unref(); }); } @@ -932,11 +958,12 @@ export class ExecManager { /** A live exec as a reaping target: its group is certainly its own. */ private liveTarget(execId: string, rec: LiveExec): Reaping { + const { processState } = rec; return { execId, groupId: rec.groupId, groupKnown: true, - leaderRunning: () => !rec.leaderExited, + leaderRunning: () => !processState.leaderExited, ...this.rootOf(rec), }; } @@ -944,7 +971,8 @@ export class ExecManager { /** The exec's subreaper shim as a reaping root, while it runs. */ private rootOf(rec: LiveExec): Pick { if (rec.rootPid === undefined) return {}; - return { rootPid: rec.rootPid, rootAlive: () => !rec.rootExited }; + const { processState } = rec; + return { rootPid: rec.rootPid, rootAlive: () => !processState.rootExited }; } /** The daemon is going down: every live exec, and what exited execs left @@ -1135,6 +1163,16 @@ export class ExecManager { if (req.b64 !== undefined && req.b64 !== '') { buf = Buffer.from(req.b64, 'base64'); if (!isSingleNdjsonLine(buf)) return { ok: false, reason: 'BAD_LINE' }; + // A held-open pipe can stop draining for an entire turn. Bound all + // queued lines together, not just each request: write(false) still + // enqueues its bytes, so refuse BEFORE write and preserve EOF on refusal. + // The existing body budget also admits the exec's initial stdin payload. + if ( + rec.stdin.writableLength + buf.byteLength > + RUNNERD_MAX_REQUEST_BODY_BYTES + ) { + return { ok: false, reason: 'WRITE_FAILED' }; + } } try { if (buf) rec.stdin.write(buf); diff --git a/services/sandbox-runtime/daemon/src/http-body.test.ts b/services/sandbox-runtime/daemon/src/http-body.test.ts index a291bdffa0..59047b57a3 100644 --- a/services/sandbox-runtime/daemon/src/http-body.test.ts +++ b/services/sandbox-runtime/daemon/src/http-body.test.ts @@ -5,8 +5,8 @@ // shared protocol constant and an oversize body is its own 413 class. import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import { createServer, type Server } from 'node:http'; -import { connect } from 'node:net'; +import { createServer, IncomingMessage, type Server } from 'node:http'; +import { connect, Socket } from 'node:net'; import { readJsonBody } from './http-body.ts'; import { RUNNERD_MAX_REQUEST_BODY_BYTES } from './protocol.ts'; @@ -38,6 +38,41 @@ afterAll(async () => { }); describe('readJsonBody', () => { + test.each(['valid', 'malformed', 'oversize', 'error'])( + 'releases body listeners after %s intake while the request stays alive', + async (outcome) => { + // Exec responses can outlive their POST body for minutes. The request + // must no longer retain the raw upload through the reader's closures. + const req = new IncomingMessage(new Socket()); + req.headers = {}; + const callerData = () => {}; + const callerError = () => {}; + req.on('data', callerData); + req.on('error', callerError); + const pending = readJsonBody(req, CAP); + expect(req.listenerCount('data')).toBe(2); + expect(req.listenerCount('error')).toBe(2); + req.emit( + 'data', + Buffer.from( + outcome === 'valid' + ? '{"ok":true}' + : outcome === 'oversize' + ? 'x'.repeat(CAP + 1) + : '{', + ), + ); + if (outcome === 'error') req.emit('error', new Error('upload lost')); + else req.emit('end'); + const result = await pending; + expect(result.ok).toBe(outcome === 'valid'); + expect(req.listeners('data')).toEqual([callerData]); + expect(req.listeners('error')).toEqual([callerError]); + expect(req.listenerCount('end')).toBe(0); + req.destroy(); + }, + ); + test('a body over the cap is 413 payload_too_large, not 400', async () => { const res = await fetch(base, { method: 'POST', diff --git a/services/sandbox-runtime/daemon/src/http-body.ts b/services/sandbox-runtime/daemon/src/http-body.ts index 6c523b7919..18500dd047 100644 --- a/services/sandbox-runtime/daemon/src/http-body.ts +++ b/services/sandbox-runtime/daemon/src/http-body.ts @@ -39,7 +39,15 @@ function readBody(req: IncomingMessage, maxBytes: number): Promise { let settled = false; const declared = Number(req.headers['content-length']); let tooLarge = Number.isFinite(declared) && declared > maxBytes; - req.on('data', (chunk: unknown) => { + const cleanup = () => { + // The response may stream for minutes after intake. Do not let its + // IncomingMessage keep the original upload through these listeners. + chunks.length = 0; + req.removeListener('data', onData); + req.removeListener('end', onEnd); + req.removeListener('error', onError); + }; + const onData = (chunk: unknown) => { if (tooLarge) return; const buf = Buffer.isBuffer(chunk) ? chunk @@ -53,21 +61,25 @@ function readBody(req: IncomingMessage, maxBytes: number): Promise { return; } chunks.push(buf); - }); - req.once('end', () => { + }; + const onEnd = () => { if (settled) return; settled = true; - resolve( - tooLarge - ? { kind: 'too_large' } - : { kind: 'read', raw: Buffer.concat(chunks).toString('utf8') }, - ); - }); - req.once('error', (error: Error) => { + const body: BodyRead = tooLarge + ? { kind: 'too_large' } + : { kind: 'read', raw: Buffer.concat(chunks).toString('utf8') }; + cleanup(); + resolve(body); + }; + const onError = (error: Error) => { if (settled) return; settled = true; + cleanup(); reject(error); - }); + }; + req.on('data', onData); + req.once('end', onEnd); + req.once('error', onError); }); } diff --git a/services/sandbox-runtime/daemon/src/main.test.ts b/services/sandbox-runtime/daemon/src/main.test.ts index a00e303596..046ed4bd54 100644 --- a/services/sandbox-runtime/daemon/src/main.test.ts +++ b/services/sandbox-runtime/daemon/src/main.test.ts @@ -9,7 +9,12 @@ import { rmSync, writeFileSync, } from 'node:fs'; -import { request, type Server, type ServerResponse } from 'node:http'; +import { + request, + type IncomingMessage, + type Server, + type ServerResponse, +} from 'node:http'; import { tmpdir } from 'node:os'; const workspace = realpathSync(mkdtempSync(`${tmpdir()}/runnerd-http-`)); @@ -249,8 +254,12 @@ describe('runnerd HTTP service', () => { const execId = `stalled-${mode}`; const path = mode === 'exec' ? '/execs' : `/execs/${execId}/attach`; let stalled: ServerResponse | undefined; - const observe = (req: { url?: string }, res: ServerResponse) => { - if (req.url === path) stalled = res; + let intake: IncomingMessage | undefined; + const observe = (req: IncomingMessage, res: ServerResponse) => { + if (req.url === path) { + stalled = res; + intake = req; + } }; server.on('request', observe); const body = JSON.stringify({ @@ -292,8 +301,13 @@ describe('runnerd HTTP service', () => { await received.promise; } expect(stalled).toBeDefined(); + // A running response must not keep the parsed upload buffered in + // IncomingMessage listeners; detach also releases its abort hook. + expect(intake?.listenerCount('data')).toBe(0); writeFileSync(`${workspace}/${execId}.emit`, 'go'); await waitUntil(() => stalled?.destroyed === true); + expect(intake?.listenerCount('aborted')).toBe(0); + expect(stalled?.listenerCount('drain')).toBe(0); expect( await (await fetch(`${baseUrl}/execs/${execId}`, { headers })).json(), ).toMatchObject({ state: 'running' }); diff --git a/services/sandbox-runtime/daemon/src/main.ts b/services/sandbox-runtime/daemon/src/main.ts index 5d388d3b10..843bff8753 100644 --- a/services/sandbox-runtime/daemon/src/main.ts +++ b/services/sandbox-runtime/daemon/src/main.ts @@ -149,23 +149,38 @@ function execConsumer( res: ServerResponse, label: string, ) { + // A detached exec can outlive this HTTP exchange. Its failure continuation + // still holds the consumer, so explicitly release the request/response pair + // when the connection ends instead of waiting for the command to finish. + let transport: { req: IncomingMessage; res: ServerResponse } | null = { + req, + res, + }; const consumer = new AbortController(); const closed = new Promise((settleClosed) => { consumer.signal.addEventListener('abort', () => settleClosed(), { once: true, }); }); - const gone = () => consumer.abort(); + const gone = () => { + transport?.req.removeListener('aborted', gone); + transport?.res.removeListener('close', gone); + transport = null; + // Node's default abort Error captures this close listener's response in + // its stack; a still-running exec retains the signal, so use no stack. + consumer.abort('consumer disconnected'); + }; // IncomingMessage 'close' also means a completely received request under // Node. The response's close is the consumer's lifetime; aborted covers an // incomplete request without mistaking normal receipt for a disconnect. req.once('aborted', gone); res.once('close', gone); const emit = (event: RunnerdExecEvent) => { - if (consumer.signal.aborted || res.destroyed || res.writableEnded) return; + const response = transport?.res; + if (!response || response.destroyed || response.writableEnded) return; const line = `${JSON.stringify(event)}\n`; if ( - res.writableLength + Buffer.byteLength(line) > + response.writableLength + Buffer.byteLength(line) > RUNNERD_CONSUMER_BUFFER_MAX_BYTES ) { console.warn( @@ -174,15 +189,15 @@ function execConsumer( gone(); // end() would leave the queued bytes waiting on the stalled reader. // Destroying just this response releases its socket and write queue. - res.destroy(); + response.destroy(); return; } try { - res.write(line); + response.write(line); } catch (err) { console.warn(`[runnerd] ${label} write failed:`, err); gone(); - res.destroy(); + response.destroy(); } }; return { @@ -191,23 +206,26 @@ function execConsumer( emit, async replay(this: void, event: RunnerdExecEvent) { emit(event); - if (!consumer.signal.aborted && res.writableNeedDrain) { + // Only this in-flight write may hold the response. The reusable replay + // callback reads the nullable transport, so detach releases it as well. + const response = transport?.res; + if (response?.writableNeedDrain) { const stalled = setTimeout(() => { gone(); - res.destroy(); + response.destroy(); }, 2_000); try { - await once(res, 'drain', { signal: consumer.signal }); + await once(response, 'drain', { signal: consumer.signal }); } finally { clearTimeout(stalled); } } }, end() { + const response = transport?.res; gone(); - req.removeListener('aborted', gone); - res.removeListener('close', gone); - if (!res.destroyed && !res.writableEnded) res.end(); + if (response && !response.destroyed && !response.writableEnded) + response.end(); }, }; } @@ -252,13 +270,15 @@ async function handleExec( // The request's activity ends with its consumer. The exec keeps running, // protected by liveCount and its orphan deadline, with any late failure // observed even after the consumer left. - const run = execManager.run(parsed, consumer.emit).catch((err: unknown) => { - consumer.emit({ - t: 'fail', - code: 'BAD_REQUEST', - message: err instanceof Error ? err.message : String(err), + const run = execManager + .run(parsed, consumer.emit, consumer.signal) + .catch((err: unknown) => { + consumer.emit({ + t: 'fail', + code: 'BAD_REQUEST', + message: err instanceof Error ? err.message : String(err), + }); }); - }); await Promise.race([run, consumer.closed]); } finally { consumer.end(); diff --git a/services/sandbox-runtime/daemon/src/protocol.ts b/services/sandbox-runtime/daemon/src/protocol.ts index 78a587b5f0..47446462f5 100644 --- a/services/sandbox-runtime/daemon/src/protocol.ts +++ b/services/sandbox-runtime/daemon/src/protocol.ts @@ -16,7 +16,7 @@ export const RUNNERD_RING_BUFFER_BYTES = 256 * 1024; * response unboundedly โ€” the only thing the old fixed stdout cap incidentally * bounded. Past this, the daemon disconnects that ONE consumer (the others * are unaffected); it reconnects via /attach?sinceSeq= and replays from the - * bounded ring. Not a stream cap โ€” it bounds memory, never truncates output. */ + * disk-backed journal. The diagnostic ring is not replay history. */ export const RUNNERD_CONSUMER_BUFFER_MAX_BYTES = 8 * 1024 * 1024; /** Cap on ONE request body runnerd accepts, on every route. The spawner's own * SANDBOX_MAX_REQUEST_BODY_BYTES is clamped to this at boot, so a stage batch @@ -77,12 +77,12 @@ export interface RunnerdExecRequest { * Code --input-format stream-json). Default 'close' = write-then-end. */ stdinMode?: 'close' | 'hold'; timeoutMs: number; - /** Cumulative stdout truncation cap. `<= 0` means UNLIMITED โ€” the live stream - * is never truncated and memory stays bounded by the ring (+ the per-consumer - * buffer ceiling). One-shot collected execs pass a positive cap to bound the - * response; long-lived streaming execs (the agent) pass 0. */ + /** Cumulative stdout truncation cap; `<= 0` disables truncation. Journal + * storage limits still end an exec with OUTPUT_LIMIT. In-memory diagnostic + * output and consumer queues remain bounded. One-shot collected execs pass + * a positive cap; long-lived streaming execs (the agent) pass 0. */ stdoutMaxBytes: number; - /** Cumulative stderr truncation cap. `<= 0` means UNLIMITED (see above). */ + /** Cumulative stderr truncation cap; `<= 0` disables truncation (see above). */ stderrMaxBytes: number; } @@ -106,7 +106,8 @@ export interface RunnerdStdinWriteResponse { ok: boolean; /** NOT_FOUND: exec not live. STDIN_CLOSED: exec spawned in 'close' mode or * EOF already sent. BAD_LINE: payload failed the single-NDJSON-line check - * (or exceeded RUNNERD_STDIN_MAX_BYTES). WRITE_FAILED: pipe write threw. */ + * (or exceeded RUNNERD_STDIN_MAX_BYTES). WRITE_FAILED: pipe write threw or + * its bounded input queue is full. */ reason?: 'NOT_FOUND' | 'STDIN_CLOSED' | 'BAD_LINE' | 'WRITE_FAILED'; } diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index c787596e36..2e0baa064a 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -195,6 +195,18 @@ omit these markers. Consumers retain their legacy completion behavior only while replay sequence continuity is verified; an observed gap fails the replay rather than treating a suffix as complete history. +The initial exec consumer releases its callback and HTTP objects on disconnect. +Body intake drops its raw upload buffers after parsing, and completed commands +release request and consumer data even when background descendants await a +sibling's completion. Deferred process cleanup keeps only ownership and +liveness information, separate from the bounded replay history. + +Held-open stdin accepts a whole line only while its pending writes plus that +line fit within 8 MiB. A full queue returns the existing `WRITE_FAILED` reason +without enqueuing any of that line; once the child drains its pipe, writes may +resume. This bounds memory when a command stops reading stdin. Device tunnel +streams also remove caller abort listeners on completion, reset or disconnect. + ### Staged inputs and output reads `POST /files/stage` accepts the existing `files` list: a destination `path` diff --git a/services/sandbox/src/devices/tunnel.test.ts b/services/sandbox/src/devices/tunnel.test.ts index 81f6a3dd30..bee14b91eb 100644 --- a/services/sandbox/src/devices/tunnel.test.ts +++ b/services/sandbox/src/devices/tunnel.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test'; +import { getEventListeners } from 'node:events'; import { encodeFrame, @@ -136,6 +137,140 @@ describe('TunnelEndpoint', () => { expect(Buffer.compare(back, payload)).toBe(0); }); + test('completed requests release their caller signal across repeated exchanges', async () => { + const { hub, device } = tunnelPair({ device: echo }); + const caller = new AbortController(); + const payload = bytes(32 * 1024); + try { + for (let wave = 0; wave < 8; wave++) { + await Promise.all( + Array.from({ length: 8 }, async () => { + const res = await hub.request( + { method: 'POST', path: '/echo', headers: [] }, + payload, + caller.signal, + ); + expect(Buffer.compare(await readAll(res.body), payload)).toBe(0); + }), + ); + expect(hub.streamCount).toBe(0); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(0); + } + } finally { + caller.abort(); + hub.close(); + device.close(); + } + }); + + test('a peer reset releases the caller signal', async () => { + const { hub } = tunnelPair({ device: (s) => s.reset('refused') }); + const caller = new AbortController(); + const error = await rejection( + hub.request( + { method: 'GET', path: '/refused', headers: [] }, + null, + caller.signal, + ), + ); + expect(error).toBeInstanceOf(TunnelStreamResetError); + expect(hub.streamCount).toBe(0); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(0); + hub.close(); + }); + + test('closing a tunnel releases caller signals while requests await a response', async () => { + const { hub } = tunnelPair({ device: () => {} }); + const caller = new AbortController(); + const pending = hub.request( + { method: 'GET', path: '/pending', headers: [] }, + null, + caller.signal, + ); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(1); + hub.close(); + expect(await rejection(pending)).toBeInstanceOf(TunnelClosedError); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(0); + }); + + test('a failed OPEN send leaves no caller signal subscription', async () => { + let sourceCancelled = false; + const source = new ReadableStream({ + cancel() { + sourceCancelled = true; + }, + }); + const endpoint = new TunnelEndpoint( + 'hub', + { + send: () => { + throw new Error('socket dropped the frame'); + }, + bufferedAmount: () => 0, + close: () => {}, + }, + { onStream: () => {}, onControl: () => {} }, + ); + const caller = new AbortController(); + expect( + await rejection( + endpoint.request( + { method: 'GET', path: '/pending', headers: [] }, + source, + caller.signal, + ), + ), + ).toBeInstanceOf(TunnelClosedError); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(0); + expect(sourceCancelled).toBe(true); + // Allow the pump's cancellation/finally to settle before checking ownership. + await Promise.resolve(); + expect(source.locked).toBe(false); + }); + + test('a synchronous peer reset cancels the request body before pumping starts', async () => { + let sourceCancelled = false; + const source = new ReadableStream({ + cancel() { + sourceCancelled = true; + }, + }); + const endpoint: TunnelEndpoint = new TunnelEndpoint( + 'hub', + { + send: (frame) => { + if (frame[0] === FRAME.OPEN) { + endpoint.receive( + encodeFrame( + FRAME.RESET, + 1, + new TextEncoder().encode('{"code":"refused"}'), + ), + ); + } + }, + bufferedAmount: () => 0, + close: () => {}, + }, + { onStream: () => {}, onControl: () => {} }, + ); + const caller = new AbortController(); + expect( + await rejection( + endpoint.request( + { method: 'POST', path: '/upload', headers: [] }, + source, + caller.signal, + ), + ), + ).toBeInstanceOf(TunnelStreamResetError); + expect(sourceCancelled).toBe(true); + expect(getEventListeners(caller.signal, 'abort')).toHaveLength(0); + await Promise.resolve(); + expect(source.locked).toBe(false); + endpoint.close(); + }); + test('device-opened streams reach the hub handler (relay direction)', async () => { const { device } = tunnelPair({ hub: (s) => { diff --git a/services/sandbox/src/devices/tunnel.ts b/services/sandbox/src/devices/tunnel.ts index 0bf2d51249..15ea76cca5 100644 --- a/services/sandbox/src/devices/tunnel.ts +++ b/services/sandbox/src/devices/tunnel.ts @@ -335,6 +335,8 @@ interface StreamState { receivedHead: boolean; reset: boolean; abort: AbortController; + /** Release the caller's signal when this exchange ends, even if it never aborts. */ + detachCallerSignal: (() => void) | undefined; /** The body being pumped out, cancelled when the stream dies. */ source: { cancel(reason?: unknown): Promise } | null; onHead: @@ -432,14 +434,16 @@ export class TunnelEndpoint { state.onHead = { resolve, reject }; }); this.streams.set(id, state); - this.sendFrame(FRAME.OPEN, id, encoder.encode(JSON.stringify(head))); if (signal) { - signal.addEventListener( - 'abort', - () => this.resetStream(state, 'cancelled', 'aborted by caller', true), - { once: true }, - ); + const onAbort = () => + this.resetStream(state, 'cancelled', 'aborted by caller', true); + signal.addEventListener('abort', onAbort, { once: true }); + state.detachCallerSignal = () => + signal.removeEventListener('abort', onAbort); } + // Sending can close the tunnel synchronously. Own the signal first so + // that failure tears it down with the rest of the stream. + this.sendFrame(FRAME.OPEN, id, encoder.encode(JSON.stringify(head))); void this.pump(state, toBodyStream(body)); return response; } @@ -563,6 +567,7 @@ export class TunnelEndpoint { receivedHead: false, reset: false, abort: new AbortController(), + detachCallerSignal: undefined, source: null, onHead: undefined, }; @@ -675,6 +680,13 @@ export class TunnelEndpoint { const reader = source.getReader(); state.source = reader; try { + // OPEN/HEAD can fail synchronously before the source was installed: + // teardown could not cancel it then. Do so before a read that might + // otherwise wait forever after the stream has already ended. + if (state.reset || this.closed) { + await reader.cancel(); + return; + } for (;;) { const { done, value } = await reader.read(); if (done) break; @@ -781,6 +793,8 @@ export class TunnelEndpoint { } private teardown(state: StreamState, error: Error): void { + state.detachCallerSignal?.(); + state.detachCallerSignal = undefined; state.reset = true; state.abort.abort(error); state.inbound.fail(error); @@ -796,7 +810,11 @@ export class TunnelEndpoint { } private retireIfDone(state: StreamState): void { - if (state.sentEnd && state.receivedEnd) this.streams.delete(state.id); + if (state.sentEnd && state.receivedEnd) { + state.detachCallerSignal?.(); + state.detachCallerSignal = undefined; + this.streams.delete(state.id); + } } private sendFrame(type: number, id: number, payload?: Uint8Array): void { diff --git a/services/sandbox/src/session/runnerd-protocol.ts b/services/sandbox/src/session/runnerd-protocol.ts index b82ee262f2..57959ccdde 100644 --- a/services/sandbox/src/session/runnerd-protocol.ts +++ b/services/sandbox/src/session/runnerd-protocol.ts @@ -17,7 +17,7 @@ // - POST /execs responds with NDJSON (one JSON object per line, flushed per // event). The spawner translates NDJSON โ†’ SSE for the platform. NDJSON // (not SSE) daemon-side keeps the in-container parser trivial and makes -// the ring-buffer replay path byte-identical to the live path. +// the journal replay path byte-identical to the live path. // - stdout/stderr ride as base64 chunks: the bytes must survive the hop // UNALTERED and in order (agent adapters parse JSONL from stdout; any // re-encoding or line-merging corrupts mid-line chunk boundaries). @@ -37,7 +37,8 @@ export const RUNNERD_RING_BUFFER_BYTES = 256 * 1024; * SSE consumer would otherwise let Node buffer un-drained stdout in the HTTP * response unboundedly. Past this, the daemon disconnects that ONE * consumer (the others are unaffected); it reconnects via /attach?sinceSeq= - * and replays from the bounded ring. Bounds memory, never truncates output. */ + * and replays from the disk-backed journal. The diagnostic ring is not replay + * history. */ export const RUNNERD_CONSUMER_BUFFER_MAX_BYTES = 8 * 1024 * 1024; /** Cap on ONE request body runnerd accepts, on every route. The spawner's own * SANDBOX_MAX_REQUEST_BODY_BYTES is clamped to this at boot, so a stage batch @@ -120,11 +121,12 @@ export interface RunnerdExecRequest { * Code --input-format stream-json). Default 'close' = write-then-end. */ stdinMode?: 'close' | 'hold'; timeoutMs: number; - /** Cumulative stdout truncation cap; `<= 0` means UNLIMITED (the live stream - * is never truncated, memory bounded by runnerd's ring). The spawner sends 0 - * for streaming execs (collectOutput=false), a positive cap otherwise. */ + /** Cumulative stdout truncation cap; `<= 0` disables truncation. Journal + * storage limits still end an exec with OUTPUT_LIMIT. In-memory diagnostic + * output and consumer queues remain bounded. The spawner sends 0 for + * streaming execs (collectOutput=false), a positive cap otherwise. */ stdoutMaxBytes: number; - /** Cumulative stderr truncation cap; `<= 0` means UNLIMITED (see above). */ + /** Cumulative stderr truncation cap; `<= 0` disables truncation (see above). */ stderrMaxBytes: number; } @@ -150,7 +152,8 @@ export interface RunnerdStdinWriteResponse { ok: boolean; /** NOT_FOUND: exec not live. STDIN_CLOSED: exec spawned in 'close' mode or * EOF already sent. BAD_LINE: payload failed the single-NDJSON-line check - * (or exceeded RUNNERD_STDIN_MAX_BYTES). WRITE_FAILED: pipe write threw. */ + * (or exceeded RUNNERD_STDIN_MAX_BYTES). WRITE_FAILED: pipe write threw or + * its bounded input queue is full. */ reason?: 'NOT_FOUND' | 'STDIN_CLOSED' | 'BAD_LINE' | 'WRITE_FAILED'; } @@ -158,11 +161,12 @@ export interface RunnerdStdinWriteResponse { * `fail` line closes the stream; `stdout`/`stderr` chunks are base64 and * preserve byte order within their own stream. * - * `seq` is a monotonic per-exec counter assigned to every emitted event. A + * `seq` is a monotonic per-exec counter assigned to journaled events. A * consumer that drops its stream reconnects via `GET /attach?sinceSeq=` * and the daemon replays only events with a higher seq โ€” making reconnect - * idempotent (no missed or double-counted lines). Optional only because the - * pre-spawn `fail` lines (which can never be reconnected to) skip the counter. */ + * idempotent (no missed or double-counted lines). Replay boundary markers and + * pre-spawn `fail` lines (which can never be reconnected to) skip the counter. + * Unavailable history fails explicitly instead of replaying a partial suffix. */ export type RunnerdExecEvent = ( | { t: 'replay-start' } | { t: 'replay-complete'; throughSeq: number }