Skip to content

feat(sandbox): pause and delete idle sandboxes from the worker - #603

Merged
aivong-openhands merged 5 commits into
mainfrom
jl/sandbox-lifecycle
Oct 6, 2026
Merged

aivong-openhands merged 5 commits into
mainfrom
jl/sandbox-lifecycle

Conversation

@jlav

@jlav jlav commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Part 5 of 5 in the sandbox lifecycle stack.

runtime-api pauses and deletes the remote backend's sandboxes. Nothing does this for docker, E2B or k8s. Docker and k8s sandboxes run until someone pauses them, and none of the three are ever deleted.

Summary

  • Three rules, taken from runtime-api. A sandbox is paused after 20 minutes idle, and 12 hours after its last start or resume even if its agent is working. It's deleted, with its workspace, after 10 days without running.
  • Every minute, a sweep of the sandbox table queues a check for each candidate. The check reads the provider and the agent server, then acts.
  • Each rule has one setting for the whole install.

Approach

Which backends take part. The worker only acts when the configured sandbox injector is a ManagedSandboxServiceInjector. The docker, E2B and k8s injectors subclass it, and their services subclass ManagedSandboxService from part 1. The remote and process ones don't. A new backend opts in by subclassing both.

When a sandbox starts or resumes:

  1. mark_running updates the three columns part 1 adds to its v1_remote_sandbox row. It sets lifecycle_state to running, and sets state_changed_at and last_active_at to now. state_changed_at is the last start, resume or pause. last_active_at is the latest agent activity the app has seen.
  2. The agent server gets OH_RUNTIME_IDLE_TIMEOUT_SECONDS, like runtime-api's pods do. The SDK caps a foreground command at 0.9 of that, so one long command doesn't look idle.

The sweep, every minute (sweep in lifecycle/tasks.py):

  1. procrastinate's scheduler queues sandbox_lifecycle:sweep. Its queueing lock keeps at most one waiting.
  2. One query on the sandbox table finds candidates (lifecycle/sweep.py). It makes no provider calls and takes no locks. A row is a candidate when any of these hold:
    • lifecycle_state is running, and the later of state_changed_at and last_active_at is older than the idle period.
    • lifecycle_state is running, and state_changed_at is older than the max session.
    • The later of state_changed_at and last_active_at is older than the delete period.
  3. It queues one sandbox_lifecycle:check per candidate, with queueing lock sandbox:<id>. A sandbox that already has a check waiting is skipped.

The check, one per sandbox (check_sandbox in lifecycle/tasks.py). It runs in one transaction, with a 120 second timeout.

  1. Lock the row with FOR UPDATE SKIP LOCKED. If the row is gone, or an API pause, resume or delete holds it, stop. A later sweep picks the sandbox up again.
  2. Read the live status from the provider.
  3. If the sandbox is running and the max session isn't due, read idle_time with the service's get_idle_time. It calls the agent server's GET /server_info.
  4. Decide (decide in lifecycle/rules.py). It's a pure function, so it reads best next to test_sandbox_lifecycle_rules.py.
  5. Act. A pause calls the service's pause_sandbox, the same code the API uses, and the check already holds its row lock. A delete calls delete_sandbox. Anything else only updates the row.
  6. Commit, which releases the lock. On an error or a timeout, it rolls back. A later check then records any pause that already happened at the provider.

The decision in step 4:

  • Running at the provider: pause once state_changed_at is older than the max session. If idle_time couldn't be read, do nothing. Otherwise the last activity is the latest of state_changed_at, last_active_at and now minus idle_time. Pause once that's older than the idle period. If it's newer than last_active_at, save it there.
  • Paused at the provider while lifecycle_state says running: mark_paused sets lifecycle_state to paused and state_changed_at to now. E2B's own timeout_seconds timer ends up here.
  • Anything else: delete once the later of state_changed_at and last_active_at is older than the delete period.

state_changed_at counts as activity, so a sandbox stays active for a full idle period after it starts or resumes. The agent server's idle clock includes time spent paused, so a resumed sandbox would otherwise look idle at once. A failed read never leads to a delete. A failed check isn't retried, and the next sweep queues it again.

Issue Number

How to Test

uv run pytest tests/unit/app_server/test_sandbox_lifecycle_rules.py \
  tests/unit/app_server/test_sandbox_lifecycle_sweep.py \
  tests/unit/app_server/test_sandbox_lifecycle_tasks.py \
  tests/unit/app_server/test_sandbox_lifecycle_config.py

By hand:

  1. Run OH_SANDBOX_LIFECYCLE_IDLE_SECONDS=120 make run and start a conversation.
  2. Let the agent finish. Within a few minutes the worker logs sandbox_lifecycle.paused with reason: idle, and docker ps -a shows the container as Exited.
  3. Open the conversation again. The sandbox resumes.

Video/Screenshots

N/A

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • Once the worker runs, docker, E2B and k8s sandboxes idle for 20 minutes get paused, and ones that haven't run for 10 days are deleted with their workspace. Self-hosted installs get this when they upgrade.
  • Nothing happens until the worker from part 3 is deployed.
  • OH_SANDBOX_LIFECYCLE_IDLE_SECONDS, OH_SANDBOX_LIFECYCLE_MAX_SESSION_SECONDS and OH_SANDBOX_LIFECYCLE_DELETE_AFTER_SECONDS set the rules. 0 turns a rule off.

Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-3863048

@jlav
jlav added this pull request to stack #604 September 30, 2026 19:42
@github-actions

github-actions Bot commented Sep 30, 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
  docker_sandbox_service.py
  e2b_sandbox_service.py
  k8s_agent_sandbox_service.py 870
  managed_sandbox_service.py
  sandbox_store.py
  openhands/app_server/sandbox/lifecycle
  rules.py
  settings.py
  sweep.py
  tasks.py 73-74, 118-122, 175
  openhands/app_server/worker
  app.py
Project Total  

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

@jlav jlav changed the title Pause and delete idle sandboxes from the worker feat(sandbox): pause and delete idle sandboxes from the worker Sep 30, 2026
@github-actions github-actions Bot added the type: feat A new feature label Sep 30, 2026
@jlav
jlav force-pushed the jl/sandbox-lifecycle branch from 9a3da06 to f3cb58e Compare September 30, 2026 21:21
@jlav
jlav force-pushed the jl/sandbox-lifecycle branch 2 times, most recently from bba6c7d to 3c16288 Compare September 30, 2026 22:13
@jlav
jlav marked this pull request as ready for review September 30, 2026 22:16
@aivong-openhands

Copy link
Copy Markdown
Contributor

✅ Replicated self-hosted validation — PASS

Tested jl/sandbox-lifecycle @ 672180b (image enterprise-server:sha-672180b) on an embedded-cluster install with external Postgres.

Install / schema

  • Running image confirmed sha-672180b; all core deployments Running.
  • alembic_version = 175; v1_remote_sandbox has lifecycle_state, state_changed_at, last_active_at; procrastinate tables present. (No new migration — reuses part-1 columns + the procrastinate schema.)
  • One transient install-window blip: a budget-maintenance cronjob pod errored with database "openhands" does not exist while the DB was being (re)created; its retry for the same schedule Completed. Unrelated to this PR.

No-regression e2e

  • Fresh login + a cold-boot conversation provisioned a runtime and the agent responded. No regression to the conversation path.

Worker / sweep (verified locally)

  • Lifecycle unit tests (sweep + tasks + rules + config + contract) = 100 passed.
  • The assembled worker app registers the expected periodic schedule: sandbox_lifecycle:sweep @ * * * * * (+ sandbox_lifecycle:check on-demand), alongside worker:retry_stalled_jobs */10 * * * * and worker:remove_old_jobs 0 4 * * *.

Notes (not blockers for this PR)

  • The sweep is a no-op on this deployment by design: the backend is runtime-api (RemoteSandboxServiceInjector), which is not a ManagedSandboxServiceInjector, so sweep/check short-circuit. runtime-api already pauses/deletes its own sandboxes; the new worker lifecycle acts only for docker / E2B / k8s-agent-sandbox.
  • Separately, the self-hosted chart does not yet deploy a procrastinate worker (python -m openhands.app_server.worker), so none of the worker tasks (this PR + the housekeeping stack) actually run self-hosted until that deployment is added. Flagging for the chart side; not a change needed in this PR.

Validation performed by an AI agent (OpenHands) on behalf of @aivong.

@aivong-openhands

Copy link
Copy Markdown
Contributor

Code review: feat(sandbox): pause and delete idle sandboxes from the worker

Head: 672180b · Taste rating: 🟢 Good

What I checked

  • CI: all 18 checks on the current head are green (16 passed, 2 skipped).
  • Tests run locally: 342 passed against a real Postgres test container (lifecycle rules/sweep/tasks/config/contract, the Docker, E2B and k8s service tests, and worker housekeeping).
  • No deadlock in the check job. The check locks the sandbox row, then pause_sandbox/delete_sandbox lock the same row again. That only works on one database session, and it is one: the session is cached on the shared InjectorState, and the Docker, E2B and k8s injectors all get it from there. The tests patch out the real _services() wiring, so I confirmed this by reading the code.
  • "A failed read never leads to a delete" holds. Provider read errors raise and the transaction rolls back. Only a confirmed "not found" counts as missing.
  • Idle probe: GET /server_info needs no session key in SDK 1.49.6. Its idle_time is wall-clock time, so it includes time spent paused, which is why state_changed_at has to count as activity. The probe URL already gets the host.docker.internal rewrite through _get_agent_server_url.
  • Same side effects as the API: the worker's pause and delete do exactly what sandbox_router does. Workspace archiving only exists for the remote backend, so skipping it here loses nothing.

Material findings

None.

Non-blocking notes

  1. Stuck rows get re-checked every minute for up to 10 days (lifecycle/rules.py:97, lifecycle/sweep.py:53). This happens when a row says running but the provider reports ERROR, STARTING or MISSING, for example a Docker container that is up but fails the default /health check past its grace period. Such a row always matches the sweep, and decide returns NOTHING until the 10-day delete. So each one costs a provider read every minute (plus an HTTP health check on Docker), they sort first under ORDER BY LAST_RAN_AT LIMIT 1000, and a container that is running but unhealthy is never paused by the 12-hour rule. Not a regression, but consider recording a state for these rows or skipping them in the sweep.
  2. Settings rollout. OH_RUNTIME_IDLE_TIMEOUT_SECONDS is only set when a sandbox is created, so sandboxes that exist before the upgrade have no 18-minute cap on foreground commands, and a long command in one of them can be paused partway through. The same happens if the worker's OH_SANDBOX_LIFECYCLE_IDLE_SECONDS is lower than the app server's. A line in the README or release notes would cover both.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🔴 HIGH

This adds a new background process that deletes sandboxes and their workspaces, and it's on by default. Docker, E2B and k8s installs get it on upgrade once the worker is deployed: pause after 20 min idle or 12 h of running, delete after 10 days. It also caps foreground terminal commands at 18 minutes on those backends. The code is careful, but nobody has run the real pause, resume and delete paths on a backend the worker manages: the "A human has tested these changes" box is unchecked, and the self-hosted QA ran on runtime-api, where the worker does nothing by design.

Recommendation: Do not auto-merge. Before merging, someone should confirm the product decision to delete workspaces by default after 10 days on self-hosted installs, and run the PR's manual test on at least Docker: pause after idle, resume, then delete with OH_SANDBOX_LIFECYCLE_DELETE_AFTER_SECONDS set low.

Key architectural insight: the worker locks rows with SKIP LOCKED, then calls the same ManagedSandboxService transitions the API uses, inside one shared transaction. So the worker and the API can never apply a transition to the same sandbox twice, and there's no second copy of the state machine to keep in sync.

Improve this review? If feedback seems incorrect or irrelevant, update the repository's .agents/skills/custom-codereview-guide.md (with the /codereview trigger), then re-request review. The reviewer reads the guide from the PR head.

Resolve with AI? Install the iterate skill and run /iterate.

Was this review helpful? React with 👍 or 👎.


This review was generated by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands

Copy link
Copy Markdown
Contributor

✅ Local Docker sandbox validation: PASS

I tested jl/sandbox-lifecycle at 672180b locally, with Docker sandboxes (DockerSandboxServiceInjector). That's the backend the worker manages, and the earlier Replicated run (runtime-api) couldn't cover it. The real pause, resume and delete paths ran end to end against real ghcr.io/openhands/agent-server:1.49.6-python containers.

Setup

  • Postgres 16 from make local-db, at alembic head 175. The backend ran with uvicorn openhands.server.listen:app and the worker with python -m openhands.app_server.worker, both from this branch, with docker-in-docker in the sandbox.
  • Lifecycle settings were lowered for the test. Each phase restarted only the worker with new values.
  • Sandboxes were started with POST /api/v1/sandboxes, the same start_sandbox path a conversation uses. No LLM key was available, so I created agent activity with the agent server's POST /api/bash/execute_bash_command. That resets the same idle_time counter that GET /server_info reports and the worker reads.
  • Test harness only, no change to PR code: the OSS server's DefaultUserAuth returns user_id=None, so POST /api/v1/sandboxes returns 401 (require_user_id). That's already the case on main, not something this PR adds. I pointed OPENHANDS_CONFIG_CLS at a tiny UserAuth that returns a fixed user id. This means step 1 of the PR's "How to Test" (make run and start a conversation) doesn't work as written in OSS mode. It needs the SaaS server or some other user context.

Results

# Scenario Settings Result
1 The agent server gets the idle cap idle=120 ✅ The container env has OH_RUNTIME_IDLE_TIMEOUT_SECONDS=120. /server_info reports runtime_idle_timeout_seconds: 120 and max_foreground_terminal_timeout_seconds: 108 (0.9×).
2 An active sandbox isn't paused idle=120 ✅ A command every 30s for ~4 min (2× the idle period). The checks at 21:10 and 21:12, while commands were running, and at 21:14, after they stopped, only moved last_active_at forward (finally to 21:12:32). No pause.
3 Idle pause idle=120 ✅ Activity stopped at 21:12:31, and at 21:15:00 the worker logged sandbox_lifecycle.paused reason=idle idle_time=148. docker ps -a showed Exited (143), and the row became paused with state_changed_at=21:15:00.
4 Resume idle=120 ✅ POST /api/v1/sandboxes/{id}/resume returned 200 and the container came back Up. The row went to running with state_changed_at=21:15:39, the same agent-server URL, and the workspace files written before the pause were still there.
5 No re-pause right after resume idle=120 ✅ No check ran at 21:16 or 21:17. The next pause came at 21:18:00 with reason=idle, idle_time=125, measured from the last activity (21:15:55), so state_changed_at counted as activity as designed.
6 Max session pauses a working sandbox idle=120, max_session=180 ✅ A command every 20s. At 21:22:00, 3 min 25s after start and 3 seconds after

@aivong-openhands

Copy link
Copy Markdown
Contributor

Code review: feat(sandbox): pause and delete idle sandboxes from the worker

Head: 672180b (base jl/worker-housekeeping, part 5 of 5) · Taste rating: 🟢 Good

What I checked

  • Tests: I ran the lifecycle tests (rules, sweep, tasks, config, contract), the Docker, E2B and k8s service tests, and the worker housekeeping tests against a real Postgres container: 342 passed. All CI checks on this head pass, including Python Tests on Linux, which runs tests/unit. The task tests use the real service classes with fake providers.
  • No deadlock between the check job and the API: the check locks the row with SKIP LOCKED, then pause_sandbox or delete_sandbox locks it again. That only works because both use the same database session. They do: DbSessionInjector.inject stores the session on the shared InjectorState.
  • A failed read never deletes a sandbox:
    • Docker's _get_container raises on a daemon error and only returns None on a real "not found".
    • E2B raises SandboxError when listing fails.
    • k8s turns every API error into SandboxError.
    • So a provider outage rolls the check back instead of showing MISSING.
  • Timeouts and duplicate runs are safe:
    • When the 120s timeout fires, the session is closed without a commit, which rolls it back.
    • If a pause already happened at the provider, a later check records it as paused.
    • If procrastinate re-runs a job it thinks has stalled, the second copy finds the row locked and does nothing.
  • Idle probe: in SDK 1.49.6, GET /server_info sits outside the session-key-protected /api router. Its idle_time is now - _last_event_time. The URL goes through _get_agent_server_url, which applies the same host.docker.internal rewrite the app server uses. The 0.9× cap on foreground commands comes from openhands/tools/terminal/timeout_policy.py.
  • Worker and API do the same thing: sandbox_router and app_conversation_router delete through the same delete_sandbox the worker calls.

Material findings

None.

Non-blocking notes

  1. Stuck rows get rechecked every minute for up to 10 days (lifecycle/rules.py:97-99, lifecycle/sweep.py:53-54). An earlier review on this PR already raised this.
    • It happens when a row says running but the provider reports ERROR, STARTING or MISSING. One example is a Docker container that is up but fails /health after its grace period.
    • Such a row always matches the sweep, and decide returns NOTHING until the 10-day delete.
    • These rows sort first under ORDER BY LAST_RAN_AT LIMIT 1000.
    • A container that is up but unhealthy is never stopped by the 12-hour rule.
    • This isn't a regression.
  2. Existing sandboxes don't get the command cap. OH_RUNTIME_IDLE_TIMEOUT_SECONDS is only set when a sandbox is created (docker_sandbox_service.py:481, e2b_sandbox_service.py:605, k8s_agent_sandbox_service.py:683).
    • Sandboxes created before the upgrade have no cap on foreground commands, so the worker can pause one partway through a long command.
    • The same happens if the worker's OH_SANDBOX_LIFECYCLE_IDLE_SECONDS is lower than the app server's.
    • A line in the README or release notes would cover both.
  3. "How to Test" step 1 doesn't work as written. The Docker validation comment on this PR reports that make run in OSS mode returns 401 on POST /api/v1/sandboxes, because DefaultUserAuth has no user id. That's not caused by this PR, but the manual steps need SaaS mode or some other user context.

Status since the earlier review

  • The "A human has tested these changes" box is now checked.
  • A local Docker run of the real pause, resume and delete paths passed (idle pause, resume, no re-pause right after resume, max session).
  • dylan-openhands has approved this head.
  • That closes the testing gap. What's left is the product decision.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🔴 HIGH

This adds a background process that deletes sandboxes and their workspaces, and it's on by default. On upgrade, once the worker is deployed, Docker, E2B and k8s installs get:

  • a pause after 20 minutes idle or 12 hours of running;
  • a delete after 10 days without running;
  • an 18-minute cap on foreground terminal commands in new sandboxes.

The code follows existing patterns and is well tested. The risk comes from destroying data by default on self-hosted installs.

Recommendation: Do not auto-merge. Before merging, a product or self-hosted owner should explicitly confirm that workspaces should be deleted after 10 days by default, and decide whether this goes in the release notes.

Verdict: COMMENT. There are no code defects, but a product decision is still open.

Key architectural insight: The worker doesn't have its own copy of the state machine. It locks the row with SKIP LOCKED, then calls the same ManagedSandboxService pause and delete the API uses, inside one transaction. So the worker and the API can never apply a transition to the same sandbox twice.

Improve this review? If feedback seems incorrect or irrelevant, update the repository's .agents/skills/custom-codereview-guide.md (with the /codereview trigger), then re-request review. The reviewer reads the guide from the PR head.

Resolve with AI? Install the iterate skill and run /iterate.

Was this review helpful? React with 👍 or 👎.


This review was generated by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands aivong-openhands 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.

Following up on my two reviews above. None of the notes block this PR or the rest of the stack (#599–#603), so I've filed follow-ups to keep them from getting lost:

Stuck rows → #626. The Docker run reproduced this with a hung agent server: the row is never paused, and each check waits 15s on /health, holding a worker slot, until the 10-day delete. It isn't a regression, since nothing pauses Docker sandboxes on a timer today, and the fix is a small change to decide, so it fits better as its own PR.

Command cap on existing sandboxes → #627. Sandboxes created before the upgrade don't get OH_RUNTIME_IDLE_TIMEOUT_SECONDS (confirmed for Docker; the issue asks to check E2B and k8s), so the worker can pause one partway through a long foreground command. The issue covers a README note, plus release notes that call out the 10-day delete default. The mismatched-settings case I raised is already covered by the README's "same env as the app server" line, so I left it out.

How to Test step 1 → #625. This isn't from this PR: since #466, start_sandbox calls require_user_id, and OSS mode's DefaultUserAuth has no user id, so make run can't start Docker sandboxes on main either. make run-saas doesn't help, because local SaaS uses the remote runtime. The Docker validation run above, which used a workaround, is the record of the real pause, resume and delete paths. @jlav, the issue asks whether OSS mode was meant to keep working after #466.

10-day delete default. This is the one open question, and I no longer think it should hold up the merge, which changes my earlier "do not auto-merge" recommendation. As far as I can tell nothing deploys the worker yet (the self-hosted chart doesn't), so the default only reaches installs with the chart change that adds it. Before that chart change lands, a product or self-hosted owner should confirm that deleting workspaces after 10 days is the default we want. If not, defaulting OH_SANDBOX_LIFECYCLE_DELETE_AFTER_SECONDS to 0 is a one-line follow-up, and pausing stays on.

With these filed, I'm happy for the stack to merge.


This review was posted by an AI agent (OpenHands) on behalf of @aivong.

@aivong-openhands
aivong-openhands force-pushed the jl/sandbox-lifecycle branch 4 times, most recently from b8c567b to 23dafd4 Compare October 5, 2026 22:20
Base automatically changed from jl/worker-housekeeping to main October 6, 2026 14:19
@aivong-openhands
aivong-openhands merged commit 218a911 into main Oct 6, 2026
16 checks passed
@aivong-openhands
aivong-openhands deleted the jl/sandbox-lifecycle branch October 6, 2026 14:36
@openhands-release-bot openhands-release-bot Bot added the released: 1.69.0 Shipped in 1.69.0 label Oct 6, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.69.0.

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

Labels

released: 1.69.0 Shipped in 1.69.0 type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants