Skip to content

fix: keep a completed run's sandbox up until its last events reach the app server - #761

Merged
neubig merged 1 commit into
mainfrom
fix/616-flush-events-before-sandbox-teardown
Nov 16, 2026
Merged

neubig merged 1 commit into
mainfrom
fix/616-flush-events-before-sandbox-teardown

Conversation

@neubig

@neubig neubig commented Nov 14, 2026

Copy link
Copy Markdown
Member

Why

Fixes #616.

The agent-server sends conversation events to the app server's webhook in batches of 5. It posts a partial batch only after WebhookSpec.flush_delay (30 s) passes with no new event. complete_run deleted the run's sandbox, or paused it when sandbox_cleanup_delay_seconds was set, in the same second as the completion callback. The runner sends /complete about 5 s after the conversation's last event. So whenever the last events don't fill a batch, the app server's copy of the run conversation stops before the agent's final reply and the finished state update. A paused agent-server can't post either.

The issue lists three places a fix could go. This PR fixes it in the service:

  • It works with every agent-server already deployed, without waiting for an SDK release and an OHE upgrade.
  • It covers custom scripts too, not only the stock runner.

An SDK-side flush on terminal status would let the grace period drop to 0 later. The setting allows that.

Summary

  • New setting AUTOMATION_SANDBOX_EVENT_FLUSH_GRACE_SECONDS, default 35 (the agent-server's 30 s flush_delay plus a 5 s margin).
  • complete_run with keep_alive not true:
    • Default (no cleanup delay): no deletion at callback time. The run gets sandbox_cleanup_due_at = completed_at + grace, and the watchdog's existing cleanup_due_sandboxes sweep deletes the sandbox. The deletion survives a service restart, unlike the previous fire-and-forget task. In practice the sandbox is deleted 35–95 s after completion, depending on the watchdog interval.
    • With sandbox_cleanup_delay_seconds: the pause runs after the grace period. Deletion is still booked at max(delay, grace). If the pause task is lost, the sandbox only runs until that booked deletion.
    • Both set to 0: immediate deletion, the same as before.
    • Background teardown tasks are now held in a set, because the event loop keeps only weak references to tasks.
  • Unchanged: keep_alive=true and subject-owning (continue_conversation) runs, cancellation, dispatch-failure cleanup, and the watchdog's own terminal paths. Those paths run at the run's timeout, long after the last event.
  • AGENTS.md: the sandbox cleanup note now describes the grace period.

How to Test

uv run pytest tests/test_router.py -k complete_run
uv run pytest tests/test_conversations.py -k completing
uv run pytest tests/test_watchdog.py
  • test_complete_run_keeps_sandbox_until_buffered_events_flush is the ordering regression test. After /complete, the test checks three things:
    • No deletion has started.
    • No pause has started.
    • sandbox_cleanup_due_at is more than 30 s after completed_at.
  • test_complete_run_with_cleanup_delay_pauses_and_stamps_due_at: no pause before the grace period ends, and exactly one pause after it.
  • test_complete_run_without_flush_grace_deletes_at_once: with both settings at 0, the sandbox is deleted at once.
  • Retention tests in tests/test_conversations.py: an ordinary run is booked for deletion, and a subject-owning run is not.

End to end: .pr/issue-616/demo_616.py, described in .pr/issue-616/README.md, is a simulation that needs no OHE install:

  • A real agent-server 1.62.0 runs on the default WebhookSpec, with a mock LLM that makes one tool call and then sends a final reply. Its webhook goes to a fake app server.
  • The real complete_run route and the real cleanup_due_sandboxes sweep (every 5 s) handle teardown.
  • A fake runtime API kills the agent-server on DELETE and freezes it on PAUSE.

The simulation ran on both the default path and with AUTOMATION_SANDBOX_CLEANUP_DELAY_SECONDS=600:

Before (main 949c001) After (this PR)
before after

On main, the app server never gets MessageEvent(agent: final reply) or ConversationStateUpdateEvent(execution_status=finished) on either path. On this branch, the last partial batch arrives about 25 s after /complete, and only then is the sandbox deleted (about 35 s) or paused.

This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.

… server

The agent-server posts a partial batch of conversation events to the app
server's webhook only after WebhookSpec.flush_delay (30 s) without a new
event. complete_run deleted (or paused) the sandbox right away, so the last
events of a run's conversation -- usually the agent's final reply and the
finished state update -- never reached the app server.

complete_run now books the deletion for the watchdog's due-sandbox sweep
AUTOMATION_SANDBOX_EVENT_FLUSH_GRACE_SECONDS (default 35) after completion,
and with AUTOMATION_SANDBOX_CLEANUP_DELAY_SECONDS set it pauses only after
the grace period. Setting both to 0 restores immediate deletion.

Fixes #616

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR adds or changes temporary PR-specific documents under .pr/. They stay on this branch for review. After this PR merges, the next release PR removes them from main.

@github-actions github-actions Bot added the type: fix A bug fix label Nov 14, 2026
@neubig
neubig requested a review from all-hands-bot November 14, 2026 00:59
@github-actions

Copy link
Copy Markdown
Contributor

Coverage

Warning

Your comment is too long (maximum is 65536 characters), so the coverage report was not added. See the job log for how to reduce it.

@neubig

neubig commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

@all-hands-bot Please review the latest head 30a46ce. All CI checks are green and the branch merges cleanly with main. Before/after evidence is in the PR description.

This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.

@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).

Reviewed 30a46cecb1d940e39327e7cf456a2e7a74558ead against main (949c001), the linked issue #616, and the repository's review guidance. Scope is correct: this repository owns sandbox lifecycle orchestration, and #616 explicitly lists the service-level fix as one of the candidate locations; the issue is currently labeled ready-for-dev.

What I verified:

  • Decision table in complete_run (openhands/automation/router.py): traced every combination of sandbox_cleanup_delay_seconds x sandbox_event_flush_grace_seconds. The default path (no delay, grace 35) now books sandbox_cleanup_due_at for the watchdog's cleanup_due_sandboxes sweep instead of deleting at callback time; both settings at 0 preserve the immediate deletion; a delay still pauses, but only after the grace, with deletion booked at max(delay, grace). There is no combination that spawns a teardown while also deferring, so no double-teardown path.
  • Deferred deletion is reachable and self-healing: the sweep runs in the watchdog loop whenever the service is not in local mode, and local runs carry sandbox_id=None so nothing is ever booked that the sweep can't consume. The stamp is cleared after one attempt and the runtime's TTL reaper remains the backstop, so a crash no longer strands an orphaned sandbox the way the old fire-and-forget task could. _spawn_teardown's strong reference fixes the weakref task-loss hazard for the remaining background paths.
  • Credentials: the deferred deletion needs no key at callback time; CloudSandboxBackend.cleanup_after_verification mints one via the service key at sweep time. Nothing new is persisted or logged.
  • Unchanged paths: keep_alive=true, subject-owning runs, cancellation, dispatch-failure cleanup, and the watchdog's own terminal paths behave as before; the watchdog still only stamps on its own RUNNING-to-terminal write, and mark_stale_runs scans only RUNNING runs, so a callback-first completion can't be re-processed.
  • Tests: the ordering regression test asserts all three invariants (no deletion started, no pause started, sandbox_cleanup_due_at more than 30 s after completed_at); the cleanup-delay test proves exactly one pause after the grace; the zero-grace test pins immediate deletion with no stamp; the retention tests cover subject-owning vs ordinary runs. Local test execution in this workspace isn't possible (no Docker daemon), so the green unit-tests/windows-tests/backend runs on this exact head are the acceptance signal, corroborated by static verification and the PR's real-path simulation output for both the default and AUTOMATION_SANDBOX_CLEANUP_DELAY_SECONDS paths, which show the final reply and finished state update arriving before teardown on this branch and not on main.
  • Docs/config: the new AUTOMATION_SANDBOX_EVENT_FLUSH_GRACE_SECONDS field is documented in ServiceSettings, and the AGENTS.md sandbox-cleanup note now matches the implemented behavior. The .pr/issue-616/ artifacts follow the repository's PR-artifacts policy.

No material correctness, security, compatibility, or acceptance-criterion defects found. The 5 s margin over the agent-server's 30 s flush_delay is deliberate and configurable; a deployment with a longer effective flush delay can raise the setting (or drop it to 0 once an SDK-side terminal flush ships), which the design explicitly supports.

APPROVED

@neubig
neubig merged commit e7d74fe into main Nov 16, 2026
10 of 11 checks passed
@openhands-release-bot openhands-release-bot Bot added the released: 1.33.0 Shipped in 1.33.0 label Nov 17, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.33.0.

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

Labels

released: 1.33.0 Shipped in 1.33.0 type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: A run's last conversation events never reach enterprise because the sandbox is deleted before the agent-server flushes them

3 participants