Repository navigation
feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer - #5265
Conversation
efa72d4 to
6daa68a
Compare
b22af13 to
5bdd336
Compare
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD
Snapshot release can delete a subsequently exported checkpoint, and cleanup can hang on connection failures or a cancelled file-lock acquisition. The remaining findings cover sandbox ownership, restore cleanup, lease timing, and parked command reads.
I reviewed all 14 changed files and traced their affected lifecycle, HTTP-client, and checkpoint-control contracts. This was a static review; I didn't execute tests or validate against a live OpenSandbox server.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Inline comments (escaped v1):
-
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 650: BLOCKER — Freeze release candidates before admitting the next checkpointFailure: hold
snapshots.lock, callrelease(frozenset({'c1'})), exportc2after that call returns, then unlock and settle. The queued release reads the index later and deletesc2because its stale kept set excludes it. This satisfies the documented precondition: no export was running when release was called. The control-plane lock protects only the awaited hook, which has already returned. Moving just the index read earlier isn't sufficient: the later prefix sweep can also discover the new snapshot. A successfully exported checkpoint can therefore become unrestorable.Correction: could you capture the complete eligible snapshot-ID set—both indexed and prefix-sweep candidates—while checkpoint admission still excludes the next export, then delete only that frozen set in the background? That discovery boundary must cover all workers sharing the index; waiting for only the current worker's release doesn't exclude another worker's stale release. The cross-process coordination needs an implementation decision, so I don't have a verified small patch.
Preserve: background deletion, failed-delete markers and retries, cleanup of crashed/unindexed dropped snapshots, and every kept checkpoint.
Acceptance (proposed): reproduce the held-lock sequence above with two checkpointers sharing a directory.
c2must remain restorable, including a snapshot whose index write is delayed. Pre-existing dropped indexed and unindexed snapshots must still be deleted. Retain the sequential-release assertions that each release deletes only its intended snapshots. -
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 657: BLOCKER — Don't abandon a blocking file-lock acquisition on cancellationFailure: hold the index lock, start
release(), wait until its worker thread attempts acquisition, then time outsettle(). The unshielded gather in settle cancels the release task, but cannot stop the thread blocked inflock. Once the original holder unlocks, that abandoned thread acquires the lock and returns a descriptor nobody closes. Thetry/finallybelow this await was never entered, so later releases sharing the index can block indefinitely.Correction: could you make lock acquisition cancellation-safe, ensuring every acquired descriptor is either transferred to a live release task or unlocked and closed during cancellation cleanup? A cancelled
settle()waiter should also not cancel the background work it merely observes. The exact handoff needs care around repeated cancellation; I haven't established a safe replacement patch.Preserve: acquisition off the event loop, serialization across processes, unlock after deletion failures, and prompt cancellation of the caller waiting in
settle().Acceptance (proposed): gate acquisition behind a held lock, cancel/time out
settle(), then release the original lock. A subsequent release and settle must finish within a bounded timeout and delete the dropped snapshots. Retain the existing assertion that no deletion occurs while another process holds the lock. -
nemo_gym/sandbox/providers/opensandbox/provider.pyline 1619: BLOCKER — Bound the shared client's retries for management requestsFailure: when the management endpoint continually refuses connections,
delete_snapshot()andlist_snapshots()never exhaustoperations.retries. This request supplies no transport retry limit, and the shared client's disconnect/ClientOSError branches retry indefinitely without one. Neither method reaches its outer retry loop, so a release can hold the shared snapshot lock forever. Unlike readiness polling, listing and deletion have no enclosing total timeout.Correction: could you make each
_management_request()use one transport attempt and leave retries to its callers? Replace this line with:_control=True, _max_num_tries=1,Also update the wait/delete/page retry handlers to catch direct aiohttp transport failures, notably
aiohttp.ClientConnectionErrorandaiohttp.ClientPayloadError, alongside their current timeout/OS errors. Otherwise the bounded transport makes disconnected or truncated responses fail immediately instead of following the documented retry policy. Please verify the suggestion before adopting it.Preserve: terminal malformed-JSON and nonretryable HTTP errors, successful 404 deletion, readiness's total timeout, and existing 429/5xx backoff.
Acceptance (proposed): patch
get_global_aiohttp_control_client()with a client raisingaiohttp.ClientOSError; with two retries and zero backoff, listing and deletion must each make three wire attempts and then raise within a test timeout. Check a disconnected/truncated response followed by success, 403 failing once, and retain the 404/429/503 cases. -
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 414: RISK — Reserve a sandbox key before awaiting creationFailure: gate provider creation and start two
checkpointer.create('s1', SPEC)calls before opening the gate. Both pass the membership check and create a remote sandbox; this assignment overwrites the first entry. Only the second remains reachable throughget()andstop(), leaving the first running and potentially receiving lease renewals. Expected behavior is the same duplicate-key rejection already provided for sequential calls.Correction: could you claim the key synchronously before the first await and release that claim on failure or cancellation? Every installing path—
create(),add(), and restore validation—must honor pending claims, so none can overwrite an in-progress creation. Different keys should remain concurrent under the existing semaphore. A pending-key collection can establish that invariant, but the complete change spans those installing paths rather than just this assignment.Acceptance (proposed): race two gated creates for
s1; exactly one should succeed, the other should reject the duplicate, and only one remote sandbox should exist. Stoppings1must leave none. Failed/cancelled creation must permit retry, and creates for distinct keys must still overlap. Retain the existing sequential duplicate assertion, and check thatadd()or restore cannot claim a pending key. -
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 567: RISK — Roll back completed forks when restore is cancelledFailure: restore two states, let the first fork finish, and block the second provider creation. Cancelling the restore task makes this
gather()raise beforefailuresis examined. The completed fork is neither installed nor stopped:keysstays empty andsettle()has no cleanup task to await. Ordinary request deadlines don't trigger this because installation is shielded, but direct cancellation or shutdown still reaches it.Correction: could you give
restore()cancellation-safe ownership of its fork tasks and completed sandboxes? On an unsuccessful exit, cancel and drain unfinished fork tasks, stop every completed fork, then propagate the original exception or cancellation. Retain any failed cleanup for retry rather than losing its wrapper. Don't install partial entries or stop the original sandboxes. This requires a cleanup boundary around the gather, not just inspection of returned exceptions.Acceptance (proposed): gate the second fork, wait for the first to exist, cancel restore, and verify the completed fork is stopped—or retained in explicitly awaitable cleanup—while cancellation propagates, no entries install, and originals remain running. A retry must restore both states. Preserve the ordinary quota-failure rollback assertions and successful restore's background superseded-sandbox cleanup.
-
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 574: RISK — Retain forks whose rollback stop failsFailure: extend the existing rollback test so creating
sb-6fails and closing the completed forksb-5fails once. This gather discards the close failure, then restore raises the creation error and loses its localcreatedmapping. Neither a retried restore norsettle()retries that stop, leaving remote resources untracked until their backend lifetime ends.Correction: could you retain failed rollback forks separately until their
stop()succeeds, with an explicit cleanup retry/drain path available tosettle()and shutdown? Don't install them in_entries: restore must remain all-or-nothing and allow a later retry. Preserve the original fork error while recording cleanup failures with enough context to retry. AsyncSandbox.stop already retains the handle after a failed remote stop; the checkpointer needs to retain its wrapper too. The pending-cleanup mechanism needs an implementation decision, so I haven't supplied an invented patch.Acceptance (proposed): inject one creation failure and one rollback-close failure. Assert no entries install and originals stay running; trigger the cleanup retry and assert the failed fork stops. A subsequent restore must succeed. Retain ordinary successful rollback and the behavior that a successful restore returns before superseded-original cleanup finishes.
-
nemo_gym/server_runtime/_checkpoint/sandbox.pyline 691: RISK — Validate the complete generated name before deleting an orphanFailure: a manual snapshot named
f'{checkpointer.snapshot_name_prefix}manual01-backup-daily'passes this guard and is deleted byrelease(frozenset()). It has three suffix parts and an eight-character first part, but neither the checkpoint/key hashes nor a numeric attempt generated by this checkpointer. The existing manual-backup preservation case has only two suffix parts and misses this destructive selection.Correction: could you add
import reand replace the suffix parsing/guard at lines 690–692 with:suffix = snapshot["name"][len(prefix) :] if re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{8}-[1-9][0-9]*", suffix) is None: continue parts = suffix.split("-")
Keep the subsequent kept-hash and indexed-ID checks. This matches the name generator and export attempts: lowercase eight-character hashes and positive attempts, including multiple digits. Please verify the suggestion before adopting it.
Acceptance (proposed): add the example, a malformed key hash, and a nonnumeric attempt to the foreign-snapshot preservation test; none may be deleted. Generated dropped orphans at attempts
1and10must still be deleted. Generated kept orphans, indexed kept snapshots, other-server names, and other-run names must survive. -
nemo_gym/sandbox/providers/opensandbox/provider.pyline 2279: RISK — Maintain the lease while provider-side startup runsFailure: creation sets the initial TTL to
renew_ttl_s, but renewal starts only after reconnect, probes, and all setup commands, then sleeps another full interval. With lease 1200/interval 300, an immediately created sandbox whose two setup commands take 500 seconds each returns successfully at roughly second 1000, but its first renewal starts around seconds 1270–1330—after expiry. Each command fits the default 600-second setup budget. A healthy sandbox can therefore disappear after being handed to its owner.Correction: could you start lease-mode maintenance as soon as the created handle is available, before provider-side reconnect/probe/setup, and keep it bound to the current handle if reconnect replaces it? Record the lifetime boundary once rather than restarting it after setup, and ensure failed/cancelled startup cancels renewal through the existing cleanup path. SDK creation/readiness can also consume lease time; its effective expiry contract needs checking before choosing the complete implementation, so I don't have a verified patch for that part.
Acceptance (proposed): use a fake backend recording initial expiry and rejecting late renewals; make setup consume most of a short lease while finishing before expiry. The sandbox must stay alive through setup and the next interval. Preserve startup-failure/cancellation cleanup, no renewal when the spec TTL is within the lease, and legacy non-lease renewal behavior.
-
nemo_gym/sandbox/providers/opensandbox/provider.pyline 2122: RISK — Keep positive jitter within the accepted TTL marginFailure: validation accepts lease 100/interval 95, but an upper-bound jitter sleeps 104.5 seconds before the first renewal, even with instantaneous startup and a healthy API. This also regresses existing non-lease configurations with
spec.ttl_s=100and interval 95: they previously renewed at second 95. An accepted configuration shouldn't expire solely because of the newly added jitter.Correction: one small correction here is to retain ±10% jitter when it fits and use negative-only jitter otherwise:
jitter_high = 1.1 if interval_s * 1.1 < ttl_s else 1.0 await asyncio.sleep(interval_s * random.uniform(0.9, jitter_high))This preserves the existing acceptance of intervals shorter than TTL rather than newly rejecting legacy configurations. It fixes jitter-induced expiry; startup/expiry accounting remains a separate requirement. Please verify the suggestion before adopting it.
Acceptance (proposed): force
uniform()to return its upper bound for both lease and non-lease 100/95 configurations; the first renewal must begin before second 100. Preserve the 1200/300 jitter test, including bounds(0.9, 1.1), whole-TTL legacy renewal, and truncation at the spec's lifetime. -
nemo_gym/sandbox/providers/opensandbox/provider.pyline 2773: RISK — Protect the final log read during a checkpoint parkFailure: block an in-flight status request, open
parked_exec_polling(), then release that request withrunning=False, exit_code=0. The loop immediately fetches logs while the sandbox is parked. If snapshotting makes that read time out or disconnect, the command fails instead of waiting for the park to end. The same overlap on a status request is explicitly forgiven. A successfully finished command can therefore fail because of checkpoint timing.Correction: could you gate the final log fetch with
_wait_while_parked()and give a log request overlapping a newly opened park the same one-time fresh allowance as a status request? Reset the overlap marker before each read so continued unavailability after the park still fails normally. Preserve cancellation/deadlines, the authoritative status exit code, and the existing deleted-output fallback; a genuinely deleted output file must not become an endless retry. The different log-error branches need coordinated handling, so I haven't supplied a blanket retry patch.Acceptance (proposed): add the gated finished-status case: no log request should start during the park, and after exit the task should return its original exit code and logs. Also start a log read before opening the park and make it time out; one post-park retry should succeed, while another timeout without a new park must raise. Retain the existing status-failure cases and the known-exit/deleted-output behavior.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| parsed[key] = (state, spec) | ||
|
|
||
| created: dict[str, AsyncSandbox] = {} | ||
| outcomes = await asyncio.gather( |
There was a problem hiding this comment.
If restore is cancelled after some forks have already started, does this rollback still run? CancelledError leaves gather before the stop, and those forks are not in _entries. return_exceptions=True also drops a stop that fails, so that fork is left untracked too. Should the rollback run on cancel, and should a fork whose stop failed stay tracked?
There was a problem hiding this comment.
Yes to both, fixed in 20daa60.
- Cancel:
restorenow catchesCancelledErroraround the forks, hands the forks that completed to a rollback task, and re-raises.settle()waits for that task. Nothing is installed in the entries and the original sandboxes keep running, so a retry restores every state. - A stop that fails: the rollback no longer drops it. The fork is logged and kept in a separate list (not in the entries, so restore stays all or nothing), and the next
restorestops it again before it forks anything.
Tests: test_a_restore_cancelled_after_a_fork_completed_stops_that_fork and test_a_fork_whose_rollback_stop_failed_is_logged_and_stopped_by_the_next_restore.
5bdd336 to
bb0a0b1
Compare
bb0a0b1 to
7f9afc6
Compare
7f9afc6 to
4f14561
Compare
| retries: 10 | ||
| retry_delay_s: 5.0 | ||
| retry_max_delay_s: 90.0 | ||
| # Optional lease, off by default (recommended with partial-rollout checkpoints): each sandbox is created |
There was a problem hiding this comment.
The sandbox lease (create.renew_ttl_s) that bounds a crashed process's sandboxes ships turned off, but the checkpointer's docstring presents it as that bound.
#4220 shipped it turned on, with renew_ttl_s: 1200 and renew_interval_s: 300.
Please turn the sandbox lease on in the shipped config.
There was a problem hiding this comment.
I've kept the lease off in the shipped config, and fixed the mismatch you pointed at instead: the checkpointer's docstring now says the lease is off in the shipped OpenSandbox config and that a config which checkpoints sandboxes should turn it on.
The reason for the default is that opensandbox.yaml is composed by many benchmark configs that do not checkpoint. With a lease, every live sandbox depends on its process reaching the management API each interval, so an API outage longer than renew_ttl_s minus renew_interval_s ends healthy sandboxes. A run that checkpoints can restore from that; a run that does not loses the episodes. Without a lease, the same outage costs nothing, and a crashed process's sandboxes are still deleted at the spec's ttl_s.
The comment above the keys in opensandbox.yaml now states this trade-off and gives the 1200/300 values from #4220 for checkpointing configs to set. This push also makes the lease safer to turn on: renewal jitter is downward only, and the first renewal counts the time setup already took.
|
/ok to test 89a2266 |
…t not found A live OpenSandbox service answers a create from a snapshot it has deleted with HTTP 404 and no error code in the body, so the SDK's error carried no SNAPSHOT::NOT_FOUND and create_from_snapshot raised a generic create failure. The checkpointer's retry of a fork whose snapshot is not found, and a caller that handles SandboxSnapshotNotFoundError, never saw the typed error. create_from_snapshot now raises SandboxSnapshotNotFoundError for that 404 as well. The create names nothing else that could be missing: the snapshot stands in for the image. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Prashant Thombre <[email protected]>
|
/ok to test 35d8f39 |
| sandbox = entry.sandbox | ||
| # Before any snapshot is taken: a spec that cannot be written fails every commit the same way. | ||
| try: | ||
| spec = _SPEC_JSON.validate_python(spec_to_json(entry.spec)) |
There was a problem hiding this comment.
[P2] Preserve updated execution defaults across restore
Could export capture the sandbox's current default user and working directory rather than only the original entry.spec? set_default_user() and set_default_workdir() replace the facade's spec, so this saved spec becomes stale. Although serialize() carries the updated defaults in the descriptor, restore uses state.spec for the fork and the descriptor only to stop the superseded sandbox. After setup changes these defaults, commands therefore resume under the original user/directory, potentially as root. Please add a round-trip test that changes both defaults before export and checks them after restore.
There was a problem hiding this comment.
Fixed in 087140f. Export now records the sandbox's current default user and working directory rather than the spec it was created with, so the fork is created with them and runs commands as setup left them. Added AsyncSandbox.default_workdir to read the directory, and a round-trip test that changes both defaults before export and checks them on the fork, on the fork's spec, and in the fork's next checkpoint.
| interval_s = self._create.renew_interval_s | ||
| lease = self._create.renew_ttl_s is not None | ||
| loop = asyncio.get_running_loop() | ||
| lifetime_end = None if lifetime_s is None else loop.time() + lifetime_s |
There was a problem hiding this comment.
[P2] Anchor the lifetime cap to creation time
Could this use created_at + lifetime_s? The new created_at correctly includes the create request, but loop.time() + lifetime_s here starts the lifetime over after creation, reconnect, probes and setup. With a lease enabled, subsequent renewals can therefore extend the sandbox beyond the spec's ttl_s by that elapsed startup time, despite the documented creation-time cap. Please cover a nonzero startup duration in the lifetime-cap test.
| lifetime_end = None if lifetime_s is None else loop.time() + lifetime_s | |
| lifetime_end = None if lifetime_s is None else created_at + lifetime_s |
There was a problem hiding this comment.
Applied the suggestion in 087140f: the cap is created_at + lifetime_s. A new test with a 120 s create checks that no renewal extends the sandbox past the spec's ttl_s from the create request, and that the loop then ends.
| timeout_s=self._connection.request_timeout_s or 60, | ||
| ) | ||
| # Jittered downward only: a renewal later than the interval could miss a TTL just above it. | ||
| await asyncio.sleep(max(0.0, interval_s * random.uniform(0.9, 1.0) - already_waited_s)) |
There was a problem hiding this comment.
[P2] Account for failed renewal time when scheduling the next attempt
Could retries be scheduled against the last successful renewal's expiry rather than sleeping another full interval after a failure? With a 1200-second lease, 300-second interval, 30-second request timeout and allowed jitter factor 1.0, attempts can time out at t=300–330, 630–660 and 960–990; the next attempt starts at 1290, after expiry at 1200. An outage from t=299 to 1050 lasts only 751 seconds, and the API has recovered 150 seconds before expiry, yet the sandbox still expires. Please retry within the remaining lease budget and update the documented renew_ttl_s - renew_interval_s outage tolerance to include request/retry time.
There was a problem hiding this comment.
Fixed in 087140f. The loop tracks when the TTL the service last accepted runs out. After a failed renewal it waits half of what is left once one request timeout is set aside, never longer than the interval and never shorter than 1 s, so tries continue up to the expiry and come closer together as it nears. Your scenario (1200 / 300 / 30, outage from 299 to 1050) is a test: the tries start at about 300, 630, 915 and 1058, and the last one renews before 1200. Once the lease has run out the tries return to the interval until the service says the sandbox is gone. The docs page and the config comment now give the tolerated outage as about renew_ttl_s - renew_interval_s - renew_timeout_s.
| ) | ||
| pages_read.append(page) | ||
| # An empty page is the end even if the server reports another: the loop must not outlive the store. | ||
| if not items or pagination.get("hasNextPage") is not True: |
There was a problem hiding this comment.
[P2] Reject malformed pagination instead of returning a partial listing
For a nonempty page, could pagination.hasNextPage be required to be a boolean? Currently a reply such as {"items": [{"id": "s1", "name": "ng-example"}], "pagination": {}} returns successfully after page 1. Missing or incorrectly typed pagination can therefore silently omit later-page orphan snapshots from cleanup. The existing snapshots.py cleanup tool validates this field explicitly. Preserve the intentional empty-page termination, but raise SandboxSnapshotError for an invalid continuation flag on a nonempty page and cover that case.
There was a problem hiding this comment.
Fixed in 087140f. A page with items must carry a boolean hasNextPage; a missing or mistyped flag raises SandboxSnapshotError naming the page. An empty page still ends the listing whatever it says. Tests cover {}, null, "false" and 0 on a page with items, and an empty page without the flag.
| if poll.wakeup.is_set(): | ||
| poll.wakeup.clear() | ||
| return | ||
| sleep_task = asyncio.create_task(asyncio.sleep(interval_s)) |
There was a problem hiding this comment.
[P3, non-blocking] Avoid two helper tasks on every command poll
Could this wait use asyncio.timeout(interval_s) around poll.wakeup.wait() while preserving the pre-delivered wakeup check and clearing the event in finally? The current path creates two tasks per poll even when checkpointing is inactive. At a configured 50 ms cadence and 1500 commands that is nominally 60,000 helper tasks/second. In three local synthetic runs of 1500 concurrent commands × 40 waits, the timeout-based alternative removed 120,000 helper-task creations per run and reduced median helper CPU from 0.632 s to 0.381 s; this is scheduling-only evidence, not a production throughput claim. Please retain wakeup and cancellation coverage; a plain sleep would lose immediate wakeups when a checkpoint scope opens.
There was a problem hiding this comment.
Done in 087140f. The wait is asyncio.timeout(interval_s) around poll.wakeup.wait(), with the pre-delivered wakeup check kept and the event cleared in finally. A new test checks that the wait starts no task, ends at the interval, ends at once on a wakeup, uses up a wakeup delivered before it, and propagates a cancel. Since the wait no longer goes through asyncio.sleep, which many existing tests replace to control time, the sandbox tests have a fixture that runs the provider's own wait and lets the replaced sleep end it.
|
|
||
| async def _delete_snapshots_locked(self, index: _SnapshotIndex, kept: frozenset[str]) -> int: | ||
| """Delete what ``kept`` drops; returns how many snapshots could not be deleted.""" | ||
| indexed = await asyncio.to_thread(index.snapshot_ids) |
There was a problem hiding this comment.
[P3, non-blocking] Exclude kept checkpoints before reading their index contents
Could the index reader accept the kept checkpoint IDs and skip those directories before enumerating/sorting their snapshot filenames? Currently snapshot_ids() reads every retained checkpoint's contents, only for the next line to filter them out. Retaining K checkpoints with N snapshots each adds K×N filename reads plus sorting and allocation to every deletion pass, under the shared index lock. The unindexed sweep already protects kept checkpoints by name hash, so their snapshot IDs are unnecessary here. Keep the dropped checkpoints' IDs for sweep deduplication, including IDs whose deletes fail, and preserve the crash-orphan sweep.
There was a problem hiding this comment.
Done in 087140f. The index reader takes the kept checkpoint ids and skips their folders without opening them, so a release reads only what it drops. The sweep is given every dropped checkpoint's ids, including those whose delete just failed, so it does not try them a second time; kept checkpoints are still protected by the checkpoint hash in the name, and the crash-orphan sweep is unchanged. Tests cover both.
… failed lease renewal in time - A checkpoint records the sandbox's current default user and working directory, so a fork runs commands as setup left them rather than as the sandbox was created. - The spec's lifetime is counted from the create request, so renewals cannot extend a sandbox past its ttl_s by the time its startup took. - A failed lease renewal is tried again within what is left of the lease, sooner as the expiry nears, instead of a full interval later. - A snapshot listing page that has items must say whether another page follows; a missing or mistyped flag raises instead of returning a partial listing. - A command poll waits for its wakeup under a timeout instead of racing two helper tasks. - A release does not read the index folders of the checkpoints it keeps. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 087140f |
…ugh create_from_snapshot The local_dir provider forked a snapshot through `create` with `provider_options["snapshot_id"]`, the convention #5265's protocol replaced. It now implements `create_from_snapshot` and raises `SandboxSnapshotNotFoundError` for a snapshot it does not have. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
| try: | ||
| sandbox = AsyncSandbox(self._provider, spec, owns_provider=False) | ||
| async with self._semaphore: | ||
| await sandbox.start() |
There was a problem hiding this comment.
[P2] Retain a sandbox whose startup cleanup fails
Could a sandbox that started but could not be cleaned up remain tracked for a later stop? AsyncSandbox.start() can create the sandbox and then fail while delivering spec.files; it calls stop(), but if that stop also fails, this method clears _pending without ever adding the wrapper to _entries or another cleanup collection. I reproduced create() failing with no tracked keys while the sandbox is still running; aclose() cannot retry its stop, and another create for the same key starts a second sandbox.
Please retain failed-start wrappers whose teardown fails or is cancelled, retry their cleanup during shutdown and before recreating that key, and cover the upload-failure plus stop-failure path. LentSandboxes.lend() already keeps failed-seed sandboxes for this purpose.
|
|
||
| def unmark(self, checkpoint_id: str, snapshot_id: str) -> None: | ||
| (self.root / checkpoint_id / snapshot_id).unlink(missing_ok=True) | ||
| self.remove_if_empty(checkpoint_id) |
There was a problem hiding this comment.
[P3, non-blocking] Prune checkpoint directories once per deletion batch
Could the bulk deletion path unlink snapshot marks without attempting to remove the checkpoint directory after every unlink? _delete_snapshots_locked() already calls remove_if_empty() once per dropped checkpoint after the deletes finish. With the current unmark(), deleting 1,000 snapshots from one checkpoint makes 1,001 rmdir attempts, most failing because other marks still exist. Deferring pruning to the existing batch cleanup reduces that to one directory-removal attempt, which avoids redundant filesystem metadata operations on shared storage.
Please keep immediate pruning for standalone failed-snapshot cleanup. Cancellation may leave an empty checkpoint directory, which the next deletion pass can safely remove; failed snapshot deletes must still retain their marks.
…boxes and jitter lease renewal retries - aclose closes the checkpointer, so create, add and restore are refused, waits for the ones already running, and then stops the sandboxes; a restore that installs its forks during a shutdown has them stopped. - Every sandbox stop has a time limit, so one that hangs does not hold up a shutdown. - A create from a snapshot counts an HTTP 404 as a missing snapshot only when the SDK parsed no error code; a 404 with a code about the sandbox keeps its own type. - A failed lease renewal's retry wait is jittered, so sandboxes created together do not retry in step. - add's docstring says the default user and working directory of a fork come from the sandbox at export. - Tests: a cancelled restore whose fork's stop fails keeps the fork tracked; the lookup-grace test no longer depends on an earlier test importing the SDK. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test 5737593 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43926466001 |
…ugh create_from_snapshot The local_dir provider forked a snapshot through `create` with `provider_options["snapshot_id"]`, the convention #5265's protocol replaced. It now implements `create_from_snapshot` and raises `SandboxSnapshotNotFoundError` for a snapshot it does not have. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…ugh create_from_snapshot The local_dir provider forked a snapshot through `create` with `provider_options["snapshot_id"]`, the convention #5265's protocol replaced. It now implements `create_from_snapshot` and raises `SandboxSnapshotNotFoundError` for a snapshot it does not have. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
NVIDIA-NeMo#5269) * test(checkpoint): end-to-end harness scenarios, SWE-bench recipe, docs - tests/e2e/checkpoint: a fake harness agent that borrows the task sandbox and runs a python harness under the real process supervisor with run_until_parked; a workspace server on CheckpointedSandboxSessionResourcesServer; and local sandboxes (directories whose snapshots fork with the same paths, with or without snapshot support). Scenarios E1-E8: pause in place, the stop fallback and relaunch, a crash at invoke_agent, close_agent and verify then a restore, a harness that finishes as the park arrives, release, and a provider without snapshots. E1 and E3 run through both single_agent_turn and single_agent_turn_legacy. - benchmarks/swebench/verified/opencode_sessions.yaml: OpenCode on SWE-bench Verified through single_agent_turn_legacy, on OpenSandbox, with checkpoint.state_dir. - Docs: "Make a resources server checkpointable", "Make a harness checkpointable", and a checkpoint section in the opencode_agent README. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> * fix(checkpoint): fork the local e2e sandbox provider's snapshots through create_from_snapshot The local_dir provider forked a snapshot through `create` with `provider_options["snapshot_id"]`, the convention NVIDIA-NeMo#5265's protocol replaced. It now implements `create_from_snapshot` and raises `SandboxSnapshotNotFoundError` for a snapshot it does not have. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> * fix(checkpoint): list the local e2e provider's snapshots as SandboxSnapshotInfo, and name the moved conformance kits in the docs Follow the sandbox snapshot contract the stack is now based on. - The local e2e provider returns SandboxSnapshotInfo from list_snapshots. - The resources server tutorial names state_dir_id, which replaced run_id, and imports check_sandbox_session_checkpoints from resources_servers.swebench.testing. - The harness tutorial imports check_harness_adapter from nemo_gym.server_runtime. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> * docs(checkpoint): say which servers need a state_dir, and which OpenCode sessions restart - Only a server that exports its sessions refuses to start without a `state_dir`: a golden-patch server, or one on a provider that cannot snapshot, starts. - OpenCode's README lists sessions that continue an imported conversation among those that restart after a crash. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> * test(checkpoint): harden the harness e2e scenarios, add restore-twice scenarios, correct the recipe and docs Found in a review of the end-to-end harness scenarios, the SWE-bench recipe and the docs. End-to-end infrastructure: - A deployment's teardown kills what its local-directory sandboxes still run. A harness a checkpoint paused waits for its continue for ever and outlives the servers, so a test that failed between a prepare and its resume left it on the machine. - The local provider forks a snapshot whatever is at the snapshot's path, running or stopped; before, a restore after the source sandbox had stopped failed with FileExistsError. A snapshot leaves out fifos, sockets and files that went away, and a copy that fails leaves no half-written snapshot. The tree copies run off the event loop. `wait_snapshot_ready` raises SandboxSnapshotNotFoundError, as the provider contract says. - The fake harness agent fails an activation whose harness died instead of reporting it completed, starts a failed activation again at its retry, counts an injected pause failure when it installs it, uploads its harness with `upload_text`, and releases the sandbox connection when the install fails. - The workspace server raises when the notes cannot be read instead of capturing empty notes. - Control deadlines default to 90 s (a pause may take 45 s to confirm) and the server logs are printed at teardown. Scenarios: - E5 shows the episode continued (no call and no sandbox after the capture) and waits with a deadline; its grading outlasts the checkpoint on a busy machine. E7 waits for the releases instead of sleeping and shows both pauses were in place. E8 shows the replacement started over in a new sandbox. E3 cannot pass on an empty set. - E9: a checkpoint of a restored episode, the older checkpoint released, a second crash and restore. - E10: a second crash before the replacement attempt starts, with restored sessions nothing has claimed yet. Recipe: the sandbox outlives the episode and its pause allowance (`ttl_s: 28800`); the `timeout` comment described another setting; OpenCode needs no "no tool grants" condition; one `state_dir` per job. A test resolves it. Docs: samples import from the public API and check their exec results; `Activation.slot`; what `replay` requires of `/verify`; the `checkpoint` block and the `sandbox_checkpoint` settings; `metadata.harness_launches`; one `state_dir` per job; cross-links between the two pages. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> * test(checkpoint): assert the harness is stopped during a checkpoint, and harden the local e2e sandbox provider E1 reads the state of the harness process between the commit and the resume: the backend holds the harness's model call, so the reward and the call and launch counts alone would pass with a pause that sent no signal. The local sandbox provider renames a snapshot's meta.json into place, so a listing never reads a half-written file, and scans /proc for a sandbox's processes off the event loop. A close and a fork read the sandbox's record again after the scan, so neither saves what the other changed meanwhile. With the scan off the event loop, stopping a superseded sandbox no longer completes in one step of the loop, so E10 waits for it before its second crash. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]> --------- Signed-off-by: Pranav Thombre <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
What changed and why
To checkpoint an episode whose agent works in a sandbox, the sandbox's filesystem has to be saved with the checkpoint and brought back after a crash. A Gym process cannot hold that state, so the provider has to snapshot it, a restore has to fork from the snapshot, and snapshots of checkpoints the controller dropped have to be deleted, including those of a process that crashed mid-commit.
This PR adds that in two separate layers.
1. Provider capability (lifecycle only, in the sandbox package)
SupportsSandboxSnapshot:snapshot(handle, *, name)starts a snapshot and returns its id at once, pluswait_snapshot_ready,delete_snapshot(gone counts as deleted) andlist_snapshots(prefix), which returnsSandboxSnapshotInforecords.create_from_snapshot(snapshot_id, spec)starts a sandbox from a snapshot in place of the spec's image, and raisesSandboxSnapshotNotFoundErrorwhen the provider has no such snapshot. Other failures are typed too:SandboxSnapshotFailedErrorfor a snapshot that failed or was not ready in time,SandboxSnapshotInUseErrorfor a delete refused because something still uses the snapshot, both underSandboxSnapshotErrorand carrying the snapshot id and the server's reason.operations.snapshot_request_timeout_s(30 s), and the snapshot calls retry transient answers (429, 5xx, connection errors) inside their own budgets, so a dead connection cannot hang a commit. A 404 to a delete counts as gone only once a lookup confirms it. A snapshot the API just created but cannot find yet is waited out for a grace period. Prefix listing filters client-side, since the API's name filter matches whole names.AsyncSandbox(no-ops on providers without them):checkpoint_exec_polling()polls a sandbox's commands frequently while a harness stops for a checkpoint, so the stop is noticed promptly;parked_exec_polling()holds command polls while a paused sandbox is being snapshotted. A status request the park left unanswered is asked again, and the provider's status-recovery window starts over once the park ends, so a snapshot is not mistaken for a lost sandbox. Without a park, status failures followmain's status-recovery rules unchanged. Scopes nest.create.renew_ttl_s): a sandbox whose owner crashed is reclaimed within one lease instead of at its full TTL. Off in the shipped config: a lease also ends a healthy sandbox when renewals fail for longer than the lease, and many configs that do not checkpoint compose that file. A checkpointing config turns it on. Renewal intervals are jittered downward only, and the first renewal counts the time sandbox setup already took, so a renewal never lands later than configured.2. Checkpointer (built on the capability, outside the sandbox package)
SandboxSessionCheckpointercheckpoints the sandboxes a server owns, by an opaque key, whatever kind of server the owner is.checkpoint.state_diris required and must be an absolute path: a relative one would resolve against each server's and each restart's own working directory.export(keys, *, checkpoint_id)snapshots each live sandbox. The saved state carries a formatversionandsnapshot_ready_ts, and a spec that cannot be saved as JSON fails before any snapshot is taken. Each snapshot is indexed understate_diras soon as its id returns, before the readiness wait, so a crash mid-commit still leaves a record to delete. Failed snapshots are retried, with every attempt indexed. A commit waits for all its snapshots at once.restore(states)validates every state first, forks all or nothing (rolling back on failure or cancellation), retries a fork the store cannot find yet, and stops the superseded sandboxes in the background;settle()waits for those stops. A fork whose rollback stop failed is stopped again by the next restore. A state of another format version is refused.release(kept)deletes under a lock shared by every process of the server, and returns only once every delete was tried: first the indexed snapshots of every dropped checkpoint (including a crashed process's), then a prefix sweep for snapshots the index never recorded, touching only names the checkpointer itself generates. A failed delete stays indexed, is retried by the next release, and makes this one raiseSnapshotReleaseError; coordination reports that per server without failing the run. The lock needsflockon thestate_dirfilesystem, and a filesystem without it fails with the lock path and a mount hint.main's existing OpenSandbox snapshot tool, which gains a--name-prefixfilter. A job that resumes needs nothing: its ownreleasefinds the dead process's snapshots through the index.This rebuilds the provider half of #4220, #4553 and #4779, and the checkpointer of #4220 and #4779 (legacy stack), on
main.How it works
Where this PR sits in the overall flow
The highlighted parts are what this PR adds.
flowchart LR C["Controller<br/>NeMo RL, or rollout collection"] CO["Coordination<br/>prepare, commit, resume, restore,<br/>retire, forget, release"] E["Environment server<br/>bookmarks, re-seed after a restore"] A["Harness agent, e.g. OpenCode<br/>run until parked, re-bind, resume"] S["Process supervisor in the task sandbox<br/>pause, continue, stop"] R["Resources server, e.g. SWE-bench<br/>owns and lends the task sandbox"] OB["Session base with checkpoints<br/>export, restore, release"] K["Sandbox checkpointer<br/>snapshot index, release, gc"] P["Sandbox provider, e.g. OpenSandbox<br/>snapshot, fork, delete, list"] M["Policy model<br/>held calls, capture ledger"] D[("Checkpoint directory<br/>and state_dir")] C --> CO --> E & A & R & M E -- "seed, re-seed" --> R E -- "seed, re-seed, activation" --> A R -. "sandbox_access" .-> A A --> S R --- OB --> K --> P A -- "model calls" --> M CO --> D classDef this fill:khaki,stroke:darkgoldenrod,stroke-width:2px,color:black class K,P thisThis PR
The life of one session's snapshots across two checkpoints, a crash and a release.
Where this sits in the stack
This is one PR in a stack for checkpointing environment-server episodes whose agent harness runs in a sandbox the resources server lends (first pair: OpenCode and SWE-bench on OpenSandbox; #5410 to #5413 add AgentENV, where OpenCode resumes in place after a restore). #5264 has merged, and the rest of the stack is rebased onto
mainafter it. Each PR is based on the one before it, so each diff shows only that PR's change. The stack runs parallel to thelegacy_agentpath of #4220 to #4936, which it does not change or depend on.Issue
No tracking issue exists. This implements the environment-server plan for checkpointing sandboxed harnesses, on top of the merged partial-rollout checkpoint stack (#3882 to #3909, #4997).
Validation
main's status-recovery window), lease and renewal timing, the absolutestate_dircheck and the--name-prefixcleanup filter; lint is clean.mainafter feat(checkpoint): protocol for harnesses that borrow a sandbox #5264 merged: the unit, server and process-level checkpoint suites fail only wheremainitself does, apart from intermittent failures in tests that pass when run alone or that fail the same way onmain.Compatibility
create.renew_ttl_sis set. New snapshot and polling settings have defaults, includingoperations.snapshot_request_timeout_s(30 s).renew_interval_susers: each renewal now comes after 0.9 to 1.0 of the interval (mainwaits the exact interval), and the first renewal is due one interval after the sandbox was created, not after setup finished.--name-prefix; existing invocations are unchanged.checkpoint.state_dirmust be absolute for a server that checkpoints sandboxes; a relative path now fails at startup.create_from_snapshot, then the review fixes.🤖 Generated with Claude Code