Skip to content

fix(platform): run a sandbox Destroy as a job, not in the request - #4087

Merged
yannickmonney merged 6 commits into
mainfrom
fix/sandbox-destroy-scheduled
Oct 2, 2026
Merged

yannickmonney merged 6 commits into
mainfrom
fix/sandbox-destroy-scheduled

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4086.

What was wrong

Settings → Sandboxes → Destroy ran the whole teardown inside the request: it waited, with no time limit, for the session's lifecycle lock (a pinned recreate holds it for minutes), then the spawner's unpin, then the spawner's delete (the recursive workspace rm has no timeout), and only then settled the row. The dialog spun the whole time and the row stayed listed. Past the spawner client's 30 s cap the admin got an error toast while the delete kept going.

What changes

  • Backend. POST /api/app/sandbox/sessions/:id/destroy takes the latest row under that id. It answers 404 when the organization holds no such row or the row is already destroyed. Otherwise it queues sandbox.destroy_session for that row (new domains/sandbox/destroy-schedule.ts) and answers 202. The queue is exclusive per row, so a second ask while one is queued, retrying or running adds nothing. The job runs teardownSession with 5 retries (30 s doubling with jitter, a quarter to half an hour in all), so lock order, unpin-first and settle rules stay exactly what lifecycle.integration.ts proves. The teardown's one addition: it does nothing when the row it was asked for is no longer the latest under the id, or is already settled. Without that, a retry could run after the reconcile had healed the row and a turn had opened a fresh incarnation under the same deterministic id, and it would delete that fresh workspace mid-turn.
  • Why not end the row synchronously and only delete in the job (the sketch in Bug: sandbox Destroy runs in the request; the row lingers until it ends #4086): a turn that starts while that delete is still queued would open a fresh incarnation over the very files the delete is about to remove, and the job would then delete them mid-turn. retireWorkspace is safe only because its claim and delete run back to back under the lock.
  • List. GET …/sessions/view adds destroyState: 'pending' | 'failed' | null to each row, read from the latest job asked for the row it lists now: pending while it is queued, retrying or running; failed once the ladder ran out. A job for an earlier incarnation never marks a fresh workspace. The list polls every 2 s while a row is pending; an adapter row's refetchInterval may now be a function of its answer (first commit).
  • UI. The confirmation closes as soon as the job is queued, with the toast Destroying sandbox · It leaves the list once its workspace is deleted. The row shows a Destroying badge, and Pin and Destroy wait until it is gone; Stop task stays available. A failed one shows Destroy failed and offers Destroy again.
  • Copy. en/de/fr. German and French use short labels that fit the 150 px Status column: Wird gelöscht / Nicht gelöscht and Suppression… / Non supprimée. The admin docs (en/de/fr) describe the background deletion and no longer promise a fresh environment for an agent that starts while a Destroy is pending. The confirmation now says the fresh sandbox comes once the old one is gone. New manual boxes SET-F73 and SET-B29, plus an automation.md row.

Review

An adversarial review before merge found three real problems, fixed in the last three commits: a retry could delete a fresh incarnation under a reused id; the docs and the confirmation promised a fresh environment during a pending Destroy; Stop task was held during one for no reason. A fourth claim was refuted.

Behaviour change to be aware of

A Destroy the spawner refuses is now retried for up to half an hour instead of stopping at the first error. If a turn resumes the workspace in that window, a later retry still force-deletes it. That matches the confirmation's "Any running task is cancelled", and the row reads Destroying throughout.

Verification

  • Unit and component tests: destroy-schedule.test.ts (new), routes.test.ts, sandboxes-settings.test.tsx, settings-sandbox.test.ts, use-backend-query.test.ts. The sandbox, jobs and adapter suites pass (1,129 tests), as do the settings UI and hooks suites (1,468). Typecheck, oxlint, oxfmt, i18n, docs, lint:links, lint:manual, check-guide and opengrep: 0 findings.
  • Real Postgres, ITEST_LANES=checkSandboxSpawner,checkSandboxLifecycle: all three new checks pass, and CI's full run passed 1323/1323 before the review fixes.
    • The spawner holds its delete, and the request still answers 202 while the row reads pending; the row settles once the delete is released.
    • The spawner refuses the delete: the job retries while the row reads pending, a duplicate ask adds no job, and the row reads failed (still active) once the ladder is marked run out. Asking again finishes it.
    • A retry that outlives its row (healed, then a fresh incarnation under the same id) leaves the fresh workspace alone, and the list never marks it. Run with the row guard removed, this check fails with freshKept=false.
    • The one red check, workspace-tool door … hit=false, fails identically on clean main in the same filtered run (it needs an earlier lane's data).
  • In a real browser, on an isolated dev stack with a stand-in spawner that holds each delete for 8 s:
    • The confirmation closed 92 ms after the click and the Destroying badge showed at 142 ms. The row left with no reload at 10.2 s, while the other workspace stayed listed.
    • With the spawner stopped, the job went to retry and the list polled every ~2 s. Once the ladder was marked run out, the row read Destroy failed and Destroy was enabled again. Asking again finished in about 4 s.
    • de and fr were checked visually, which is how the original labels were caught truncating.

Not observed: a real spawner deleting a large workspace, and the full half-hour ladder (stood in for by marking the job failed).

An adapter row's refetchInterval may now be a function of the fetched
body, so a list can poll faster while one of its rows is changing and
fall back to its usual cadence (or stop) once nothing is.
…equest

The Sandboxes page's Destroy ran the whole teardown inside the request:
the session's lifecycle lock (which a pinned recreate holds for minutes),
the spawner's unpin and its delete of the workspace, then the settled row.
The confirmation spun for all of it and the row stayed until it ended; past
the spawner client's 30 s the admin got an error while the delete went on.

The request now checks that the organization holds an undestroyed row
under the id and queues `sandbox.destroy_session` (exclusive per session,
six tries over a quarter to half an hour), then answers 202. The job runs
the same `teardownSession`, so its lock order, unpin-first and settle
rules are unchanged. The teardown stays one step under the lock rather
than ending the row early: a turn started while a split-off delete was
still queued would resume the very files it is about to remove.

The list reads each row's latest Destroy job back: Destroying while it is
queued, retrying or running (the list then polls every 2 s), and Destroy
failed once its ladder ran out, for the incarnation it was asked of. The
dialog closes as soon as the job is queued; the row's menu offers nothing
while it is pending. Copy in en/de/fr, the admin docs, and manual boxes
SET-F73 and SET-B29 follow.

Closes #4086
A Destroy job carried only the session id. Its retry can run long after
the request: if an attempt's answer was lost after the spawner deleted
the workspace, the reconcile heals the row, and a turn opens a fresh
incarnation under the same deterministic id (a project agent's is the
same every time). The retry then deleted that fresh workspace mid-turn
and settled its row, and the list read it as being destroyed.

The job now names the latest row it was asked for. The teardown leaves a
session alone when that row is no longer the latest under the id, or is
already settled. The exclusive queue is keyed by the row, so a Destroy of
the newer incarnation is queued on its own rather than absorbed by the
older one still retrying. The list reads each job against the live row
it names.
A pending Destroy held every row action. Pin and Destroy must wait for
it, since the teardown unpins and deletes the workspace whatever is asked
meanwhile, but stopping a task does not touch the pin or the row. A task
that runs while the Destroy retries could no longer be stopped from the
page.
The Destroy confirmation and the admin docs promised a fresh environment
on the next agent start. While a Destroy waits for its next attempt, an
agent that starts still works in the old workspace, and removing it
cancels that work. Only a start after the row is gone gets a fresh one.
@yannickmonney yannickmonney changed the title fix(platform): queue a sandbox Destroy instead of running it in the request fix(platform): run a sandbox Destroy as a job, not in the request Oct 2, 2026
@yannickmonney
yannickmonney merged commit eee0a10 into main Oct 2, 2026
@yannickmonney
yannickmonney deleted the fix/sandbox-destroy-scheduled branch October 2, 2026 16:53
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent post-merge review of #4087 at b2af0f5967afc4bb2273265184a4da1805c0bf90 (merged as eee0a1098): sound, with one MEDIUM to route as a follow-up.

What holds

  • Duplicate asks: a double click or two tabs queue one job. pg-boss exclusive puts a unique index on the row-keyed singletonKey, and a newer row's Destroy isn't absorbed.
  • Authorization: only admins can queue a Destroy, the organization comes from the membership, and every query is org-scoped. I found no cross-organization path.
  • Responses: 202 or 404; the app doesn't read the body.
  • Shared poll hook: a numeric refetchInterval passes through unchanged. The function form gets the raw answer, never returns false, and leaks no timer.
  • UI:
    • Pin and Destroy wait while a Destroy is pending, Stop task stays available, and a failed Destroy can be asked again.
    • The EN/DE/FR keys and docs match.
  • With fix(sandbox): delete a destroyed workspace in the background #4088: only the sandbox service deletes files, and a repeated delete settles without a double delete.
  • Local, synthetic:
    • at the head: the sandbox, schedule, routes and adapter tests pass 78/78, and the settings UI and hook tests 38/38;
    • at e1e175170: the services/sandbox suite passes 640/640.
  • CI at the head (merge ref onto 1f0009cc3): 50 jobs succeeded on their latest attempt and 10 were skipped by design. Backend integration passed 1324/1324 across 215/215 lanes.

M1 (MEDIUM): a retrying Destroy still kills and deletes a workspace a turn resumed after the click.

  • The guard (backend/domains/sandbox/service.ts, teardownSession) skips only a row that is not the latest under the id, or one already destroyed.
  • A turn resumes the same row in place: sessions.ts "Resume in place … preserving createdAt (same incarnation)", UPDATE … SET status = 'active' … WHERE id = ${row.id}. So the row-id guard passes.
  • The delete is unconditional (await destroy(sessionId)).
  • The ladder (jobs/tasks.ts: retryLimit: 5, retryDelay: 30, retryBackoff: true, expireInSeconds: 900) keeps that window open for 15–31 minutes, where before it lasted as long as the request (about 30 s).
  • Scenario:
    1. An admin destroys a Stopped agent workspace, and the first attempt fails, for example because the sandbox service is restarting.
    2. A member's chat or a scheduled automation then resumes that workspace.
    3. The next attempt kills that turn, deletes its workspace and revokes its token and gateway keys.
    • The work created after the click is lost, and its owner gets no warning.
  • With fix(sandbox): delete a destroyed workspace in the background #4088 merged, "a start during a pending Destroy uses the old files" isn't always true. If the failed attempt's delete did reach the service, the old tree is already in .trash, so the resumed turn gets an empty workspace, which the retry then kills.
  • The PR's "Behaviour change" section names the force-delete. I rate it MEDIUM because the person who loses work isn't the one who clicked Destroy.
  • Fix options:
    • refuse to resume a row with an unfinished sandbox.destroy_session job, or with a marker set in the scheduling transaction;
    • or, on retries, delete only while idle (sessionDestroyIfIdle) and throw to retry.
  • Missing test: the same row resumed between two attempts.

LOW

  1. sandbox.destroy_session is in neither the slot queues nor the batch limits (jobs/tasks.ts). A batch of up to WORKER_CONCURRENCY is awaited as a whole, so one teardown waiting on a pinned recreate's lock delays other organizations' Destroys. Each teardown also holds pool connections. A slot queue or a cap would fix it.
  2. The handler ignores signal, and the queue has no heartbeat (task-list.ts). An attempt that runs past its 900 s expiry overlaps its own retry. Unverified at runtime.
  3. The visible state expires silently. Finished jobs are deleted after pg-boss's default 7 days, so "Destroy failed" disappears from a row that was never destroyed. Recording the outcome on the row would fix it.
  4. The manual total is stale: tests/manual/readme.md lists settings at 114, while the suite says 116.
  5. Copy: with fix(sandbox): delete a destroyed workspace in the background #4088, "It leaves the list once its workspace is deleted" happens when the tree is moved to .trash, before the bytes are gone.
  6. Guards no CI test pins:
    • the handler's rowId schema (zod would silently drop it);
    • policy: 'exclusive', which only the integration lane checks;
    • the org filters and the created_on DESC order in sessionDestroyStates;
    • "a fresh row's Destroy is queued on its own".

No production contact, and nothing was merged by this run.

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.

Bug: sandbox Destroy runs in the request; the row lingers until it ends

1 participant