Skip to content

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

Closed

Description

@yannickmonney

What happened

On Settings → Sandboxes → Workspaces, Destroy runs the whole teardown inside the HTTP request. The confirm dialog keeps spinning and the row stays listed until the spawner has removed the container and deleted the workspace directory. Nothing is scheduled: the route awaits teardownSession, which holds the session's lifecycle lock across both remote calls, and the row only flips to destroyed (and leaves the list) after the spawner answers. On a large workspace, or behind a pinned recreate that holds the lock, this takes from tens of seconds to minutes. Past 30 s the admin gets an error toast while the delete keeps running on the spawner anyway.

Steps to reproduce

  1. Run an agent in a project until its workspace holds a realistic tree (e.g. node_modules, a .venv, Playwright browsers).
  2. As an Owner/Admin, open /dashboard/{org}/settings/sandboxes.
  3. Pick that row → Destroy → confirm.
  4. The dialog spins and the page is blocked until the remote delete returns. The row disappears only after that, or the dialog closes with an error toast and the row stays listed.

Expected behavior

Destroy answers right away. The row leaves the list (or reads as being deleted) at once, the deletion finishes in the background with retries, and a failure surfaces without the admin waiting on it.

Where the time goes (all awaited before the response)

  1. services/platform/backend/domains/sandbox/routes.ts:401-410: POST /sessions/:sessionId/destroy awaits teardownSession.
  2. services/platform/backend/domains/sandbox/service.ts:62: waits without a limit for pg_advisory_xact_lock on the session. A pinned recreate holds that lock "for minutes" (service.ts:47-49; runnerd readiness alone is allowed 180 s, service.ts:212-221). The page's own mount reconcile (sandboxes-settings.tsx:109-110) is what queues such recreates. The integration check "Destroy waits for an in-flight recreate then destroys it" (lifecycle.integration.ts:252) pins this down.
  3. service.ts:137: spawner unpin (PATCH /v1/sessions/:id/pin), 30 s cap (core/node_only/sandbox/helpers/session_client.ts:706). Best-effort, but awaited.
  4. service.ts:144 → session_client.ts:570-582: unconditional DELETE /v1/sessions/:id, 30 s cap (:573).
  5. Sandbox side: services/sandbox/src/session/session-routes.ts:1113 waits, without a limit, behind any earlier destroy of the same id, then :1166 awaits backend.destroySession. On Docker and devices that is docker inspect (5 s) → docker rm --force (30 s, spawn-util.ts:264-271) → confirm-gone inspect (5 s) → dind volume rm (10 s, dind only) → rm(workspaceHostDir, { recursive: true }) with no timeout (backend/docker/docker-session-backend.ts:696). The sandbox's own comment says this step is slow: "A destroy deletes the whole workspace, which a large one takes a while for" (session-routes.ts:52-55, CREATE_WAITS_FOR_DESTROY_MS = 120_000). Kubernetes deletes pod, secret and PVC without waiting for termination (each call capped at 10 s).
  6. service.ts:145 → sessions.ts:408-450: gateway key revoke, then status = 'destroyed', then capacity wake.
  7. Only now does the UI close the dialog (sandboxes-settings.tsx:417,425), toast, and invalidate. The list shows only live statuses (sessions.ts:216), so the row disappears on that refetch.

Why it matters

  • A timeout leaves the row behind while the delete goes on. The 30 s abort in step 4 raises a TimeoutError that spawnerFetch rethrows (session_client.ts:294), so markSessionDestroyed never runs. The admin sees an error and the row stays active (unpinned). handleDestroy takes no abort signal, though, so the spawner keeps deleting. A retry then queues behind that delete (step 5). The docs promise "If destruction fails … retry Destroy" (docs/en/platform/admin/sandboxes.md:68). For a slow delete, that retry is the same long wait again.
  • The timeouts disagree. The admin path allows 30 s for the delete. The workspace cleanup allows 60 s for the same delete (session_client.ts:617). The sandbox lets a create wait 120 s for a destroy.
  • The page is blocked meanwhile. The modal stays open for the whole chain, and pendingId is one slot (sandboxes-settings.tsx:300), so destroying several workspaces runs one at a time.
  • An open request holds a lock and a connection. The lifecycle lock's transaction stays open across both remote calls, plus a dedicated connection per lock holder (service.ts:36-82).

Suggested fix

Do what the reconcile already does for recreates (recreate: 'schedule' → schedulePinnedRecreate, service.ts:201-224, "a create can take minutes … a batch that waited … would stall … the page's request"), and reuse the merged retire path instead of a second copy:

  • Synchronous (the request): authorize, then claim the row the way claimWorkspace does (domains/sandbox/workspace-cleanup.ts:265-306): end the live incarnation (expired, unpinned) under the org admission lock, revoke the gateway key, and enqueue the destroy job in the same transaction (addJobInTx, singleton per session). Answer 202. The row leaves the list immediately, because expired is not a live status.
  • Job: retireWorkspace(..., mode: 'force') (workspace-cleanup.ts:218) already does lifecycle lock → spawner unpin → destroy → settle the claimed rows → sandbox_workspace.deleted audit. Run it from a job with the retry ladder of sandbox.retire_workspaces (jobs/tasks.ts:590-595), with a new reason (e.g. admin_destroyed) and the acting admin as actor. The hourly sandbox.workspace_gc stays the backstop.
  • Keep the existing guarantees: unpin before the delete, settle only the claimed rows (a fresh incarnation created during the delete must survive), and a create still waits ≤ 2 min for an in-flight destroy, then 429s. It also gives an explicit Destroy an audit row: teardownSession writes none today.
  • Decide whether teardownSession stays at all. It is the only caller of the 30 s inline delete.

Acceptance

  • Destroy answers without waiting on the lifecycle lock or the spawner. The row is gone from the list on the next read.
  • A spawner that is slow, offline or failing leaves the deletion retrying in the background, never a live row with a lost delete behind it.
  • A recreate in flight for the same session neither blocks the request nor resurrects the workspace.
  • Unit and real-Postgres integration coverage (lifecycle.integration.ts and the workspace-cleanup lane) for: schedule + claim, job retry, fresh incarnation during the delete, and the audit row.
  • docs/en/platform/admin/sandboxes.md:68 and the sandboxes.destroyConfirm / toast.destroyed copy (en/de/fr) describe the background deletion. The manual box SET-F30 (or a new appended box) covers "Destroy returns at once; the row leaves without a reload".

Affected service: Platform (backend + Sandboxes settings), Sandbox (spawner destroy path)

Activity

  1. yannickmonney commented on Oct 2, 2026

    @yannickmonney
    ContributorAuthor

    Additional evidence from read-only inspection of the existing production logs, deployed 0.5.68 / e6132644fc20962041a9b69b6228ee31b9d51185:

    • Six existing POST /api/app/sandbox/sessions/:sessionId/destroy requests across three sessions returned 500 after 30.07–30.48 seconds between 14:17 and 14:22 UTC on 2 October. Every response matches a backend TimeoutError with a sessionDestroy stack frame.
    • All three workspace directories were later absent, while their latest database rows still said Stopped, without a destruction timestamp. Subsequent ordinary sessions/view polling repeatedly answered 304.
    • A fourth session provides a useful control: its Destroy returned 200 after 21.94 seconds, and its row acquired the matching Destroyed timestamp.
    • Ordinary retention does not explain these three stale rows: their agents still exist; the current unused-workspace window is 30 days and only took effect that morning. The explicit route also has no workspace-deletion audit, so audit absence does not mean no delete occurred.

    This confirms that the timeout is an uncertain remote outcome, not evidence that the workspace survived. The durable claim plus background job in this issue should ensure the row cannot appear resumable while its deletion is still pending, retry against the claimed incarnation only, and record the authorized actor and final outcome. Merely extending the request timeout would retain the lost-response failure mode.

    The inspection did not send a Destroy, start a run, or run fault tests on production. An isolated local proof using an inert backend is being prepared separately; no duplicate implementation will be made alongside the existing repair.

  2. yannickmonney commented on Oct 2, 2026

    @yannickmonney
    ContributorAuthor

    Independent exact-deployed-source proof and passive evidence support this issue.

    Local reproduction: with e613264, real isolated PostgreSQL 16.13, the actual teardownSession/sessionDestroy client, real HMAC verification and SessionRoutes.handleDestroy, the unchanged 30-second deadline raises TimeoutError after 30051.1ms. An inert backend simulates a slow operation without deleting files: the request aborts at 30005ms, but that same operation completes at 31502ms. The real session row remains stopped, destroyed_at_ms=NULL, with zero deletion audits. Both normal reconcileSession and reconcileOrgSessions skip it and leave the state unchanged.

    Controls: a timely destroy marks the row destroyed in 73.3ms; an unsigned DELETE is 401 and never reaches the inert backend. The final run records 6/6 controls/observations in 35.77s. The three desired lifecycle/audit assertions remain red on deployed source. No files, containers or prior fixtures were deleted. Test-runtime limits: Node 22.22.0/Bun 1.4.2 and retained dependencies, with exact product source and a thin loopback HTTP dispatcher; deployed Docker pins Node 22.21.1/Bun 1.3.12.

    Passive production correlation (2026-10-02 UTC): proxy logs show six explicit Destroy POSTs returning 500 after 30.07–30.48s, matching six backend TimeoutError + sessionDestroy pairs. These target exactly the three workspaces whose directories disappeared while their rows stayed Stopped. A fourth target returned 200 in 21.94s at 14:19:55 and its row became Destroyed. Subsequent sessions/view polls continued 304 after the failures. These were read-only retained-log observations, not production fault tests. The user confirmed this cleanup was intentional. The defect concerns the timeout response and stale lifecycle state.

    The source explains the outcome: teardownSession commits no durable deletion intent for an unpinned Stopped row and only settles after the remote answer. The 30-second client can time out while the spawner's recursive removal continues. Explicit Destroy emits no workspace-deleted audit, even on success; the retention service's audit is a separate path.

    The proposed durable claim/job/audit direction fits this proof. Please preserve authorized actor/intent before remote mutation, block stale-incarnation resume after the claim, reconcile eventual completion after timeout/restart, and audit the truthful outcome. Verify retries and duplicate requests do not destroy a newer incarnation, preserve scope/permissions, and expose pending/retryable/finished state in the UI. Extending the synchronous timeout alone cannot guarantee correctness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugservice: platform

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions