From 45f06fdc46a82e0f25673acc0459bf0b2dcb618c Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:26:00 +0200 Subject: [PATCH 01/14] fix(sandbox): let a busy Docker session end its work before its stop Every Docker stop removed the container with `docker rm --force`, a SIGKILL, so runnerd's SIGTERM path (it gives live execs 2 s to write their harness transcripts and restore what they staged) and the Docker-in-sandbox supervisor's clean engine shutdown never ran. A stop can now carry a grace: the backend first runs `docker stop -t` on the same fenced container id, then removes it as before, and the removal's result is still the one that counts. The max-linger self-reap, the one stop that meets sessions with live execs, uses it: 5 s for a plain session and 20 s for a Docker-in-sandbox one (runnerd's 2 s plus dockerd's 15 s shutdown timeout for its own containers), four at a time so graceful stops hold at most a third of the 12 shared docker CLI slots. Each linger stop now registers in the routes' stop map, so a sweep or idle reclaim already stopping the session is joined rather than cut short, and a later sweep cannot start a second one. Idle stops, pressure reclaims, failed-create cleanup and destroys keep the instant removal: an idle session has nothing to end, and a destroy deletes the workspace and inner image store a grace would flush into. --- services/sandbox/docs/sessions.md | 18 ++-- .../docker/docker-session-backend.test.ts | 61 +++++++++++++ .../backend/docker/docker-session-backend.ts | 20 +++++ services/sandbox/src/backend/types.ts | 13 +++ .../src/session/session-routes.test.ts | 85 +++++++++++++++++++ .../sandbox/src/session/session-routes.ts | 85 ++++++++++++++----- services/sandbox/src/spawn-util.ts | 17 ++++ 7 files changed, 275 insertions(+), 24 deletions(-) diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index 639c44f3b3..4e13dcc46b 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -179,11 +179,19 @@ has been replaced by newly forked, untagged processes after the leader exits. **Session teardown is best effort, not a wrapper-cleanup guarantee.** runnerd passes SIGTERM to execs when it receives a graceful stop, but does not await -their completion before exiting. Docker's force-removal path does not deliver -that graceful stop at all. This change intentionally retains those teardown -semantics; guaranteeing wrapper cleanup would require a separate provider and -daemon shutdown change. The unit tests prove the manager's signal delivery, -not provider teardown or the timing of wrapper completion. +their completion before exiting. On Docker a stop removes the container with +`docker rm --force`, which kills at once and delivers no graceful stop; only a +stop of a session with a live exec through this spawner asks first. The +max-linger self-reap stops such a session with `docker stop -t 5` (`-t 20` for +a Docker-in-sandbox session, whose supervisor also shuts its inner engine down +and whose dockerd waits up to 15 s for its own containers) and then removes it, +inside the same lifecycle serialization as every other stop: a sweep or an +idle reclaim already stopping the session is joined, never cut short. Idle +stops, pressure reclaims, failed-create cleanup and destroys still remove at +once: an idle session has nothing to end, and a destroy deletes the workspace +and the inner image store a grace would flush into. Kubernetes deletes every +Pod with a 5 s grace period. The unit tests prove the manager's signal +delivery and which stops ask first, not the timing of wrapper completion. Avoid `pkill -9 -f ''` for managed execs: the shim's argv contains the command too, so that pattern can kill the shim. runnerd then reports the shim's diff --git a/services/sandbox/src/backend/docker/docker-session-backend.test.ts b/services/sandbox/src/backend/docker/docker-session-backend.test.ts index e1af148392..0c3e339ba0 100644 --- a/services/sandbox/src/backend/docker/docker-session-backend.test.ts +++ b/services/sandbox/src/backend/docker/docker-session-backend.test.ts @@ -158,6 +158,13 @@ case "$cmd" in version) echo "29.0.0" exit 0 ;; + stop) + printf '%s\\n' "$@" > "$here/last-stop" + if [ "$(cat "$here/stop-mode" 2>/dev/null)" = "fail" ]; then + echo "Error response from daemon: cannot stop container: permission denied" >&2 + exit 1 + fi + exit 0 ;; rm) printf '%s\\n' "$@" > "$here/last-rm" case "$rm_mode" in @@ -485,6 +492,60 @@ describe('DockerSessionBackend stop/destroy honour the rm result', () => { expect(await backend.stopSession('rm-ok')).toBe(true); }); + test('a stop with a grace asks the container to stop before it is removed; one without kills at once', async () => { + await fakeDocker({ present: true, rm: 'ok' }); + await rm(join(fakeRoot, 'last-stop'), { force: true }); + const backend = new DockerSessionBackend(backendConfig()); + expect(await backend.stopSession('graceful', 1_700_000_000_000)).toBe(true); + expect(await exists(join(fakeRoot, 'last-stop'))).toBe(false); + expect( + await backend.stopSession('graceful', 1_700_000_000_000, { + graceMs: 20_000, + }), + ).toBe(true); + // The grace goes to the same fenced container id the removal takes. + expect( + (await readFile(join(fakeRoot, 'last-stop'), 'utf8')).split('\n'), + ).toEqual(['-t', '20', 'abcdef123456', '']); + expect(await readFile(join(fakeRoot, 'last-rm'), 'utf8')).toBe( + '--force\nabcdef123456\n', + ); + }); + + test('a graceful stop the daemon refuses still removes the container', async () => { + await fakeDocker({ present: true, rm: 'ok' }); + await writeFile(join(fakeRoot, 'stop-mode'), 'fail'); + await writeFile(join(fakeRoot, 'last-rm'), 'untouched'); + const warn = spyOn(console, 'warn').mockImplementation(() => {}); + try { + const backend = new DockerSessionBackend(backendConfig()); + expect( + await backend.stopSession('stop-refused', undefined, { + graceMs: 5_000, + }), + ).toBe(true); + expect(await readFile(join(fakeRoot, 'last-rm'), 'utf8')).toBe( + '--force\ntale-sbx-ses-stop-refused\n', + ); + expect(String(warn.mock.calls[0]?.[0])).toContain( + 'graceful stop of tale-sbx-ses-stop-refused failed', + ); + } finally { + warn.mockRestore(); + await rm(join(fakeRoot, 'stop-mode'), { force: true }); + } + }); + + test('nothing to stop gracefully when the container is already gone', async () => { + await fakeDocker({ present: false, rm: 'nosuch' }); + await rm(join(fakeRoot, 'last-stop'), { force: true }); + const backend = new DockerSessionBackend(backendConfig()); + expect( + await backend.stopSession('stop-gone', undefined, { graceMs: 5_000 }), + ).toBe(false); + expect(await exists(join(fakeRoot, 'last-stop'))).toBe(false); + }); + test('a failed removal of the inner image volume is reported, never silent', async () => { // The fake CLI answers `volume rm` with a non-zero exit. await fakeDocker({ present: true, rm: 'ok' }); diff --git a/services/sandbox/src/backend/docker/docker-session-backend.ts b/services/sandbox/src/backend/docker/docker-session-backend.ts index b3683b1283..4ed7e7dbd4 100644 --- a/services/sandbox/src/backend/docker/docker-session-backend.ts +++ b/services/sandbox/src/backend/docker/docker-session-backend.ts @@ -75,6 +75,7 @@ import { import { dockerRm, dockerRmSucceeded, + dockerStop, isDockerMissingImage, isDockerNoSuchObject, runDocker, @@ -99,6 +100,7 @@ import { type OrganizationTeardownResult, type SessionBackend, type SessionSpec, + type StopSessionOptions, type WorkspaceDeletion, } from '../types.ts'; @@ -904,6 +906,7 @@ export class DockerSessionBackend implements SessionBackend { sessionId: string, expectedCreatedAtMs?: number, expectedCreateAttemptId?: string, + graceMs = 0, ): Promise<{ existed: boolean; docker: boolean }> { const containerName = sessionContainerName(sessionId); let removalTarget = containerName; @@ -944,6 +947,20 @@ export class DockerSessionBackend implements SessionBackend { } catch { existed = false; } + if (existed && graceMs > 0) { + // `rm --force` kills at once. A busy session gets its init's SIGTERM + // first, which runnerd passes on to its execs; the removal below then + // takes what the grace left, and its result is the one that counts. + const stop = await dockerStop( + removalTarget, + Math.max(1, Math.ceil(graceMs / 1000)), + ); + if (stop.exitCode !== 0 && !isDockerNoSuchObject(stop.stderr)) { + console.warn( + `[sandbox.session] graceful stop of ${containerName} failed (exit ${stop.exitCode}); removing it at once: ${stop.stderr.trim() || 'no output'}`, + ); + } + } const removal = await dockerRm(removalTarget); if (!dockerRmSucceeded(removal)) { throw new Error( @@ -1088,6 +1105,7 @@ export class DockerSessionBackend implements SessionBackend { async stopSession( sessionId: string, expectedCreatedAtMs?: number, + options: StopSessionOptions = {}, ): Promise { // Release compute but PRESERVE the host workspace dir — a later // createSession with the same sessionId re-mounts it (resume). The inner @@ -1095,6 +1113,8 @@ export class DockerSessionBackend implements SessionBackend { const { existed, docker } = await this.removeContainer( sessionId, expectedCreatedAtMs, + undefined, + options.graceMs, ); if (docker) await this.removeDindVolume(sessionId); // The pin belongs to the container that just went away; the resume's diff --git a/services/sandbox/src/backend/types.ts b/services/sandbox/src/backend/types.ts index 745491985d..c2a7786ee9 100644 --- a/services/sandbox/src/backend/types.ts +++ b/services/sandbox/src/backend/types.ts @@ -207,6 +207,18 @@ export interface BuildCacheUpkeep { sessionDisk?: () => Promise; } +/** How a stop ends what still runs in the session. */ +export interface StopSessionOptions { + /** Let the session end its own work for this long before it is killed: + * runnerd passes the stop on to every live exec (a harness writes its + * transcript, a wrapper restores what it staged) and a Docker-in-sandbox + * session's supervisor shuts its inner engine down. Absent or 0, the + * compute is killed at once — the stop of an idle session, which has + * nothing to end. Docker only: a Kubernetes Pod is always deleted with its + * own grace period. */ + graceMs?: number; +} + export interface SessionBackend { readonly kind: 'docker' | 'kubernetes'; /** @@ -277,6 +289,7 @@ export interface SessionBackend { stopSession( sessionId: string, expectedCreatedAtMs?: number, + options?: StopSessionOptions, ): Promise; /** Recover an abandoned startup only when its durable age and current * backend state prove no peer is still starting it. Fenced to the original diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index 890d186eee..3820725445 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -3909,6 +3909,91 @@ describe('SessionRoutes (fake runnerd)', () => { expect([...stopped]).toEqual(['drain-owned']); }); + test('the linger reap lets a session with a live exec end its work, and stops an idle one at once', async () => { + const graces = new Map(); + const routes = new SessionRoutes( + { ...cfg, dockerInContainer: true }, + { + ...fakeBackend, + async stopSession(id, _stamp, options) { + graces.set(id, options?.graceMs); + return fakeBackend.stopSession(id); + }, + }, + ); + for (const [sessionId, docker] of [ + ['linger-busy', false], + ['linger-busy-docker', true], + ['linger-idle', false], + ] as const) { + expect( + ( + await routes.handleCreate( + JSON.stringify({ + sessionId, + organizationId: 'org_linger', + profile: 'agent', + docker, + }), + ) + ).status, + ).toBe(201); + } + const callers = [new AbortController(), new AbortController()]; + try { + for (const [index, sessionId] of [ + 'linger-busy', + 'linger-busy-docker', + ].entries()) { + const exec = await routes.handleExec( + new Request('http://sandbox/exec', { + signal: callers[index]?.signal, + }), + sessionId, + JSON.stringify({ execId: `hang-${sessionId}`, command: ['true'] }), + ); + await exec.body?.getReader().read(); + } + expect(await routes.stopAllSessions()).toBe(3); + } finally { + for (const caller of callers) caller.abort(); + } + expect(Object.fromEntries(graces)).toEqual({ + 'linger-busy': 5_000, + 'linger-busy-docker': 20_000, + 'linger-idle': 0, + }); + expect(routes.sessionIds()).toEqual([]); + }); + + test('the linger reap joins a stop already under way instead of cutting it short', async () => { + const release = Promise.withResolvers(); + const started = Promise.withResolvers(); + let stops = 0; + const routes = new SessionRoutes(cfg, { + ...fakeBackend, + async stopSession(id) { + stops += 1; + started.resolve(); + await release.promise; + return fakeBackend.stopSession(id); + }, + }); + await routes.handleCreate( + JSON.stringify({ sessionId: 'linger-joined', organizationId: 'org_a' }), + ); + fakeHealth.lastActivityAtMs = 0; + const sweep = routes.sweepExpired( + Date.now() + cfg.session.maxLifetimeMs + 1, + ); + await started.promise; + const linger = routes.stopAllSessions(); + release.resolve(); + expect(await sweep).toBe(1); + expect(await linger).toBe(1); + expect(stops).toBe(1); + }); + test.each(['get', 'pin'])( 'a %s miss whose endpoint resolves after drain begins cannot adopt a peer', async (action) => { diff --git a/services/sandbox/src/session/session-routes.ts b/services/sandbox/src/session/session-routes.ts index 648b06057e..57c7e3421a 100644 --- a/services/sandbox/src/session/session-routes.ts +++ b/services/sandbox/src/session/session-routes.ts @@ -150,6 +150,19 @@ const LIVENESS_PROBE_TIMEOUT_MS = 1_500; * again. */ const ENDED_REAP_BACKOFF_MS = 10 * 60_000; +/** How long a stop lets a session with a live exec end its work before its + * compute is killed. runnerd passes the stop on to every exec and exits + * within 2 s (a harness writes its transcript, a wrapper restores what it + * staged); a Docker-in-sandbox session's supervisor also shuts its inner + * engine down, and dockerd waits up to 15 s for its own containers. An idle + * session's stop kills at once: it has nothing to end. */ +const BUSY_STOP_GRACE_MS = 5_000; +const BUSY_DOCKER_STOP_GRACE_MS = 20_000; + +/** Busy sessions the linger reap stops at once: each graceful stop holds a + * docker CLI slot for up to its grace, and the rest stay for the others. */ +const LINGER_STOP_CONCURRENCY = 4; + /** How long a session that just started keeps part of its planned working * set reserved at admission: its turn is still growing toward it while * MemAvailable shows only the idle footprint. The reservation shrinks @@ -464,31 +477,65 @@ export class SessionRoutes { return this.registry.list().map((s) => s.sessionId); } - /** Force-stop every non-finished session (compute reclaimed, workspace - * preserved). Used by the spawner's max-linger self-reap so a spawner that - * lingered past its TTL can shut down without orphaning containers — even if - * the deploy died mid-roll. Returns the number stopped. */ + /** Stop every non-finished session (compute reclaimed, workspace + * preserved); one with a live exec gets a grace to end its work first. + * Used by the spawner's max-linger self-reap so a spawner that lingered + * past its TTL can shut down without orphaning containers — even if the + * deploy died mid-roll. Returns the number stopped. */ async stopAllSessions(): Promise { let stopped = 0; - for (const s of this.registry.list()) { - try { - await this.backend.stopSession(s.sessionId, s.createdAtMs); - this.forgetReclaimed(s); - stopped += 1; - } catch (err) { - if (err instanceof SessionIncarnationChangedError) { - this.forgetReclaimed(s); - continue; + await forEachLimited( + this.registry.list(), + LINGER_STOP_CONCURRENCY, + async (s) => { + // A stop already under way (a sweep's, an idle reclaim's) owns the + // incarnation; a second one would cut its grace short. + const pending = this.stopping.get(s.sessionId); + if (pending !== undefined) { + if (await pending) stopped += 1; + return; } - console.warn( - `[sandbox.session] linger stop failed for ${s.sessionId}:`, - err, - ); - } - } + const stop = this.backend + .stopSession(s.sessionId, s.createdAtMs, { + graceMs: this.stopGraceMs(s), + }) + .then( + () => { + this.forgetReclaimed(s); + return true; + }, + (err: unknown) => { + if (err instanceof SessionIncarnationChangedError) { + this.forgetReclaimed(s); + return false; + } + console.warn( + `[sandbox.session] linger stop failed for ${s.sessionId}:`, + err, + ); + return false; + }, + ) + .finally(() => { + if (this.stopping.get(s.sessionId) === stop) + this.stopping.delete(s.sessionId); + }); + this.stopping.set(s.sessionId, stop); + if (await stop) stopped += 1; + }, + ); return stopped; } + /** How long a stop of this session lets its work end: a grace while an + * exec runs through this replica, none for an idle session. */ + private stopGraceMs(session: RegistrySession): number { + if (session.liveExecs.size === 0) return 0; + return (session.docker ?? this.cfg.dockerInContainer) + ? BUSY_DOCKER_STOP_GRACE_MS + : BUSY_STOP_GRACE_MS; + } + /** runnerd token for a session: derived from SANDBOX_TOKEN (always set — * loadConfig fails closed without it, so every session carries a real * token and runnerd always verifies). */ diff --git a/services/sandbox/src/spawn-util.ts b/services/sandbox/src/spawn-util.ts index 316571ffb6..06d8ded85d 100644 --- a/services/sandbox/src/spawn-util.ts +++ b/services/sandbox/src/spawn-util.ts @@ -456,6 +456,23 @@ export async function dockerRm( return runDocker(['rm', '--force', containerName], { timeoutMs: 30_000 }); } +/** + * `docker stop -t `: SIGTERM to the container's init, + * SIGKILL once the grace has passed. The CLI returns when the container has + * stopped, so its budget is the grace plus 15 s for the daemon to answer; a + * wedged one costs no more than that. Never rejects. A stop only prepares a + * removal: whatever it answers, the caller removes the container with + * {@link dockerRm}, whose result is the one that counts. + */ +export async function dockerStop( + containerName: string, + graceSeconds: number, +): Promise { + return runDocker(['stop', '-t', String(graceSeconds), containerName], { + timeoutMs: graceSeconds * 1000 + 15_000, + }); +} + /** Did a `dockerRm` leave the object gone? A clean exit, or a "no such * container" refusal (already gone — the idempotent success). A timeout (124) * or any other daemon error is a FAILURE: the container may still be running. */ From b4a07ee1a00027554c090c1148355ae0cac88ac5 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:26:35 +0200 Subject: [PATCH 02/14] fix(sandbox): add a critical tier to the session disk floor The free-space floor only holds creates and acquires back. Sessions already running write until the disk is full, and runnerd's replay journal sits on the same disk, so a full disk ends every running exec. Below a critical tier (SANDBOX_CRITICAL_FREE_DISK, unset a quarter of the floor, at least 1 GiB and never above it: 1 GiB on a 20 GiB disk, 1.25 GiB on 100 GiB, 5 GiB under the 20 GiB floor cap; 0, or a floor of 0, turns it off) the sweep now acts on the probe's five-second reading: - a released idle Docker-in-sandbox session is stopped at once instead of after its full idle window, through runnerd's claim like every idle stop, so a turn that acquires it meanwhile keeps it; its stop removes its inner image store, the most a stop gives back; - the three largest workspaces are logged, measured by one `du` of every workspace dir at nice 19 (the lowest best-effort I/O priority), cut off after 30 s and run at most every ten minutes; - the disk going below the tier and coming back is logged once each. An unknown or unreadable disk is never critical. New streaming execs are not refused here: every agent turn acquires its session right before its exec, and acquires are already refused below the floor, which lies above this tier. --- .env.example | 6 + .../configuration/environment-reference.md | 3 +- .../configuration/environment-reference.md | 3 +- .../configuration/environment-reference.md | 3 +- .../tests/manual/reference/automation.md | 1 + services/sandbox/README.md | 7 +- services/sandbox/docs/sessions.md | 16 +++ .../backend/docker/docker-session-backend.ts | 10 ++ services/sandbox/src/backend/types.ts | 9 ++ services/sandbox/src/config.test.ts | 12 ++ services/sandbox/src/config.ts | 2 + services/sandbox/src/host-disk.test.ts | 47 +++++++ services/sandbox/src/host-disk.ts | 32 +++++ .../src/session/session-routes.test.ts | 125 ++++++++++++++++++ .../sandbox/src/session/session-routes.ts | 111 +++++++++++++++- .../src/session/workspace-inventory.ts | 9 ++ .../src/session/workspace-usage.test.ts | 90 +++++++++++++ .../sandbox/src/session/workspace-usage.ts | 85 ++++++++++++ services/sandbox/src/types.ts | 5 + 19 files changed, 568 insertions(+), 8 deletions(-) create mode 100644 services/sandbox/src/session/workspace-usage.test.ts create mode 100644 services/sandbox/src/session/workspace-usage.ts diff --git a/.env.example b/.env.example index 913f40308b..7082c2fe06 100644 --- a/.env.example +++ b/.env.example @@ -456,6 +456,12 @@ TALE_AUDIT_PEPPER=9c1e5b7d3a2f8064e1c7a9d5b3f2e8c604a7d1b9e5c3f8a2d6b0e4c7a1f9d3 # off). Below it, new sessions wait and the build caches of organizations that # are not building go first. # SANDBOX_MIN_FREE_DISK=10g +# Free space below which that disk is critical: running sessions' writes are +# about to fail, so released idle sessions with Docker inside are stopped at +# once (their inner image stores go with them) and the largest workspaces are +# logged (default: a quarter of the floor, at least 1g and never above it; 0 +# turns it off). +# SANDBOX_CRITICAL_FREE_DISK=2g # How long a session that no turn or run holds stays up once idle, in ms (agent # sessions with Docker inside keep the full idle window). # SANDBOX_SESSION_RELEASED_IDLE_MS=300000 diff --git a/docs/de/self-hosted/configuration/environment-reference.md b/docs/de/self-hosted/configuration/environment-reference.md index 9cf760f0dc..95acde272e 100644 --- a/docs/de/self-hosted/configuration/environment-reference.md +++ b/docs/de/self-hosted/configuration/environment-reference.md @@ -255,6 +255,7 @@ Der Sandbox-Spawner liest die folgenden Einstellungen. Übergib sie seiner Umgeb | `SANDBOX_MAX_SESSIONS` | auf einem lokalen Docker-Host nach dem Host-Speicher bemessen (mindestens `8`, höchstens `256`); sonst `8` | Höchstzahl laufender und startender Sessions aller Organisationen auf dem Docker-Host oder im Kubernetes-Namespace, einschließlich weiterlaufender Container im Leerlauf. Die Kapazität reserviert weder CPU noch Arbeitsspeicher. Fehlt die Variable auf einem Docker-Host, dessen Speicher der Spawner lesen kann, bemisst er sie nach diesem Speicher: eine Session je 768 MiB, die nach `SANDBOX_MIN_FREE_MEMORY` übrig bleiben, oder je 1,5 GiB, wenn Agent-Sessions Docker in der Sandbox betreiben. Lässt sich der Speicher beim Start nicht lesen, bleibt die Kapazität bei `8`, bis er lesbar ist. Ein expliziter Wert legt sie fest. Gleichzeitige Kubernetes-Replikate setzen sie nach bestem Bemühen durch; harte Ressourcengrenzen im Namespace setzt du mit ResourceQuota. | | `SANDBOX_MIN_FREE_MEMORY` | ein Zehntel des Host-Speichers, mindestens `1g` | Speicher, den eine neue Session oder eine freigegebene, noch laufende Session bei der Wiederaufnahme auf einem lokalen Docker-Host frei lassen muss, neben dem, was noch startende und eben gestartete Sessions gleich belegen werden. Würde ein Start weniger übrig lassen, stoppt der Spawner zuerst eine freigegebene Session im Leerlauf; reicht der Speicher dann immer noch nicht, antwortet er mit „beschäftigt“, und die Arbeit wartet, bis laufende Sessions Speicher freigeben. Akzeptiert Größen wie `2g` oder `1536m`. Wirkt nicht unter Kubernetes oder mit einem entfernten Docker-Daemon. | | `SANDBOX_MIN_FREE_DISK` | ein Zwanzigstel jedes Datenträgers, mindestens `2g`, höchstens `20g` | Freier Speicher für neue und reaktivierte Sitzungen im Dateisystem der Arbeitsbereiche und im verifizierten Docker-Daten-Dateisystem. Unterhalb der Grenze wartet die Arbeit; gestoppte, ungenutzte Build-Caches werden zuerst entfernt. Akzeptiert `10g` oder `4096m`; `0` deaktiviert die Prüfung. Kubernetes stützt sich auf Storage-Klasse und Volume-Bereitstellung. | +| `SANDBOX_CRITICAL_FREE_DISK` | ein Viertel der Grenze aus `SANDBOX_MIN_FREE_DISK`, mindestens `1g` und nie darüber | Freier Speicher, unterhalb dessen der Datenträger der Sessions kritisch ist: Was laufende Sessions dort schreiben, schlägt bald fehl. Darunter werden freigegebene Sessions mit Docker in der Sandbox im Leerlauf sofort gestoppt, was ihre inneren Image-Speicher entfernt, und der Spawner protokolliert höchstens alle zehn Minuten die drei größten Arbeitsbereiche. Akzeptiert `2g` oder `2048m`; `0` deaktiviert die Stufe, ebenso eine Grenze von `0`. Nur mit dem Docker-Backend. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Workloads, die Docker in ihrer Sandbox nutzen dürfen, wenn es für das Deployment aktiviert ist. Mit `project` starten Workflow-Agenten ohne Docker, mit `workflow` gilt das für Projektagenten und mit `none` für beide. Die Einstellung gilt für neu erstellte Sessions; bestehende behalten ihre Fähigkeiten. Eine Session-Anfrage kann Docker mit `docker: false` abwählen, aber weder diese Liste noch die Deployment-Einstellung erweitern. | | `SANDBOX_AGENT_CPUS` | `2` | CPU-Grenze je Agent-Session. Berücksichtige bei der Session-Anzahl gleichzeitig laufende Builds und andere Aufgaben auf dem Host. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | CPU-Gewichtung einer Agent-Session und der Build-Cache-Hilfscontainer ihrer Organisation, solange die CPUs des Hosts ausgelastet sind, gegenüber Dockers Standardwert `1024`, den die eigenen Dienste der Plattform behalten; Sessions mit dem Profil `default` (Codeausführungen, Seiten-Renderings) nutzen `128`. Ausgelastete Sessions überlassen die CPU dann der Datenbank und dem Backend, statt sie auszubremsen; auf einem Host mit freier CPU nutzt eine Session weiterhin bis zu `SANDBOX_AGENT_CPUS`. Eine ganze Zahl von `2` bis `262144`. Gilt für neu erstellte Sessions; ein laufender Hilfscontainer übernimmt einen neuen Wert sofort. | @@ -306,7 +307,7 @@ Kubernetes-Sitzungen verwenden `/readyz` für die Startprüfung und `/livez` fü Eine bereits aktive Generation wird nicht erneut angerechnet. Ein Workflow ohne inneres Docker behält die Identität und Werkzeuge seines Agenten, startet aber keinen Docker-Daemon und hält keine Build-Cache-Hilfscontainer aktiv. Ohne expliziten Wert für `SANDBOX_AGENT_MEMORY` gilt pro Session standardmäßig `4g` ohne inneres Docker oder `8g` mit Docker, auch wenn andere Sessions im Deployment Docker nutzen. Ein expliziter Wert gilt für beide Varianten. Die Grenzen sind Obergrenzen, kein reservierter Arbeitsspeicher. -Bei voller Kapazität kann der Spawner eine freigegebene, nicht angepinnte Session im Leerlauf schon vor Ablauf des Leerlauffensters stoppen, um neue Arbeit zuzulassen, zuerst die am längsten untätige. Der Daemon muss bestätigen, dass keine Arbeit läuft; beschäftigte Sessions und Sessions mit unbekanntem Zustand bleiben geschützt. Das dauerhafte Arbeitsverzeichnis oder Volume bleibt beim Stoppen erhalten. Lässt sich keine Session sicher freigeben, blockiert die Kapazitätsgrenze weiterhin neue Starts. Dasselbe gilt, wenn der freie Speicher des Hosts unter `SANDBOX_MIN_FREE_MEMORY` fallen würde. Solange der Datenträger mit den Arbeitsverzeichnissen der Sessions unter `SANDBOX_MIN_FREE_DISK` liegt, wartet neue Arbeit, ohne dass Sessions im Leerlauf gestoppt werden: Eine gestoppte Session behält ihr Arbeitsverzeichnis. +Bei voller Kapazität kann der Spawner eine freigegebene, nicht angepinnte Session im Leerlauf schon vor Ablauf des Leerlauffensters stoppen, um neue Arbeit zuzulassen, zuerst die am längsten untätige. Der Daemon muss bestätigen, dass keine Arbeit läuft; beschäftigte Sessions und Sessions mit unbekanntem Zustand bleiben geschützt. Das dauerhafte Arbeitsverzeichnis oder Volume bleibt beim Stoppen erhalten. Lässt sich keine Session sicher freigeben, blockiert die Kapazitätsgrenze weiterhin neue Starts. Dasselbe gilt, wenn der freie Speicher des Hosts unter `SANDBOX_MIN_FREE_MEMORY` fallen würde. Solange der Datenträger mit den Arbeitsverzeichnissen der Sessions unter `SANDBOX_MIN_FREE_DISK` liegt, wartet neue Arbeit, ohne dass Sessions im Leerlauf gestoppt werden: Eine gestoppte Session behält ihr Arbeitsverzeichnis. Erst unterhalb von `SANDBOX_CRITICAL_FREE_DISK` stoppt der Spawner freigegebene Sessions mit Docker in der Sandbox im Leerlauf sofort, weil ihr Stopp ihre inneren Image-Speicher entfernt. Datensätze im Agent-Laufzeit-Protokoll, einschließlich unvollständiger Zeilen, sind auf 8 MiB begrenzt. Zu große oder unvollständige Ausgaben führen zu einem ausdrücklichen Fehler; eine begrenzte Fortschrittsvorschau gilt nie als vollständiges strukturiertes Ergebnis. Vollständige Endantworten bleiben getrennt von dieser Vorschau erhalten. diff --git a/docs/en/self-hosted/configuration/environment-reference.md b/docs/en/self-hosted/configuration/environment-reference.md index f3144f19ee..ed678d3b2a 100644 --- a/docs/en/self-hosted/configuration/environment-reference.md +++ b/docs/en/self-hosted/configuration/environment-reference.md @@ -255,6 +255,7 @@ The sandbox spawner reads the settings below. Pass them into its environment and | `SANDBOX_MAX_SESSIONS` | sized from host memory on a local Docker host (at least `8`, at most `256`); `8` elsewhere | Maximum running and starting sessions across all organizations on the Docker host or in the Kubernetes namespace, including idle containers kept for reuse. This capacity does not reserve CPU or memory. Unset on a Docker host whose memory the spawner can read, it is sized from that memory: one session per 768 MiB left after `SANDBOX_MIN_FREE_MEMORY`, or per 1.5 GiB where agent sessions run Docker inside the sandbox. If the memory cannot be read at start, the capacity stays `8` until it can. An explicit value fixes it. Concurrent Kubernetes replicas enforce it on a best-effort basis; use ResourceQuota for hard namespace resource bounds. | | `SANDBOX_MIN_FREE_MEMORY` | a tenth of host memory, at least `1g` | Memory a new session or a released warm session resuming work must leave free on a local Docker host, beside what the sessions still starting or just started are about to use. A create that would leave less first stops a released idle session; if memory is still short, the spawner answers busy and the work waits until running sessions free some. Accepts sizes such as `2g` or `1536m`. Has no effect on Kubernetes or with a remote Docker daemon. | | `SANDBOX_MIN_FREE_DISK` | a twentieth of each disk, at least `2g`, at most `20g` | Free space required for new and reactivated sessions on the workspace filesystem and the verified Docker data filesystem. Below the floor work waits; stopped unused build caches are reclaimed first. Accepts `10g` or `4096m`; `0` disables the check. Kubernetes relies on its storage class and volume provisioning. | +| `SANDBOX_CRITICAL_FREE_DISK` | a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least `1g` and never above it | Free space below which the session disk is critical: what running sessions write there is about to fail. Below it, released idle sessions with Docker inside are stopped at once, which removes their inner image stores, and the spawner logs the three largest workspaces at most every ten minutes. Accepts `2g` or `2048m`; `0` turns it off, as does a floor of `0`. Docker backend only. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Workloads allowed to use inner Docker when it is enabled for the deployment. Set `project` to allow Docker only for project agents, `workflow` only for workflow agents, or `none` to disable both. Applies to newly created sessions; existing sessions keep their capabilities. A session request can opt out with `docker: false`, but cannot enable Docker beyond this allowlist or the deployment setting. | | `SANDBOX_AGENT_CPUS` | `2` | CPU limit per agent session. Account for overlapping builds and other host workloads when choosing the session count. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | CPU weight of an agent session and of its organization's build-cache helpers while the host's CPUs are saturated, against Docker's default of `1024` that the platform's own services keep; sessions of the `default` profile (code runs, page renders) use `128`. Busy sessions then yield the CPU to the database and backend instead of stalling them; on a host with spare CPU a session still uses up to `SANDBOX_AGENT_CPUS`. A whole number from `2` to `262144`. Applies to newly created sessions; a running helper takes a new value at once. | @@ -306,7 +307,7 @@ Kubernetes sessions use `/readyz` for startup and `/livez` for daemon liveness. An already active generation is not charged again. A workflow without inner Docker keeps its agent identity and tools, but starts no Docker daemon and does not keep build-cache helpers alive. Without an explicit `SANDBOX_AGENT_MEMORY`, each session defaults to `4g` without inner Docker or `8g` with it, even when other sessions in the deployment use Docker. An explicit value applies to both modes. These limits are ceilings, not reserved RAM. -At full capacity, the spawner can stop a released, unpinned idle session before the idle timeout to admit new work, starting with the one idle longest. The daemon must confirm that no work is in progress; busy sessions and sessions with unknown state are protected. Stopping compute preserves the persistent workspace directory or volume. If no safe session can be reclaimed, admission remains blocked by the deployment capacity. The same applies when the host's free memory would drop below `SANDBOX_MIN_FREE_MEMORY`. While the disk that holds the session workspaces is below `SANDBOX_MIN_FREE_DISK`, new work waits without stopping idle sessions: a stopped session keeps its workspace. +At full capacity, the spawner can stop a released, unpinned idle session before the idle timeout to admit new work, starting with the one idle longest. The daemon must confirm that no work is in progress; busy sessions and sessions with unknown state are protected. Stopping compute preserves the persistent workspace directory or volume. If no safe session can be reclaimed, admission remains blocked by the deployment capacity. The same applies when the host's free memory would drop below `SANDBOX_MIN_FREE_MEMORY`. While the disk that holds the session workspaces is below `SANDBOX_MIN_FREE_DISK`, new work waits without stopping idle sessions: a stopped session keeps its workspace. Only below `SANDBOX_CRITICAL_FREE_DISK` does the spawner stop released idle sessions with Docker inside at once, since their stop removes their inner image stores. Agent runtime protocol records, including unfinished lines, are limited to 8 MiB. Oversized or incomplete output fails explicitly; a bounded progress preview is never treated as a complete structured result. Complete final answers are retained separately from that preview. diff --git a/docs/fr/self-hosted/configuration/environment-reference.md b/docs/fr/self-hosted/configuration/environment-reference.md index 5e56d8378c..c89505638e 100644 --- a/docs/fr/self-hosted/configuration/environment-reference.md +++ b/docs/fr/self-hosted/configuration/environment-reference.md @@ -255,6 +255,7 @@ Le spawner sandbox lit les paramètres ci-dessous. Transmets-les dans son enviro | `SANDBOX_MAX_SESSIONS` | dimensionnée selon la mémoire de l’hôte sur un hôte Docker local (au moins `8`, au plus `256`) ; `8` ailleurs | Nombre maximal de sessions actives ou au démarrage de toutes les organisations sur l’hôte Docker ou dans le namespace Kubernetes, y compris les conteneurs inactifs conservés pour être réutilisés. Cette capacité ne réserve ni CPU ni mémoire. Sans valeur, sur un hôte Docker dont le spawner peut lire la mémoire, elle est dimensionnée selon cette mémoire : une session par tranche de 768 MiB restant après `SANDBOX_MIN_FREE_MEMORY`, ou de 1,5 GiB quand les sessions d’agent font tourner Docker dans la sandbox. Si la mémoire ne peut pas être lue au démarrage, la capacité reste à `8` jusqu’à ce qu’elle le soit. Une valeur explicite la fixe. Des réplicas Kubernetes concurrents l’appliquent au mieux ; utilise ResourceQuota pour imposer des limites strictes aux ressources du namespace. | | `SANDBOX_MIN_FREE_MEMORY` | un dixième de la mémoire de l’hôte, au moins `1g` | Mémoire qu’une nouvelle session ou une session libérée qui reprend du travail doit laisser libre sur un hôte Docker local, en plus de ce que les sessions encore au démarrage ou tout juste démarrées vont bientôt occuper. Si un démarrage en laissait moins, le spawner arrête d’abord une session libérée inactive ; si la mémoire manque encore, il répond « occupé » et le travail attend que des sessions en cours en libèrent. Accepte des tailles comme `2g` ou `1536m`. Sans effet sous Kubernetes ou avec un daemon Docker distant. | | `SANDBOX_MIN_FREE_DISK` | un vingtième de chaque disque, au moins `2g`, au plus `20g` | Espace libre requis pour les sessions nouvelles et réactivées sur le système de fichiers des espaces de travail et celui, vérifié, des données Docker. Sous ce seuil, le travail attend ; les caches de build arrêtés et inutilisés sont supprimés en premier. Accepte `10g` ou `4096m` ; `0` désactive le contrôle. Kubernetes dépend de sa classe de stockage et du provisionnement des volumes. | +| `SANDBOX_CRITICAL_FREE_DISK` | un quart du seuil `SANDBOX_MIN_FREE_DISK`, au moins `1g` et jamais au-dessus | Espace libre sous lequel le disque des sessions devient critique : ce que les sessions en cours y écrivent est sur le point d’échouer. En dessous, les sessions libérées et inactives avec Docker dans la sandbox sont arrêtées aussitôt, ce qui supprime leur stockage d’images interne, et le spawner journalise les trois plus grands espaces de travail au plus toutes les dix minutes. Accepte `2g` ou `2048m` ; `0` désactive ce palier, tout comme un seuil de `0`. Backend Docker uniquement. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Types de travail autorisés à utiliser Docker dans leur sandbox, lorsque le déploiement le permet. Avec `project`, les agents de workflow démarrent sans Docker ; avec `workflow`, ce sont les agents de projet ; avec `none`, les deux. Le réglage s’applique aux nouvelles sessions ; les sessions existantes conservent leurs capacités. Une demande de session peut renoncer à Docker avec `docker: false`, mais ne peut pas dépasser cette liste ni le réglage du déploiement. | | `SANDBOX_AGENT_CPUS` | `2` | Limite de CPU par session d’agent. Tiens compte des builds simultanés et des autres tâches de l’hôte pour choisir le nombre de sessions. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | Poids CPU d’une session d’agent et des conteneurs auxiliaires du cache de build de son organisation tant que les CPU de l’hôte sont saturés, face à la valeur Docker par défaut de `1024` que gardent les services de la plateforme ; les sessions du profil `default` (exécutions de code, rendus de pages) utilisent `128`. Les sessions chargées laissent alors le CPU à la base de données et au backend au lieu de les bloquer ; sur un hôte où il reste du CPU, une session utilise toujours jusqu’à `SANDBOX_AGENT_CPUS`. Un nombre entier de `2` à `262144`. S’applique aux nouvelles sessions ; un conteneur auxiliaire en cours prend une nouvelle valeur aussitôt. | @@ -306,7 +307,7 @@ Les sessions Kubernetes utilisent `/readyz` pour le démarrage et `/livez` pour Une génération déjà active n’est pas comptée une seconde fois. Un workflow sans Docker interne garde l’identité et les outils de son agent, mais ne démarre aucun daemon Docker et ne maintient pas les conteneurs auxiliaires du cache de build en activité. Sans valeur explicite pour `SANDBOX_AGENT_MEMORY`, chaque session a une limite par défaut de `4g` sans Docker interne ou de `8g` avec Docker, même si d’autres sessions du déploiement utilisent Docker. Une valeur explicite s’applique aux deux modes. Ces limites sont des plafonds, pas de la mémoire réservée. -À pleine capacité, le spawner peut arrêter une session inactive, libérée et non épinglée avant le délai d’inactivité pour accepter un nouveau travail, en commençant par celle qui est inactive depuis le plus longtemps. Le daemon doit confirmer qu’aucun travail n’est en cours ; les sessions occupées ou dont l’état est inconnu restent protégées. L’arrêt conserve le répertoire ou le volume persistant de l’espace de travail. Sans session à récupérer en toute sécurité, la capacité du déploiement continue de bloquer les nouveaux démarrages. Il en va de même lorsque la mémoire libre de l’hôte passerait sous `SANDBOX_MIN_FREE_MEMORY`. Tant que le disque qui contient les espaces de travail des sessions reste sous `SANDBOX_MIN_FREE_DISK`, le nouveau travail attend sans que des sessions inactives soient arrêtées : une session arrêtée garde son espace de travail. +À pleine capacité, le spawner peut arrêter une session inactive, libérée et non épinglée avant le délai d’inactivité pour accepter un nouveau travail, en commençant par celle qui est inactive depuis le plus longtemps. Le daemon doit confirmer qu’aucun travail n’est en cours ; les sessions occupées ou dont l’état est inconnu restent protégées. L’arrêt conserve le répertoire ou le volume persistant de l’espace de travail. Sans session à récupérer en toute sécurité, la capacité du déploiement continue de bloquer les nouveaux démarrages. Il en va de même lorsque la mémoire libre de l’hôte passerait sous `SANDBOX_MIN_FREE_MEMORY`. Tant que le disque qui contient les espaces de travail des sessions reste sous `SANDBOX_MIN_FREE_DISK`, le nouveau travail attend sans que des sessions inactives soient arrêtées : une session arrêtée garde son espace de travail. Ce n’est que sous `SANDBOX_CRITICAL_FREE_DISK` que le spawner arrête aussitôt les sessions libérées et inactives avec Docker dans la sandbox, car leur arrêt supprime leur stockage d’images interne. Les enregistrements du protocole des environnements d’agent, y compris les lignes inachevées, sont limités à 8 Mio. Une sortie trop volumineuse ou incomplète provoque un échec explicite ; l’aperçu de progression borné n’est jamais considéré comme un résultat structuré complet. Les réponses finales complètes sont conservées séparément de cet aperçu. diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 51b48ab4a2..1e26cdf4f0 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -501,6 +501,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [settings](../suites/settings.md) | Authoritative sandbox quota save boundary | ✅ automated | `backend/domains/governance/routes.test.ts` (exact-capacity acceptance, over-capacity and unavailable-capacity rejection before audit/file writes, forged total ignored, deployment capacity reread at each save, invalid-field and role boundaries) | | [settings](../suites/settings.md) | Memory-aware admission: on a Docker host whose memory the spawner can read, a create that would leave less than `SANDBOX_MIN_FREE_MEMORY` free (creates still starting counted at their working set, sessions that just started at what they are still growing into, a destroyed one at nothing) reclaims a released idle session or answers 429 `host_memory`, a burst admits exactly what fits, unknown memory never refuses; the reading is refreshed every second and concurrent reads share one; a Docker CLI that could not answer is asked again within a minute, a host once verified keeping its verdict meanwhile; an unset `SANDBOX_MAX_SESSIONS` is sized from host memory (8–256, a whole Docker-in-sandbox turn per slot where agent sessions run Docker inside); at most 12 Docker CLI processes run at once, and a call that waits past its budget for a slot answers as a timeout; short calls (the health probe, identity and liveness inspects, the build helper and host memory checks) take a free shared slot or one of 4 kept for them and never queue behind long calls, and a health probe that found no slot answers unhealthy without caching it | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`memory-aware admission`), `services/sandbox/src/host-memory.test.ts`, `services/sandbox/src/spawn-util.test.ts` (`docker CLI concurrency`), `services/sandbox/src/health-probe.test.ts`, `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (`short docker calls beside a burst`) | | [settings](../suites/settings.md) | Disk-aware admission: on the Docker backend, while the disk the session workspaces live on has less than `SANDBOX_MIN_FREE_DISK` free (a twentieth of it, between 2 and 20 GiB; `0` turns it off), every create answers 429 `host_disk` in the first-come line without stopping an idle session, and gets in once space is freed; an unknown or unreadable disk never refuses; the probe reads it with `statfs` every five seconds and logs the disk going below its floor and coming back once each; meanwhile each build-cache upkeep removes the helpers and caches of organizations whose helpers are all stopped and that no session or create may use, the longest-stopped first, at most three a run and only while the disk stays short, and a removal that frees nothing on that disk pauses the removals for six hours | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`disk-aware admission`), `services/sandbox/src/host-disk.test.ts`, `services/sandbox/src/buildkit-lifecycle.test.ts` (`a session disk below its floor`), `services/sandbox/src/config.test.ts` | +| [settings](../suites/settings.md) | The session disk's critical tier: below `SANDBOX_CRITICAL_FREE_DISK` (a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least 1 GiB and never above it; `0`, or a floor of `0`, turns it off), read from the same five-second reading, the sweep stops a released idle Docker-in-sandbox session at once through runnerd's claim instead of after its full idle window, never one a turn holds, and logs the three largest workspaces — one niced `du` of every workspace dir, cut off after 30 s, a session's flat and legacy copies counted together — at most every ten minutes; the disk going below the tier and coming back is logged once each; an unknown or unreadable disk is never critical | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`below its critical tier, the sweep stops a released Docker-in-sandbox session at once`, `an unknown disk, or a critical tier of 0, stops nothing for the disk`), `services/sandbox/src/host-disk.test.ts` (`diskCriticalBytes`), `services/sandbox/src/session/workspace-usage.test.ts`, `services/sandbox/src/config.test.ts` | | [settings](../suites/settings.md) | The first-come line for host room: a create refused for room waits by session id in the order of its first refusal; freed room goes to the oldest waiters still asking (a slot each, and memory for their working sets, before a newer create — none for a waiter the host could never fit); each 429 carries `queue: { position, waiting }` and a `retry-after` of 5 s plus 5 s a place, up to 60 s; asking again keeps a waiter's place, one that stops asking gives it up after twice its hint and 15 s, a destroy takes it out, and a restart starts with no line | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`the first-come line for host room`, and the capacity and memory admission tests) | | [settings](../suites/settings.md) | Idle sandbox reclamation under deployment capacity pressure | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (released compute reclaimed before admission, persistent workspace retained, busy/pinned/unknown/legacy runtime protection, delayed release after reacquire, concurrent creates and stop failure); `services/sandbox-runtime/daemon/src/activity-gate.test.ts` (atomic idle claim, active-operation protection and frozen execution gate); `services/sandbox/src/backend/docker/docker-session-backend.test.ts`, `backend/kubernetes/k8s-session-backend.test.ts` (incarnation-fenced compute removal and retained workspace); `backend/domains/sandbox/idle-release.test.ts` (ticket capture, transactional queueing and committed-state checks), `idle-release.integration.ts` (28 real-Postgres checks: organization/allocation/owner guards, admission and release ordering, atomic cancellation and release-job rollback, post-op retry on an already-stopped workflow); `backend/core/node_only/sandbox/agent_session.test.ts` (`ensureAgentSession` refuses a false allocation resume before acquiring runtime compute) | | [settings](../suites/settings.md) | The session sweep frees what nothing uses: a released session stops after the short idle window (Docker-in-sandbox agent sessions keep the full one once their inner engine has run, as runnerd's `/healthz` `docker.used` says; one whose engine never started gets the short window, and a runtime that does not report its engine keeps the full one), a running session whose daemon has not answered five sweeps is stopped (a sweep that cannot probe it starts the count over), ended containers and Pods are removed by their incarnation with the workspace kept, beside the API and several at a time, a create of the id waits for that removal (bounded) and a session registered under the id is neither held up by it nor counted as freed by it, a pass still running is joined, a burst of creates at capacity reclaims one released session each, idle-longest first, a create refused at capacity probes at most eight daemons, sessions last seen released first, and none that answered busy (to a reclaim probe or the sweep) or was acquired within 15 s unless released since, and the refusals in the 3 s after a walk that found nothing are answered at once, the build-cache reconcile after adoption covers agent sessions without holding adoption up, a slow build-cache job never holds the next pass's sweep up (one job at a time, organizations adopted meanwhile reconciled right after it), and a caller hanging up on an attach costs no backend check | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`sweep and adoption hygiene`, `creates refused at capacity do not probe every busy session`), `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (a failed inner image volume removal is reported) | diff --git a/services/sandbox/README.md b/services/sandbox/README.md index 9a7d0e80e8..60bb50b12f 100644 --- a/services/sandbox/README.md +++ b/services/sandbox/README.md @@ -101,7 +101,12 @@ cap already-running writers; hard per-volume quotas require operator provisioning (docs/docker-in-container.md). Below either observed filesystem's floor every create answers 429 `host_disk`, and the build-cache upkeep removes the caches of organizations whose helpers are all stopped, the -longest-stopped first. Creates refused for room wait in a +longest-stopped first. Below its critical tier (`SANDBOX_CRITICAL_FREE_DISK`, +a quarter of the floor, at least 1 GiB; `0` turns it off), where running +sessions' writes are about to fail, the sweep also stops released idle +Docker-in-sandbox sessions at once, which removes their inner image stores, +and logs the three largest workspaces at most every ten minutes. Creates +refused for room wait in a first-come line: freed room goes to the oldest waiter still asking, and each 429 names the create's place (`queue: { position, waiting }`) with a `retry-after` for when it comes up (docs/sessions.md). At most 12 Docker CLI processes run at diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index 4e13dcc46b..c359f7de67 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -569,6 +569,22 @@ live on another one) pauses the removals for six hours. If a different filesystem becomes the most constrained after removal, upkeep stops that pass and reassesses next sweep instead of comparing free bytes across disks. +The floor holds new work back; it does not stop what already runs, which +writes until the disk is full, and with it the replay journal of every running +exec. So the disk also has a critical tier, below which those writes are about +to fail: `SANDBOX_CRITICAL_FREE_DISK`, unset a quarter of the floor, at least +1 GiB and never above the floor (`0` turns it off, and so does a floor of +`0`). The sweep reads it from the same five-second reading, and an unknown or +unreadable disk is never critical. While the disk is below it, the sweep +stops a released, idle Docker-in-sandbox session at once instead of after its +full idle window — through runnerd's claim like every idle stop, so a turn +that acquires it meanwhile keeps it — because its stop removes its inner image +store, the most a stop gives back. It also logs the three largest workspaces, +measured by one `du` of every workspace dir at the lowest CPU priority (and so +the lowest best-effort I/O priority) and cut off after 30 seconds, at most +every ten minutes. The spawner logs the disk going below the tier and coming +back. + The Docker observation reuses the spawner's existing `/etc/hostname` bind. Its full container identity and source path must agree with the selected daemon's container inspection and data-root, which bounded Docker metadata diff --git a/services/sandbox/src/backend/docker/docker-session-backend.ts b/services/sandbox/src/backend/docker/docker-session-backend.ts index 4ed7e7dbd4..df2a9e3152 100644 --- a/services/sandbox/src/backend/docker/docker-session-backend.ts +++ b/services/sandbox/src/backend/docker/docker-session-backend.ts @@ -72,6 +72,10 @@ import { workspaceTrash, type WorkspaceTrash, } from '../../session/workspace-trash.ts'; +import { + largestWorkspaces, + type LargestWorkspaces, +} from '../../session/workspace-usage.ts'; import { dockerRm, dockerRmSucceeded, @@ -1413,6 +1417,12 @@ export class DockerSessionBackend implements SessionBackend { * label, or else the workspace's own marker. `listSessions` THROWS on a * failed `docker ps`, so a container that merely could not be listed never * reads as inactive. */ + /** One bounded, lowest-priority `du` over every workspace dir under the + * session root (workspace-usage.ts). */ + largestWorkspaces(limit: number): Promise { + return largestWorkspaces(this.cfg.hostSessionRoot, { limit }); + } + async listWorkspaces(): Promise { const dirs = await listWorkspaceDirs(this.cfg.hostSessionRoot); const containers = new Map( diff --git a/services/sandbox/src/backend/types.ts b/services/sandbox/src/backend/types.ts index c2a7786ee9..027734dc1f 100644 --- a/services/sandbox/src/backend/types.ts +++ b/services/sandbox/src/backend/types.ts @@ -6,6 +6,7 @@ // chosen once at boot from `SANDBOX_BACKEND` (see backend/index.ts). import type { SessionDiskState } from '../host-disk.ts'; +import type { LargestWorkspaces } from '../session/workspace-usage.ts'; import type { SpawnerConfig } from '../types.ts'; import type { SandboxSessionProfile, SandboxSessionState } from '../wire.ts'; @@ -357,6 +358,14 @@ export interface SessionBackend { * containers/Pods beside them cannot be listed at all. */ listWorkspaces(): Promise; + /** + * The `limit` largest workspaces this backend holds, measured now, for the + * log of a session disk below its critical tier. Bounded in time: what was + * measured by the deadline is answered, with how much that was. THROWS + * when the workspaces cannot be listed. Absent where the spawner does not + * hold the workspaces' disk (Kubernetes). + */ + largestWorkspaces?(limit: number): Promise; /** * The organizations holding resources beyond their sessions' workspaces * (Docker: the organization's build helpers, their network and cache diff --git a/services/sandbox/src/config.test.ts b/services/sandbox/src/config.test.ts index 5b1c02fc8a..6e5cdb6503 100644 --- a/services/sandbox/src/config.test.ts +++ b/services/sandbox/src/config.test.ts @@ -42,6 +42,7 @@ const KEYS = [ 'SANDBOX_BUILDKITD_CACHE_RETENTION', 'SANDBOX_PACKAGE_CACHE_RETENTION', 'SANDBOX_MIN_FREE_DISK', + 'SANDBOX_CRITICAL_FREE_DISK', 'TALE_PLATFORM_SHARED_CONFIG_DIR', ] as const; @@ -334,6 +335,17 @@ test('the free space kept on the session disk is optional and validated', () => expect(() => loadConfig()).toThrow(/SANDBOX_MIN_FREE_DISK/); }); +test('the critical tier of the session disk is optional and validated', () => { + expect(loadConfig().session).not.toHaveProperty('criticalFreeDiskBytes'); + process.env.SANDBOX_CRITICAL_FREE_DISK = '3g'; + expect(loadConfig().session.criticalFreeDiskBytes).toBe(3 * 1024 ** 3); + // 0 turns the tier off. + process.env.SANDBOX_CRITICAL_FREE_DISK = '0'; + expect(loadConfig().session.criticalFreeDiskBytes).toBe(0); + process.env.SANDBOX_CRITICAL_FREE_DISK = 'soon'; + expect(() => loadConfig()).toThrow(/SANDBOX_CRITICAL_FREE_DISK/); +}); + test('how long stopped build caches are kept is optional and validated', () => { expect(loadConfig()).not.toHaveProperty('buildkitdCacheRetentionMs'); const hour = 60 * 60 * 1000; diff --git a/services/sandbox/src/config.ts b/services/sandbox/src/config.ts index 16f30c6347..39b036d528 100644 --- a/services/sandbox/src/config.ts +++ b/services/sandbox/src/config.ts @@ -548,6 +548,7 @@ export function loadConfig(): SpawnerConfig { ); const minFreeMemoryBytes = sizeEnv('SANDBOX_MIN_FREE_MEMORY'); const minFreeDiskBytes = sizeEnv('SANDBOX_MIN_FREE_DISK'); + const criticalFreeDiskBytes = sizeEnv('SANDBOX_CRITICAL_FREE_DISK'); const buildkitdMemoryBytes = sizeEnv('SANDBOX_BUILDKITD_MEMORY'); const buildkitdIdleCacheBytes = sizeEnv('SANDBOX_BUILDKITD_IDLE_CACHE'); const buildkitdCacheRetentionMs = retentionEnv( @@ -885,6 +886,7 @@ export function loadConfig(): SpawnerConfig { autoMaxSessions: (process.env.SANDBOX_MAX_SESSIONS ?? '').trim() === '', ...(minFreeMemoryBytes !== undefined ? { minFreeMemoryBytes } : {}), ...(minFreeDiskBytes !== undefined ? { minFreeDiskBytes } : {}), + ...(criticalFreeDiskBytes !== undefined ? { criticalFreeDiskBytes } : {}), maxLifetimeMs: numEnv( 'SANDBOX_SESSION_MAX_LIFETIME_MS', 24 * 60 * 60 * 1000, diff --git a/services/sandbox/src/host-disk.test.ts b/services/sandbox/src/host-disk.test.ts index fea55b337e..0155d4fe03 100644 --- a/services/sandbox/src/host-disk.test.ts +++ b/services/sandbox/src/host-disk.test.ts @@ -1,7 +1,9 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { + belowDiskCritical, belowDiskFloor, + diskCriticalBytes, diskReserveBytes, DockerDataRootMount, HostDiskProbe, @@ -35,6 +37,51 @@ describe('diskReserveBytes', () => { }); }); +describe('diskCriticalBytes', () => { + test('a quarter of the floor, at least 1 GiB and never above the floor', () => { + // Floors of 2, 5 and 20 GiB. + expect(diskCriticalBytes(20 * GIB)).toBe(GIB); + expect(diskCriticalBytes(100 * GIB)).toBe(1.25 * GIB); + expect(diskCriticalBytes(4096 * GIB)).toBe(5 * GIB); + expect(diskCriticalBytes(100 * GIB, 40 * GIB)).toBe(10 * GIB); + expect(diskCriticalBytes(100 * GIB, GIB / 2)).toBe(GIB / 2); + }); + + test('an operator’s tier stands as given, 0 turning it off; none while the floor is off', () => { + expect(diskCriticalBytes(100 * GIB, undefined, 3 * GIB)).toBe(3 * GIB); + expect(diskCriticalBytes(100 * GIB, undefined, 0)).toBe(0); + expect(diskCriticalBytes(100 * GIB, 0)).toBe(0); + expect( + belowDiskCritical({ totalBytes: 100 * GIB, availableBytes: 0 }, 0), + ).toBe(false); + expect( + belowDiskCritical( + { totalBytes: 100 * GIB, availableBytes: 2 * GIB }, + undefined, + 3 * GIB, + ), + ).toBe(true); + }); + + test('an unknown or unreadable disk is never critical', () => { + expect(belowDiskCritical(null)).toBe(false); + expect( + belowDiskCritical({ + totalBytes: 0, + availableBytes: 0, + unavailable: true, + }), + ).toBe(false); + // Below the 5 GiB floor of a 100 GiB disk, above its 1.25 GiB tier. + expect( + belowDiskCritical({ totalBytes: 100 * GIB, availableBytes: 2 * GIB }), + ).toBe(false); + expect( + belowDiskCritical({ totalBytes: 100 * GIB, availableBytes: GIB }), + ).toBe(true); + }); +}); + describe('HostDiskProbe', () => { let logs: string[]; const log = console.log; diff --git a/services/sandbox/src/host-disk.ts b/services/sandbox/src/host-disk.ts index 8d4828eecf..83e2cb045a 100644 --- a/services/sandbox/src/host-disk.ts +++ b/services/sandbox/src/host-disk.ts @@ -64,6 +64,38 @@ export function belowDiskFloor( ); } +/** The free space below which the session disk is critical: what running + * sessions still write there is about to fail, and with it the replay + * journal of every running exec. The operator's (0 turns the tier off), else + * a quarter of the floor, at least 1 GiB and never above the floor; none + * while the floor is off. */ +export function diskCriticalBytes( + totalBytes: number, + configuredFloorBytes?: number, + configuredBytes?: number, +): number { + if (configuredBytes !== undefined) return configuredBytes; + if (configuredFloorBytes === 0) return 0; + const floor = diskReserveBytes(totalBytes, configuredFloorBytes); + return Math.min(floor, Math.max(GIB, Math.floor(floor / 4))); +} + +/** Whether a reading is below the critical tier. An unknown disk, and one + * whose reading is a placeholder, never is: the tier acts on what it read. */ +export function belowDiskCritical( + disk: HostDisk | null, + configuredFloorBytes?: number, + configuredBytes?: number, +): boolean { + if (disk === null || disk.unavailable === true) return false; + const critical = diskCriticalBytes( + disk.totalBytes, + configuredFloorBytes, + configuredBytes, + ); + return critical > 0 && disk.availableBytes < critical; +} + /** A reading may be reused this long: disk fills over minutes, not * milliseconds, and the probe refreshes it at this pace. */ const READING_TTL_MS = 5_000; diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index 3820725445..67b8789980 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -6726,6 +6726,131 @@ describe('disk-aware admission', () => { { availableBytes: 8 * GIB, short: false }, ]); }); + + /** Two Docker-in-sandbox sessions, one of them released by its platform + * and active a moment ago. */ + async function releasedDockerSessions(routes: SessionRoutes): Promise { + for (const id of ['dind-released', 'dind-held']) + expect((await create(routes, id)).status).toBe(201); + const ticket: unknown = await ( + await routes.handleActivity('dind-released', 'ticket') + ).json(); + await routes.handleActivity( + 'dind-released', + 'release', + JSON.stringify(ticket), + ); + fakeHealth.lastActivityAtMs = Date.now(); + } + + test('below its critical tier, the sweep stops a released Docker-in-sandbox session at once and logs the largest workspaces at most every ten minutes', async () => { + let available = 50; + const measured: number[] = []; + const warnings: string[] = []; + const warn = spyOn(console, 'warn').mockImplementation( + (...args: unknown[]) => { + warnings.push(args.map(String).join(' ')); + }, + ); + const routes = new SessionRoutes( + { ...cfg, dockerInContainer: true }, + { + ...fakeBackend, + async largestWorkspaces(limit) { + measured.push(limit); + return { + largest: [ + { sessionId: 'big', bytes: 12 * GIB }, + { sessionId: 'dind-held', bytes: 3 * GIB }, + ], + measured: 2, + total: 3, + }; + }, + }, + undefined, + undefined, + disk(() => available), + ); + try { + await releasedDockerSessions(routes); + // Below the 5 GiB floor, above the 1.25 GiB tier: the released session + // keeps its full idle window, and nothing is measured. + available = 4; + expect(await routes.sweepExpired()).toBe(0); + expect(measured).toEqual([]); + available = 1; + expect(await routes.sweepExpired()).toBe(1); + expect(stopped.has('dind-released')).toBe(true); + // Held by its turn: never stopped for the disk. + expect(stopped.has('dind-held')).toBe(false); + expect(reclaimRequests).toHaveLength(1); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(measured).toEqual([3]); + expect( + warnings.filter((line) => line.includes('below its critical 1.3 GiB')), + ).toHaveLength(1); + expect(warnings).toContain( + '[sandbox.session] the session disk is critical; its largest workspaces: big 12.0 GiB, dind-held 3.0 GiB (2 of 3 workspaces measured in time)', + ); + // Still critical a sweep later: said and measured once. + expect(await routes.sweepExpired()).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(measured).toEqual([3]); + expect( + warnings.filter((line) => line.includes('below its critical')), + ).toHaveLength(1); + } finally { + warn.mockRestore(); + } + }); + + test('an unknown disk, or a critical tier of 0, stops nothing for the disk', async () => { + const off = { + ...cfg, + dockerInContainer: true, + session: { ...cfg.session, criticalFreeDiskBytes: 0 }, + }; + let measured = 0; + const backend = { + ...fakeBackend, + async largestWorkspaces() { + measured += 1; + return { largest: [], measured: 0, total: 0 }; + }, + }; + let available: number | null = 50; + const reading = () => + available === null + ? null + : { totalBytes: 100 * GIB, availableBytes: available * GIB }; + const source = { + latest: reading, + read: () => Promise.resolve(reading()), + }; + for (const [routes, after] of [ + [new SessionRoutes(off, backend, undefined, undefined, source), 1], + [ + new SessionRoutes( + { ...cfg, dockerInContainer: true }, + backend, + undefined, + undefined, + source, + ), + null, + ], + ] as const) { + available = 50; + await releasedDockerSessions(routes); + available = after; + expect(await routes.sweepExpired()).toBe(0); + expect(stopped.has('dind-released')).toBe(false); + await routes.handleDestroy('dind-released'); + await routes.handleDestroy('dind-held'); + } + expect(measured).toBe(0); + }); }); describe('settlesWithin', () => { diff --git a/services/sandbox/src/session/session-routes.ts b/services/sandbox/src/session/session-routes.ts index 57c7e3421a..3c5c25fff6 100644 --- a/services/sandbox/src/session/session-routes.ts +++ b/services/sandbox/src/session/session-routes.ts @@ -13,7 +13,9 @@ import { } from '../backend/types.ts'; import { reportSandboxError } from '../error-reporting.ts'; import { + belowDiskCritical, belowDiskFloor, + diskCriticalBytes, type HostDiskSource, type SessionDiskState, } from '../host-disk.ts'; @@ -69,6 +71,7 @@ import { validateCreateSession, validateExecSession, } from './validate-session.ts'; +import type { LargestWorkspaces } from './workspace-usage.ts'; function b64decode(b64: string): Uint8Array { return new Uint8Array(Buffer.from(b64, 'base64')); @@ -163,6 +166,12 @@ const BUSY_DOCKER_STOP_GRACE_MS = 20_000; * docker CLI slot for up to its grace, and the rest stay for the others. */ const LINGER_STOP_CONCURRENCY = 4; +/** While the session disk is critical, its largest workspaces are logged at + * most this often (each measurement is a bounded `du` of every workspace). */ +const WORKSPACE_USAGE_LOG_MS = 10 * 60_000; +const WORKSPACES_LOGGED = 3; +const GIB = 1024 ** 3; + /** How long a session that just started keeps part of its planned working * set reserved at admission: its turn is still growing toward it while * MemAvailable shows only the idle footprint. The reservation shrinks @@ -367,6 +376,11 @@ export class SessionRoutes { // Until when a create at capacity skips the reclaim walk: the last walk // found nothing (RECLAIM_NOTHING_FOR_MS). private nothingToReclaimUntilMs = 0; + // The session disk's critical state as the last sweep saw it, so each + // change is logged once; and the measurement of its largest workspaces. + private diskWasCritical = false; + private workspaceUsageAtMs = Number.NEGATIVE_INFINITY; + private workspaceUsage: Promise | null = null; // Settles when the destroy of that id is done (success or failure): // destroys of one id run one after another, and a create of the id waits // for the one under way instead of racing its workspace removal. @@ -718,6 +732,86 @@ export class SessionRoutes { } } + /** Is the disk the workspaces live on below its critical tier (the probe's + * last reading)? An unknown disk never is. Each change is logged once. */ + private diskCritical(): boolean { + let disk; + try { + disk = this.hostDisk.latest(); + } catch (error) { + console.warn('[sandbox.session] session disk unreadable:', error); + return false; + } + const { minFreeDiskBytes, criticalFreeDiskBytes } = this.cfg.session; + const critical = belowDiskCritical( + disk, + minFreeDiskBytes, + criticalFreeDiskBytes, + ); + if (critical !== this.diskWasCritical && disk !== null) { + this.diskWasCritical = critical; + const free = `${(disk.availableBytes / GIB).toFixed(1)} GiB`; + const tier = `${(diskCriticalBytes(disk.totalBytes, minFreeDiskBytes, criticalFreeDiskBytes) / GIB).toFixed(1)} GiB`; + if (critical) { + console.warn( + `[sandbox.session] the session disk has ${free} free, below its critical ${tier}: running sessions are about to fail their writes; released Docker-in-sandbox sessions stop now and the largest workspaces are logged (SANDBOX_CRITICAL_FREE_DISK)`, + ); + } else { + console.log( + `[sandbox.session] the session disk has ${free} free again, above its critical ${tier}`, + ); + } + } + return critical; + } + + /** Log the largest workspaces of a critical session disk: at most every + * {@link WORKSPACE_USAGE_LOG_MS}, one measurement at a time, beside the + * sweep rather than in its way. */ + private logLargestWorkspaces(): void { + const now = Date.now(); + if ( + this.workspaceUsage !== null || + now - this.workspaceUsageAtMs < WORKSPACE_USAGE_LOG_MS + ) + return; + const measuring = this.backend.largestWorkspaces?.(WORKSPACES_LOGGED); + if (measuring === undefined) return; + this.workspaceUsageAtMs = now; + this.workspaceUsage = this.sayLargestWorkspaces(measuring).finally(() => { + this.workspaceUsage = null; + }); + } + + private async sayLargestWorkspaces( + measuring: Promise, + ): Promise { + let usage: LargestWorkspaces; + try { + usage = await measuring; + } catch (error) { + console.warn( + '[sandbox.session] measuring the largest workspaces failed:', + error, + ); + return; + } + const { largest, measured, total } = usage; + if (largest.length === 0) return; + const sizes = largest + .map( + (entry) => `${entry.sessionId} ${(entry.bytes / GIB).toFixed(1)} GiB`, + ) + .join(', '); + const partial = + measured < total + ? ` (${measured} of ${total} workspaces measured in time)` + : ''; + console.warn( + `[sandbox.session] the session disk is critical; its largest workspaces: ${sizes}${partial}`, + ); + } + /** The disk read now, for upkeep that frees space on it and goes on only * while it is still short. */ private async sessionDiskNow(): Promise { @@ -1565,11 +1659,13 @@ export class SessionRoutes { */ async sweepExpired(nowMs: number = Date.now()): Promise { let reaped = 0; + const diskCritical = this.diskCritical(); + if (diskCritical) this.logLargestWorkspaces(); await forEachLimited( this.registry.list(), SWEEP_CONCURRENCY, async (session) => { - if (await this.sweepSession(session, nowMs)) reaped += 1; + if (await this.sweepSession(session, nowMs, diskCritical)) reaped += 1; }, ); // The build helpers follow the sessions just stopped, beside the sweep @@ -1613,6 +1709,7 @@ export class SessionRoutes { private async sweepSession( s: RegistrySession, nowMs: number, + diskCritical = false, ): Promise { if (this.reclaimClaims.has(s.sessionId)) return this.reclaimIdle(s); // Pinned ("always-on") sessions are exempt from BOTH idle and TTL reap. @@ -1690,12 +1787,18 @@ export class SessionRoutes { } // Released by the platform (its turn or run settled, nothing holds it): // a few idle minutes are enough. The stop goes through runnerd's - // claim, so a turn that acquires the session meanwhile keeps it. + // claim, so a turn that acquires the session meanwhile keeps it. On a + // critical session disk a released Docker-in-sandbox session goes at + // once: its stop removes its inner image store, the most a stop gives + // back, and its resume's re-pull costs less than the writes of every + // running session failing. if ( !expired && health.activity?.released === true && - !this.keepsFullIdleWindow(s, health) && - idleForMs > Math.min(this.cfg.session.releasedIdleMs, s.idleTimeoutMs) + ((diskCritical && (s.docker ?? this.cfg.dockerInContainer)) || + (!this.keepsFullIdleWindow(s, health) && + idleForMs > + Math.min(this.cfg.session.releasedIdleMs, s.idleTimeoutMs))) ) { return this.reclaimIdle(s); } diff --git a/services/sandbox/src/session/workspace-inventory.ts b/services/sandbox/src/session/workspace-inventory.ts index de475ab59a..a3524fc99a 100644 --- a/services/sandbox/src/session/workspace-inventory.ts +++ b/services/sandbox/src/session/workspace-inventory.ts @@ -119,6 +119,15 @@ async function readWorkspaceDirs( return found; } +/** Every workspace dir under `root`, with the session it belongs to: a + * session with copies in both layouts is listed once per copy. Dirs below the + * root that cannot be read are left out (logged); an unreadable root THROWS. */ +export function listWorkspacePaths( + root: string, +): Promise> { + return readWorkspaceDirs(root, false); +} + /** Every directory of one session, including copies left in legacy roots. * THROWS on an unreadable root instead of hiding data from its destroy. */ export async function listSessionWorkspaceDirs( diff --git a/services/sandbox/src/session/workspace-usage.test.ts b/services/sandbox/src/session/workspace-usage.test.ts new file mode 100644 index 0000000000..1a4366d8b8 --- /dev/null +++ b/services/sandbox/src/session/workspace-usage.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { randomBytes } from 'node:crypto'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { largestWorkspaces } from './workspace-usage.ts'; + +const MIB = 1024 * 1024; + +let root = ''; + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'tale-workspace-usage-')); +}); + +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +/** A workspace dir holding `mib` MiB of incompressible bytes. */ +async function workspace(path: string, mib: number): Promise { + await mkdir(path, { recursive: true }); + await writeFile(join(path, 'data.bin'), randomBytes(mib * MIB)); +} + +describe('largestWorkspaces', () => { + test('names the largest workspaces with du, a session’s copies in both layouts together', async () => { + await workspace(join(root, 'ses-big'), 8); + await workspace(join(root, 'ses-split'), 3); + await workspace(join(root, 'blue', 'ses-split'), 3); + await workspace(join(root, 'ses-mid'), 4); + await workspace(join(root, 'ses-small'), 1); + // Not workspaces: the trash, a file. + await workspace(join(root, '.trash', 'ses-gone.1'), 16); + await writeFile(join(root, 'spawner.lock'), 'x'); + + const usage = await largestWorkspaces(root); + expect(usage.total).toBe(5); + expect(usage.measured).toBe(5); + expect(usage.largest.map((entry) => entry.sessionId)).toEqual([ + 'big', + 'split', + 'mid', + ]); + expect(usage.largest[0]?.bytes).toBeGreaterThanOrEqual(8 * MIB); + expect(usage.largest[1]?.bytes).toBeGreaterThanOrEqual(6 * MIB); + }); + + test('reports what du measured before its deadline', async () => { + await mkdir(join(root, 'ses-first')); + await mkdir(join(root, 'ses-second')); + let deadline: AbortSignal | undefined; + const usage = await largestWorkspaces( + root, + { timeoutMs: 20 }, + { + du: async (paths, signal) => { + deadline = signal; + await new Promise((resolve) => + signal.addEventListener('abort', resolve, { once: true }), + ); + return `2048\t${paths.find((path) => path.endsWith('ses-second'))}\n`; + }, + }, + ); + expect(deadline?.aborted).toBe(true); + expect(usage).toEqual({ + largest: [{ sessionId: 'second', bytes: 2048 * 1024 }], + measured: 1, + total: 2, + }); + }); + + test('an empty session root runs no du', async () => { + let ran = false; + const usage = await largestWorkspaces( + root, + {}, + { + du: async () => { + ran = true; + return ''; + }, + }, + ); + expect(ran).toBe(false); + expect(usage).toEqual({ largest: [], measured: 0, total: 0 }); + }); +}); diff --git a/services/sandbox/src/session/workspace-usage.ts b/services/sandbox/src/session/workspace-usage.ts new file mode 100644 index 0000000000..d21271a049 --- /dev/null +++ b/services/sandbox/src/session/workspace-usage.ts @@ -0,0 +1,85 @@ +// How much the largest session workspaces hold, for the operator of a session +// disk that is about to run out: which sessions are filling it is the first +// thing to know, and nothing else on the host says it. +// +// One `du` measures every workspace dir under the session root, at the +// lowest CPU priority — which also gives it the lowest best-effort I/O +// priority, the kernel's default for a niced process — and only for so long: +// a disk this full is usually a busy one, and a workspace can hold millions +// of files. Whatever it measured by the deadline is reported, marked as +// incomplete. + +import { listWorkspacePaths } from './workspace-inventory.ts'; + +export interface WorkspaceUsage { + sessionId: string; + bytes: number; +} + +export interface LargestWorkspaces { + /** Largest first, at most the limit asked for. */ + largest: WorkspaceUsage[]; + /** Workspace dirs measured, of `total` found. */ + measured: number; + total: number; +} + +export interface WorkspaceUsageDeps { + /** Run `du` over the paths and resolve with what it printed until it + * ended or the signal stopped it. */ + du?: (paths: string[], signal: AbortSignal) => Promise; + listPaths?: typeof listWorkspacePaths; +} + +/** How long one measurement may take. */ +export const WORKSPACE_USAGE_TIMEOUT_MS = 30_000; + +async function runDu(paths: string[], signal: AbortSignal): Promise { + // `-x`: a workspace never spans filesystems, and a mount inside one is not + // what fills the session disk. + const proc = Bun.spawn( + ['nice', '-n', '19', 'du', '-s', '-k', '-x', '--', ...paths], + { stdout: 'pipe', stderr: 'ignore' }, + ); + const stop = () => proc.kill(); + signal.addEventListener('abort', stop, { once: true }); + try { + return await new Response(proc.stdout).text(); + } finally { + signal.removeEventListener('abort', stop); + await proc.exited; + } +} + +/** The `limit` largest workspaces under `root`, as far as one `du` measured + * them within `timeoutMs`. THROWS when the root cannot be read. */ +export async function largestWorkspaces( + root: string, + { limit = 3, timeoutMs = WORKSPACE_USAGE_TIMEOUT_MS } = {}, + deps: WorkspaceUsageDeps = {}, +): Promise { + const dirs = await (deps.listPaths ?? listWorkspacePaths)(root); + if (dirs.length === 0) return { largest: [], measured: 0, total: 0 }; + const sessionOf = new Map(dirs.map((dir) => [dir.path, dir.sessionId])); + const output = await (deps.du ?? runDu)( + dirs.map((dir) => dir.path), + AbortSignal.timeout(timeoutMs), + ); + const bytes = new Map(); + let measured = 0; + for (const line of output.split('\n')) { + const tab = line.indexOf('\t'); + if (tab <= 0) continue; + const kib = Number(line.slice(0, tab)); + const sessionId = sessionOf.get(line.slice(tab + 1)); + if (!Number.isSafeInteger(kib) || sessionId === undefined) continue; + measured += 1; + // A session with copies in both layouts holds them all. + bytes.set(sessionId, (bytes.get(sessionId) ?? 0) + kib * 1024); + } + const largest = [...bytes] + .map(([sessionId, size]) => ({ sessionId, bytes: size })) + .sort((a, b) => b.bytes - a.bytes) + .slice(0, limit); + return { largest, measured, total: dirs.length }; +} diff --git a/services/sandbox/src/types.ts b/services/sandbox/src/types.ts index 699bc08d04..05efef74ce 100644 --- a/services/sandbox/src/types.ts +++ b/services/sandbox/src/types.ts @@ -191,6 +191,11 @@ export interface SessionConfig { * (SANDBOX_MIN_FREE_DISK; 0 turns the floor off); unset is a twentieth of * each filesystem, at least 2 GiB and at most 20 GiB (host-disk.ts). */ minFreeDiskBytes?: number; + /** Free space below which that disk is critical (SANDBOX_CRITICAL_FREE_DISK; + * 0 turns the tier off): released Docker-in-sandbox sessions are stopped + * at once, and the largest workspaces are logged. Unset is a quarter of + * the floor, at least 1 GiB and never above it (host-disk.ts). */ + criticalFreeDiskBytes?: number; /** Hard wall-clock ceiling on a session's lifetime. */ maxLifetimeMs: number; /** Idle ceiling — sessions with no runnerd activity past this are reaped. */ From 050f8582e88f024e67258cf184a052d62bccb2a8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:28:07 +0200 Subject: [PATCH 03/14] fix(sandbox): name a full sandbox disk instead of a lost transcript When the disk under a session filled up, runnerd's replay journal failed its next write and ended the exec with REPLAY_UNAVAILABLE, so the turn read as a lost transcript and nobody learned the host's disk was full. The journal now maps a write the disk refuses for want of space (ENOSPC, or EDQUOT for a spent quota) to DISK_FULL, "The sandbox host ran out of disk space."; every other storage error stays REPLAY_UNAVAILABLE, and the failure still stands for every later write. exec-manager reports the journal's own code, so it needs no change. Both protocol copies accept the code, the spawner forwards it like the other terminal replay codes, as the stream's `error` code with no result, and the platform ends the drain on it without reattaching, as ExecDiskFullError: "the sandbox host ran out of disk space", in its own words rather than the payload. That is the reason the automation lane and a task's start window give; a task drive window keeps its generic "stopped unexpectedly". The reason string is not a localized message: run failure reasons are stored English text, like the replay failure it replaces. --- services/platform/backend/README.md | 6 ++- .../sandbox/helpers/session_client.test.ts | 22 +++++++++- .../sandbox/helpers/session_client.ts | 12 ++++++ .../tests/manual/reference/automation.md | 1 + services/sandbox-runtime/README.md | 3 ++ .../daemon/src/exec-replay.test.ts | 40 +++++++++++++++++++ .../sandbox-runtime/daemon/src/exec-replay.ts | 23 ++++++++--- .../sandbox-runtime/daemon/src/protocol.ts | 6 ++- services/sandbox/docs/sessions.md | 7 +++- .../src/session/runnerd-client.test.ts | 2 +- .../sandbox/src/session/runnerd-client.ts | 7 +++- .../src/session/runnerd-protocol.test.ts | 2 + .../sandbox/src/session/runnerd-protocol.ts | 6 ++- .../src/session/session-routes.test.ts | 35 ++++++++++++++++ 14 files changed, 156 insertions(+), 16 deletions(-) diff --git a/services/platform/backend/README.md b/services/platform/backend/README.md index 0be81f65e9..1e56e8cdec 100644 --- a/services/platform/backend/README.md +++ b/services/platform/backend/README.md @@ -293,8 +293,10 @@ timeline snapshot. Slow storage therefore drops superseded progress snapshots without retaining a growing promise chain. Drain windows rebuild bounded UI projections from the runtime journal, publishing resumed progress only after replay catches up. Missing journal history is an explicit `REPLAY_UNAVAILABLE` -failure, and output beyond the journal budget fails with `OUTPUT_LIMIT`; -neither can be booked as a successful turn with incomplete usage or tools. +failure, output beyond the journal budget fails with `OUTPUT_LIMIT`, and a +journal the sandbox host's full disk refused fails with `DISK_FULL`, read as +"the sandbox host ran out of disk space" (`ExecDiskFullError`); none can be +booked as a successful turn with incomplete usage or tools. Task and workflow recovery claim candidates with `FOR UPDATE SKIP LOCKED` and a separate recovery timestamp. Unreachable sandboxes rotate behind other runs diff --git a/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts b/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts index c5273d73b3..540da7e809 100644 --- a/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts +++ b/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts @@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { chunkStageFiles, drainSessionExecResilient, + ExecDiskFullError, ExecStreamProtocolError, ExecOutputGapError, SandboxDeviceOfflineError, @@ -888,7 +889,7 @@ describe('drainSessionExecResilient', () => { expect(requests).toBe(1); }); - test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE'])( + test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE', 'DISK_FULL'])( 'fails %s terminally without retrying missing or refused history', async (code) => { let requests = 0; @@ -913,6 +914,25 @@ describe('drainSessionExecResilient', () => { }, ); + test('a sandbox disk that ran out ends the exec in words of its own, never the payload', async () => { + globalThis.fetch = (async () => + sseResponse([ + `event: error\ndata: ${JSON.stringify({ code: 'DISK_FULL', message: '{"internal":"payload"}' })}\n\n`, + ])) as unknown as typeof fetch; + const failure = await drainSessionExecResilient( + 's', + { execId: 'e' }, + new AbortController().signal, + {}, + { resumeSinceSeq: 0 }, + ).catch((error: unknown) => error); + expect(failure).toBeInstanceOf(ExecDiskFullError); + expect(failure).toMatchObject({ + code: 'DISK_FULL', + message: 'the sandbox host ran out of disk space', + }); + }); + test('does not advance past a refused harness record and cancels its reader', async () => { let cancelled = false; let requests = 0; diff --git a/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts b/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts index 6fc8165add..ced629a138 100644 --- a/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts +++ b/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts @@ -1809,6 +1809,17 @@ export class ExecOutputGapError extends ExecStreamProtocolError { readonly code = 'OUTPUT_GAP'; } +/** The session's runtime could not write the exec's output because the + * sandbox host's disk is full (runnerd's `DISK_FULL`), and ended the exec: a + * condition of the host, not a lost transcript, so it says so in its own + * words. Reattaching cannot help. */ +export class ExecDiskFullError extends ExecStreamProtocolError { + readonly code = 'DISK_FULL'; + constructor() { + super('the sandbox host ran out of disk space'); + } +} + /** * POST /v1/sessions/:id/exec as SSE. Streams stdout/stderr deltas to the * callbacks (the progress-bridge action feeds these through the agent adapter @@ -2151,6 +2162,7 @@ async function consumeExecSse( if (parsed?.code === 'ATTACH_BUSY') throw new ExecAttachBusyError(message); if (parsed?.code === 'OUTPUT_GAP') throw new ExecOutputGapError(message); + if (parsed?.code === 'DISK_FULL') throw new ExecDiskFullError(); if (message === `exec ${execId} not found`) { throw new ExecNotFoundError(execId); } diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 1e26cdf4f0..866564e5ac 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -502,6 +502,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [settings](../suites/settings.md) | Memory-aware admission: on a Docker host whose memory the spawner can read, a create that would leave less than `SANDBOX_MIN_FREE_MEMORY` free (creates still starting counted at their working set, sessions that just started at what they are still growing into, a destroyed one at nothing) reclaims a released idle session or answers 429 `host_memory`, a burst admits exactly what fits, unknown memory never refuses; the reading is refreshed every second and concurrent reads share one; a Docker CLI that could not answer is asked again within a minute, a host once verified keeping its verdict meanwhile; an unset `SANDBOX_MAX_SESSIONS` is sized from host memory (8–256, a whole Docker-in-sandbox turn per slot where agent sessions run Docker inside); at most 12 Docker CLI processes run at once, and a call that waits past its budget for a slot answers as a timeout; short calls (the health probe, identity and liveness inspects, the build helper and host memory checks) take a free shared slot or one of 4 kept for them and never queue behind long calls, and a health probe that found no slot answers unhealthy without caching it | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`memory-aware admission`), `services/sandbox/src/host-memory.test.ts`, `services/sandbox/src/spawn-util.test.ts` (`docker CLI concurrency`), `services/sandbox/src/health-probe.test.ts`, `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (`short docker calls beside a burst`) | | [settings](../suites/settings.md) | Disk-aware admission: on the Docker backend, while the disk the session workspaces live on has less than `SANDBOX_MIN_FREE_DISK` free (a twentieth of it, between 2 and 20 GiB; `0` turns it off), every create answers 429 `host_disk` in the first-come line without stopping an idle session, and gets in once space is freed; an unknown or unreadable disk never refuses; the probe reads it with `statfs` every five seconds and logs the disk going below its floor and coming back once each; meanwhile each build-cache upkeep removes the helpers and caches of organizations whose helpers are all stopped and that no session or create may use, the longest-stopped first, at most three a run and only while the disk stays short, and a removal that frees nothing on that disk pauses the removals for six hours | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`disk-aware admission`), `services/sandbox/src/host-disk.test.ts`, `services/sandbox/src/buildkit-lifecycle.test.ts` (`a session disk below its floor`), `services/sandbox/src/config.test.ts` | | [settings](../suites/settings.md) | The session disk's critical tier: below `SANDBOX_CRITICAL_FREE_DISK` (a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least 1 GiB and never above it; `0`, or a floor of `0`, turns it off), read from the same five-second reading, the sweep stops a released idle Docker-in-sandbox session at once through runnerd's claim instead of after its full idle window, never one a turn holds, and logs the three largest workspaces — one niced `du` of every workspace dir, cut off after 30 s, a session's flat and legacy copies counted together — at most every ten minutes; the disk going below the tier and coming back is logged once each; an unknown or unreadable disk is never critical | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`below its critical tier, the sweep stops a released Docker-in-sandbox session at once`, `an unknown disk, or a critical tier of 0, stops nothing for the disk`), `services/sandbox/src/host-disk.test.ts` (`diskCriticalBytes`), `services/sandbox/src/session/workspace-usage.test.ts`, `services/sandbox/src/config.test.ts` | +| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A sandbox disk that fills up mid-turn is named as such: runnerd's replay journal maps a write the disk refuses for want of space (`ENOSPC`, `EDQUOT`) to `DISK_FULL` instead of `REPLAY_UNAVAILABLE` (any other storage error stays `REPLAY_UNAVAILABLE`) and the failure stands for every later write; both protocol copies accept the code; the spawner forwards it as the stream's terminal `error` code without a result and keeps the session; the platform ends the drain on it without reattaching, with "the sandbox host ran out of disk space" (`ExecDiskFullError`), never the payload | ✅ automated | `services/sandbox-runtime/daemon/src/exec-replay.test.ts` (`a journal write that fails with %s ends the replay as %s`), `services/sandbox/src/session/runnerd-protocol.test.ts`, `services/sandbox/src/session/runnerd-client.test.ts` (`daemon replay failure %s retains its terminal diagnostic code`), `services/sandbox/src/session/session-routes.test.ts` (`a journal that ran out of disk ends the exec stream with DISK_FULL`), `services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts` (`a sandbox disk that ran out ends the exec in words of its own`) | | [settings](../suites/settings.md) | The first-come line for host room: a create refused for room waits by session id in the order of its first refusal; freed room goes to the oldest waiters still asking (a slot each, and memory for their working sets, before a newer create — none for a waiter the host could never fit); each 429 carries `queue: { position, waiting }` and a `retry-after` of 5 s plus 5 s a place, up to 60 s; asking again keeps a waiter's place, one that stops asking gives it up after twice its hint and 15 s, a destroy takes it out, and a restart starts with no line | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`the first-come line for host room`, and the capacity and memory admission tests) | | [settings](../suites/settings.md) | Idle sandbox reclamation under deployment capacity pressure | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (released compute reclaimed before admission, persistent workspace retained, busy/pinned/unknown/legacy runtime protection, delayed release after reacquire, concurrent creates and stop failure); `services/sandbox-runtime/daemon/src/activity-gate.test.ts` (atomic idle claim, active-operation protection and frozen execution gate); `services/sandbox/src/backend/docker/docker-session-backend.test.ts`, `backend/kubernetes/k8s-session-backend.test.ts` (incarnation-fenced compute removal and retained workspace); `backend/domains/sandbox/idle-release.test.ts` (ticket capture, transactional queueing and committed-state checks), `idle-release.integration.ts` (28 real-Postgres checks: organization/allocation/owner guards, admission and release ordering, atomic cancellation and release-job rollback, post-op retry on an already-stopped workflow); `backend/core/node_only/sandbox/agent_session.test.ts` (`ensureAgentSession` refuses a false allocation resume before acquiring runtime compute) | | [settings](../suites/settings.md) | The session sweep frees what nothing uses: a released session stops after the short idle window (Docker-in-sandbox agent sessions keep the full one once their inner engine has run, as runnerd's `/healthz` `docker.used` says; one whose engine never started gets the short window, and a runtime that does not report its engine keeps the full one), a running session whose daemon has not answered five sweeps is stopped (a sweep that cannot probe it starts the count over), ended containers and Pods are removed by their incarnation with the workspace kept, beside the API and several at a time, a create of the id waits for that removal (bounded) and a session registered under the id is neither held up by it nor counted as freed by it, a pass still running is joined, a burst of creates at capacity reclaims one released session each, idle-longest first, a create refused at capacity probes at most eight daemons, sessions last seen released first, and none that answered busy (to a reclaim probe or the sweep) or was acquired within 15 s unless released since, and the refusals in the 3 s after a walk that found nothing are answered at once, the build-cache reconcile after adoption covers agent sessions without holding adoption up, a slow build-cache job never holds the next pass's sweep up (one job at a time, organizations adopted meanwhile reconciled right after it), and a caller hanging up on an attach costs no backend check | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`sweep and adoption hygiene`, `creates refused at capacity do not probe every busy session`), `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (a failed inner image volume removal is reported) | diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index c1ec5e4699..1059e48654 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -68,6 +68,9 @@ Disk replay is the sole retained output history. A committed parser checkpoint acknowledges its prefix before segments are pruned, allowing long runs to exceed the per-exec bound over time. Unacknowledged overflow ends the writer with `OUTPUT_LIMIT`; evicted or unreadable replay reports `REPLAY_UNAVAILABLE`. +A journal write the disk refuses for want of space (`ENOSPC`, or `EDQUOT` for +a spent quota) ends the exec with `DISK_FULL` instead, so the failure names +the host's full disk rather than a lost transcript. An acknowledged prefix missing from an older reader's cursor produces an exact gap range, which the platform can recover from a covering checkpoint. Spools live under `/agent/.runtime/tmp` on the workspace disk, independently diff --git a/services/sandbox-runtime/daemon/src/exec-replay.test.ts b/services/sandbox-runtime/daemon/src/exec-replay.test.ts index 3d7c0a0b31..028a3b86a5 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.test.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.test.ts @@ -142,6 +142,46 @@ describe('disk exec replay', () => { } }); + test.each([ + ['ENOSPC', 'DISK_FULL'], + ['EDQUOT', 'DISK_FULL'], + ['EIO', 'REPLAY_UNAVAILABLE'], + ])( + 'a journal write that fails with %s ends the replay as %s', + async (errno, code) => { + const originalOpen = fs.open; + const opened = spyOn(fs, 'open').mockImplementation(async (...args) => { + const file = await originalOpen(...args); + if (args[1] === 'ax') { + file.writev = async () => { + throw Object.assign(new Error('write failed'), { code: errno }); + }; + } + return file; + }); + const replay = createReplay(); + try { + await expectOutputLimit(replay.append(line(1), 1), code); + // The failure stands: nothing later is journaled past it. + await expectOutputLimit(replay.append(line(2), 2), code); + expect( + await replay.append(line(3), 3).then( + () => null, + (error: unknown) => error, + ), + ).toMatchObject({ + message: + code === 'DISK_FULL' + ? 'The sandbox host ran out of disk space.' + : 'The complete execution transcript is unavailable.', + }); + } finally { + opened.mockRestore(); + await replay.dispose(); + } + }, + ); + test('checkpoint acknowledgements let lifetime output exceed the per-exec cap', async () => { const replay = createReplay({ segmentBytes: 1, diff --git a/services/sandbox-runtime/daemon/src/exec-replay.ts b/services/sandbox-runtime/daemon/src/exec-replay.ts index 0869a97bc2..25380a2b41 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.ts @@ -28,7 +28,7 @@ export const REPLAY_WRITE_WATERMARK = 128 * 1024; const WRITE_VECTORS = 64; const READ_CHUNK = 64 * 1024; -type ReplayFailure = 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE'; +type ReplayFailure = 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' | 'DISK_FULL'; export class ReplayError extends Error { constructor( readonly code: ReplayFailure, @@ -38,11 +38,25 @@ export class ReplayError extends Error { message ?? (code === 'OUTPUT_LIMIT' ? 'Execution output exceeded its replay storage limit.' - : 'The complete execution transcript is unavailable.'), + : code === 'DISK_FULL' + ? 'The sandbox host ran out of disk space.' + : 'The complete execution transcript is unavailable.'), ); } } +/** The replay failure a failed journal write is. A full disk (or a spent + * quota) is the host's condition, not a lost transcript, and is named as + * such, so whoever reads the failure can say what to free. */ +export function journalFailure(error: unknown): ReplayError { + if (error instanceof ReplayError) return error; + const code = + error instanceof Error && 'code' in error ? error.code : undefined; + return new ReplayError( + code === 'ENOSPC' || code === 'EDQUOT' ? 'DISK_FULL' : 'REPLAY_UNAVAILABLE', + ); +} + /** Queued output may already have reached a live reader; later output cannot. */ export function isReplayCursor(since: number, throughSeq: number): boolean { return Number.isSafeInteger(since) && since >= 0 && since <= throughSeq; @@ -378,10 +392,7 @@ export class ExecReplay { start = end; } } catch (error) { - this.failure = - error instanceof ReplayError - ? error - : new ReplayError('REPLAY_UNAVAILABLE'); + this.failure = journalFailure(error); throw this.failure; } } diff --git a/services/sandbox-runtime/daemon/src/protocol.ts b/services/sandbox-runtime/daemon/src/protocol.ts index f27b293c19..0dc6e3de5d 100644 --- a/services/sandbox-runtime/daemon/src/protocol.ts +++ b/services/sandbox-runtime/daemon/src/protocol.ts @@ -173,7 +173,8 @@ export type RunnerdExecEvent = ( | 'BAD_REQUEST' | 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' - | 'OUTPUT_GAP'; + | 'OUTPUT_GAP' + | 'DISK_FULL'; message: string; } ) & { seq?: number }; @@ -232,7 +233,8 @@ export function isRunnerdExecEvent(value: unknown): value is RunnerdExecEvent { value.code === 'BAD_REQUEST' || value.code === 'OUTPUT_LIMIT' || value.code === 'REPLAY_UNAVAILABLE' || - value.code === 'OUTPUT_GAP') + value.code === 'OUTPUT_GAP' || + value.code === 'DISK_FULL') ); default: return false; diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index c359f7de67..46fb572f4b 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -359,7 +359,12 @@ storage per session**, including files held open by readers. At most four execs run at once and 16 exec records are retained. Completed spools are evicted first under the shared budget. An active writer that exhausts its budget ends with `OUTPUT_LIMIT`; unavailable or evicted history reports -`REPLAY_UNAVAILABLE`. The disk-backed spool is the sole retained output history. +`REPLAY_UNAVAILABLE`, and a journal write the disk refuses for want of space +(`ENOSPC`, `EDQUOT`) ends the exec with `DISK_FULL`. The spawner forwards each +of the three as the code of the stream's terminal `error` event; the platform +ends the turn on it without reattaching, and names `DISK_FULL` in words of its +own: the sandbox host ran out of disk space. The disk-backed spool is the sole +retained output history. A checkpoint is committed (written to a temporary file and renamed into place) before its acknowledged prefix is pruned, so a run can produce more diff --git a/services/sandbox/src/session/runnerd-client.test.ts b/services/sandbox/src/session/runnerd-client.test.ts index 51a95a4a17..f832350af8 100644 --- a/services/sandbox/src/session/runnerd-client.test.ts +++ b/services/sandbox/src/session/runnerd-client.test.ts @@ -821,7 +821,7 @@ describe('runnerd replay continuity', () => { ).toBe(true); expect(seen).toHaveLength(1); }); - test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE'])( + test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE', 'DISK_FULL'])( 'daemon replay failure %s retains its terminal diagnostic code', async (code) => { setReplayBody('journal-gap', [ diff --git a/services/sandbox/src/session/runnerd-client.ts b/services/sandbox/src/session/runnerd-client.ts index 65af81a96d..22acf3de42 100644 --- a/services/sandbox/src/session/runnerd-client.ts +++ b/services/sandbox/src/session/runnerd-client.ts @@ -332,7 +332,12 @@ async function pumpNdjson( throw new RunnerdProtocolError('invalid execution event'); if ( event.t === 'fail' && - ['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE'].includes(event.code) + [ + 'OUTPUT_GAP', + 'OUTPUT_LIMIT', + 'REPLAY_UNAVAILABLE', + 'DISK_FULL', + ].includes(event.code) ) { throw new RunnerdOutputGapError(event.message, event.code); } diff --git a/services/sandbox/src/session/runnerd-protocol.test.ts b/services/sandbox/src/session/runnerd-protocol.test.ts index b33faafe47..fa7683974d 100644 --- a/services/sandbox/src/session/runnerd-protocol.test.ts +++ b/services/sandbox/src/session/runnerd-protocol.test.ts @@ -58,6 +58,7 @@ describe('runnerd protocol mirror', () => { { t: 'fail', code: 'OUTPUT_LIMIT', message: 'limit' }, { t: 'fail', code: 'OUTPUT_GAP', message: 'gap' }, { t: 'fail', code: 'REPLAY_UNAVAILABLE', message: 'unavailable' }, + { t: 'fail', code: 'DISK_FULL', message: 'disk full' }, ]; const mirrored: MirrorEvent[] = events; const roundTrip: CanonicalEvent[] = mirrored; @@ -148,6 +149,7 @@ describe('runnerd protocol mirror', () => { [{ t: 'replay-complete', throughSeq: 0 }, true], [exit, true], [{ t: 'fail', code: 'OUTPUT_LIMIT', message: 'storage full' }, true], + [{ t: 'fail', code: 'DISK_FULL', message: 'disk full' }, true], [null, false], [[], false], [{ t: 'stdout', b64: 'YQ' }, false], diff --git a/services/sandbox/src/session/runnerd-protocol.ts b/services/sandbox/src/session/runnerd-protocol.ts index f27b293c19..0dc6e3de5d 100644 --- a/services/sandbox/src/session/runnerd-protocol.ts +++ b/services/sandbox/src/session/runnerd-protocol.ts @@ -173,7 +173,8 @@ export type RunnerdExecEvent = ( | 'BAD_REQUEST' | 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' - | 'OUTPUT_GAP'; + | 'OUTPUT_GAP' + | 'DISK_FULL'; message: string; } ) & { seq?: number }; @@ -232,7 +233,8 @@ export function isRunnerdExecEvent(value: unknown): value is RunnerdExecEvent { value.code === 'BAD_REQUEST' || value.code === 'OUTPUT_LIMIT' || value.code === 'REPLAY_UNAVAILABLE' || - value.code === 'OUTPUT_GAP') + value.code === 'OUTPUT_GAP' || + value.code === 'DISK_FULL') ); default: return false; diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index 67b8789980..953a397991 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -333,6 +333,21 @@ beforeAll(() => { { headers: { 'content-type': 'application/x-ndjson' } }, ); } + if (text.includes('__disk_full__')) { + // runnerd's journal hit ENOSPC (exec-replay.ts): the exec ends. + return new Response( + ndjson([ + { t: 'start', execId: 'e1', startedAtMs: 1, seq: 1 }, + { + t: 'fail', + code: 'DISK_FULL', + message: 'The sandbox host ran out of disk space.', + seq: 2, + }, + ]), + { headers: { 'content-type': 'application/x-ndjson' } }, + ); + } if (text.includes('__output_limit__')) { return new Response( ndjson([ @@ -1873,6 +1888,26 @@ describe('SessionRoutes (fake runnerd)', () => { }, ); + test('a journal that ran out of disk ends the exec stream with DISK_FULL, never a result, and keeps the session', async () => { + const routes = new SessionRoutes(cfg, fakeBackend); + await routes.handleCreate( + JSON.stringify({ sessionId: 'disk-full', organizationId: 'org_disk' }), + ); + const { events } = await readSse( + await routes.handleExec( + new Request('http://x'), + 'disk-full', + JSON.stringify({ execId: 'full', command: ['echo', '__disk_full__'] }), + ), + ); + expect(events.map((event) => event.event)).toEqual(['phase', 'error']); + expect(events[1]?.data).toEqual({ + code: 'DISK_FULL', + message: 'The sandbox host ran out of disk space.', + }); + expect(routes.holds('disk-full')).toBe(true); + }); + test('env/files/attach against unknown session → 404', async () => { const routes = new SessionRoutes(cfg, fakeBackend); expect((await routes.handleEnvPatch('nope', '{}')).status).toBe(404); From 440080bd6a65103b0bc15487dbbacc8776a65ecc Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:31:05 +0200 Subject: [PATCH 04/14] perf(sandbox): probe the spawner every 30 s once it is healthy The spawner's healthcheck ran `curl` every 10 s, a runc exec each time: 6 container execs a minute for the life of every spawner. It now probes every 30 s once healthy (2 a minute, a third of the cost) and every 2 s during its first 30 s (`start_interval`), so a deploy still sees a booting spawner ready within seconds instead of waiting up to an interval. The start period grows from 15 s to 30 s because the spawner takes its host lock and runs its boot sweep before it listens, which can pass 15 s on a busy host, and the fast cadence only applies inside the start period; failures in it still do not count, as before. compose.yml, the CLI generator (whose healthcheck type gains `start_interval`) and the image's HEALTHCHECK change together, and a test holds the three to the same cadence. `start_interval` needs Docker Engine 25 or later; the repository states no older minimum. --- compose.yml | 9 +++-- services/sandbox/Dockerfile | 7 ++-- services/sandbox/README.md | 6 +++- .../services/create-sandbox-service.test.ts | 36 +++++++++++++++++++ .../services/create-sandbox-service.ts | 8 +++-- tools/cli/src/lib/compose/types.ts | 2 ++ 6 files changed, 61 insertions(+), 7 deletions(-) diff --git a/compose.yml b/compose.yml index 2b0752f112..e643509dd9 100644 --- a/compose.yml +++ b/compose.yml @@ -884,12 +884,17 @@ services: nofile: soft: 4096 hard: 8192 + # Each probe is a runc exec of curl: every 30 s once healthy, every 2 s + # while the spawner boots, so a deploy sees it ready within seconds. + # `start_interval` needs Docker Engine 25 or later. Mirrors the CLI + # generator and the image's HEALTHCHECK. healthcheck: test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8003/health'] - interval: 10s + interval: 30s timeout: 5s retries: 3 - start_period: 15s + start_period: 30s + start_interval: 2s depends_on: sandbox-egress: condition: service_healthy diff --git a/services/sandbox/Dockerfile b/services/sandbox/Dockerfile index f4b00c9551..5828c9f0b1 100644 --- a/services/sandbox/Dockerfile +++ b/services/sandbox/Dockerfile @@ -109,8 +109,11 @@ ENV TALE_VERSION=${VERSION} \ EXPOSE 8003 # Healthcheck mirrors compose.yml's external probe so direct `docker run` -# (without compose) gets the same liveness signal. -HEALTHCHECK --interval=10s --timeout=5s --retries=3 --start-period=15s \ +# (without compose) gets the same liveness signal: a runc exec every 30 s +# once healthy, every 2 s while the spawner boots (an engine older than +# Docker 25 ignores the start interval and probes every 30 s from the start). +HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=30s \ + --start-interval=2s \ CMD curl -fsS http://127.0.0.1:8003/health || exit 1 # Root by design — see header comment. The docker socket is the boundary. diff --git a/services/sandbox/README.md b/services/sandbox/README.md index 60bb50b12f..9a080f42f3 100644 --- a/services/sandbox/README.md +++ b/services/sandbox/README.md @@ -49,7 +49,11 @@ runtime_image`. A pull that fails is retried after 30 s, 1, 2, 5 and then every 10 minutes, and creates wait meanwhile (`Retry-After` follows the next pull, 5–60 s). `GET /health` reports `runtimeImage: { state, lastError, nextAttemptAtMs }` with `state` one of `unchecked`, `pulling`, `ready` or -`missing`; a missing image never makes the spawner unhealthy. Session lookups whose backend inventory or endpoint +`missing`; a missing image never makes the spawner unhealthy. Docker probes +`GET /health` with `curl` (a runc exec each time) every 30 s once the spawner +is healthy and every 2 s during its first 30 s, so a deploy sees it ready +within seconds of booting; the start interval needs Docker Engine 25 or later +(compose.yml, the CLI generator and the image's `HEALTHCHECK` agree). Session lookups whose backend inventory or endpoint cannot be read, or whose nonterminal runtime is still starting, answer `503 session_unavailable` and `Retry-After: 1`; callers retry without treating that temporary uncertainty as a lost session. diff --git a/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts b/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts index e31a90e39b..a4488311b8 100644 --- a/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts +++ b/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts @@ -1,6 +1,11 @@ import { afterEach, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +import { parse } from 'yaml'; import { setProjectId } from '../../project/project-context'; +import { generateStatefulCompose } from '../generators/generate-stateful-compose'; import { createSandboxService } from './create-sandbox-service'; const originalRoot = process.env.SANDBOX_DOCKER_DATA_ROOT; @@ -37,3 +42,34 @@ test('mount paths cannot inject another compose mount option', () => { process.env.SANDBOX_DOCKER_DATA_ROOT = '/srv/docker:/unexpected'; expect(() => createSandboxService(config)).toThrow('mount separators'); }); + +test('the spawner is probed every 30 s once healthy and every 2 s while it boots, alike in every pipeline', () => { + const repoRoot = fileURLToPath( + new URL('../../../../../../', import.meta.url), + ); + const cadence = { + interval: '30s', + start_period: '30s', + start_interval: '2s', + }; + expect(createSandboxService(config).healthcheck).toMatchObject(cadence); + // The generated stack file carries the field through to Compose. + const generated = parse(generateStatefulCompose(config, 'localhost')) as { + services: Record }>; + }; + expect(generated.services['sandbox']?.healthcheck).toMatchObject(cadence); + const compose = parse( + readFileSync(`${repoRoot}compose.yml`, 'utf8'), + ) as typeof generated; + expect(compose.services['sandbox']?.healthcheck).toMatchObject(cadence); + const dockerfile = readFileSync( + `${repoRoot}services/sandbox/Dockerfile`, + 'utf8', + ).replace(/\\\n\s*/g, ' '); + const directive = dockerfile + .split('\n') + .find((line) => line.startsWith('HEALTHCHECK')); + expect(directive).toContain('--interval=30s'); + expect(directive).toContain('--start-period=30s'); + expect(directive).toContain('--start-interval=2s'); +}); diff --git a/tools/cli/src/lib/compose/services/create-sandbox-service.ts b/tools/cli/src/lib/compose/services/create-sandbox-service.ts index b38e2bfa21..8aff552c9b 100644 --- a/tools/cli/src/lib/compose/services/create-sandbox-service.ts +++ b/tools/cli/src/lib/compose/services/create-sandbox-service.ts @@ -130,12 +130,16 @@ export function createSandboxService(config: ServiceConfig): ComposeService { '${PLATFORM_SHARED_CONFIG:-config-data}:/app/platform-config:ro', ], restart: 'unless-stopped', + // Each probe is a runc exec of curl: every 30 s once healthy, every 2 s + // while the spawner boots (Docker Engine 25+), so a deploy sees it ready + // within seconds. Mirrors compose.yml and the image's HEALTHCHECK. healthcheck: { test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8003/health'], - interval: '10s', + interval: '30s', timeout: '5s', retries: 3, - start_period: '15s', + start_period: '30s', + start_interval: '2s', }, depends_on: { 'sandbox-egress': { condition: 'service_healthy' }, diff --git a/tools/cli/src/lib/compose/types.ts b/tools/cli/src/lib/compose/types.ts index 6f1976c724..9b22a0580a 100644 --- a/tools/cli/src/lib/compose/types.ts +++ b/tools/cli/src/lib/compose/types.ts @@ -44,6 +44,8 @@ export interface ComposeService { timeout: string; retries: number; start_period?: string; + /** Probe cadence during `start_period` (Docker Engine 25+). */ + start_interval?: string; } // A service with no HTTP surface (the job worker) disables the image's // baked healthcheck rather than reading permanently unhealthy. From ba36278d729573c263f81e1b7a9777817118b4c7 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:32:36 +0200 Subject: [PATCH 05/14] refactor(sandbox): keep the disk helpers private to their modules The journal's storage-failure mapping and the workspace measurement's time limit are read only inside their own modules; exporting them left two exports nothing imports, which knip reports. --- services/sandbox-runtime/daemon/src/exec-replay.ts | 2 +- services/sandbox/src/session/workspace-usage.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/sandbox-runtime/daemon/src/exec-replay.ts b/services/sandbox-runtime/daemon/src/exec-replay.ts index 25380a2b41..4e5c3580e0 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.ts @@ -48,7 +48,7 @@ export class ReplayError extends Error { /** The replay failure a failed journal write is. A full disk (or a spent * quota) is the host's condition, not a lost transcript, and is named as * such, so whoever reads the failure can say what to free. */ -export function journalFailure(error: unknown): ReplayError { +function journalFailure(error: unknown): ReplayError { if (error instanceof ReplayError) return error; const code = error instanceof Error && 'code' in error ? error.code : undefined; diff --git a/services/sandbox/src/session/workspace-usage.ts b/services/sandbox/src/session/workspace-usage.ts index d21271a049..50edfcbd25 100644 --- a/services/sandbox/src/session/workspace-usage.ts +++ b/services/sandbox/src/session/workspace-usage.ts @@ -32,7 +32,7 @@ export interface WorkspaceUsageDeps { } /** How long one measurement may take. */ -export const WORKSPACE_USAGE_TIMEOUT_MS = 30_000; +const WORKSPACE_USAGE_TIMEOUT_MS = 30_000; async function runDu(paths: string[], signal: AbortSignal): Promise { // `-x`: a workspace never spans filesystems, and a mount inside one is not From 7445020decf71210a764ab9e648ffc74f099b3a2 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 01:54:59 +0200 Subject: [PATCH 06/14] fix(sandbox): hold the critical disk tier to the floor it sits under The docs say a floor of 0 turns the critical tier off, but an explicit SANDBOX_CRITICAL_FREE_DISK still applied: with SANDBOX_MIN_FREE_DISK=0 and a 2g tier, the sweep stopped released Docker-in-sandbox sessions below 2 GiB while admission, its floor off, kept accepting creates. An explicit tier above the floor did the same: with the 5 GiB default floor of a 100 GiB disk and an 8g tier, everything between 5 and 8 GiB free stopped those sessions while new ones still got in. The tier is now off whenever the floor is, and an explicit one never stands above the floor; the env reference (EN, DE, FR), .env.example, the README and sessions.md say so. --- .env.example | 4 ++-- .../configuration/environment-reference.md | 2 +- .../configuration/environment-reference.md | 2 +- .../configuration/environment-reference.md | 2 +- services/sandbox/README.md | 3 ++- services/sandbox/docs/sessions.md | 4 ++-- services/sandbox/src/host-disk.test.ts | 14 ++++++++++++++ services/sandbox/src/host-disk.ts | 7 ++++--- services/sandbox/src/types.ts | 3 ++- 9 files changed, 29 insertions(+), 12 deletions(-) diff --git a/.env.example b/.env.example index 7082c2fe06..ee468a3abb 100644 --- a/.env.example +++ b/.env.example @@ -459,8 +459,8 @@ TALE_AUDIT_PEPPER=9c1e5b7d3a2f8064e1c7a9d5b3f2e8c604a7d1b9e5c3f8a2d6b0e4c7a1f9d3 # Free space below which that disk is critical: running sessions' writes are # about to fail, so released idle sessions with Docker inside are stopped at # once (their inner image stores go with them) and the largest workspaces are -# logged (default: a quarter of the floor, at least 1g and never above it; 0 -# turns it off). +# logged (default: a quarter of the floor, at least 1g; never above the floor, +# and 0 or a floor of 0 turns it off). # SANDBOX_CRITICAL_FREE_DISK=2g # How long a session that no turn or run holds stays up once idle, in ms (agent # sessions with Docker inside keep the full idle window). diff --git a/docs/de/self-hosted/configuration/environment-reference.md b/docs/de/self-hosted/configuration/environment-reference.md index 95acde272e..7adf7cfa38 100644 --- a/docs/de/self-hosted/configuration/environment-reference.md +++ b/docs/de/self-hosted/configuration/environment-reference.md @@ -255,7 +255,7 @@ Der Sandbox-Spawner liest die folgenden Einstellungen. Übergib sie seiner Umgeb | `SANDBOX_MAX_SESSIONS` | auf einem lokalen Docker-Host nach dem Host-Speicher bemessen (mindestens `8`, höchstens `256`); sonst `8` | Höchstzahl laufender und startender Sessions aller Organisationen auf dem Docker-Host oder im Kubernetes-Namespace, einschließlich weiterlaufender Container im Leerlauf. Die Kapazität reserviert weder CPU noch Arbeitsspeicher. Fehlt die Variable auf einem Docker-Host, dessen Speicher der Spawner lesen kann, bemisst er sie nach diesem Speicher: eine Session je 768 MiB, die nach `SANDBOX_MIN_FREE_MEMORY` übrig bleiben, oder je 1,5 GiB, wenn Agent-Sessions Docker in der Sandbox betreiben. Lässt sich der Speicher beim Start nicht lesen, bleibt die Kapazität bei `8`, bis er lesbar ist. Ein expliziter Wert legt sie fest. Gleichzeitige Kubernetes-Replikate setzen sie nach bestem Bemühen durch; harte Ressourcengrenzen im Namespace setzt du mit ResourceQuota. | | `SANDBOX_MIN_FREE_MEMORY` | ein Zehntel des Host-Speichers, mindestens `1g` | Speicher, den eine neue Session oder eine freigegebene, noch laufende Session bei der Wiederaufnahme auf einem lokalen Docker-Host frei lassen muss, neben dem, was noch startende und eben gestartete Sessions gleich belegen werden. Würde ein Start weniger übrig lassen, stoppt der Spawner zuerst eine freigegebene Session im Leerlauf; reicht der Speicher dann immer noch nicht, antwortet er mit „beschäftigt“, und die Arbeit wartet, bis laufende Sessions Speicher freigeben. Akzeptiert Größen wie `2g` oder `1536m`. Wirkt nicht unter Kubernetes oder mit einem entfernten Docker-Daemon. | | `SANDBOX_MIN_FREE_DISK` | ein Zwanzigstel jedes Datenträgers, mindestens `2g`, höchstens `20g` | Freier Speicher für neue und reaktivierte Sitzungen im Dateisystem der Arbeitsbereiche und im verifizierten Docker-Daten-Dateisystem. Unterhalb der Grenze wartet die Arbeit; gestoppte, ungenutzte Build-Caches werden zuerst entfernt. Akzeptiert `10g` oder `4096m`; `0` deaktiviert die Prüfung. Kubernetes stützt sich auf Storage-Klasse und Volume-Bereitstellung. | -| `SANDBOX_CRITICAL_FREE_DISK` | ein Viertel der Grenze aus `SANDBOX_MIN_FREE_DISK`, mindestens `1g` und nie darüber | Freier Speicher, unterhalb dessen der Datenträger der Sessions kritisch ist: Was laufende Sessions dort schreiben, schlägt bald fehl. Darunter werden freigegebene Sessions mit Docker in der Sandbox im Leerlauf sofort gestoppt, was ihre inneren Image-Speicher entfernt, und der Spawner protokolliert höchstens alle zehn Minuten die drei größten Arbeitsbereiche. Akzeptiert `2g` oder `2048m`; `0` deaktiviert die Stufe, ebenso eine Grenze von `0`. Nur mit dem Docker-Backend. | +| `SANDBOX_CRITICAL_FREE_DISK` | ein Viertel der Grenze aus `SANDBOX_MIN_FREE_DISK`, mindestens `1g` und nie darüber | Freier Speicher, unterhalb dessen der Datenträger der Sessions kritisch ist: Was laufende Sessions dort schreiben, schlägt bald fehl. Darunter werden freigegebene Sessions mit Docker in der Sandbox im Leerlauf sofort gestoppt, was ihre inneren Image-Speicher entfernt, und der Spawner protokolliert höchstens alle zehn Minuten die drei größten Arbeitsbereiche. Akzeptiert `2g` oder `2048m`; ein Wert über der Grenze zählt als die Grenze; `0` deaktiviert die Stufe, ebenso eine Grenze von `0`. Nur mit dem Docker-Backend. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Workloads, die Docker in ihrer Sandbox nutzen dürfen, wenn es für das Deployment aktiviert ist. Mit `project` starten Workflow-Agenten ohne Docker, mit `workflow` gilt das für Projektagenten und mit `none` für beide. Die Einstellung gilt für neu erstellte Sessions; bestehende behalten ihre Fähigkeiten. Eine Session-Anfrage kann Docker mit `docker: false` abwählen, aber weder diese Liste noch die Deployment-Einstellung erweitern. | | `SANDBOX_AGENT_CPUS` | `2` | CPU-Grenze je Agent-Session. Berücksichtige bei der Session-Anzahl gleichzeitig laufende Builds und andere Aufgaben auf dem Host. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | CPU-Gewichtung einer Agent-Session und der Build-Cache-Hilfscontainer ihrer Organisation, solange die CPUs des Hosts ausgelastet sind, gegenüber Dockers Standardwert `1024`, den die eigenen Dienste der Plattform behalten; Sessions mit dem Profil `default` (Codeausführungen, Seiten-Renderings) nutzen `128`. Ausgelastete Sessions überlassen die CPU dann der Datenbank und dem Backend, statt sie auszubremsen; auf einem Host mit freier CPU nutzt eine Session weiterhin bis zu `SANDBOX_AGENT_CPUS`. Eine ganze Zahl von `2` bis `262144`. Gilt für neu erstellte Sessions; ein laufender Hilfscontainer übernimmt einen neuen Wert sofort. | diff --git a/docs/en/self-hosted/configuration/environment-reference.md b/docs/en/self-hosted/configuration/environment-reference.md index ed678d3b2a..184d1655be 100644 --- a/docs/en/self-hosted/configuration/environment-reference.md +++ b/docs/en/self-hosted/configuration/environment-reference.md @@ -255,7 +255,7 @@ The sandbox spawner reads the settings below. Pass them into its environment and | `SANDBOX_MAX_SESSIONS` | sized from host memory on a local Docker host (at least `8`, at most `256`); `8` elsewhere | Maximum running and starting sessions across all organizations on the Docker host or in the Kubernetes namespace, including idle containers kept for reuse. This capacity does not reserve CPU or memory. Unset on a Docker host whose memory the spawner can read, it is sized from that memory: one session per 768 MiB left after `SANDBOX_MIN_FREE_MEMORY`, or per 1.5 GiB where agent sessions run Docker inside the sandbox. If the memory cannot be read at start, the capacity stays `8` until it can. An explicit value fixes it. Concurrent Kubernetes replicas enforce it on a best-effort basis; use ResourceQuota for hard namespace resource bounds. | | `SANDBOX_MIN_FREE_MEMORY` | a tenth of host memory, at least `1g` | Memory a new session or a released warm session resuming work must leave free on a local Docker host, beside what the sessions still starting or just started are about to use. A create that would leave less first stops a released idle session; if memory is still short, the spawner answers busy and the work waits until running sessions free some. Accepts sizes such as `2g` or `1536m`. Has no effect on Kubernetes or with a remote Docker daemon. | | `SANDBOX_MIN_FREE_DISK` | a twentieth of each disk, at least `2g`, at most `20g` | Free space required for new and reactivated sessions on the workspace filesystem and the verified Docker data filesystem. Below the floor work waits; stopped unused build caches are reclaimed first. Accepts `10g` or `4096m`; `0` disables the check. Kubernetes relies on its storage class and volume provisioning. | -| `SANDBOX_CRITICAL_FREE_DISK` | a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least `1g` and never above it | Free space below which the session disk is critical: what running sessions write there is about to fail. Below it, released idle sessions with Docker inside are stopped at once, which removes their inner image stores, and the spawner logs the three largest workspaces at most every ten minutes. Accepts `2g` or `2048m`; `0` turns it off, as does a floor of `0`. Docker backend only. | +| `SANDBOX_CRITICAL_FREE_DISK` | a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least `1g` and never above it | Free space below which the session disk is critical: what running sessions write there is about to fail. Below it, released idle sessions with Docker inside are stopped at once, which removes their inner image stores, and the spawner logs the three largest workspaces at most every ten minutes. Accepts `2g` or `2048m`; a value above the floor counts as the floor; `0` turns it off, as does a floor of `0`. Docker backend only. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Workloads allowed to use inner Docker when it is enabled for the deployment. Set `project` to allow Docker only for project agents, `workflow` only for workflow agents, or `none` to disable both. Applies to newly created sessions; existing sessions keep their capabilities. A session request can opt out with `docker: false`, but cannot enable Docker beyond this allowlist or the deployment setting. | | `SANDBOX_AGENT_CPUS` | `2` | CPU limit per agent session. Account for overlapping builds and other host workloads when choosing the session count. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | CPU weight of an agent session and of its organization's build-cache helpers while the host's CPUs are saturated, against Docker's default of `1024` that the platform's own services keep; sessions of the `default` profile (code runs, page renders) use `128`. Busy sessions then yield the CPU to the database and backend instead of stalling them; on a host with spare CPU a session still uses up to `SANDBOX_AGENT_CPUS`. A whole number from `2` to `262144`. Applies to newly created sessions; a running helper takes a new value at once. | diff --git a/docs/fr/self-hosted/configuration/environment-reference.md b/docs/fr/self-hosted/configuration/environment-reference.md index c89505638e..e53132bfb4 100644 --- a/docs/fr/self-hosted/configuration/environment-reference.md +++ b/docs/fr/self-hosted/configuration/environment-reference.md @@ -255,7 +255,7 @@ Le spawner sandbox lit les paramètres ci-dessous. Transmets-les dans son enviro | `SANDBOX_MAX_SESSIONS` | dimensionnée selon la mémoire de l’hôte sur un hôte Docker local (au moins `8`, au plus `256`) ; `8` ailleurs | Nombre maximal de sessions actives ou au démarrage de toutes les organisations sur l’hôte Docker ou dans le namespace Kubernetes, y compris les conteneurs inactifs conservés pour être réutilisés. Cette capacité ne réserve ni CPU ni mémoire. Sans valeur, sur un hôte Docker dont le spawner peut lire la mémoire, elle est dimensionnée selon cette mémoire : une session par tranche de 768 MiB restant après `SANDBOX_MIN_FREE_MEMORY`, ou de 1,5 GiB quand les sessions d’agent font tourner Docker dans la sandbox. Si la mémoire ne peut pas être lue au démarrage, la capacité reste à `8` jusqu’à ce qu’elle le soit. Une valeur explicite la fixe. Des réplicas Kubernetes concurrents l’appliquent au mieux ; utilise ResourceQuota pour imposer des limites strictes aux ressources du namespace. | | `SANDBOX_MIN_FREE_MEMORY` | un dixième de la mémoire de l’hôte, au moins `1g` | Mémoire qu’une nouvelle session ou une session libérée qui reprend du travail doit laisser libre sur un hôte Docker local, en plus de ce que les sessions encore au démarrage ou tout juste démarrées vont bientôt occuper. Si un démarrage en laissait moins, le spawner arrête d’abord une session libérée inactive ; si la mémoire manque encore, il répond « occupé » et le travail attend que des sessions en cours en libèrent. Accepte des tailles comme `2g` ou `1536m`. Sans effet sous Kubernetes ou avec un daemon Docker distant. | | `SANDBOX_MIN_FREE_DISK` | un vingtième de chaque disque, au moins `2g`, au plus `20g` | Espace libre requis pour les sessions nouvelles et réactivées sur le système de fichiers des espaces de travail et celui, vérifié, des données Docker. Sous ce seuil, le travail attend ; les caches de build arrêtés et inutilisés sont supprimés en premier. Accepte `10g` ou `4096m` ; `0` désactive le contrôle. Kubernetes dépend de sa classe de stockage et du provisionnement des volumes. | -| `SANDBOX_CRITICAL_FREE_DISK` | un quart du seuil `SANDBOX_MIN_FREE_DISK`, au moins `1g` et jamais au-dessus | Espace libre sous lequel le disque des sessions devient critique : ce que les sessions en cours y écrivent est sur le point d’échouer. En dessous, les sessions libérées et inactives avec Docker dans la sandbox sont arrêtées aussitôt, ce qui supprime leur stockage d’images interne, et le spawner journalise les trois plus grands espaces de travail au plus toutes les dix minutes. Accepte `2g` ou `2048m` ; `0` désactive ce palier, tout comme un seuil de `0`. Backend Docker uniquement. | +| `SANDBOX_CRITICAL_FREE_DISK` | un quart du seuil `SANDBOX_MIN_FREE_DISK`, au moins `1g` et jamais au-dessus | Espace libre sous lequel le disque des sessions devient critique : ce que les sessions en cours y écrivent est sur le point d’échouer. En dessous, les sessions libérées et inactives avec Docker dans la sandbox sont arrêtées aussitôt, ce qui supprime leur stockage d’images interne, et le spawner journalise les trois plus grands espaces de travail au plus toutes les dix minutes. Accepte `2g` ou `2048m` ; une valeur au-dessus du seuil compte comme le seuil ; `0` désactive ce palier, tout comme un seuil de `0`. Backend Docker uniquement. | | `SANDBOX_DOCKER_WORKLOADS` | `project,workflow` | Types de travail autorisés à utiliser Docker dans leur sandbox, lorsque le déploiement le permet. Avec `project`, les agents de workflow démarrent sans Docker ; avec `workflow`, ce sont les agents de projet ; avec `none`, les deux. Le réglage s’applique aux nouvelles sessions ; les sessions existantes conservent leurs capacités. Une demande de session peut renoncer à Docker avec `docker: false`, mais ne peut pas dépasser cette liste ni le réglage du déploiement. | | `SANDBOX_AGENT_CPUS` | `2` | Limite de CPU par session d’agent. Tiens compte des builds simultanés et des autres tâches de l’hôte pour choisir le nombre de sessions. | | `SANDBOX_AGENT_CPU_SHARES` | `256` | Poids CPU d’une session d’agent et des conteneurs auxiliaires du cache de build de son organisation tant que les CPU de l’hôte sont saturés, face à la valeur Docker par défaut de `1024` que gardent les services de la plateforme ; les sessions du profil `default` (exécutions de code, rendus de pages) utilisent `128`. Les sessions chargées laissent alors le CPU à la base de données et au backend au lieu de les bloquer ; sur un hôte où il reste du CPU, une session utilise toujours jusqu’à `SANDBOX_AGENT_CPUS`. Un nombre entier de `2` à `262144`. S’applique aux nouvelles sessions ; un conteneur auxiliaire en cours prend une nouvelle valeur aussitôt. | diff --git a/services/sandbox/README.md b/services/sandbox/README.md index 9a080f42f3..49be0c33d5 100644 --- a/services/sandbox/README.md +++ b/services/sandbox/README.md @@ -106,7 +106,8 @@ provisioning (docs/docker-in-container.md). Below either observed filesystem's floor every create answers 429 `host_disk`, and the build-cache upkeep removes the caches of organizations whose helpers are all stopped, the longest-stopped first. Below its critical tier (`SANDBOX_CRITICAL_FREE_DISK`, -a quarter of the floor, at least 1 GiB; `0` turns it off), where running +a quarter of the floor, at least 1 GiB; never above the floor; `0`, or a +floor of `0`, turns it off), where running sessions' writes are about to fail, the sweep also stops released idle Docker-in-sandbox sessions at once, which removes their inner image stores, and logs the three largest workspaces at most every ten minutes. Creates diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index 46fb572f4b..fc7a00d285 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -578,8 +578,8 @@ The floor holds new work back; it does not stop what already runs, which writes until the disk is full, and with it the replay journal of every running exec. So the disk also has a critical tier, below which those writes are about to fail: `SANDBOX_CRITICAL_FREE_DISK`, unset a quarter of the floor, at least -1 GiB and never above the floor (`0` turns it off, and so does a floor of -`0`). The sweep reads it from the same five-second reading, and an unknown or +1 GiB, and never above the floor, set or unset (`0` turns it off, and so does +a floor of `0`). The sweep reads it from the same five-second reading, and an unknown or unreadable disk is never critical. While the disk is below it, the sweep stops a released, idle Docker-in-sandbox session at once instead of after its full idle window — through runnerd's claim like every idle stop, so a turn diff --git a/services/sandbox/src/host-disk.test.ts b/services/sandbox/src/host-disk.test.ts index 0155d4fe03..b70dc60238 100644 --- a/services/sandbox/src/host-disk.test.ts +++ b/services/sandbox/src/host-disk.test.ts @@ -63,6 +63,20 @@ describe('diskCriticalBytes', () => { ).toBe(true); }); + test('an operator’s tier never stands above the floor, and a floor of 0 turns it off too', () => { + // A 100 GiB disk keeps a 5 GiB floor unset. + expect(diskCriticalBytes(100 * GIB, undefined, 8 * GIB)).toBe(5 * GIB); + expect(diskCriticalBytes(100 * GIB, 4 * GIB, 8 * GIB)).toBe(4 * GIB); + expect(diskCriticalBytes(100 * GIB, 0, 2 * GIB)).toBe(0); + expect( + belowDiskCritical( + { totalBytes: 100 * GIB, availableBytes: GIB }, + 0, + 2 * GIB, + ), + ).toBe(false); + }); + test('an unknown or unreadable disk is never critical', () => { expect(belowDiskCritical(null)).toBe(false); expect( diff --git a/services/sandbox/src/host-disk.ts b/services/sandbox/src/host-disk.ts index 83e2cb045a..494c1c5b77 100644 --- a/services/sandbox/src/host-disk.ts +++ b/services/sandbox/src/host-disk.ts @@ -67,16 +67,17 @@ export function belowDiskFloor( /** The free space below which the session disk is critical: what running * sessions still write there is about to fail, and with it the replay * journal of every running exec. The operator's (0 turns the tier off), else - * a quarter of the floor, at least 1 GiB and never above the floor; none - * while the floor is off. */ + * a quarter of the floor, at least 1 GiB; never above the floor, and none + * while the floor is off: a disk the tier calls critical must also be one + * admission refuses new sessions on. */ export function diskCriticalBytes( totalBytes: number, configuredFloorBytes?: number, configuredBytes?: number, ): number { - if (configuredBytes !== undefined) return configuredBytes; if (configuredFloorBytes === 0) return 0; const floor = diskReserveBytes(totalBytes, configuredFloorBytes); + if (configuredBytes !== undefined) return Math.min(floor, configuredBytes); return Math.min(floor, Math.max(GIB, Math.floor(floor / 4))); } diff --git a/services/sandbox/src/types.ts b/services/sandbox/src/types.ts index 05efef74ce..8e186af8ef 100644 --- a/services/sandbox/src/types.ts +++ b/services/sandbox/src/types.ts @@ -194,7 +194,8 @@ export interface SessionConfig { /** Free space below which that disk is critical (SANDBOX_CRITICAL_FREE_DISK; * 0 turns the tier off): released Docker-in-sandbox sessions are stopped * at once, and the largest workspaces are logged. Unset is a quarter of - * the floor, at least 1 GiB and never above it (host-disk.ts). */ + * the floor, at least 1 GiB; set or unset never above the floor, and off + * while the floor is (host-disk.ts). */ criticalFreeDiskBytes?: number; /** Hard wall-clock ceiling on a session's lifetime. */ maxLifetimeMs: number; From 004389ee44b9e1a2ecb2a88d970ede5ee7ab43db Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 02:10:36 +0200 Subject: [PATCH 07/14] fix(platform): name a full sandbox disk when a task run's drain ends A task run's drive window settled every drain failure as "the agent run stopped unexpectedly", so a run whose sandbox host ran out of disk read as a crash even though the drain ended on ExecDiskFullError. Task runs are the long agent runs most likely to fill a disk, and the automation lane and a task's start window already carry the error's own words. The drive window now settles that failure as "the agent run stopped: the sandbox host ran out of disk space"; every other drain failure keeps the generic reason, and the failure code stays turn_crashed. --- .../core/tasks/agent_run_host.reap.test.ts | 25 ++++++++++++++++++- .../backend/core/tasks/agent_run_host.ts | 8 +++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/services/platform/backend/core/tasks/agent_run_host.reap.test.ts b/services/platform/backend/core/tasks/agent_run_host.reap.test.ts index 2c406c8e5f..b7e232d023 100644 --- a/services/platform/backend/core/tasks/agent_run_host.reap.test.ts +++ b/services/platform/backend/core/tasks/agent_run_host.reap.test.ts @@ -32,7 +32,7 @@ const io = vi.hoisted(() => ({ released: [] as Array<{ execId: string; status: string }>, /** How many status probes still answer `running` for the predecessor. */ predecessorRunningPolls: 0, - drainThrows: false, + drainThrows: false as boolean | 'disk-full', afterDrain: undefined as (() => void) | undefined, /** A terminal window the drain answers instead of `running`. */ terminal: undefined as Record | undefined, @@ -51,6 +51,11 @@ vi.mock('../chat/external_turn_shared', async (importActual) => { execId: string; start?: { argv: string[]; stdin?: string }; }) => { + if (io.drainThrows === 'disk-full') { + const { ExecDiskFullError } = + await import('../node_only/sandbox/helpers/session_client'); + throw new ExecDiskFullError(); + } if (io.drainThrows) { throw new Error('sandbox session attach failed (502)'); } @@ -301,9 +306,27 @@ describe('drive window failure', () => { m.name.endsWith(':markTaskAgentRunFailed'), ); expect(failed?.args.failureCode).toBe('turn_crashed'); + expect(failed?.args.error).toBe('the agent run stopped unexpectedly'); // The cancel precedes the settle's key release. expect(io.released).toEqual([{ execId: 'exec-old', status: 'failed' }]); }); + it('names a full sandbox disk instead of an unexpected stop', async () => { + io.drainThrows = 'disk-full'; + const run: RunState = { status: 'running', execId: 'exec-old' }; + const { ctx, mutations } = makeCtx(run); + + await driveTaskAgentTurnImpl(ctx, KEYS as never); + + expect(io.cancels).toEqual(['exec-old']); + expect(run.status).toBe('failed'); + const failed = mutations.find((m) => + m.name.endsWith(':markTaskAgentRunFailed'), + ); + expect(failed?.args.error).toBe( + 'the agent run stopped: the sandbox host ran out of disk space', + ); + expect(failed?.args.failureCode).toBe('turn_crashed'); + }); }); describe('settle harvest', () => { diff --git a/services/platform/backend/core/tasks/agent_run_host.ts b/services/platform/backend/core/tasks/agent_run_host.ts index d843f53073..afa29241f9 100644 --- a/services/platform/backend/core/tasks/agent_run_host.ts +++ b/services/platform/backend/core/tasks/agent_run_host.ts @@ -65,6 +65,7 @@ import { import type { TurnConnectorCaller } from '../node_only/sandbox/connectors_bridge'; import { provisionSessionGatewayKey } from '../node_only/sandbox/gateway_provisioning'; import { + ExecDiskFullError, isSessionExecLimitResult, SessionExecLimitError, sessionCancelExec, @@ -1803,7 +1804,12 @@ export async function driveTaskAgentTurnImpl( ); await settleTaskAgentTurn(ctx, args, { errored: true, - reason: 'the agent run stopped unexpectedly', + // A full sandbox disk is the host's condition, named so whoever + // reads the failure knows what to free. + reason: + err instanceof ExecDiskFullError + ? `the agent run stopped: ${err.message}` + : 'the agent run stopped unexpectedly', text: '', failureCode: 'turn_crashed', }); From 0a63783983b2ed0970a99964a0dea6ce98bed125 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 03:56:03 +0200 Subject: [PATCH 08/14] fix(sandbox): carry the full-disk exec code under the REPLAY_ prefix runnerd ended an exec whose journal the disk refused with DISK_FULL, a code no platform before this one knows. Such a platform reads an unknown terminal code as a dropped stream: it reattached up to its reconnect limit, each attach replayed the same sticky failure, and the turn ended with a bare error, where REPLAY_UNAVAILABLE had ended it at once. The code is now REPLAY_DISK_FULL. Every platform already ends a turn on any REPLAY_ code without reattaching, so an older one reads it as a replay failure, and this one still names the full disk. --- services/platform/backend/README.md | 2 +- .../sandbox/helpers/session_client.test.ts | 11 ++++-- .../sandbox/helpers/session_client.ts | 6 +-- services/sandbox-runtime/README.md | 4 +- .../daemon/src/exec-replay.test.ts | 39 +++++++++++++++++-- .../sandbox-runtime/daemon/src/exec-replay.ts | 8 ++-- .../sandbox-runtime/daemon/src/protocol.ts | 4 +- services/sandbox/docs/sessions.md | 12 +++--- .../src/session/runnerd-client.test.ts | 7 +++- .../sandbox/src/session/runnerd-client.ts | 2 +- .../src/session/runnerd-protocol.test.ts | 4 +- .../sandbox/src/session/runnerd-protocol.ts | 4 +- .../src/session/session-routes.test.ts | 6 +-- 13 files changed, 78 insertions(+), 31 deletions(-) diff --git a/services/platform/backend/README.md b/services/platform/backend/README.md index 1e56e8cdec..5913d12714 100644 --- a/services/platform/backend/README.md +++ b/services/platform/backend/README.md @@ -294,7 +294,7 @@ without retaining a growing promise chain. Drain windows rebuild bounded UI projections from the runtime journal, publishing resumed progress only after replay catches up. Missing journal history is an explicit `REPLAY_UNAVAILABLE` failure, output beyond the journal budget fails with `OUTPUT_LIMIT`, and a -journal the sandbox host's full disk refused fails with `DISK_FULL`, read as +journal the sandbox host's full disk refused fails with `REPLAY_DISK_FULL`, read as "the sandbox host ran out of disk space" (`ExecDiskFullError`); none can be booked as a successful turn with incomplete usage or tools. diff --git a/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts b/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts index 540da7e809..06d97ca434 100644 --- a/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts +++ b/services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts @@ -889,7 +889,12 @@ describe('drainSessionExecResilient', () => { expect(requests).toBe(1); }); - test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE', 'DISK_FULL'])( + test.each([ + 'OUTPUT_GAP', + 'OUTPUT_LIMIT', + 'REPLAY_UNAVAILABLE', + 'REPLAY_DISK_FULL', + ])( 'fails %s terminally without retrying missing or refused history', async (code) => { let requests = 0; @@ -917,7 +922,7 @@ describe('drainSessionExecResilient', () => { test('a sandbox disk that ran out ends the exec in words of its own, never the payload', async () => { globalThis.fetch = (async () => sseResponse([ - `event: error\ndata: ${JSON.stringify({ code: 'DISK_FULL', message: '{"internal":"payload"}' })}\n\n`, + `event: error\ndata: ${JSON.stringify({ code: 'REPLAY_DISK_FULL', message: '{"internal":"payload"}' })}\n\n`, ])) as unknown as typeof fetch; const failure = await drainSessionExecResilient( 's', @@ -928,7 +933,7 @@ describe('drainSessionExecResilient', () => { ).catch((error: unknown) => error); expect(failure).toBeInstanceOf(ExecDiskFullError); expect(failure).toMatchObject({ - code: 'DISK_FULL', + code: 'REPLAY_DISK_FULL', message: 'the sandbox host ran out of disk space', }); }); diff --git a/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts b/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts index ced629a138..99da67beec 100644 --- a/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts +++ b/services/platform/backend/core/node_only/sandbox/helpers/session_client.ts @@ -1810,11 +1810,11 @@ export class ExecOutputGapError extends ExecStreamProtocolError { } /** The session's runtime could not write the exec's output because the - * sandbox host's disk is full (runnerd's `DISK_FULL`), and ended the exec: a + * sandbox host's disk is full (runnerd's `REPLAY_DISK_FULL`), and ended the exec: a * condition of the host, not a lost transcript, so it says so in its own * words. Reattaching cannot help. */ export class ExecDiskFullError extends ExecStreamProtocolError { - readonly code = 'DISK_FULL'; + readonly code = 'REPLAY_DISK_FULL'; constructor() { super('the sandbox host ran out of disk space'); } @@ -2162,7 +2162,7 @@ async function consumeExecSse( if (parsed?.code === 'ATTACH_BUSY') throw new ExecAttachBusyError(message); if (parsed?.code === 'OUTPUT_GAP') throw new ExecOutputGapError(message); - if (parsed?.code === 'DISK_FULL') throw new ExecDiskFullError(); + if (parsed?.code === 'REPLAY_DISK_FULL') throw new ExecDiskFullError(); if (message === `exec ${execId} not found`) { throw new ExecNotFoundError(execId); } diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 1059e48654..03c71724ee 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -68,8 +68,8 @@ Disk replay is the sole retained output history. A committed parser checkpoint acknowledges its prefix before segments are pruned, allowing long runs to exceed the per-exec bound over time. Unacknowledged overflow ends the writer with `OUTPUT_LIMIT`; evicted or unreadable replay reports `REPLAY_UNAVAILABLE`. -A journal write the disk refuses for want of space (`ENOSPC`, or `EDQUOT` for -a spent quota) ends the exec with `DISK_FULL` instead, so the failure names +A journal or checkpoint write the disk refuses for want of space (`ENOSPC`, or +`EDQUOT` for a spent quota) ends the exec with `REPLAY_DISK_FULL` instead, so the failure names the host's full disk rather than a lost transcript. An acknowledged prefix missing from an older reader's cursor produces an exact gap range, which the platform can recover from a covering checkpoint. diff --git a/services/sandbox-runtime/daemon/src/exec-replay.test.ts b/services/sandbox-runtime/daemon/src/exec-replay.test.ts index 028a3b86a5..25cf8f8da7 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.test.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.test.ts @@ -143,8 +143,8 @@ describe('disk exec replay', () => { }); test.each([ - ['ENOSPC', 'DISK_FULL'], - ['EDQUOT', 'DISK_FULL'], + ['ENOSPC', 'REPLAY_DISK_FULL'], + ['EDQUOT', 'REPLAY_DISK_FULL'], ['EIO', 'REPLAY_UNAVAILABLE'], ])( 'a journal write that fails with %s ends the replay as %s', @@ -171,7 +171,7 @@ describe('disk exec replay', () => { ), ).toMatchObject({ message: - code === 'DISK_FULL' + code === 'REPLAY_DISK_FULL' ? 'The sandbox host ran out of disk space.' : 'The complete execution transcript is unavailable.', }); @@ -182,6 +182,39 @@ describe('disk exec replay', () => { }, ); + test.each([ + ['ENOSPC', 'REPLAY_DISK_FULL'], + ['EDQUOT', 'REPLAY_DISK_FULL'], + ['EIO', 'REPLAY_UNAVAILABLE'], + ])( + 'a checkpoint write that fails with %s ends the replay as %s', + async (errno, code) => { + const originalOpen = fs.open; + const opened = spyOn(fs, 'open').mockImplementation(async (...args) => { + const file = await originalOpen(...args); + if (args[1] === 'w') { + file.writeFile = async () => { + throw Object.assign(new Error('write failed'), { code: errno }); + }; + } + return file; + }); + const replay = createReplay(); + try { + await replay.append(line(1), 1); + await expectOutputLimit( + replay.saveCheckpoint({ seq: 1, state: null }), + code, + ); + // The failure stands for the output after it as well. + await expectOutputLimit(replay.append(line(2), 2), code); + } finally { + opened.mockRestore(); + await replay.dispose(); + } + }, + ); + test('checkpoint acknowledgements let lifetime output exceed the per-exec cap', async () => { const replay = createReplay({ segmentBytes: 1, diff --git a/services/sandbox-runtime/daemon/src/exec-replay.ts b/services/sandbox-runtime/daemon/src/exec-replay.ts index 4e5c3580e0..3a2f7d998a 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.ts @@ -28,7 +28,7 @@ export const REPLAY_WRITE_WATERMARK = 128 * 1024; const WRITE_VECTORS = 64; const READ_CHUNK = 64 * 1024; -type ReplayFailure = 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' | 'DISK_FULL'; +type ReplayFailure = 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' | 'REPLAY_DISK_FULL'; export class ReplayError extends Error { constructor( readonly code: ReplayFailure, @@ -38,7 +38,7 @@ export class ReplayError extends Error { message ?? (code === 'OUTPUT_LIMIT' ? 'Execution output exceeded its replay storage limit.' - : code === 'DISK_FULL' + : code === 'REPLAY_DISK_FULL' ? 'The sandbox host ran out of disk space.' : 'The complete execution transcript is unavailable.'), ); @@ -53,7 +53,9 @@ function journalFailure(error: unknown): ReplayError { const code = error instanceof Error && 'code' in error ? error.code : undefined; return new ReplayError( - code === 'ENOSPC' || code === 'EDQUOT' ? 'DISK_FULL' : 'REPLAY_UNAVAILABLE', + code === 'ENOSPC' || code === 'EDQUOT' + ? 'REPLAY_DISK_FULL' + : 'REPLAY_UNAVAILABLE', ); } diff --git a/services/sandbox-runtime/daemon/src/protocol.ts b/services/sandbox-runtime/daemon/src/protocol.ts index 0dc6e3de5d..775a8cf62d 100644 --- a/services/sandbox-runtime/daemon/src/protocol.ts +++ b/services/sandbox-runtime/daemon/src/protocol.ts @@ -174,7 +174,7 @@ export type RunnerdExecEvent = ( | 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' | 'OUTPUT_GAP' - | 'DISK_FULL'; + | 'REPLAY_DISK_FULL'; message: string; } ) & { seq?: number }; @@ -234,7 +234,7 @@ export function isRunnerdExecEvent(value: unknown): value is RunnerdExecEvent { value.code === 'OUTPUT_LIMIT' || value.code === 'REPLAY_UNAVAILABLE' || value.code === 'OUTPUT_GAP' || - value.code === 'DISK_FULL') + value.code === 'REPLAY_DISK_FULL') ); default: return false; diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index fc7a00d285..f4ddd17463 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -359,12 +359,14 @@ storage per session**, including files held open by readers. At most four execs run at once and 16 exec records are retained. Completed spools are evicted first under the shared budget. An active writer that exhausts its budget ends with `OUTPUT_LIMIT`; unavailable or evicted history reports -`REPLAY_UNAVAILABLE`, and a journal write the disk refuses for want of space -(`ENOSPC`, `EDQUOT`) ends the exec with `DISK_FULL`. The spawner forwards each +`REPLAY_UNAVAILABLE`, and a journal or checkpoint write the disk refuses for +want of space (`ENOSPC`, `EDQUOT`) ends the exec with `REPLAY_DISK_FULL`. The spawner forwards each of the three as the code of the stream's terminal `error` event; the platform -ends the turn on it without reattaching, and names `DISK_FULL` in words of its -own: the sandbox host ran out of disk space. The disk-backed spool is the sole -retained output history. +ends the turn on it without reattaching, and names `REPLAY_DISK_FULL` in words of its +own: the sandbox host ran out of disk space. The full-disk code carries the +`REPLAY_` prefix on purpose: a platform older than the runtime already ends a +turn on every `REPLAY_` code instead of reattaching. The disk-backed spool is +the sole retained output history. A checkpoint is committed (written to a temporary file and renamed into place) before its acknowledged prefix is pruned, so a run can produce more diff --git a/services/sandbox/src/session/runnerd-client.test.ts b/services/sandbox/src/session/runnerd-client.test.ts index f832350af8..05a8186701 100644 --- a/services/sandbox/src/session/runnerd-client.test.ts +++ b/services/sandbox/src/session/runnerd-client.test.ts @@ -821,7 +821,12 @@ describe('runnerd replay continuity', () => { ).toBe(true); expect(seen).toHaveLength(1); }); - test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE', 'DISK_FULL'])( + test.each([ + 'OUTPUT_GAP', + 'OUTPUT_LIMIT', + 'REPLAY_UNAVAILABLE', + 'REPLAY_DISK_FULL', + ])( 'daemon replay failure %s retains its terminal diagnostic code', async (code) => { setReplayBody('journal-gap', [ diff --git a/services/sandbox/src/session/runnerd-client.ts b/services/sandbox/src/session/runnerd-client.ts index 22acf3de42..53f195e69a 100644 --- a/services/sandbox/src/session/runnerd-client.ts +++ b/services/sandbox/src/session/runnerd-client.ts @@ -336,7 +336,7 @@ async function pumpNdjson( 'OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE', - 'DISK_FULL', + 'REPLAY_DISK_FULL', ].includes(event.code) ) { throw new RunnerdOutputGapError(event.message, event.code); diff --git a/services/sandbox/src/session/runnerd-protocol.test.ts b/services/sandbox/src/session/runnerd-protocol.test.ts index fa7683974d..d9924d9d7c 100644 --- a/services/sandbox/src/session/runnerd-protocol.test.ts +++ b/services/sandbox/src/session/runnerd-protocol.test.ts @@ -58,7 +58,7 @@ describe('runnerd protocol mirror', () => { { t: 'fail', code: 'OUTPUT_LIMIT', message: 'limit' }, { t: 'fail', code: 'OUTPUT_GAP', message: 'gap' }, { t: 'fail', code: 'REPLAY_UNAVAILABLE', message: 'unavailable' }, - { t: 'fail', code: 'DISK_FULL', message: 'disk full' }, + { t: 'fail', code: 'REPLAY_DISK_FULL', message: 'disk full' }, ]; const mirrored: MirrorEvent[] = events; const roundTrip: CanonicalEvent[] = mirrored; @@ -149,7 +149,7 @@ describe('runnerd protocol mirror', () => { [{ t: 'replay-complete', throughSeq: 0 }, true], [exit, true], [{ t: 'fail', code: 'OUTPUT_LIMIT', message: 'storage full' }, true], - [{ t: 'fail', code: 'DISK_FULL', message: 'disk full' }, true], + [{ t: 'fail', code: 'REPLAY_DISK_FULL', message: 'disk full' }, true], [null, false], [[], false], [{ t: 'stdout', b64: 'YQ' }, false], diff --git a/services/sandbox/src/session/runnerd-protocol.ts b/services/sandbox/src/session/runnerd-protocol.ts index 0dc6e3de5d..775a8cf62d 100644 --- a/services/sandbox/src/session/runnerd-protocol.ts +++ b/services/sandbox/src/session/runnerd-protocol.ts @@ -174,7 +174,7 @@ export type RunnerdExecEvent = ( | 'OUTPUT_LIMIT' | 'REPLAY_UNAVAILABLE' | 'OUTPUT_GAP' - | 'DISK_FULL'; + | 'REPLAY_DISK_FULL'; message: string; } ) & { seq?: number }; @@ -234,7 +234,7 @@ export function isRunnerdExecEvent(value: unknown): value is RunnerdExecEvent { value.code === 'OUTPUT_LIMIT' || value.code === 'REPLAY_UNAVAILABLE' || value.code === 'OUTPUT_GAP' || - value.code === 'DISK_FULL') + value.code === 'REPLAY_DISK_FULL') ); default: return false; diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index 953a397991..5b1e4d7a68 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -340,7 +340,7 @@ beforeAll(() => { { t: 'start', execId: 'e1', startedAtMs: 1, seq: 1 }, { t: 'fail', - code: 'DISK_FULL', + code: 'REPLAY_DISK_FULL', message: 'The sandbox host ran out of disk space.', seq: 2, }, @@ -1888,7 +1888,7 @@ describe('SessionRoutes (fake runnerd)', () => { }, ); - test('a journal that ran out of disk ends the exec stream with DISK_FULL, never a result, and keeps the session', async () => { + test('a journal that ran out of disk ends the exec stream with REPLAY_DISK_FULL, never a result, and keeps the session', async () => { const routes = new SessionRoutes(cfg, fakeBackend); await routes.handleCreate( JSON.stringify({ sessionId: 'disk-full', organizationId: 'org_disk' }), @@ -1902,7 +1902,7 @@ describe('SessionRoutes (fake runnerd)', () => { ); expect(events.map((event) => event.event)).toEqual(['phase', 'error']); expect(events[1]?.data).toEqual({ - code: 'DISK_FULL', + code: 'REPLAY_DISK_FULL', message: 'The sandbox host ran out of disk space.', }); expect(routes.holds('disk-full')).toBe(true); From 82be838c0fbe6d8b1691718b3ea629837524411e Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 03:57:56 +0200 Subject: [PATCH 09/14] fix(sandbox): judge the critical disk tier per watched filesystem The critical tier read one disk reading, the one the probe picks for having less headroom against the floor. With Docker's data root watched apart, that could miss a critical Docker data disk, and it stopped released Docker-in-sandbox sessions when only the workspace disk was short, although their inner image stores live on Docker's data root and stopping them freed nothing there. The log always said "the session disk". Each filesystem now has its own verdict: a critical workspace disk logs the largest workspaces, a critical Docker data disk stops released Docker-in-sandbox sessions, and each log line names its disk. On a host where they are one disk, nothing changes. A reading that is missing or a placeholder for an unverifiable mount no longer flips the verdict or logs a recovery it did not see. --- services/sandbox/src/docker-data-disk.ts | 10 +++ services/sandbox/src/host-disk.ts | 9 ++ .../src/session/session-routes.test.ts | 68 +++++++++++++++ .../sandbox/src/session/session-routes.ts | 82 +++++++++++++------ 4 files changed, 146 insertions(+), 23 deletions(-) diff --git a/services/sandbox/src/docker-data-disk.ts b/services/sandbox/src/docker-data-disk.ts index 51460309b7..107703e348 100644 --- a/services/sandbox/src/docker-data-disk.ts +++ b/services/sandbox/src/docker-data-disk.ts @@ -314,6 +314,16 @@ export class SandboxDiskProbe implements HostDiskSource { return headroom(docker) < headroom(workspace) ? docker : workspace; } + byFilesystem(): { + workspace: HostDisk | null; + dockerData: HostDisk | null | undefined; + } { + return { + workspace: this.workspace.latest(), + dockerData: this.dockerData?.latest(), + }; + } + read(fresh = false): Promise { this.reading ??= Promise.all([ this.workspace.read(fresh), diff --git a/services/sandbox/src/host-disk.ts b/services/sandbox/src/host-disk.ts index 494c1c5b77..193fd4b728 100644 --- a/services/sandbox/src/host-disk.ts +++ b/services/sandbox/src/host-disk.ts @@ -112,6 +112,15 @@ export interface HostDiskDeps { export interface HostDiskSource { latest(): HostDisk | null; read(fresh?: boolean): Promise; + /** The workspace and Docker data filesystems' last readings apart, when + * they are watched apart: `latest` is the one with less headroom, but the + * critical tier acts on each for what lives there. `dockerData` is + * undefined when that filesystem is not watched (it is then the + * workspace's), null while it cannot be read. */ + byFilesystem?(): { + workspace: HostDisk | null; + dockerData: HostDisk | null | undefined; + }; } export class HostDiskProbe implements HostDiskSource { diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index 5b1e4d7a68..a0630c25f2 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -6840,6 +6840,74 @@ describe('disk-aware admission', () => { } }); + test('a critical tier acts on each watched filesystem for what lives there', async () => { + const warnings: string[] = []; + const warn = spyOn(console, 'warn').mockImplementation( + (...args: unknown[]) => { + warnings.push(args.map(String).join(' ')); + }, + ); + let measured = 0; + let workspaceFree = 50; + let dockerFree = 50; + const reading = (free: number) => ({ + totalBytes: 100 * GIB, + availableBytes: free * GIB, + }); + const routes = new SessionRoutes( + { ...cfg, dockerInContainer: true }, + { + ...fakeBackend, + async largestWorkspaces() { + measured += 1; + return { largest: [], measured: 0, total: 0 }; + }, + }, + undefined, + undefined, + { + latest: () => reading(Math.min(workspaceFree, dockerFree)), + read: () => + Promise.resolve(reading(Math.min(workspaceFree, dockerFree))), + byFilesystem: () => ({ + workspace: reading(workspaceFree), + dockerData: reading(dockerFree), + }), + }, + ); + try { + await releasedDockerSessions(routes); + // Only the workspace disk is critical: its largest workspaces are + // logged, and no Docker-in-sandbox session stops, since its inner + // image store lives on Docker's data disk. + workspaceFree = 1; + expect(await routes.sweepExpired()).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(measured).toBe(1); + expect(stopped.has('dind-released')).toBe(false); + expect( + warnings.some((line) => + line.startsWith( + '[sandbox.session] the session disk has 1.0 GiB free', + ), + ), + ).toBe(true); + // Docker's data disk turns critical too: the released session stops. + dockerFree = 1; + expect(await routes.sweepExpired()).toBe(1); + expect(stopped.has('dind-released')).toBe(true); + expect( + warnings.some((line) => + line.startsWith( + "[sandbox.session] Docker's data disk has 1.0 GiB free", + ), + ), + ).toBe(true); + } finally { + warn.mockRestore(); + } + }); + test('an unknown disk, or a critical tier of 0, stops nothing for the disk', async () => { const off = { ...cfg, diff --git a/services/sandbox/src/session/session-routes.ts b/services/sandbox/src/session/session-routes.ts index 3c5c25fff6..ac25f0eb20 100644 --- a/services/sandbox/src/session/session-routes.ts +++ b/services/sandbox/src/session/session-routes.ts @@ -16,6 +16,7 @@ import { belowDiskCritical, belowDiskFloor, diskCriticalBytes, + type HostDisk, type HostDiskSource, type SessionDiskState, } from '../host-disk.ts'; @@ -378,7 +379,11 @@ export class SessionRoutes { private nothingToReclaimUntilMs = 0; // The session disk's critical state as the last sweep saw it, so each // change is logged once; and the measurement of its largest workspaces. - private diskWasCritical = false; + private diskWasCritical = { + both: false, + workspace: false, + dockerData: false, + }; private workspaceUsageAtMs = Number.NEGATIVE_INFINITY; private workspaceUsage: Promise | null = null; // Settles when the destroy of that id is done (success or failure): @@ -732,35 +737,65 @@ export class SessionRoutes { } } - /** Is the disk the workspaces live on below its critical tier (the probe's - * last reading)? An unknown disk never is. Each change is logged once. */ - private diskCritical(): boolean { - let disk; + /** Which filesystems are below their critical tier (the probe's last + * readings): the workspaces' own, whose largest workspaces are then + * logged, and Docker's data root, where a Docker-in-sandbox session keeps + * its inner image store, so a released one then stops. They are one disk + * unless Docker's data root is watched apart. An unknown disk never is + * critical. Each change is logged once per filesystem. */ + private diskCritical(): { workspace: boolean; dockerData: boolean } { + let workspace: HostDisk | null; + let dockerData: HostDisk | null | undefined; try { - disk = this.hostDisk.latest(); + const apart = this.hostDisk.byFilesystem?.(); + workspace = apart ? apart.workspace : this.hostDisk.latest(); + dockerData = apart?.dockerData; } catch (error) { console.warn('[sandbox.session] session disk unreadable:', error); - return false; + return { workspace: false, dockerData: false }; + } + if (dockerData === undefined) { + const both = this.criticalTransition('both', workspace); + return { workspace: both, dockerData: both }; } + return { + workspace: this.criticalTransition('workspace', workspace), + dockerData: this.criticalTransition('dockerData', dockerData), + }; + } + + private criticalTransition( + filesystem: 'both' | 'workspace' | 'dockerData', + disk: HostDisk | null, + ): boolean { const { minFreeDiskBytes, criticalFreeDiskBytes } = this.cfg.session; const critical = belowDiskCritical( disk, minFreeDiskBytes, criticalFreeDiskBytes, ); - if (critical !== this.diskWasCritical && disk !== null) { - this.diskWasCritical = critical; - const free = `${(disk.availableBytes / GIB).toFixed(1)} GiB`; - const tier = `${(diskCriticalBytes(disk.totalBytes, minFreeDiskBytes, criticalFreeDiskBytes) / GIB).toFixed(1)} GiB`; - if (critical) { - console.warn( - `[sandbox.session] the session disk has ${free} free, below its critical ${tier}: running sessions are about to fail their writes; released Docker-in-sandbox sessions stop now and the largest workspaces are logged (SANDBOX_CRITICAL_FREE_DISK)`, - ); - } else { - console.log( - `[sandbox.session] the session disk has ${free} free again, above its critical ${tier}`, - ); - } + // A reading that is missing or a placeholder says nothing either way: + // the last verdict stands, unlogged, until a real one lands. + if (disk === null || disk.unavailable === true) return critical; + if (critical === this.diskWasCritical[filesystem]) return critical; + this.diskWasCritical[filesystem] = critical; + const name = + filesystem === 'dockerData' ? "Docker's data disk" : 'the session disk'; + const actions = { + both: 'released Docker-in-sandbox sessions stop now and the largest workspaces are logged', + workspace: 'the largest workspaces are logged', + dockerData: 'released Docker-in-sandbox sessions stop now', + }[filesystem]; + const free = `${(disk.availableBytes / GIB).toFixed(1)} GiB`; + const tier = `${(diskCriticalBytes(disk.totalBytes, minFreeDiskBytes, criticalFreeDiskBytes) / GIB).toFixed(1)} GiB`; + if (critical) { + console.warn( + `[sandbox.session] ${name} has ${free} free, below its critical ${tier}: running sessions are about to fail their writes; ${actions} (SANDBOX_CRITICAL_FREE_DISK)`, + ); + } else { + console.log( + `[sandbox.session] ${name} has ${free} free again, above its critical ${tier}`, + ); } return critical; } @@ -1659,13 +1694,14 @@ export class SessionRoutes { */ async sweepExpired(nowMs: number = Date.now()): Promise { let reaped = 0; - const diskCritical = this.diskCritical(); - if (diskCritical) this.logLargestWorkspaces(); + const critical = this.diskCritical(); + if (critical.workspace) this.logLargestWorkspaces(); await forEachLimited( this.registry.list(), SWEEP_CONCURRENCY, async (session) => { - if (await this.sweepSession(session, nowMs, diskCritical)) reaped += 1; + if (await this.sweepSession(session, nowMs, critical.dockerData)) + reaped += 1; }, ); // The build helpers follow the sessions just stopped, beside the sweep From 9eeab41863b86725b363e00d96e94914cde1528c Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 03:58:01 +0200 Subject: [PATCH 10/14] docs(sandbox): keep the workspace listing's doc with its method The new largestWorkspaces method was inserted between listWorkspaces' docblock and its declaration, leaving that doc above the wrong method. The workspace-usage header also claimed a niced du gets the lowest I/O priority, which holds only under the CFQ and BFQ schedulers; it now says what the deadline bounds instead. --- .../src/backend/docker/docker-session-backend.ts | 10 +++++----- services/sandbox/src/session/workspace-usage.ts | 9 +++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/services/sandbox/src/backend/docker/docker-session-backend.ts b/services/sandbox/src/backend/docker/docker-session-backend.ts index df2a9e3152..e56287eb23 100644 --- a/services/sandbox/src/backend/docker/docker-session-backend.ts +++ b/services/sandbox/src/backend/docker/docker-session-backend.ts @@ -1412,17 +1412,17 @@ export class DockerSessionBackend implements SessionBackend { return out; } - /** Every workspace dir under the host session root, joined with the - * session containers beside them; the organization is the container's - * label, or else the workspace's own marker. `listSessions` THROWS on a - * failed `docker ps`, so a container that merely could not be listed never - * reads as inactive. */ /** One bounded, lowest-priority `du` over every workspace dir under the * session root (workspace-usage.ts). */ largestWorkspaces(limit: number): Promise { return largestWorkspaces(this.cfg.hostSessionRoot, { limit }); } + /** Every workspace dir under the host session root, joined with the + * session containers beside them; the organization is the container's + * label, or else the workspace's own marker. `listSessions` THROWS on a + * failed `docker ps`, so a container that merely could not be listed never + * reads as inactive. */ async listWorkspaces(): Promise { const dirs = await listWorkspaceDirs(this.cfg.hostSessionRoot); const containers = new Map( diff --git a/services/sandbox/src/session/workspace-usage.ts b/services/sandbox/src/session/workspace-usage.ts index 50edfcbd25..e337f7b051 100644 --- a/services/sandbox/src/session/workspace-usage.ts +++ b/services/sandbox/src/session/workspace-usage.ts @@ -3,10 +3,11 @@ // thing to know, and nothing else on the host says it. // // One `du` measures every workspace dir under the session root, at the -// lowest CPU priority — which also gives it the lowest best-effort I/O -// priority, the kernel's default for a niced process — and only for so long: -// a disk this full is usually a busy one, and a workspace can hold millions -// of files. Whatever it measured by the deadline is reported, marked as +// lowest CPU priority, and only for so long: a disk this full is usually a +// busy one, and a workspace can hold millions of files. Its I/O priority is +// the ordinary one under the mq-deadline and none schedulers most NVMe disks +// use (only CFQ and BFQ derive it from the nice value), which the deadline +// bounds. Whatever it measured by the deadline is reported, marked as // incomplete. import { listWorkspacePaths } from './workspace-inventory.ts'; From 0024b611254453f799b022e6fa461508b9118764 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 02:08:19 +0200 Subject: [PATCH 11/14] fix(sandbox): drop the healthcheck start interval Engine 24 refuses The spawner's healthcheck set `start_interval: 2s` (and the image's HEALTHCHECK `--start-interval=2s`) to see a booting spawner ready within seconds. Docker Compose refuses to create a container with `start_interval` on an engine older than 25, and the CLI states Engine 24 as the minimum Tale requires, so `docker compose up` and `tale deploy` would fail outright there rather than probe more slowly. The Dockerfile frontend Engine 24 bundles does not know the flag either, so a local image build there fails too. The healthcheck keeps its 30 s interval and 30 s start period (2 runc execs a minute instead of 6) without a start interval, in compose.yml, the CLI generator and the image alike. The cost is the first healthy reading, which comes up to 30 s after the spawner starts instead of within a few seconds, well inside the deploy's 300 s health wait. The test now also holds all three free of the start interval. --- compose.yml | 9 ++++--- services/sandbox/Dockerfile | 7 +++--- services/sandbox/README.md | 9 +++---- .../services/create-sandbox-service.test.ts | 24 ++++++++++++------- .../services/create-sandbox-service.ts | 8 +++---- tools/cli/src/lib/compose/types.ts | 2 -- 6 files changed, 31 insertions(+), 28 deletions(-) diff --git a/compose.yml b/compose.yml index e643509dd9..9f4c62dd13 100644 --- a/compose.yml +++ b/compose.yml @@ -884,17 +884,16 @@ services: nofile: soft: 4096 hard: 8192 - # Each probe is a runc exec of curl: every 30 s once healthy, every 2 s - # while the spawner boots, so a deploy sees it ready within seconds. - # `start_interval` needs Docker Engine 25 or later. Mirrors the CLI - # generator and the image's HEALTHCHECK. + # Each probe is a runc exec of curl, every 30 s, so a booting spawner + # reads healthy up to 30 s after it starts. No `start_interval`: Docker + # Compose refuses it on Engine 24, the oldest engine Tale supports. + # Mirrors the CLI generator and the image's HEALTHCHECK. healthcheck: test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8003/health'] interval: 30s timeout: 5s retries: 3 start_period: 30s - start_interval: 2s depends_on: sandbox-egress: condition: service_healthy diff --git a/services/sandbox/Dockerfile b/services/sandbox/Dockerfile index 5828c9f0b1..3635604709 100644 --- a/services/sandbox/Dockerfile +++ b/services/sandbox/Dockerfile @@ -109,11 +109,10 @@ ENV TALE_VERSION=${VERSION} \ EXPOSE 8003 # Healthcheck mirrors compose.yml's external probe so direct `docker run` -# (without compose) gets the same liveness signal: a runc exec every 30 s -# once healthy, every 2 s while the spawner boots (an engine older than -# Docker 25 ignores the start interval and probes every 30 s from the start). +# (without compose) gets the same liveness signal: a runc exec every 30 s. No +# --start-interval: the Dockerfile frontend Docker Engine 24 bundles, the +# oldest engine Tale supports, does not know the flag. HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=30s \ - --start-interval=2s \ CMD curl -fsS http://127.0.0.1:8003/health || exit 1 # Root by design — see header comment. The docker socket is the boundary. diff --git a/services/sandbox/README.md b/services/sandbox/README.md index 49be0c33d5..86562c6acd 100644 --- a/services/sandbox/README.md +++ b/services/sandbox/README.md @@ -50,10 +50,11 @@ runtime_image`. A pull that fails is retried after 30 s, 1, 2, 5 and then every 5–60 s). `GET /health` reports `runtimeImage: { state, lastError, nextAttemptAtMs }` with `state` one of `unchecked`, `pulling`, `ready` or `missing`; a missing image never makes the spawner unhealthy. Docker probes -`GET /health` with `curl` (a runc exec each time) every 30 s once the spawner -is healthy and every 2 s during its first 30 s, so a deploy sees it ready -within seconds of booting; the start interval needs Docker Engine 25 or later -(compose.yml, the CLI generator and the image's `HEALTHCHECK` agree). Session lookups whose backend inventory or endpoint +`GET /health` with `curl` (a runc exec each time) every 30 s, so a booting +spawner reads healthy up to 30 s after it starts; failures in its first 30 s +do not count. There is no faster start interval: Docker Compose refuses +`start_interval` on Engine 24, the oldest engine Tale supports (compose.yml, +the CLI generator and the image's `HEALTHCHECK` agree). Session lookups whose backend inventory or endpoint cannot be read, or whose nonterminal runtime is still starting, answer `503 session_unavailable` and `Retry-After: 1`; callers retry without treating that temporary uncertainty as a lost session. diff --git a/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts b/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts index a4488311b8..e1a8bb3c71 100644 --- a/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts +++ b/tools/cli/src/lib/compose/services/create-sandbox-service.test.ts @@ -43,25 +43,31 @@ test('mount paths cannot inject another compose mount option', () => { expect(() => createSandboxService(config)).toThrow('mount separators'); }); -test('the spawner is probed every 30 s once healthy and every 2 s while it boots, alike in every pipeline', () => { +test('the spawner is probed every 30 s, alike in every pipeline, with nothing Docker Engine 24 refuses', () => { const repoRoot = fileURLToPath( new URL('../../../../../../', import.meta.url), ); - const cadence = { - interval: '30s', - start_period: '30s', - start_interval: '2s', - }; - expect(createSandboxService(config).healthcheck).toMatchObject(cadence); - // The generated stack file carries the field through to Compose. + const cadence = { interval: '30s', start_period: '30s' }; + // Docker Compose refuses `start_interval` on an engine older than 25, and + // the Dockerfile frontend Engine 24 bundles does not know `--start-interval`. + const generatedCheck = createSandboxService(config).healthcheck; + expect(generatedCheck).toMatchObject(cadence); + expect(generatedCheck).not.toHaveProperty('start_interval'); + // The generated stack file carries the cadence through to Compose. const generated = parse(generateStatefulCompose(config, 'localhost')) as { services: Record }>; }; expect(generated.services['sandbox']?.healthcheck).toMatchObject(cadence); + expect(generated.services['sandbox']?.healthcheck).not.toHaveProperty( + 'start_interval', + ); const compose = parse( readFileSync(`${repoRoot}compose.yml`, 'utf8'), ) as typeof generated; expect(compose.services['sandbox']?.healthcheck).toMatchObject(cadence); + expect(compose.services['sandbox']?.healthcheck).not.toHaveProperty( + 'start_interval', + ); const dockerfile = readFileSync( `${repoRoot}services/sandbox/Dockerfile`, 'utf8', @@ -71,5 +77,5 @@ test('the spawner is probed every 30 s once healthy and every 2 s while it boots .find((line) => line.startsWith('HEALTHCHECK')); expect(directive).toContain('--interval=30s'); expect(directive).toContain('--start-period=30s'); - expect(directive).toContain('--start-interval=2s'); + expect(directive).not.toContain('--start-interval'); }); diff --git a/tools/cli/src/lib/compose/services/create-sandbox-service.ts b/tools/cli/src/lib/compose/services/create-sandbox-service.ts index 8aff552c9b..979f27b283 100644 --- a/tools/cli/src/lib/compose/services/create-sandbox-service.ts +++ b/tools/cli/src/lib/compose/services/create-sandbox-service.ts @@ -130,16 +130,16 @@ export function createSandboxService(config: ServiceConfig): ComposeService { '${PLATFORM_SHARED_CONFIG:-config-data}:/app/platform-config:ro', ], restart: 'unless-stopped', - // Each probe is a runc exec of curl: every 30 s once healthy, every 2 s - // while the spawner boots (Docker Engine 25+), so a deploy sees it ready - // within seconds. Mirrors compose.yml and the image's HEALTHCHECK. + // Each probe is a runc exec of curl, every 30 s, so a booting spawner + // reads healthy up to 30 s after it starts. No `start_interval`: Docker + // Compose refuses it on Engine 24, the oldest engine Tale supports. + // Mirrors compose.yml and the image's HEALTHCHECK. healthcheck: { test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8003/health'], interval: '30s', timeout: '5s', retries: 3, start_period: '30s', - start_interval: '2s', }, depends_on: { 'sandbox-egress': { condition: 'service_healthy' }, diff --git a/tools/cli/src/lib/compose/types.ts b/tools/cli/src/lib/compose/types.ts index 9b22a0580a..6f1976c724 100644 --- a/tools/cli/src/lib/compose/types.ts +++ b/tools/cli/src/lib/compose/types.ts @@ -44,8 +44,6 @@ export interface ComposeService { timeout: string; retries: number; start_period?: string; - /** Probe cadence during `start_period` (Docker Engine 25+). */ - start_interval?: string; } // A service with no HTTP surface (the job worker) disables the image's // baked healthcheck rather than reading permanently unhealthy. From 45b1977ec7bca17caf5ebc4436e106f8241867fd Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 03:54:33 +0200 Subject: [PATCH 12/14] fix(sandbox): ask runnerd whether a lingering session is still busy The max-linger self-reap gave a session a stop grace only when an exec ran through this spawner's own stream. The platform follows a long turn by attach and hangs up at every drain window, so the exec it is still draining is usually registered in no spawner at the moment the reap fires, and the busy sessions the grace exists for (harness transcripts to flush, staged files to restore) were still killed outright. With no exec of its own, the reap now asks the session's runnerd, within 3 s, whether it has a live exec or an operation under way, and grants the grace when it does. A daemon that does not answer could not act on the stop and is removed at once. A reap that joined a stop already under way and saw it end without stopping the session (a claim a turn won, a failed removal) used to skip the session, leaving its compute to the sweep's idle logic. It now falls through to its own graceful stop of that same incarnation. --- services/sandbox/docs/sessions.md | 11 ++- .../src/session/session-routes.test.ts | 94 ++++++++++++++++++- .../sandbox/src/session/session-routes.ts | 67 ++++++++++--- 3 files changed, 154 insertions(+), 18 deletions(-) diff --git a/services/sandbox/docs/sessions.md b/services/sandbox/docs/sessions.md index f4ddd17463..246af57b39 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -180,9 +180,14 @@ has been replaced by newly forked, untagged processes after the leader exits. **Session teardown is best effort, not a wrapper-cleanup guarantee.** runnerd passes SIGTERM to execs when it receives a graceful stop, but does not await their completion before exiting. On Docker a stop removes the container with -`docker rm --force`, which kills at once and delivers no graceful stop; only a -stop of a session with a live exec through this spawner asks first. The -max-linger self-reap stops such a session with `docker stop -t 5` (`-t 20` for +`docker rm --force`, which kills at once and delivers no graceful stop; only +the max-linger self-reap's stop of a busy session asks first. Busy is an exec +running through this spawner or, failing one, a live exec or an operation +under way as runnerd's health reports it (asked with a 3 s bound): the +platform follows a long turn by attach and hangs up at every drain window, so +an exec it is draining is usually registered in no spawner. A daemon that +does not answer could not act on the stop and is removed at once. The +max-linger self-reap stops a busy session with `docker stop -t 5` (`-t 20` for a Docker-in-sandbox session, whose supervisor also shuts its inner engine down and whose dockerd waits up to 15 s for its own containers) and then removes it, inside the same lifecycle serialization as every other stop: a sweep or an diff --git a/services/sandbox/src/session/session-routes.test.ts b/services/sandbox/src/session/session-routes.test.ts index a0630c25f2..7981ed0203 100644 --- a/services/sandbox/src/session/session-routes.test.ts +++ b/services/sandbox/src/session/session-routes.test.ts @@ -117,6 +117,9 @@ const daemonLastActivity = new Map(); const daemonIncarnations = new Map(); // The incarnation each activity request named, in arrival order. const activityIncarnations: Array<{ path: string; named: string | null }> = []; +// Per-daemon live exec counts (by session token) /healthz reports, over +// fakeHealth's shared one: an exec runnerd runs that no spawner registered. +const daemonLiveExecs = new Map(); function ndjson( lines: Array<{ t: string; seq?: number; [key: string]: unknown }>, @@ -210,7 +213,7 @@ beforeAll(() => { ...incarnation, lastActivityAtMs: daemonLastActivity.get(token) ?? fakeHealth.lastActivityAtMs, - liveExecs: fakeHealth.liveExecs, + liveExecs: daemonLiveExecs.get(token) ?? fakeHealth.liveExecs, ...(dockerReady === undefined ? {} : { dockerReady }), ...(fakeHealth.dockerRecoveryRequired === undefined ? {} @@ -706,6 +709,7 @@ beforeEach(() => { daemonLastActivity.clear(); daemonIncarnations.clear(); activityIncarnations.length = 0; + daemonLiveExecs.clear(); }); describe('SessionRoutes (fake runnerd)', () => { @@ -4001,6 +4005,59 @@ describe('SessionRoutes (fake runnerd)', () => { expect(routes.sessionIds()).toEqual([]); }); + test('the linger reap asks runnerd whether a session is busy: an exec it follows by attach, or an operation, keeps its grace', async () => { + const tokenOf = (id: string) => deriveRunnerdToken(cfg.sandboxToken, id); + const graces = new Map(); + const routes = new SessionRoutes( + { ...cfg, dockerInContainer: true }, + { + ...fakeBackend, + async stopSession(id, _stamp, options) { + graces.set(id, options?.graceMs); + return fakeBackend.stopSession(id); + }, + }, + ); + for (const [sessionId, docker] of [ + ['linger-attached', false], + ['linger-attached-docker', true], + ['linger-operating', false], + ['linger-silent', false], + ['linger-quiet', false], + ] as const) { + expect( + ( + await routes.handleCreate( + JSON.stringify({ + sessionId, + organizationId: 'org_linger', + profile: 'agent', + docker, + }), + ) + ).status, + ).toBe(201); + } + // Between drain windows nothing is attached, so no exec is registered + // here; runnerd still runs one. + daemonLiveExecs.set(tokenOf('linger-attached'), 1); + daemonLiveExecs.set(tokenOf('linger-attached-docker'), 1); + const operating = new ActivityGate(() => 0); + operating.enter(); + fakeActivities.set(tokenOf('linger-operating'), operating); + // A daemon that does not answer could not act on a stop's signal. + deadDaemons.add(tokenOf('linger-silent')); + expect(await routes.stopAllSessions()).toBe(5); + expect(Object.fromEntries(graces)).toEqual({ + 'linger-attached': 5_000, + 'linger-attached-docker': 20_000, + 'linger-operating': 5_000, + 'linger-silent': 0, + 'linger-quiet': 0, + }); + expect(routes.sessionIds()).toEqual([]); + }); + test('the linger reap joins a stop already under way instead of cutting it short', async () => { const release = Promise.withResolvers(); const started = Promise.withResolvers(); @@ -4029,6 +4086,41 @@ describe('SessionRoutes (fake runnerd)', () => { expect(stops).toBe(1); }); + test('the linger reap stops a session itself when the stop it joined ends without stopping it', async () => { + const release = Promise.withResolvers(); + const started = Promise.withResolvers(); + let stops = 0; + const routes = new SessionRoutes(cfg, { + ...fakeBackend, + async stopSession(id) { + stops += 1; + if (stops === 1) { + started.resolve(); + await release.promise; + throw new Error('docker rm timed out'); + } + return fakeBackend.stopSession(id); + }, + }); + await routes.handleCreate( + JSON.stringify({ + sessionId: 'linger-refused', + organizationId: 'org_a', + }), + ); + fakeHealth.lastActivityAtMs = 0; + const sweep = routes.sweepExpired( + Date.now() + cfg.session.maxLifetimeMs + 1, + ); + await started.promise; + const linger = routes.stopAllSessions(); + release.resolve(); + expect(await sweep).toBe(0); + expect(await linger).toBe(1); + expect(stops).toBe(2); + expect(routes.sessionIds()).toEqual([]); + }); + test.each(['get', 'pin'])( 'a %s miss whose endpoint resolves after drain begins cannot adopt a peer', async (action) => { diff --git a/services/sandbox/src/session/session-routes.ts b/services/sandbox/src/session/session-routes.ts index ac25f0eb20..9a5d9b4cfb 100644 --- a/services/sandbox/src/session/session-routes.ts +++ b/services/sandbox/src/session/session-routes.ts @@ -167,6 +167,11 @@ const BUSY_DOCKER_STOP_GRACE_MS = 20_000; * docker CLI slot for up to its grace, and the rest stay for the others. */ const LINGER_STOP_CONCURRENCY = 4; +/** How long the linger reap waits for a session's runnerd to say whether it + * is busy, under the ordinary 5 s probe: a hung daemon holds one of its four + * lanes no longer than this, and is stopped at once after it. */ +const LINGER_HEALTH_PROBE_MS = 3_000; + /** While the session disk is critical, its largest workspaces are logged at * most this often (each measurement is a bounded `du` of every workspace). */ const WORKSPACE_USAGE_LOG_MS = 10 * 60_000; @@ -497,7 +502,7 @@ export class SessionRoutes { } /** Stop every non-finished session (compute reclaimed, workspace - * preserved); one with a live exec gets a grace to end its work first. + * preserved); a busy one gets a grace to end its work first. * Used by the spawner's max-linger self-reap so a spawner that lingered * past its TTL can shut down without orphaning containers — even if the * deploy died mid-roll. Returns the number stopped. */ @@ -508,16 +513,24 @@ export class SessionRoutes { LINGER_STOP_CONCURRENCY, async (s) => { // A stop already under way (a sweep's, an idle reclaim's) owns the - // incarnation; a second one would cut its grace short. - const pending = this.stopping.get(s.sessionId); - if (pending !== undefined) { - if (await pending) stopped += 1; - return; + // incarnation; a second one would cut its grace short. One that ends + // without stopping it (a claim a turn won, a failed removal) leaves + // the session to this reap's own stop. + for ( + let pending = this.stopping.get(s.sessionId); + pending !== undefined; + pending = this.stopping.get(s.sessionId) + ) { + if (await pending) { + stopped += 1; + return; + } + if (this.registry.get(s.sessionId) !== s) return; } - const stop = this.backend - .stopSession(s.sessionId, s.createdAtMs, { - graceMs: this.stopGraceMs(s), - }) + const stop = this.lingerGraceMs(s) + .then((graceMs) => + this.backend.stopSession(s.sessionId, s.createdAtMs, { graceMs }), + ) .then( () => { this.forgetReclaimed(s); @@ -546,10 +559,36 @@ export class SessionRoutes { return stopped; } - /** How long a stop of this session lets its work end: a grace while an - * exec runs through this replica, none for an idle session. */ - private stopGraceMs(session: RegistrySession): number { - if (session.liveExecs.size === 0) return 0; + /** How long the linger reap lets this session's work end: a grace while + * it is busy, none for an idle session. Busy is an exec through this + * replica or, failing one, what runnerd counts: its live execs and its + * operations under way. The platform follows a long turn by attach and + * hangs up at every drain window, so an exec it is still draining is + * usually registered nowhere here. A daemon that does not answer gets no + * grace: it could not act on the stop. Never rejects. */ + private async lingerGraceMs(session: RegistrySession): Promise { + if (session.liveExecs.size === 0) { + try { + const health = await runnerdHealth( + { + baseUrl: session.endpoint, + token: this.tokenFor(session.sessionId), + }, + AbortSignal.timeout(LINGER_HEALTH_PROBE_MS), + ); + if ( + health.liveExecs === 0 && + (health.activity?.activeOperations ?? 0) === 0 + ) + return 0; + } catch (error) { + console.warn( + `[sandbox.session] linger health probe failed for ${session.sessionId}; stopping it without a grace:`, + error, + ); + return 0; + } + } return (session.docker ?? this.cfg.dockerInContainer) ? BUSY_DOCKER_STOP_GRACE_MS : BUSY_STOP_GRACE_MS; From 38fc4f24ed3e61e582ea6fb61355e3f4969c74c2 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 05:27:30 +0200 Subject: [PATCH 13/14] docs(manual): move this change's automation rows to the settings file The automation coverage map now keeps one file per suite; this change's rows move there. --- services/platform/tests/manual/reference/automation.md | 2 -- .../platform/tests/manual/reference/automation/settings.md | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 866564e5ac..51b48ab4a2 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -501,8 +501,6 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [settings](../suites/settings.md) | Authoritative sandbox quota save boundary | ✅ automated | `backend/domains/governance/routes.test.ts` (exact-capacity acceptance, over-capacity and unavailable-capacity rejection before audit/file writes, forged total ignored, deployment capacity reread at each save, invalid-field and role boundaries) | | [settings](../suites/settings.md) | Memory-aware admission: on a Docker host whose memory the spawner can read, a create that would leave less than `SANDBOX_MIN_FREE_MEMORY` free (creates still starting counted at their working set, sessions that just started at what they are still growing into, a destroyed one at nothing) reclaims a released idle session or answers 429 `host_memory`, a burst admits exactly what fits, unknown memory never refuses; the reading is refreshed every second and concurrent reads share one; a Docker CLI that could not answer is asked again within a minute, a host once verified keeping its verdict meanwhile; an unset `SANDBOX_MAX_SESSIONS` is sized from host memory (8–256, a whole Docker-in-sandbox turn per slot where agent sessions run Docker inside); at most 12 Docker CLI processes run at once, and a call that waits past its budget for a slot answers as a timeout; short calls (the health probe, identity and liveness inspects, the build helper and host memory checks) take a free shared slot or one of 4 kept for them and never queue behind long calls, and a health probe that found no slot answers unhealthy without caching it | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`memory-aware admission`), `services/sandbox/src/host-memory.test.ts`, `services/sandbox/src/spawn-util.test.ts` (`docker CLI concurrency`), `services/sandbox/src/health-probe.test.ts`, `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (`short docker calls beside a burst`) | | [settings](../suites/settings.md) | Disk-aware admission: on the Docker backend, while the disk the session workspaces live on has less than `SANDBOX_MIN_FREE_DISK` free (a twentieth of it, between 2 and 20 GiB; `0` turns it off), every create answers 429 `host_disk` in the first-come line without stopping an idle session, and gets in once space is freed; an unknown or unreadable disk never refuses; the probe reads it with `statfs` every five seconds and logs the disk going below its floor and coming back once each; meanwhile each build-cache upkeep removes the helpers and caches of organizations whose helpers are all stopped and that no session or create may use, the longest-stopped first, at most three a run and only while the disk stays short, and a removal that frees nothing on that disk pauses the removals for six hours | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`disk-aware admission`), `services/sandbox/src/host-disk.test.ts`, `services/sandbox/src/buildkit-lifecycle.test.ts` (`a session disk below its floor`), `services/sandbox/src/config.test.ts` | -| [settings](../suites/settings.md) | The session disk's critical tier: below `SANDBOX_CRITICAL_FREE_DISK` (a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least 1 GiB and never above it; `0`, or a floor of `0`, turns it off), read from the same five-second reading, the sweep stops a released idle Docker-in-sandbox session at once through runnerd's claim instead of after its full idle window, never one a turn holds, and logs the three largest workspaces — one niced `du` of every workspace dir, cut off after 30 s, a session's flat and legacy copies counted together — at most every ten minutes; the disk going below the tier and coming back is logged once each; an unknown or unreadable disk is never critical | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`below its critical tier, the sweep stops a released Docker-in-sandbox session at once`, `an unknown disk, or a critical tier of 0, stops nothing for the disk`), `services/sandbox/src/host-disk.test.ts` (`diskCriticalBytes`), `services/sandbox/src/session/workspace-usage.test.ts`, `services/sandbox/src/config.test.ts` | -| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A sandbox disk that fills up mid-turn is named as such: runnerd's replay journal maps a write the disk refuses for want of space (`ENOSPC`, `EDQUOT`) to `DISK_FULL` instead of `REPLAY_UNAVAILABLE` (any other storage error stays `REPLAY_UNAVAILABLE`) and the failure stands for every later write; both protocol copies accept the code; the spawner forwards it as the stream's terminal `error` code without a result and keeps the session; the platform ends the drain on it without reattaching, with "the sandbox host ran out of disk space" (`ExecDiskFullError`), never the payload | ✅ automated | `services/sandbox-runtime/daemon/src/exec-replay.test.ts` (`a journal write that fails with %s ends the replay as %s`), `services/sandbox/src/session/runnerd-protocol.test.ts`, `services/sandbox/src/session/runnerd-client.test.ts` (`daemon replay failure %s retains its terminal diagnostic code`), `services/sandbox/src/session/session-routes.test.ts` (`a journal that ran out of disk ends the exec stream with DISK_FULL`), `services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts` (`a sandbox disk that ran out ends the exec in words of its own`) | | [settings](../suites/settings.md) | The first-come line for host room: a create refused for room waits by session id in the order of its first refusal; freed room goes to the oldest waiters still asking (a slot each, and memory for their working sets, before a newer create — none for a waiter the host could never fit); each 429 carries `queue: { position, waiting }` and a `retry-after` of 5 s plus 5 s a place, up to 60 s; asking again keeps a waiter's place, one that stops asking gives it up after twice its hint and 15 s, a destroy takes it out, and a restart starts with no line | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`the first-come line for host room`, and the capacity and memory admission tests) | | [settings](../suites/settings.md) | Idle sandbox reclamation under deployment capacity pressure | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (released compute reclaimed before admission, persistent workspace retained, busy/pinned/unknown/legacy runtime protection, delayed release after reacquire, concurrent creates and stop failure); `services/sandbox-runtime/daemon/src/activity-gate.test.ts` (atomic idle claim, active-operation protection and frozen execution gate); `services/sandbox/src/backend/docker/docker-session-backend.test.ts`, `backend/kubernetes/k8s-session-backend.test.ts` (incarnation-fenced compute removal and retained workspace); `backend/domains/sandbox/idle-release.test.ts` (ticket capture, transactional queueing and committed-state checks), `idle-release.integration.ts` (28 real-Postgres checks: organization/allocation/owner guards, admission and release ordering, atomic cancellation and release-job rollback, post-op retry on an already-stopped workflow); `backend/core/node_only/sandbox/agent_session.test.ts` (`ensureAgentSession` refuses a false allocation resume before acquiring runtime compute) | | [settings](../suites/settings.md) | The session sweep frees what nothing uses: a released session stops after the short idle window (Docker-in-sandbox agent sessions keep the full one once their inner engine has run, as runnerd's `/healthz` `docker.used` says; one whose engine never started gets the short window, and a runtime that does not report its engine keeps the full one), a running session whose daemon has not answered five sweeps is stopped (a sweep that cannot probe it starts the count over), ended containers and Pods are removed by their incarnation with the workspace kept, beside the API and several at a time, a create of the id waits for that removal (bounded) and a session registered under the id is neither held up by it nor counted as freed by it, a pass still running is joined, a burst of creates at capacity reclaims one released session each, idle-longest first, a create refused at capacity probes at most eight daemons, sessions last seen released first, and none that answered busy (to a reclaim probe or the sweep) or was acquired within 15 s unless released since, and the refusals in the 3 s after a walk that found nothing are answered at once, the build-cache reconcile after adoption covers agent sessions without holding adoption up, a slow build-cache job never holds the next pass's sweep up (one job at a time, organizations adopted meanwhile reconciled right after it), and a caller hanging up on an attach costs no backend check | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`sweep and adoption hygiene`, `creates refused at capacity do not probe every busy session`), `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (a failed inner image volume removal is reported) | diff --git a/services/platform/tests/manual/reference/automation/settings.md b/services/platform/tests/manual/reference/automation/settings.md index 5b28a92bdd..b0c04c44b3 100644 --- a/services/platform/tests/manual/reference/automation/settings.md +++ b/services/platform/tests/manual/reference/automation/settings.md @@ -21,3 +21,7 @@ Rows for [`settings`](../../suites/settings.md) boxes that moved out of the suit | [settings](../../suites/settings.md) | Exec replay checkpoints are committed by writing a temporary file and renaming it over the last one, with no sync to disk (nothing reads a checkpoint after a restart); a failure after the rename still refuses a stale checkpoint, the checkpoint read and further output, and a checkpoint write stalled past the replay I/O deadline fails the callers queued behind it while its bytes stay charged until the write settles | ✅ automated | `services/sandbox-runtime/daemon/src/exec-replay.test.ts` (no sync or datasync on any handle, no temporary file left beside the checkpoint, a failed prune after the rename), `exec-replay.io.test.ts` (the stalled checkpoint write) | | [settings](../../suites/settings.md) | Every provider record pushed to the sandbox LLM gateway carries a request-worker pool sized by its kind, since the gateway parks a record's workers from the moment it loads it: a shared standard record 512 workers, an org-scoped custom record (per organization, connector and model, the `…__anthropic` sibling included) 64, each with a queue 16 deep per worker. `SANDBOX_LLM_GATEWAY_PROVIDER_CONCURRENCY` and `SANDBOX_LLM_GATEWAY_CUSTOM_PROVIDER_CONCURRENCY` override them; a value that is not a positive whole number keeps the default with one warning, and one above 5,000 is held to 5,000. A resized pool rewrites an already provisioned record at its next provision. A record no provision names again is resized by a pass each backend process starts in the background two to five minutes, drawn at random, after its first provision applied the auth posture (`scheduleProviderPoolShrink`, `shrinkProviderPools`), and once per process unless its listing failed: it lists every record, reads each one over its kind's pool again and writes it back with that pool and its own `network_config`, `custom_provider_config` and raw-payload switches; a record the process provisioned is skipped, a provision waits for the pass's write to its record once that write is sent (one that starts during the pass's read makes the pass leave the record), a failed listing is tried again at the next provision, and a record the gateway refuses keeps its pool, with a warning that names it and, only for a record that carries a base URL (one whose upstream host stopped resolving is refused at every pass), says to delete it from the gateway. A write is given 30 s; one the gateway fails or does not answer is read back and counts as resized when the record holds the new pool, else as unconfirmed; one the gateway failed with a 5xx goes out again after 250, 750 and 2,000 ms only to a record that still reads as there and over its pool, with the config it reads then, so a record deleted meanwhile is never created again, and one it did not answer is never sent again; and the pass always ends with one `provider worker resize finished` line counting resized, refused and unconfirmed records. The gateway's `drop_excess_requests` stays off (a store with it on is rewritten), so a request past a full queue waits for room instead of a 503. | 🔶 backend | `backend/core/node_only/sandbox/llm_gateway_admin.test.ts`, `backend/core/node_only/sandbox/gateway_provisioning.test.ts`; the gateway's memory at boot with many records stays a deployment check | | [settings](../../suites/settings.md) | Docker-in-sandbox start cost and inner store: a resumed workspace whose agent user owns its endpoint-named buildx definition selects it without running the Docker CLI (the shell-derived name equals the earlier Node-derived one; otherwise inspect, then create; a failing digest or create leaves the local builder and never stops the boot); every session exports a persistent `NODE_COMPILE_CACHE` under its HOME, which the root Docker supervisor never loads and runnerd gets back (a cache directory the session user cannot write is skipped with a warning and never stops the boot); with its organization's build network the inner engine pulls docker.io through the organization's mirror, outside the proxy (a malformed mirror is ignored with a warning); an idle engine whose images and build cache exceed 10 GiB prunes dangling images and its build cache to 5 GiB before it sleeps (bounded, a failure logged and the stop kept, a client arriving during the trim keeping the engine); runnerd's `/healthz` reports the engine as `docker: { engine, used }` without activating it | ✅ automated | `services/sandbox-runtime/daemon/src/build-cache-startup.test.ts`, `entrypoint-dispatch.test.ts`, `lazy-docker.test.ts` (with `lazy-docker.node-fixture.ts`), `inner-docker-network.test.ts`, `inner-docker-health.test.ts`, `lazy-docker-health.test.ts`; `services/sandbox/src/session/docker-session-args.test.ts`, `session/runnerd-protocol.test.ts`, `session/session-routes.test.ts` (`sweep and adoption hygiene`); a real pull through a live mirror and compile-cache reuse in a built image stay deployment checks | +| [settings](../../suites/settings.md) | The session disk's critical tier: below `SANDBOX_CRITICAL_FREE_DISK` (a quarter of the `SANDBOX_MIN_FREE_DISK` floor, at least 1 GiB; never above the floor, set or unset; `0`, or a floor of `0`, turns it off), read from the same five-second reading, the sweep stops a released idle Docker-in-sandbox session at once through runnerd's claim instead of after its full idle window, never one a turn holds, and logs the three largest workspaces — one niced `du` of every workspace dir, cut off after 30 s, a session's flat and legacy copies counted together — at most every ten minutes; the disk going below the tier and coming back is logged once each; an unknown or unreadable disk is never critical | ✅ automated | `services/sandbox/src/session/session-routes.test.ts` (`below its critical tier, the sweep stops a released Docker-in-sandbox session at once`, `an unknown disk, or a critical tier of 0, stops nothing for the disk`), `services/sandbox/src/host-disk.test.ts` (`diskCriticalBytes`, `an operator’s tier never stands above the floor`), `services/sandbox/src/session/workspace-usage.test.ts`, `services/sandbox/src/config.test.ts` | +| [tasks](../../suites/tasks.md) / [automations](../../suites/automations.md) | A sandbox disk that fills up mid-turn is named as such: runnerd's replay journal maps an output or checkpoint write the disk refuses for want of space (`ENOSPC`, `EDQUOT`) to `REPLAY_DISK_FULL` instead of `REPLAY_UNAVAILABLE` (any other storage error stays `REPLAY_UNAVAILABLE`) and the failure stands for every later write; both protocol copies accept the code; the spawner forwards it as the stream's terminal `error` code without a result and keeps the session; the platform ends the drain on it without reattaching, with "the sandbox host ran out of disk space" (`ExecDiskFullError`), never the payload, and a task run's drive window that ends on it fails with "the agent run stopped: the sandbox host ran out of disk space" rather than an unexpected stop | ✅ automated | `services/sandbox-runtime/daemon/src/exec-replay.test.ts` (`a journal write that fails with %s ends the replay as %s`, `a checkpoint write that fails with %s ends the replay as %s`), `services/sandbox/src/session/runnerd-protocol.test.ts`, `services/sandbox/src/session/runnerd-client.test.ts` (`daemon replay failure %s retains its terminal diagnostic code`), `services/sandbox/src/session/session-routes.test.ts` (`a journal that ran out of disk ends the exec stream with REPLAY_DISK_FULL`), `services/platform/backend/core/node_only/sandbox/helpers/session_client.test.ts` (`a sandbox disk that ran out ends the exec in words of its own`), `services/platform/backend/core/tasks/agent_run_host.reap.test.ts` (`names a full sandbox disk instead of an unexpected stop`) | +| [settings](../../suites/settings.md) | A Docker stop lets a busy session end its work: the max-linger self-reap stops a busy session — an exec running through the spawner or, failing one, a live exec or an operation under way as runnerd's health reports it within 3 s (an exec the platform follows by attach between drain windows), never one whose daemon does not answer — with `docker stop -t 5` (`-t 20` for a Docker-in-sandbox session, whose inner engine shuts down too) before it removes it, at most four at a time, and joins a sweep or an idle reclaim already stopping a session instead of cutting its grace short; a graceful stop the daemon refuses still removes the container; idle stops, pressure reclaims, failed-create cleanup and destroys remove at once | ✅ automated | `services/sandbox/src/backend/docker/docker-session-backend.test.ts` (`a stop with a grace asks the container to stop before it is removed`, `a graceful stop the daemon refuses still removes the container`), `services/sandbox/src/session/session-routes.test.ts` (`the linger reap lets a session with a live exec end its work`, `the linger reap asks runnerd whether a session is busy`, `the linger reap joins a stop already under way`) | +| [settings](../../suites/settings.md) | The sandbox spawner's healthcheck costs a runc exec every 30 s, not every 10 s, with a 30 s start period whose failures do not count, so a booting spawner reads healthy up to 30 s after it starts; no `start_interval` or `--start-interval`, which Docker Engine 24 refuses; alike in `compose.yml`, the CLI generator's stack file and the image's `HEALTHCHECK` | ✅ automated | `tools/cli/src/lib/compose/services/create-sandbox-service.test.ts` (`the spawner is probed every 30 s, alike in every pipeline, with nothing Docker Engine 24 refuses`) | From 3a59b588983f1fb49281a26ea614d05579d3d103 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 05:28:30 +0200 Subject: [PATCH 14/14] fix(sandbox): keep naming a full disk when a checkpoint save hits it Rebasing onto main, whose checkpoint save now writes a temporary file and renames it without syncing, dropped the mapping this change made: a checkpoint save the disk refused for want of space reported REPLAY_UNAVAILABLE again. It maps the failure like an output write once more. --- services/sandbox-runtime/daemon/src/exec-replay.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/services/sandbox-runtime/daemon/src/exec-replay.ts b/services/sandbox-runtime/daemon/src/exec-replay.ts index 3a2f7d998a..2211e048ca 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.ts @@ -476,12 +476,13 @@ export class ExecReplay { this.checkpoint = checkpoint; await this.prune(); return true; - } catch { + } catch (error) { // A failure after the rename has exposed the newer checkpoint (while // pruning the output it covers) leaves the commit uncertain. Never // let an older in-memory cursor authorize a stale overwrite, or prune - // output against it. - this.failure = new ReplayError('REPLAY_UNAVAILABLE'); + // output against it. A checkpoint the disk refuses for want of space + // is named as such, like a refused output write. + this.failure = journalFailure(error); throw this.failure; } finally { if (!committed) {