Repository navigation
fix(platform): refuse new work in a sandbox being destroyed - #4095
Conversation
A sandbox Destroy whose first attempt fails retries for a quarter to half an hour, and its retry checks only that the row is still the one it was asked for. A resume keeps the row id, so a turn let in between two attempts loses its container, workspace and tokens to the next one. The spawner lane drives the real Destroy job through the admin route and the HTTP stand-in spawner: the first attempt fails, then a member's chat run, an agent's next task and an automation step ask for the row through their own shims (ensureAgentSession), then the retry runs. The lifecycle lane holds a pending Destroy against both lock orders, a repeated and a failed Destroy, eventual success, a newer incarnation and another organization's row under the same id. Refs #4091
A Destroy that is queued, retrying or running now closes its row to new work. The hosts' one admission refuses the session under the organization's admission lock: reserveSessionSlot while a live row under the id has an unfinished sandbox.destroy_session job, resumeSessionSlot for the row it would resume. scheduleSessionDestroy takes the same lock, so a turn is admitted either before the request (and cancelled by the Destroy, as running work always was) or after it, and refused. The refusal is quota-shaped (SandboxDestroyPendingError extends SandboxQuotaError): a task's run parks as on a full budget and is woken when the Destroy settles or by the watchdog, then starts in a fresh workspace; an automation step fails with the reason before it begins. A Destroy whose every attempt failed reopens the row, so a deterministic workspace id is never locked for good. The pending state is the same queue row the page reads as Destroying, so the rule and the badge agree; the teardown, its row-id guard and its unpin, settle and key cleanup are unchanged, and no migration is needed. Closes #4091
The Sandboxes page's Destroy row said an agent that starts while the row reads Destroying still works in the old files until the deletion cancels it. It now says nothing new starts there: an agent's run waits, reading Waiting for a sandbox slot, and a workflow run's step fails with the reason; once the row is gone the next start gets a fresh environment, and if the Destroy fails the waiting work continues in the old files. EN, DE and FR. SET-B30 is the manual box; the automation register names the checks that own the logic half. Refs #4091
Knip reads SandboxDestroyPendingError as an unused export: only the admission verbs in sessions.ts throw it, and every caller sees it as the quota refusal it extends. Refs #4091
In the full Backend integration run the lane's organization already holds as many project sandbox sessions as its budget allows, so provisioning the chat and task workspaces threw the cap's SandboxQuotaError and truncated the run at checkSandboxSpawner. The three paths now work in a synthetic organization: the Destroy is asked for through the route's own scheduler and read back through the page's reader, the real worker still runs it against the stand-in spawner, and the rows and jobs go afterwards. Refs #4091
yannickmonney
left a comment
There was a problem hiding this comment.
Independent review verdict: changes requested. Reviewed by a separate agent and cross-checked by the coordinating reviewer; submitted as a comment because this repository shares one GitHub principal with the author. No GitHub approval is asserted.
Request changes on the source-derived terminal-settlement/resume gap described inline. No local concurrency or teardown test was run. Exact-head hosted Backend integration is 1,440/1,440 across 217 lanes; all 18 Playwright jobs succeeded, and their annotations/artifact listing show no retry/failure diagnostics. Also correct the manual overview total: 1,079 boxes are present, while the readme still says 1,078. This review does not claim the ordering concern was reproduced.
Review 5396935490 (r4169908059) found that resumeSessionSlot reads its row without a lock and writes it back by id alone, while a terminal write takes no admission lock. A settlement that commits between the read and the pending-Destroy predicate leaves the predicate no live row to find, and the write then moves the destroyed row back to active. The lifecycle lane now pauses the resume exactly there, deterministically: an ACCESS EXCLUSIVE lock on the queue's table holds the predicate after the row read (the wait is observed in pg_locks), the settlement commits on a connection of its own, then the lock is released. At e73d55a both a Destroy attempt's settlement and a heal end with the resume admitted and the row active again, its destroyed stamp kept. Refs #4091
resumeSessionSlot read its row without a lock and wrote it back by id alone, while a terminal write (markSessionDestroyed from a Destroy attempt, a heal or a reclaim; the cleanup's claim; a watchdog's stamp) takes no admission lock. A settlement committing between the read and the pending-Destroy predicate left the predicate no live row to find, and the write moved the destroyed row back to active: the caller resumed the old incarnation, its createdAt and conversation, over a deleted workspace. The write is now the boundary: it moves the row only while it is still live and answers false when it moved nothing, as if the settlement had come first; the caller already reads false as an allocation that no longer exists, and its next start opens a fresh incarnation. A write that lands holds the row until the commit; after it, an administrator's Destroy settles only from inside an attempt while its job is unfinished, so one queued earlier refused the turn at the predicate or had settled the row already, and one asked for later waits for the admission lock and cancels the turn. The source states this ordering at the write. Refs #4091
…etry-resumed-work
The platform manual's overview said 1078 boxes while 1079 were present at e73d55a (SET-B30 was counted in its suite but not in the total); with main's three new boxes it now reads 1082, the sum of its own table. The automation register names the new interleaving check: a resume moves its row only while it is still live. Refs #4091
yannickmonney
left a comment
There was a problem hiding this comment.
Source re-review of the P1 at adf8c4640522bafbbf91979cbf02af837c2790a9: the new live-status compare-and-set on the resume UPDATE addresses the ordering gap in my previous review. A terminal settlement committed before the write now makes it update zero rows and return false; a successful write holds the row through commit. This avoids reviving the already-settled incarnation. The surrounding explanation correctly distinguishes a prior unfinished Destroy from a later request serialized by the admission lock.
This is a bounded source disposition for the original P1, not whole-PR merge acceptance. I read the changed lifecycle regression source but ran no new interleaving experiment. Preserve the author's local environment limitations and verify the full native/CI and current-main composition evidence through the independent review owner (Tale agent #2). No skipped or pending job is counted as success, and the release hold remains until that acceptance and merge are observed.
|
Independent review of PR #4095 at
Local evidence. PostgreSQL 16.14 with pgvector and no
The ordering argument holds for the row a Destroy names. I checked:
MEDIUM (pre-existing on Three facts combine:
Two writers take the named row out of the live set without either lock:
If either happens while an attempt deletes, a reserve under the same id is admitted, and the attempt then destroys it. Probe. I inserted it untracked into
The real path (from source; the timing is not measured):
On Fix options:
LOW and INFO
Verdict: accepted for #4091's resumed-work path and root's P1. The MEDIUM goes to a follow-up issue through the manager. No browser pass: the UI strings are unchanged and the docs were read in EN, DE and FR. |
|
Whole-PR acceptance addendum for #4095, answering root's review 5397655922 (01:20 Zurich). Tale agent #2 I read everything below from the GitHub API and the job logs myself; none of it is taken from the author's report. Exact-head coverage
Composition with current
Follow-ups: dispositions, not waivers. All three pre-existing items are deduplicated into #4106, and none comes from this PR.
So whole-PR acceptance at |
Repair round 1: a resume could revive a row settled under it
The finding (review 5396935490, r4169908059).
resumeSessionSlotread its row without a lock and wrote it back by id alone. A terminal write takes no admission lock. That coversmarkSessionDestroyed(from a Destroy attempt, a heal or a reclaim), the cleanup's claim and a watchdog's stamp. So a settlement could commit between the row read andsessionDestroyPending, and the predicate would find no live row. The write then moved the destroyed row back toactive, andensureAgentSessionreturned the oldcreatedAt: the old conversation over a deleted workspace.Reproduced first, deterministically, at the reviewed head
e73d55aaa. I added the check ind5a4864e2:ACCESS EXCLUSIVElock onpgboss.jobholds the resume exactly between its row read and its predicate. The wait is observed inpg_locks; no sleep orders anything.Both variants end the same way at
e73d55aaa:The fix (
eeaac14f1): compare-and-set on the resume write.UPDATE … WHERE id = $row AND status = ANY(live) RETURNING id, and 0 rows answersfalse.falseas an allocation that no longer exists (ensureAgentSessionthrows, and the task's retry opens a fresh incarnation).The ordering guarantee is stated in the source at the write:
There's no new lock and no migration, and the rule and docs are unchanged. With the fix:
Also in this round:
aef578832mergesmainb7d1c1d7e(fix: name budget-rule keys, explain empty chat replies, land docs labels #4012), with no conflicts.adf8c4640corrects the platform manual overview to 1082 boxes: 1079 ate73d55aaa, plus fix: name budget-rule keys, explain empty chat replies, land docs labels #4012's three, which is the sum of its own table. It also adds the new check to the automation register.Adjacent, not changed here (pre-existing on
main). The task host's activation after a fresh create (sandbox/session_mutations:setSessionStatusin the agent-turn shim) also writes by row id alone. A Destroy that settles acreatingrow during its create can therefore be undone by that activation. It isn't a delayed retry deleting resumed work, and closing it means the host failing the start when the activation moves nothing. I suggest a follow-up.What changed
If a sandbox Destroy is queued, retrying or running, its row no longer accepts new work.
The bug (#4091, found in the #4087 review). If the first Destroy attempt fails, the
sandbox.destroy_sessionladder retries for 15 to 30 minutes. Each retry checks only that the row is still the one it was asked for (teardownSession's row-id guard). A resume keeps the row id (resumeSessionSlotupdates the row in place), so a turn could resume between two attempts. The next attempt then:The rule: a pending Destroy closes its row to admission, enforced at the hosts' one admission boundary under the organization's admission lock.
reserveSessionSlot()refuses the session while a live row under that id has an unfinished Destroy job.resumeSessionSlot()refuses the row it would resume.scheduleSessionDestroy()now takes the same lock. A turn is therefore admitted either before the request, and cancelled by the Destroy as running work always was, or after it, and refused.sessionDestroyPending()indestroy-schedule.ts. It reads the same queue row the page shows as Destroying (sessionDestroyStates), so the server rule and the badge agree by construction.What a refused turn does. The refusal is
SandboxDestroyPendingError, a subclass ofSandboxQuotaError(QUOTA_EXCEEDEDwith its own message).tasks.agentRun.waitingForSlot,chat.taskTray.waitingForSlot). It wakes when the Destroy settles (markSessionDestroyed's release edge) or on the 2-minute watchdog tick, then starts in a fresh workspace.failed): the row reopens, so an agent's deterministic workspace id is never locked for good.Why this rule and not "delete only if idle". With #4088, a first attempt whose answer was lost may already have moved the tree to
.trash. A turn let in between attempts would then resume the same incarnation (with its--resumehandle) over a half-deleted workspace. Refusing admission also carries out the administrator's request instead of silently dropping it, and needs no migration.Unchanged:
Finding → commit → test
ensureAgentSessionon each lane's own shimef83dc8a0(regression),0ae685338(fix)checkSandboxSpawner:sandbox Destroy retry never deletes work resumed after the request: a member's chat run/an agent's next task/an automation's next step. These use the real admin route, the real pg-boss retry and the HTTP stand-in spawner, and cover eventual success with a fresh incarnation afterwardscheckSandboxLifecycle:a resume while a retry deletes the workspace is refused before it startsa request waits for an admission in progress, and a turn after it is refused(observes the waiter inpg_locks; a fresh reserve beside the row is refused too)a repeated Destroy is absorbed while pending, a failed one reopens the row, a new one closes itonce the Destroy has deleted the workspace, the next start opens a fresh incarnation(passes onmaintoo; it guards against over-refusal)a Destroy pending for a settled incarnation blocks no newer one(passes onmaintoo; it guards the row-id scoping)a Destroy holds its own organization's row only0ae685338destroy-schedule.test.ts(unit)b9409324fe73d55aaad5a4864e2(regression),eeaac14f1(fix)checkSandboxLifecycle:a resume never revives a row settled between its read and its predicate (a Destroy attempt)/(a heal)adf8c4640lint:manual; the overview equals the sum of the suite table (1082)mainb7d1c1d7eaef578832aedeb4f80platform/admin/sandboxes.md; manual boxSET-B30; automation-register rowHow I verified it
Real Postgres: PostgreSQL 16.14 with pgvector 0.8.6, from the PGDG bookworm debs, checksums recorded. There is no
pg_search. Each run used a fresh database pair:main19776cf18, untouchedmaincode + the final regressionsstart between attempts=resumed (want refused), container after it=running, row=active, page=pending, …, container after the retry=none, turn tokens revoked=1/1e73d55aaastart between attempts=refused, container after it=none, row=stopped, page=pending, retry settled=true, turn tokens revoked=0/0, start after the Destroy=freshd5a4864e2(e73d55aaa's code + the interleaving regression), lanecheckSandboxLifecycleresume=admitted … row after=active … revived with its destroyed stamp)eeaac14f1(the fix)resume=absent … row after=destroyed)adf8c4640(fix merged withmainb7d1c1d7e)Locally, the same two checks fail in every run, and both are environmental:
knowledge BM25 indexes verified at bootneedspg_search;workspace-tool door … product_find=ok (hit=false)also fails on the untouchedmainrun.CI's tale-db image has
pg_search.CI on head
e73d55aaa: Backend integration is 1440/1440 checks across 217/217 lanes, including all 9 new checks (run 37058930318, job 111010513842). Knip, Type check, Unit and the rest of Checks are green. The first round atb9409324ftruncated atcheckSandboxSpawner: the lane org's project-session cap, fixed ine73d55aaa.CI on head
adf8c4640: Backend integration is 1447/1447 checks across 217/217 lanes (run 37072554375, job 111055188406). That includes both interleaving checks (resume paused between its read and its predicate=true … resume=absent … row after=destroyed) and the 9 earlier ones. Every workflow succeeded: Checks 37072554375, Build 37072554384, E2E 37072554430, SAST 37072554519 and Commitlint 37072554459. The skipped checks are fork-PR jobs, containers this change doesn't touch, and the candidate gates.Other local checks (repeated at the round-1 head):
destroy-schedule.test.ts9/9. The 62 sandbox, session-client, shim, task-host and jobs test files: 966/966. I left outrender_fetch.test.ts, which fails 15/30 identically on unmodifiedmainbecause there's no browser here.oxlint --type-awareexits 0 on the changed files, andoxfmt --checkis clean.tsc --noEmitover the changed files plusintegration-check.tsin an isolated config: 0 errors, 3,255 files.integration-scopeandintegration-skips9/9.lint:manualok (1427 boxes across 5 trees), andcheck-guide.ts settings.mdOK.bun run knip:checkclean.Not in this change
sandbox.destroy_session;signal, so an attempt that runs past its 900 s expiry can overlap its retry. If pg-boss marks that expired attemptfailedwhile it still runs, admission reopens under it. I didn't verify this at runtime;AppErrorJSON. That's how everyQUOTA_EXCEEDEDreads there today.QUOTA_EXCEEDEDis reused, and no secret reaches a message or log.Closes #4091