diff --git a/.env.example b/.env.example index 913f40308b..ee468a3abb 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; 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). # SANDBOX_SESSION_RELEASED_IDLE_MS=300000 diff --git a/compose.yml b/compose.yml index 2b0752f112..9f4c62dd13 100644 --- a/compose.yml +++ b/compose.yml @@ -884,12 +884,16 @@ services: nofile: soft: 4096 hard: 8192 + # 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: 10s + interval: 30s timeout: 5s retries: 3 - start_period: 15s + start_period: 30s depends_on: sandbox-egress: condition: service_healthy diff --git a/docs/de/self-hosted/configuration/environment-reference.md b/docs/de/self-hosted/configuration/environment-reference.md index 9cf760f0dc..7adf7cfa38 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`; 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. | @@ -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..184d1655be 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`; 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. | @@ -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..e53132bfb4 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` ; 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. | @@ -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/backend/README.md b/services/platform/backend/README.md index 0be81f65e9..5913d12714 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 `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. 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..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 @@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { chunkStageFiles, drainSessionExecResilient, + ExecDiskFullError, ExecStreamProtocolError, ExecOutputGapError, SandboxDeviceOfflineError, @@ -888,7 +889,12 @@ describe('drainSessionExecResilient', () => { expect(requests).toBe(1); }); - test.each(['OUTPUT_GAP', 'OUTPUT_LIMIT', 'REPLAY_UNAVAILABLE'])( + 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; @@ -913,6 +919,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: 'REPLAY_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: 'REPLAY_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..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 @@ -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 `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 = 'REPLAY_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 === 'REPLAY_DISK_FULL') throw new ExecDiskFullError(); if (message === `exec ${execId} not found`) { throw new ExecNotFoundError(execId); } 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', }); 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`) | diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index c1ec5e4699..03c71724ee 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 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. 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..25cf8f8da7 100644 --- a/services/sandbox-runtime/daemon/src/exec-replay.test.ts +++ b/services/sandbox-runtime/daemon/src/exec-replay.test.ts @@ -142,6 +142,79 @@ describe('disk exec replay', () => { } }); + test.each([ + ['ENOSPC', 'REPLAY_DISK_FULL'], + ['EDQUOT', 'REPLAY_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 === 'REPLAY_DISK_FULL' + ? 'The sandbox host ran out of disk space.' + : 'The complete execution transcript is unavailable.', + }); + } finally { + opened.mockRestore(); + await replay.dispose(); + } + }, + ); + + 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 0869a97bc2..2211e048ca 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' | 'REPLAY_DISK_FULL'; export class ReplayError extends Error { constructor( readonly code: ReplayFailure, @@ -38,11 +38,27 @@ export class ReplayError extends Error { message ?? (code === 'OUTPUT_LIMIT' ? 'Execution output exceeded its replay storage limit.' - : 'The complete execution transcript is unavailable.'), + : code === 'REPLAY_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. */ +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' + ? 'REPLAY_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 +394,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; } } @@ -463,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) { diff --git a/services/sandbox-runtime/daemon/src/protocol.ts b/services/sandbox-runtime/daemon/src/protocol.ts index f27b293c19..775a8cf62d 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' + | 'REPLAY_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 === 'REPLAY_DISK_FULL') ); default: return false; diff --git a/services/sandbox/Dockerfile b/services/sandbox/Dockerfile index f4b00c9551..3635604709 100644 --- a/services/sandbox/Dockerfile +++ b/services/sandbox/Dockerfile @@ -109,8 +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. -HEALTHCHECK --interval=10s --timeout=5s --retries=3 --start-period=15s \ +# (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 \ 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 9a7d0e80e8..86562c6acd 100644 --- a/services/sandbox/README.md +++ b/services/sandbox/README.md @@ -49,7 +49,12 @@ 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, 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. @@ -101,7 +106,13 @@ 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; 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 +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 639c44f3b3..246af57b39 100644 --- a/services/sandbox/docs/sessions.md +++ b/services/sandbox/docs/sessions.md @@ -179,11 +179,24 @@ 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 +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 +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 @@ -351,7 +364,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`. The disk-backed spool is the sole retained output history. +`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 `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 @@ -561,6 +581,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, 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 +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.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..e56287eb23 100644 --- a/services/sandbox/src/backend/docker/docker-session-backend.ts +++ b/services/sandbox/src/backend/docker/docker-session-backend.ts @@ -72,9 +72,14 @@ import { workspaceTrash, type WorkspaceTrash, } from '../../session/workspace-trash.ts'; +import { + largestWorkspaces, + type LargestWorkspaces, +} from '../../session/workspace-usage.ts'; import { dockerRm, dockerRmSucceeded, + dockerStop, isDockerMissingImage, isDockerNoSuchObject, runDocker, @@ -99,6 +104,7 @@ import { type OrganizationTeardownResult, type SessionBackend, type SessionSpec, + type StopSessionOptions, type WorkspaceDeletion, } from '../types.ts'; @@ -904,6 +910,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 +951,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 +1109,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 +1117,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 @@ -1388,6 +1412,12 @@ export class DockerSessionBackend implements SessionBackend { return out; } + /** 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 diff --git a/services/sandbox/src/backend/types.ts b/services/sandbox/src/backend/types.ts index 745491985d..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'; @@ -207,6 +208,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 +290,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 @@ -344,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/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.test.ts b/services/sandbox/src/host-disk.test.ts index fea55b337e..b70dc60238 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,65 @@ 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 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( + 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..193fd4b728 100644 --- a/services/sandbox/src/host-disk.ts +++ b/services/sandbox/src/host-disk.ts @@ -64,6 +64,39 @@ 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; 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 (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))); +} + +/** 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; @@ -79,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/runnerd-client.test.ts b/services/sandbox/src/session/runnerd-client.test.ts index 51a95a4a17..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'])( + 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 65af81a96d..53f195e69a 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', + '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 b33faafe47..d9924d9d7c 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: 'REPLAY_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: '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 f27b293c19..775a8cf62d 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' + | 'REPLAY_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 === '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 890d186eee..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 ? {} @@ -333,6 +336,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: 'REPLAY_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([ @@ -691,6 +709,7 @@ beforeEach(() => { daemonLastActivity.clear(); daemonIncarnations.clear(); activityIncarnations.length = 0; + daemonLiveExecs.clear(); }); describe('SessionRoutes (fake runnerd)', () => { @@ -1873,6 +1892,26 @@ describe('SessionRoutes (fake runnerd)', () => { }, ); + 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' }), + ); + 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: 'REPLAY_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); @@ -3909,6 +3948,179 @@ 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 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(); + 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('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) => { @@ -6641,6 +6853,199 @@ 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('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, + 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 648b06057e..9a5d9b4cfb 100644 --- a/services/sandbox/src/session/session-routes.ts +++ b/services/sandbox/src/session/session-routes.ts @@ -13,7 +13,10 @@ import { } from '../backend/types.ts'; import { reportSandboxError } from '../error-reporting.ts'; import { + belowDiskCritical, belowDiskFloor, + diskCriticalBytes, + type HostDisk, type HostDiskSource, type SessionDiskState, } from '../host-disk.ts'; @@ -69,6 +72,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')); @@ -150,6 +154,30 @@ 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 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; +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 @@ -354,6 +382,15 @@ 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 = { + 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): // 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. @@ -464,29 +501,97 @@ 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); 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. */ 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. 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.lingerGraceMs(s) + .then((graceMs) => + this.backend.stopSession(s.sessionId, s.createdAtMs, { graceMs }), + ) + .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 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 stop failed for ${s.sessionId}:`, - err, + `[sandbox.session] linger health probe failed for ${session.sessionId}; stopping it without a grace:`, + error, ); + return 0; } } - return stopped; + 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 — @@ -671,6 +776,116 @@ export class SessionRoutes { } } + /** 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 { + 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 { 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, + ); + // 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; + } + + /** 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 { @@ -1518,11 +1733,14 @@ export class SessionRoutes { */ async sweepExpired(nowMs: number = Date.now()): Promise { let reaped = 0; + const critical = this.diskCritical(); + if (critical.workspace) 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, critical.dockerData)) + reaped += 1; }, ); // The build helpers follow the sessions just stopped, beside the sweep @@ -1566,6 +1784,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. @@ -1643,12 +1862,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..e337f7b051 --- /dev/null +++ b/services/sandbox/src/session/workspace-usage.ts @@ -0,0 +1,86 @@ +// 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, 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'; + +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. */ +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/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. */ diff --git a/services/sandbox/src/types.ts b/services/sandbox/src/types.ts index 699bc08d04..8e186af8ef 100644 --- a/services/sandbox/src/types.ts +++ b/services/sandbox/src/types.ts @@ -191,6 +191,12 @@ 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; 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; /** Idle ceiling — sessions with no runnerd activity past this are reaped. */ 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..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 @@ -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,40 @@ 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, 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' }; + // 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', + ).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).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 b38e2bfa21..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,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, 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: '10s', + interval: '30s', timeout: '5s', retries: 3, - start_period: '15s', + start_period: '30s', }, depends_on: { 'sandbox-egress': { condition: 'service_healthy' },