Repository navigation
fix(orchestrator): delete the sandbox of a create whose caller left - #554
iaroslav-reflection wants to merge 1 commit into
Conversation
A create runs on its own task, so it still finishes when its HTTP request is dropped. The sandbox ID is only in the answer to that request. When the client had left, the runtime logged a debug line and kept the sandbox. With the default timeout action that sandbox ran until its TTL, was then paused, and stayed on the node. The client saw a failed create and had no ID to delete. create_sandbox now deletes the sandbox when its create succeeds and the caller never takes the result. run_cancellation_safe gets a variant, run_cancellation_safe_then, with a callback for such a result. The result travels in a guard that calls the callback when it is dropped unclaimed. That covers a caller that left before the result was ready, and one that left after the result was sent but before it was read. The delete claims the sandbox the way timeout eviction does: under the deletion lock, from Running or Paused, and then it runs delete_sandbox_impl. Nobody else has the ID, so the runtime tries a failed delete up to three times, five seconds apart. Shutdown pauses every running sandbox and counts one that vanishes under it as a failure. So the delete checks the shutdown flag right before its claim and holds a lock across the two. Shutdown takes that lock for writing after it set its flag. So no claim overlaps the shutdown passes, and a delete that reads the flag later finds it set. A delete that still waits when shutdown begins leaves the sandbox to shutdown. A client that closed its create request must not use that sandbox. GET /v2/sandboxes without a state filter shows a sandbox while its create runs, so such a client can still find it. The docs say so. Not covered: a caller that leaves after the handler took the result, the children of a fork whose caller left, and the volume reservation of such a create. Tests: eight unit tests and the e2e suite 20_abandoned_create. The suite starts a cold create, closes the request once a list shows the create, and passes when the sandbox goes away. A sandbox that stays is a warning and not a failure: the suite cannot see whether the server had dropped the handler of the closed request before the create finished. The unit tests are the regression gate. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Hi @yingdi-shan and @LSX-s-Software, could you take a look at this PR when you have time? It deletes the sandbox of a create whose caller left before the answer. Thanks! |
|
Thanks for the detailed write-up. One question about the premise: the client isn't really left without the ID. A sandbox from an abandoned create shows up in If the real concern is paused sandboxes piling up when nobody cleans them up, we need a retention policy for paused sandboxes to cover that. |
|
🔍 OpenCodeReview found 5 issue(s) in this PR.
|
| curl -s -o /dev/null -w '%{http_code}' -X POST \ | ||
| -H "X-API-Key: ${AENV_API_KEY}" \ | ||
| -H "Content-Type: application/json" \ | ||
| -d "$(create_payload "${marker}")" \ | ||
| "${AENV_URL}/sandboxes-cold" > "${create_status_file}" 2>/dev/null & |
There was a problem hiding this comment.
This background request has no --max-time/--connect-timeout. If the suite exits through an error before the normal kill, or if the child does not terminate promptly, the trap can leave a cold-create request running while cleanup proceeds; that request can later create a sandbox which cleanup has already finished scanning. Bound the request lifetime (and wait for the child in cleanup_suite) so a failed run cannot leak resources into subsequent suites.
| kill "${create_pid}" 2>/dev/null || true | ||
| wait "${create_pid}" 2>/dev/null || true | ||
| create_pid="" | ||
| closed_at_ms=$(now_ms) | ||
| create_status=$(<"${create_status_file}") |
There was a problem hiding this comment.
The empty status is used as the proof that the HTTP client was abandoned, but it is not synchronized with the server-side request. After the list observes the sandbox, the handler may already have produced and sent the 201 response while curl is still draining/writing its status; killing curl can then leave an empty status and make this look like an abandoned create. Conversely, the status-file check is only meaningful after confirming the client was actually terminated before the response completed. Capture an explicit client-side termination/response outcome (or use a request that is deliberately closed before the server can finish) to avoid false positives.
| if [[ "${deleted}" == "1" ]]; then | ||
| _pass "sandbox of a create that outlived its request is gone" | ||
| elif [[ -n "${failure}" ]]; then | ||
| _fail "the lists show a create whose request was closed" "listed" "${failure}" | ||
| else | ||
| warn "the delete was not observed in ${ABANDON_ATTEMPTS} attempts: the sandbox stayed in ${stayed}, and the create was answered in ${answered}" | ||
| fi |
There was a problem hiding this comment.
When all attempts either stay alive or receive a response, this only logs a warning and leaves _FAIL_COUNT unchanged. Consequently suite_summary returns success (and even reports all tests passed with zero assertions), so this E2E suite cannot detect a regression in the abandoned-create cleanup path. If this is intentionally best-effort, consider making that explicit in the runner; otherwise record this outcome as a failure (or add a separate required assertion).
| if created.is_ok() { | ||
| runtime | ||
| .spawn(async move { cleanup.delete_unclaimed_sandbox(sandbox_id).await }); | ||
| } |
There was a problem hiding this comment.
The cleanup task is detached and is not included in shutdown's synchronization. Once is_shutting_down is set, try_delete_unclaimed_sandbox refuses to claim the sandbox, while run_shutdown_cleanup only processes the store snapshots it observes. Thus a create can finish after a shutdown snapshot, invoke this callback after shutdown has begun, and leave its successfully-created sandbox persisted (typically paused) even though its result was never delivered. Track/await these cleanup tasks, or make shutdown reconcile unclaimed creations before completing.
| for attempt in 1..=UNCLAIMED_DELETE_ATTEMPTS { | ||
| match self.try_delete_unclaimed_sandbox(sandbox_id).await { | ||
| Ok(()) => return, | ||
| Err(error) => warn!( | ||
| sandbox_id = %sandbox_id, | ||
| attempt, | ||
| error = %error, | ||
| "failed to delete the sandbox of a create whose caller left" | ||
| ), | ||
| } | ||
| if attempt < UNCLAIMED_DELETE_ATTEMPTS { | ||
| tokio::time::sleep(UNCLAIMED_DELETE_RETRY_DELAY).await; | ||
| } | ||
| } |
There was a problem hiding this comment.
After three attempts this function only logs the failure and drops the sandbox ID; there is no durable retry or reconciliation path for an unclaimed create during normal operation. A transient failure in stop, volume release, or store/persistence cleanup can therefore permanently orphan a sandbox that no caller can identify. Consider retaining failed IDs for a later reconciler (or otherwise ensuring shutdown/periodic cleanup will retry them) rather than exhausting the only cleanup owner after roughly ten seconds.
What
When the caller of a sandbox create never takes the result, the runtime deletes that sandbox.
Why
A create runs on its own task, so it still finishes when its HTTP request is dropped. The sandbox ID is only in the answer to that request. When the client has left, the runtime logs a debug line and keeps the sandbox. The client saw a failed create and has no ID to delete.
With the default
autoPause: true, that sandbox runs until its TTL, is then paused, and stays on the node.Reproduction on a single node, TTL 15 s. The client closes its create request after 0.05 s. Times count from the request:
mainRelated issue
None.
Scope and non-goals
The change covers creates through
Orchestrator::create_sandbox, which servesPOST /sandboxesandPOST /sandboxes-cold.Not included:
Design and behavior changes
run_cancellation_safegets a variant,run_cancellation_safe_then. The result travels in a guard that calls the callback when it is dropped unclaimed. That covers a caller that left before the result was ready, and one that left after the result was sent but before it was read. Onlycreate_sandboxpasses a callback.RunningorPaused. Then it runsdelete_sandbox_impl. Nobody else has the ID, so the runtime tries a failed delete up to three times, five seconds apart. It logscreate finished after its caller left; deleting the sandboxat info level.Compatibility and operations
GET /v2/sandboxeswithout astatefilter can show that sandbox while its create runs. The docs now say that such a client must not use it and must send the create again.Validation
make fmtmake clippymake test-unitmake -C services test(required whenservices/changes)maketarget8 new unit tests. They cover a caller that is cancelled during the create, the guard (also for a result that was sent and never read), a delete that finds the shutdown flag set, shutdown that waits for a claim in progress, a delete that waits while shutdown begins, a sandbox that was paused first, and a retry after a failed stop.
I removed or weakened each part in turn, and each time its test failed. Nine checks:
Runningsandbox.1 new end-to-end suite,
20_abandoned_create. It first requires that a cold create succeeds when the client waits. Then it starts the same create with its own marker, closes the request once a list shows the create, and watches the sandbox. It tries up to three times:A sandbox that stays does not fail the suite. The suite cannot see when the server dropped the handler of the closed request. A handler that is still alive when the create finishes takes the result, and then the runtime is right to keep the sandbox. The suite cannot tell that case from a runtime that keeps every such sandbox, so the unit tests are the regression gate.
The suite is a smoke test. It also cannot tell a deleted sandbox from a create that failed after the client left.
Commands and results:
Skipped checks and reasons:
make test-unitdid not run: the ignored tests and the ublk tests need root capabilities.make test-integrationdid not run.Risks and reviewer notes
GET /v2/sandboxeswithout astatefilter shows a sandbox while its create runs. A client that closed its create request and uses that sandbox loses it when the create finishes. In the reproduction that list showed the sandbox in 9 of 222 requests, until it was deleted. The v1 list never showed it.Killing, or in its earlier state when the try failed before the stop. The runtime does not try again.The change is in
src/orchestrator/service.rs:Delivery,run_cancellation_safe_then,try_delete_unclaimed_sandbox, and one line inshutdown().Checklist
🤖 Generated with Claude Code