Skip to content

fix(orchestrator): delete the sandbox of a create whose caller left - #554

Open
iaroslav-reflection wants to merge 1 commit into
kvcache-ai:mainfrom
iaroslav-reflection:orchestrator-delete-unclaimed-create
Open

iaroslav-reflection wants to merge 1 commit into
kvcache-ai:mainfrom
iaroslav-reflection:orchestrator-delete-unclaimed-create

Conversation

@iaroslav-reflection

Copy link
Copy Markdown
Contributor

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:

The sandbox after the client left
main Listed from 0.08 s by the v2 list and from 0.2 s by the v1 list. Paused at 16 s. Still paused at 54 s, when the watch ended.
This change The create finished at 0.22 s and the sandbox was gone at 0.26 s.

Related issue

None.

Scope and non-goals

The change covers creates through Orchestrator::create_sandbox, which serves POST /sandboxes and POST /sandboxes-cold.

Not included:

  • A caller that leaves after the handler took the result. Covering that case needs a create ID from the caller.
  • The children of a fork whose caller left. They stay.
  • Volume reservations of such a create. The handler completes or releases them after the create returns, and a dropped handler does neither, as before.
  • A stop of the create in the middle. The create still runs to its end before the delete.

Design and behavior changes

  • A callback for a result that nobody takes. run_cancellation_safe gets 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. Only create_sandbox passes a callback.
  • The delete. For a successful create, the callback starts a delete. It claims the sandbox the way timeout eviction does: under the deletion lock, from Running or Paused. 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. It logs create finished after its caller left; deleting the sandbox at info level.
  • Shutdown. Shutdown pauses every running sandbox and counts one that vanishes as a failure. So the delete checks the shutdown flag right before its claim and holds a lock across the two, and shutdown takes that lock for writing after it set its flag. A delete that finds the flag set does not claim the sandbox, and shutdown pauses that sandbox like any other. Shutdown waits for a claim that is in progress, and a delete that already claimed its sandbox may finish.

Compatibility and operations

  • Public API or generated protocol: no new field. When a client closes its create request before the sandbox is ready, the runtime now deletes the sandbox once its create finishes. Scope and Risks name the cases in which a sandbox still stays. GET /v2/sandboxes without a state filter 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.
  • Configuration or defaults: unchanged.
  • Snapshot manifest, artifact layout, or storage format: unchanged.
  • Upgrade and rollback: only the runtime changes. A revert restores the old behavior.
  • Host requirements, permissions, ports, or dependencies: unchanged.

Validation

  • make fmt
  • make clippy
  • make test-unit
  • Relevant Rust integration tests
  • make -C services test (required when services/ changes)
  • Generated clients/server regenerated with the documented make target
  • Documentation updated
  • Benchmarks or performance comparison completed

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

  • The guard calls nothing when it is dropped.
  • Shutdown does not wait for a claim.
  • Shutdown waits at most 60 s for a claim.
  • The delete does not hold the claim lock.
  • The delete reads the shutdown flag before it takes the claim lock.
  • The delete reads the shutdown flag before it waits for the deletion lock.
  • The delete does not read the shutdown flag.
  • The delete claims only a Running sandbox.
  • The delete is tried once.

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:

Outcome When
Pass The sandbox of an unanswered create went away.
Fail The cold create fails when the client waits, or the lists do not work or do not show the create.
Warning, not a failure No attempt saw the sandbox go away: it stayed, or the create was answered.

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:

make fmt                                             # passed
make clippy                                          # passed
cargo test -p agentenv -p envd -p linux-cap --lib    # 1,068 + 1 + 3 passed, 5 ignored, in 2 of 2 runs
cargo test -p agentenv --lib <the eight tests>       # passed in 10 of 10 runs
bash scripts/tests/e2e/run_e2e.sh                    # single node, Linux 6.8 VM with nested KVM
  20_abandoned_create on main                        # warning: the sandbox stayed in 3 of 3 attempts
  20_abandoned_create with this change               # passed in 6 of 6 runs, each in the first attempt
  02, 03, 04 with this change                        # passed

Skipped checks and reasons:

  • The rest of make test-unit did not run: the ignored tests and the ublk tests need root capabilities.
  • make test-integration did not run.
  • Go tests did not run, because no Go code changed.
  • The Docker Compose and Kubernetes e2e modes, where the request goes through the gateway, did not run locally.

Risks and reviewer notes

  • A client can find the sandbox and lose it. GET /v2/sandboxes without a state filter 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.
  • After three failed tries the sandbox stays. It is then in Killing, or in its earlier state when the try failed before the stop. The runtime does not try again.
  • The node does the whole create and then a delete. A burst of creates whose callers left costs the node both.

The change is in src/orchestrator/service.rs: Delivery, run_cancellation_safe_then, try_delete_unclaimed_sandbox, and one line in shutdown().

Checklist

  • The PR contains one coherent change and no unrelated formatting or refactoring.
  • New behavior is covered by tests, or I explained why testing is impractical.
  • Logs and examples contain no credentials, tokens, or private registry information.
  • I did not manually edit generated code without updating its source and regenerating it.

🤖 Generated with Claude Code

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>
@iaroslav-reflection

Copy link
Copy Markdown
Contributor Author

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!

@yingdi-shan

Copy link
Copy Markdown
Collaborator

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 aenv list, and the cluster list reaches every node, so a client can find it and delete it. So why not leave this to the client?

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.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 5 issue(s) in this PR.

  • ✅ Successfully posted inline: 5 comment(s)

Comment on lines +182 to +186
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 &

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.

performance · low
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.

Comment on lines +222 to +226
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}")

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.

test · medium
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.

Comment on lines +251 to +257
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

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.

test · medium
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).

Comment on lines +513 to +516
if created.is_ok() {
runtime
.spawn(async move { cleanup.delete_unclaimed_sandbox(sandbox_id).await });
}

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.

bug · high
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.

Comment on lines +525 to +538
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;
}
}

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.

bug · medium
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.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants