Skip to content

fix(platform): destroy the container of a failed agent session - #3505

Merged
yannickmonney merged 3 commits into
mainfrom
fix/destroy-failed-agent-session
Sep 27, 2026
Merged

yannickmonney merged 3 commits into
mainfrom
fix/destroy-failed-agent-session

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When a fresh agent session's spawner create failed, ensureAgentSession marked the app.sandbox_sessions row failed and rethrew. It never asked the spawner to destroy what it might already have made. A create cut short between Docker's create and start leaves its container in state created, and nothing ever removed it:

  • the watchdog's reconcile pass walks creating/active/degraded rows and reclaim walks stopped/expired ones, so no pass reached a failed row;
  • failed isn't a live status, so the Sandboxes page never listed the row and nobody could destroy it by hand;
  • the spawner adopts only running session containers, and its one-shot sweep keys on another label.

As #3494 reports, the leaked container kept its runtime image, and with it a whole superseded release (about 12.5 GB), alive through every later deploy. Its host workspace directory stayed too.

Fix

  • Failure path (backend/core/node_only/sandbox/agent_session.ts): the fresh-row catch now calls sessionDestroyIfIdle(sessionId) before the row is marked failed. Only an idle session goes: a sibling turn of the same owner can resume the still-creating row and create or adopt the session itself, and its running exec must never die for this turn's failure (a busy answer is logged and left to the sweep). A container that never started runs no exec, so the leak from Sandbox: an agent session that fails after its container was created leaves the container behind #3494 is still destroyed. The call is best-effort: a failure is logged with console.warn and never masks the create's error. The destroy runs while the still-creating row holds the owner's slot, so no fresh create of the same deterministic id can start underneath it. The resume path is unchanged: a failed resume releases its slot and never destroys the standing workspace.
  • COLLECT pass (backend/domains/sandbox/watchdogs.ts): the 5-minute sandbox sweep gains a pass over failed rows with destroyed_at_ms IS NULL, once they are past a 10-minute grace. It uses the same fair walk and visit stamps as the other spawner-facing passes.
    • Reused ids. Session ids are deterministic (pa-<agentId>, wf-<runId>-…), and the next turn inserts a new row under the same id. A failed row whose id a newer row (any status) or a live row (any age) also carries is stamped without a spawner call: whatever the spawner holds under that id belongs to the newer incarnation. This check runs per row, just before the spawner call, and is deployment-wide, because the spawner's session namespace is.
    • Otherwise the spawner destroys the session with ?if_idle=1, as the ended-run reclaim does. A busy session or a spawner error leaves the row for a later tick.
    • The stamp is by primary key, and the row keeps status failed, which records what happened to that incarnation. markSessionDestroyed would settle every row and revoke every token under the session id, a live successor's included. A failed incarnation never minted credentials (the hosts mint only after ensureAgentSession returns), so its docstring now names this exception.
    • SandboxWatchdogResult.collected reports the count, and the watchdog.sandbox job logs it.
  • No migration. The candidate query uses sandbox_sessions_reconcile_order; the successor check uses sandbox_sessions_session_id.
  • Comments only: session_constants.ts no longer credits a non-existent "owner-cascade teardown" with reaping failed rows.

Proof

  • Unit, agent_session.test.ts (both owner types):
    • a session whose create was started and then threw is destroyed after create and before setSessionStatus(failed);
    • an adopted orphan that turned out to be gone is destroyed as well;
    • a destroy that fails is logged, the row still reads failed, and the original error survives;
    • the resume path and the success paths never destroy.
    • a session a sibling turn is executing in answers busy: it is left alone, the busy answer is logged, and the row still reads failed.
    • Against the unfixed source, 8 of these cases fail.
  • Unit, watchdogs.test.ts:
    • a failed row whose spawner session is still live is destroyed when idle and stamped by id, never via markSessionDestroyed;
    • a superseded row is stamped without a spawner call;
    • busy sessions and spawner errors are left unstamped but visited;
    • the query shape (unstamped failed rows, grace, fair order) is pinned;
    • skipReconcile skips the new pass.
    • Against the unfixed source, 5 of these cases fail.
  • Real Postgres, checkWatchdogs lane 3c in backend:integration, with a scripted spawner:
    • wd-collect-live=failed/stamped, and the spawner was asked;
    • reused id: wd-collect-reused=failed/stamped with no spawner call, while the newer stopped incarnation stays unstamped and its token stays live;
    • busy and in-grace rows stay unstamped;
    • with the unfixed watchdogs.ts the same lane FAILS (after 8 ticks every row is still unstamped).
    • Run with ITEST_LANES=checkWatchdogs on PostgreSQL 16.14 + pgvector: 23/24. The one failure is the boot-time knowledge BM25 indexes verified at boot check, because that database had no ParadeDB pg_search; it is unrelated to this change.
  • CI on this PR, all executed rather than replayed (cache miss, executing):
    • Type check: platform tsc --noEmit passes.
    • Unit: 808/808 files and 77,244 tests pass, including the two changed suites.
    • Lint, Knip, Opengrep and Lint commits pass.
  • Local runs.
    • The platform unit gate matched CI apart from 4 tests (render_fetch.test.ts ×3, openai-compat.test.ts ×1). They fail identically on untouched origin/main in that sandbox and pass in CI.
    • oxlint --type-aware --type-check is clean on every changed file, the hosts that call ensureAgentSession, and the touched directories. The whole-workspace tsc/lint does not fit that sandbox's 4 GiB, which is why CI's run is quoted above.
  • oxfmt --check, bun run lint:manual, and opengrep on the changed files (0 findings) all pass.
  • Not run: the host check. docker ps -a --filter name=tale-sbx --filter status=created --format '{{.Names}} {{.Status}} {{.Image}}' on a Docker host has not been run, because this environment has no Docker daemon. After deploy it should list no new entries. Existing leftovers of failed rows are collected by the sweep within a few ticks (25 rows per tick). A container with no platform row at all stays out of reach and needs a manual docker rm.

Notes for review

  • On the fresh path, DELETE /v1/sessions/:id also removes the host workspace directory, as Sandbox: an agent session that fails after its container was created leaves the container behind #3494 asks ("container and workspace"). A directory there can only be a leftover of an incarnation the platform already ended (a destroyed, expired or failed row), because a live or hibernated row sends the turn down the resume path.
  • Pre-existing race, not fixed here. A second turn of the same project agent can resume the fresh row while it is still creating, and end up creating the session itself; the first turn's catch then flips that row to failed. Both destroys (the catch's and the sweep's) are if_idle, so neither kills a session that turn is executing in; the flip itself is the pre-existing part.

Out of scope

  • The render lane (render_fetch.ts) has the same shape: a failed create skips the spawner destroy and the row is flipped to destroyed, so the sweep never sees it. Its batch key can repeat on a job retry, so a 409 there needs its own analysis.

Closes #3494

yannickmonney and others added 3 commits September 27, 2026 12:17
A fresh agent session whose spawner create failed was marked `failed`
without asking the spawner to destroy what it may already have made. A
create cut short between Docker's create and start leaves its container
in state `created`, and nothing ever removed it: the row is never
reconciled, resumed or listed, and the spawner only adopts running
session containers. The leaked container kept its runtime image, and with
it a whole superseded release, alive through every later deploy.

ensureAgentSession now calls sessionDestroy best-effort before the row
reads `failed`, while the still-`creating` row holds the owner's slot, so
no fresh create of the same deterministic id can start under the destroy.
A destroy failure is logged and never masks the create's error. The resume
path is unchanged: a failed resume releases its slot and never destroys
the standing workspace.
Nothing ever collected a `failed` session row: reconcile walks
creating/active/degraded rows and reclaim walks stopped/expired ones. A
destroy the failing turn could not complete (a spawner being rolled, a
wedged daemon) therefore left the container and its host workspace for
good.

The sandbox sweep gains a COLLECT pass over `failed` rows without
`destroyed_at_ms`, past a ten-minute grace, in the same fair walk as the
other spawner-facing passes. Session ids are deterministic and the next
turn inserts a fresh row under the same id, so a row whose id a newer or
live incarnation carries is settled without a spawner call. Otherwise the
spawner destroys the session only when idle (`if_idle`), as for the
ended-run reclaim; busy and erroring sessions wait for a later tick. The
row is stamped by primary key and keeps its `failed` status:
markSessionDestroyed would settle every row and revoke every token under
the session id, a live successor's included.

The real-Postgres checkWatchdogs lane drives the pass with a scripted
spawner, and the manual automation register records the coverage.
A sibling turn of the same owner can resume the still-creating row and create or adopt the session itself; an unconditional destroy on this turn's failure would kill that turn's running exec. The failure path now destroys only an idle session (if_idle), which still covers a container cut short before it started, and leaves a busy one to the watchdog's collect pass.
@yannickmonney
yannickmonney merged commit 7f6fe10 into main Sep 27, 2026
50 checks passed
@yannickmonney
yannickmonney deleted the fix/destroy-failed-agent-session branch September 27, 2026 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sandbox: an agent session that fails after its container was created leaves the container behind

1 participant