Skip to content

fix(sandbox): archive conversation workspaces before pausing/deleting in lifecycle reap - #1467

Open
juanmichelini wants to merge 10 commits into
mainfrom
fix/lifecycle-reap-archive-conversation-workspace
Open

juanmichelini wants to merge 10 commits into
mainfrom
fix/lifecycle-reap-archive-conversation-workspace

Conversation

@juanmichelini

@juanmichelini juanmichelini commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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

# before — check_sandbox acted on the decision directly
if decision.action == Action.PAUSE:
    await sandbox_service.pause_sandbox(sandbox_id)      # runtime stopped, no capture
elif decision.action == Action.DELETE:
    await sandbox_service.delete_sandbox(sandbox_id)     # runtime torn down, no capture
# after — capture every conversation's workspace first, then reap
if decision.action == Action.PAUSE:
    if not await _archive_conversations_for_sandbox(...):  # capture while still RUNNING
        return decision                                    # REQUIRED failed → keep for retry
    await sandbox_service.pause_sandbox(sandbox_id)
elif decision.action == Action.DELETE:
    if not await _archive_conversations_for_sandbox(...):  # capture before teardown
        return decision                                    # REQUIRED failed → keep for retry
    await sandbox_service.delete_sandbox(sandbox_id)

_archive_conversations_for_sandbox 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 (#1460): 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.

Design notes

  • One transaction. The conversation info service is built on the worker's own db session (_services now yields it as a third element), so the archive reads share one transaction with the row lock — no cross-session reads.
  • No double-capture under Helm-remote. The remote backend's injector is not ManagedSandboxServiceInjector, so _managed_backend() returns None for 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.
  • Per-conversation keying. The archive API is keyed by conversation id, so a grouped sandbox with multiple conversations captures each one's workspace separately, using each conversation's pinned path.
  • Shutdown pause is out of scope. pause_running_sandboxes (the shutdown hook) is a separate code path that calls pause_sandbox directly, not check_sandbox. It stays as-is; the issue scopes to the idle/expiry reap path.

Tests

New TestCheckArchivesBeforeReap class in tests/unit/app_server/test_sandbox_lifecycle_tasks.py (8 tests × 3 backends = 24 cases), parametrized over the existing Docker / E2B / k8s-agent harnesses:

  • pause captures each conversation (id + pinned workspace_path) before stopping the runtime, for every conversation referencing the sandbox
  • delete captures each conversation before tearing the sandbox down
  • REQUIRED archive failure defers the pause (sandbox + runtime left RUNNING)
  • REQUIRED archive failure defers the delete (row + container kept)
  • best-effort failure (REQUIRED off) does not block the pause
  • archive step skipped entirely when archiving disabled (no lookups)
  • no conversations → proceeds straight to pause
  • conversation-info lookup failure blocks the reap only when REQUIRED

The existing 44 lifecycle-tasks tests were updated to thread the new conversation_info_service arg (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 a sandbox_lifecycle.check job (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:

[verify] READY: conversation=c82d97bbb8f045ef816d5e3686cd19f0 sandbox=oh-agent-server-18OXGuT5TDfdyUTEjuHQ0t
[verify] marker uploaded (http 200, body={"success":true,"file_size":28})
[verify] live marker confirmed in container: 'pr1467-e2e-marker-1795562941'
[verify] deferring sandbox_lifecycle.check job via procrastinate App
[verify]   container status=exited (paused) at t+2s
[verify]   container gone (deleted) at t+49s
[verify] final: saw_paused=True saw_gone=True
[verify] PASS: marker found in archive: 'pr1467-e2e-marker-1795562941'

Archive bucket layout (pause-time capture at 232917Z, delete-time capture at 233004Z — per-conversation keying, sandbox_id/conversation_id/timestamp):

archives/bucket/workspace-archives/oh-agent-server-18OXGuT5TDfdyUTEjuHQ0t/c82d97bbb8f045ef816d5e3686cd19f0/
├── 20261124T232917Z.patch / .patch.manifest.json
├── 20261124T232917Z.tar.gz / .tar.gz.manifest.json
├── 20261124T233004Z.patch / .patch.manifest.json
└── 20261124T233004Z.tar.gz / .tar.gz.manifest.json

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):

{'id': 21, 'task_name': 'sandbox_lifecycle:check', 'status': 'succeeded', 'event_type': 'deferred/started/succeeded', 'at': 23:29:17–23:29:18}
{'id': 26, 'task_name': 'sandbox_lifecycle:check', 'status': 'succeeded', 'event_type': 'deferred/started/succeeded', 'at': 23:30:00–23:30:05}

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_failed and 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:

ghcr.io/openhands/enterprise-server:sha-7b71d27

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>
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  openhands/app_server/sandbox/lifecycle
  tasks.py 92-95, 235-240
Project Total  

This report was generated by python-coverage-comment-action

juanmichelini and others added 6 commits November 19, 2026 20:08
…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>
juanmichelini and others added 2 commits November 20, 2026 00:19
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>
@juanmichelini
juanmichelini force-pushed the fix/lifecycle-reap-archive-conversation-workspace branch from 53122ae to 6cd1392 Compare November 20, 2026 03:41
Base automatically changed from fix/docker-archive-conversation-workspace to main November 20, 2026 13:53
@juanmichelini juanmichelini changed the title Lifecycle reap: archive conversation workspaces before pausing/deleting a sandbox fix(sandbox): archive conversation workspaces before pausing/deleting in lifecycle reap Nov 24, 2026
@github-actions github-actions Bot added the type: fix A bug fix label Nov 24, 2026
@all-hands-bot

all-hands-bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Review posted for 7b71d272607a

Verdict: 🔄 CHANGES REQUESTED. See the review.

This is an automated status.

@all-hands-bot all-hands-bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 #1457 overstates the fix for E2B and K8s-agent. E2BSandboxService and K8sAgentSandboxService don't override archive_conversation_workspace, so they use the base no-op in sandbox_service.py:413, which returns True. The new step runs on those backends but captures nothing. The new tests replace archive_conversation_workspace with 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. The HUMAN:/AGENT: sections and the Why / Summary / How to Test / Type headings are missing, and .agents/skills/custom-codereview-guide.md requires 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 to ARCHIVE_RESUME_HEALTH_TIMEOUT_SECONDS = 60 for 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.

This branch has not been deployed

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

Labels

type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Idle/expiry sandbox reap (lifecycle worker) skips workspace archiving on all non-remote backends

2 participants