Repository navigation
fix(sandbox): archive conversation workspaces before pausing/deleting in lifecycle reap - #1467
juanmichelini wants to merge 10 commits into
Conversation
The conversation-delete finalizer calls archive_conversation_workspace on every conversation delete, but only RemoteSandboxService overrides the base no-op — so on Docker Compose / self-hosted installs the call succeeds vacuously and the sandbox is torn down with no capture, even with RUNTIME_FILE_ARCHIVE_ENABLED=true. Implement the method on DockerSandboxService, mirroring the remote backend's contract: resolve the stored sandbox and its container, capture via the shared workspace_archive sink using the agent-server URL and session_api_key from the container, then let the finalizer proceed. Honors REQUIRED (returns False to keep the sandbox for a later retry) only on confirmed capture failure, lookup failure, or a non-running container; missing rows/containers are nothing to capture. The archive path prefers the workspace_path pinned at conversation creation and otherwise re-derives it from the sandbox spec's working_dir plus the grouping nesting, exactly as the remote backend does. Fixes #1458 Co-authored-by: openhands <openhands@all-hands.dev>
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||
…r archive_conversation_workspace The Lint python CI job pins ruff 0.12.5, whose isort places openhands.agent_server.utils in the third-party block. Adds an opt-in integration test that exercises the archive wiring against a real Docker agent-server container (auto-skips when Docker is unavailable). Co-authored-by: openhands <openhands@all-hands.dev>
The archive codepath never looks sandboxes up by key hash, so the test no longer populates session_api_key_hash. This removes a new py/weak-sensitive-data-hashing flow (uuid4 key -> pre-existing SHA-256 sink in sandbox_store.py) that the CodeQL PR check flagged. Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Resolve import conflict in docker_sandbox_service.py: keep both the PR's settings_models import and main's customer_gateway_hooks import, ordered per ruff 0.12.5 isort (app_server.* first-party). Co-authored-by: openhands <openhands@all-hands.dev>
Address review: a paused/exited container (the common delete-time state, since the lifecycle worker stops idle sandboxes) was silently skipped. Now archive_conversation_workspace resumes it via _resume_for_archive (restart + bounded /health probe) so the intact filesystem is captured; if the resume fails, REQUIRED still blocks teardown. Also fix log/comment wording, drop the evidence-dump from the E2E test, and add unit + E2E coverage for the resume path. Co-authored-by: openhands <openhands@all-hands.dev>
Resume for archive called _resume_at_provider directly, so the row kept lifecycle_state=PAUSED while the container ran. When teardown did not follow (REQUIRED capture failure, grouped sandboxes with surviving siblings) the lifecycle worker never re-paused it: idle/max-session rules only apply to RUNNING rows. Call mark_running on a successful resume, matching ManagedSandboxService.resume_sandbox's contract. Co-authored-by: openhands <openhands@all-hands.dev>
The idle/expiry reap path (sweep → check) pauses or deletes sandboxes without going through conversation delete, so on Docker Compose / self-hosted installs nobody captured the workspace before the runtime was stopped or torn down — the same silent gap #1458 fixed for the explicit- delete path, on the other code path. Add an archive step to check_sandbox, run before PAUSE and DELETE act. It finds every conversation still referencing the sandbox and calls archive_conversation_workspace for each, keyed by conversation id and using the workspace path pinned at creation (read from the conversation's tags). REQUIRED gating matches the delete finalizer: a capture that could not confirm returns False and the sandbox + runtime are left for the next sweep to retry, instead of being torn down with uncaptured work. Best-effort failures and missing conversations proceed. Disabled archiving short-circuits before any lookup. Never raises. The conversation info service is built on the worker's own db session so the archive reads share one transaction with the row lock. The remote backend's injector is not Managed, so _managed_backend() returns None for it and the jobs don't run there — runtime-api's own cron still covers Helm-remote, so there's no double-capture. The shutdown pause (pause_running_sandboxes) is a separate code path and out of scope; it stays as-is. Fixes #1457 Stacked on #1460 (the explicit-delete path fix for #1458). Co-authored-by: openhands <openhands@all-hands.dev>
53122ae to
6cd1392
Compare
Review posted for
|
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
The archive-before-reap step is in the right place, and the REQUIRED gating matches the delete finalizer from #1460. One blocking problem remains: the new capture runs inside the check job's 120s timeout, and a slow capture now stops the pause or delete completely, even when archiving is only best-effort. Details are in the inline comment.
Non-blocking, but act on it before merge:
Fixes #1457overstates the fix for E2B and K8s-agent.E2BSandboxServiceandK8sAgentSandboxServicedon't overridearchive_conversation_workspace, so they use the base no-op insandbox_service.py:413, which returnsTrue. The new step runs on those backends but captures nothing. The new tests replacearchive_conversation_workspacewith a stub for all three harnesses, so they don't show this. #1457 asks for capture on every non-remote backend. Either limit the closing reference to Docker or track E2B and K8s-agent as follow-up work, so merging doesn't silently close the issue.- The PR body doesn't follow
.github/pull_request_template.md. TheHUMAN:/AGENT:sections and the Why / Summary / How to Test / Type headings are missing, and.agents/skills/custom-codereview-guide.mdrequires them before review.
Verification: tests/unit/app_server/test_sandbox_lifecycle_tasks.py passes locally (68 passed). CI for 7b71d27 is green; the one failed PR-title lint run was replaced by later successful runs. I also ran a throwaway probe, deleted afterward: with archiving enabled but not REQUIRED, I made the archive slower than an outer asyncio.timeout around check_sandbox. On Docker, E2B and K8s-agent alike, the check raised TimeoutError and the sandbox stayed RUNNING (row and live status). On main, the same check pauses it.
🔄 CHANGES REQUESTED
LLM profile: unknown · Model: openhands/claude-opus-5-5
| # Capture every conversation's workspace before the runtime is stopped, | ||
| # so an idle/max-session pause does not lose work on self-hosted installs | ||
| # where the runtime's own idle reap does not run. | ||
| if not await _archive_conversations_for_sandbox( |
There was a problem hiding this comment.
Blocking: a slow capture now stops idle pause and inactive delete, even when archiving is best-effort.
check() runs this whole function inside asyncio.timeout(CHECK_TIMEOUT_SECONDS), which is 120s. The capture this step runs can legitimately take much longer:
workspace_archive._archive_timeout()defaults to 660s. That limit exists to cover the agent-server git build for large repos.- On the delete path, the Docker backend first restarts the stopped container (
_resume_for_archive) and waits up toARCHIVE_RESUME_HEALTH_TIMEOUT_SECONDS = 60for it to become healthy. - Conversations are archived one after another (up to 100 per sandbox).
When the budget runs out, the timeout raises CancelledError/TimeoutError. The except Exception here doesn't catch them, so pause_sandbox and delete_sandbox never run and the transaction rolls back. The next sweep repeats the same capture and times out again. A sandbox with a large workspace is then never paused or deleted, regardless of RUNTIME_FILE_ARCHIVE_REQUIRED. On main, the same sandbox would simply be paused.
On Docker's delete path it also leaks a container. _resume_for_archive has already restarted it, but the rollback reverts mark_running, so the container keeps running while its row still says paused.
I confirmed the best-effort case with a throwaway probe: an archive slower than an outer asyncio.timeout left the sandbox RUNNING on all three harnesses.
Fix options, any of which works:
- Give the archive step its own time budget, outside or larger than the check timeout.
- Bound each capture, and in best-effort mode treat a timeout as "proceed".
- Move the capture to its own job that the pause or delete waits for.
Whichever you pick, add a test for the slow and timeout case.
Fixes #1457 (sub-issue of #1456). Stacked on #1460 (the explicit-delete path fix for #1458).
What changed and why
The idle/expiry reap path (
sweep → check) pauses or deletes sandboxes without going through conversation delete — so on Docker Compose / self-hosted installs, nobody captured the workspace before the runtime was stopped or torn down. This is the same silent gap #1458 fixed for the explicit-delete path, but on the other code path: the lifecycle worker that reaps idle sandboxes never archived anything either.This adds an archive step to
check_sandbox, run before PAUSE and DELETE act.Before / after
_archive_conversations_for_sandboxfinds every conversation still referencing the sandbox and callsarchive_conversation_workspacefor each, keyed by conversation id and using the workspace path pinned at creation (read from the conversation's tags). REQUIRED gating matches the delete finalizer (#1460): a capture that could not confirm returnsFalseand the sandbox + runtime are left for the next sweep to retry, instead of being torn down with uncaptured work. Best-effort failures and missing conversations proceed. Disabled archiving short-circuits before any lookup. Never raises.Design notes
_servicesnow yields it as a third element), so the archive reads share one transaction with the row lock — no cross-session reads.ManagedSandboxServiceInjector, so_managed_backend()returnsNonefor it and these jobs don't run there at all. Runtime-api's own cleanup cron still covers idle capture on Helm-remote. The new step only fires for Docker / E2B / k8s-agent-sandbox, where runtime-api's idle reap does not run.pause_running_sandboxes(the shutdown hook) is a separate code path that callspause_sandboxdirectly, notcheck_sandbox. It stays as-is; the issue scopes to the idle/expiry reap path.Tests
New
TestCheckArchivesBeforeReapclass intests/unit/app_server/test_sandbox_lifecycle_tasks.py(8 tests × 3 backends = 24 cases), parametrized over the existing Docker / E2B / k8s-agent harnesses:The existing 44 lifecycle-tasks tests were updated to thread the new
conversation_info_servicearg (a no-conversations mock, so legacy behavior is unchanged) and still pass. 546 tests pass across the lifecycle, docker, remote, conversation-router, saas-lifespan, and worker-queue suites. Ruff format/check clean; mypy shows no new errors (only pre-existing missing-stub notes).End-to-end verification (local isolated stack, Docker backend)
Deployed this branch on an isolated local stack (Postgres :5434, backend :31010,
python -m openhands.app_server.worker, archive bucket on local disk,OH_SANDBOX_LIFECYCLE_IDLE_SECONDS=3,OH_SANDBOX_LIFECYCLE_DELETE_AFTER_SECONDS=6) and ran a full reap cycle against a real Docker sandbox created through the API.Scenario: created a conversation + live sandbox via
POST /api/v1/app-conversations→ uploaded a marker file into the sandbox workspace via the runtime/api/file/upload→ confirmed it live via/api/file/download→ deferred asandbox_lifecycle.checkjob (same call the periodic sweep makes:check.configure(queueing_lock=f"sandbox:{id}").defer_async(sandbox_id=...)) → watched the container be paused then deleted, and inspected the archive bucket.Result — PASS. Both the pause and the delete captured the workspace before tearing the container down, and the marker file is inside both archives:
Archive bucket layout (pause-time capture at
232917Z, delete-time capture at233004Z— per-conversation keying,sandbox_id/conversation_id/timestamp):The marker file survives in both tarballs (
tar tzf→project/PR1467_MARKER.txt), and the manifest pins the capture:{"conversation_id": "c82d97bbb8f045ef816d5e3686cd19f0", "phase": "final", "sandbox_id": "oh-agent-server-18OXGuT5TDfdyUTEjuHQ0t", "source_path": "/workspace/project", ...}Job history from Postgres confirms the exact code path ran on the worker (job 21 = pause, job 26 = delete, both
succeeded):The durability backstop also behaves as designed: a sandbox whose container was force-removed externally (so a REQUIRED archive could not run) logged
sandbox_lifecycle.archive_required_failedand the reap was deferred instead of deleting the workspace-less row.This PR was created by an AI agent (OpenHands) on behalf of Juan Michelini.
Enterprise server image for this PR: