Repository navigation
Conversation
6e24ef3 to
74f4bd9
Compare
74f4bd9 to
9ab8a45
Compare
|
Rebased onto the current |
883f681 to
73289c8
Compare
73289c8 to
011c338
Compare
|
Rewritten in place (2026-10-09): an explicit snapshot taken at commit is now the only restore point of a checkpointed sandbox. Pause is no longer a restore point: the lazy thaw, resume hooks, 🤖 Generated with Claude Code |
011c338 to
6a3c661
Compare
e301273 to
de74a72
Compare
6952832 to
9054f72
Compare
…f operations Seeded random sequences of episode steps, prepare, commit, resume, retire, restore, crashes, and injected faults, run against one participant, a worker coordinator, a whole deployment through coordination, and a real single_agent_turn deployment. The checkpoint invariants are checked after every step, including that no commit ever includes, or accepts a scope naming, an episode marked as a restart. An opt-in stress test (NEMO_GYM_CHECKPOINT_MULTIWORKER_STRESS, set to the number of rollouts) checkpoints counter rollouts in flight across 8 resources and 4 agent workers, kills every Gym process, restores onto 4 and 8 workers, and the reverse, and checks that every rollout finished before the checkpoint or continues with reward 1.0, and that no claim or session is left behind. Signed-off-by: Ananth Subramaniam <[email protected]>
uvicorn's workers share one listening socket, so each request goes to whichever worker accepts the connection, while session state lives in the memory of the worker that created the session. With the stateful counter resources server at 4 workers, 200 concurrent episodes through /run scored 1.0 on only 7; swe_rebench (8 workers) can lose a session's sandbox at /verify and score 0. With num_workers > 1, resources and agent servers now route every request by one rule: 1. find the request's session ID; 2. look up the session's claim, which names the worker that created it; 3. forward the request to that worker's private Unix socket, unchanged, and stream its reply back unchanged. If this worker holds the claim, or nobody does, the request is handled here. The session ID comes from the request: - on a resources server, the session cookie's session_id; for an MCP tool call, or a request with an MCP session token and no cookie, the token's sid; for a typed /seed_session or /close_session, the body's resources_session_id; - on an agent server, the cookie's agent_session_id, or the body's agent_session_id on the agent session seed and close. A typed resources seed now gives its cookie its resources_session_id as the session_id, so the seed, its close and every request in between name the session by one ID. If the cookie and the body name different sessions, the reply is 409, with one worker too. A resources request with no session ID gets a new ID from the router. A session start (/seed_session, or another route in checkpoint_session_starts) claims it before its handler runs, since its reply's cookie names the session; the default seed_session, which an agent's own /run reaches with its untyped body, never reads the session. Any other request claims its new ID only if the handler read or wrote the session, before the reply leaves the worker; a request that keeps nothing, such as a health check, /aggregate_metrics or a checkpoint control route, leaves no claim and gets no session cookie, so no cookie names a session nobody claims. A request whose cookie names a session whose claim ended is claimed the same way by the worker that serves it. If another worker claimed the same ID meanwhile, the request gets 409 rather than being served twice. A claim is a file in the server's runtime directory, created atomically by the worker that creates the session: on a seed with or without a cookie, an agent seed, another session start, a resources session whose handler used it, or a close of an unknown ID, so a delayed seed is refused as on one worker. A request over a private socket is always handled where it arrives, and a claimant whose socket is gone gives 410 instead of running against empty state. Cookies and MCP tokens no longer carry the creating worker's ID; one minted by an earlier version is read for its session ID only. Every claim ends. An agent releases its claim when it drops the session's last record: the close receipt or the failed seed, session_close_retry_window_seconds after it was written. A resources claim lasts while the session is open, from a successful seed (or another route in checkpoint_session_starts) until its close, its /verify or checkpoint_session_ended (a /verify that says a close follows, as single_agent_turn's does, leaves it open for that close), and otherwise ends session_close_retry_window_seconds (a new resources server setting, default 300) after the last request for the session. Each worker sweeps its own expired claims, so they end even when no more requests arrive. An agent seed whose state was set up but cannot be registered, for example because the checkpoint participant refuses it, now releases that state and its claim at once, or keeps it as a failed seed if the release fails. The claims of a worker that exited, and the whole directory, go when the server exits. With one worker nothing is claimed. ClosedResourcesSessionRecords keeps a closed resources session for the same window, counted from its first close, so the record never outlives the claim. NOOA keeps its closed sessions in it, and its tool routes refuse a cookie whose counter is gone, so a stale cookie cannot recreate a counter that no close would remove. An agent drops a failed seed that nobody closed once the window has passed, running its close hook in a background task with a fresh context, under the session's own rollout. If the hook raises, the record keeps its state for a later close and the release is tried again a window later. Seeds and closes of any size are routed: the router reads the whole body, as the app does anyway. Each worker's private socket is served by a second uvicorn server, which leaves uvicorn's process-wide loggers as the worker's main server configured them and writes no access lines of its own, so uvicorn_logging_show_200_ok logs each request once. Agent sessions no longer require num_workers=1. Codex and NOOA drop their own copies of the check, so the harnesses (Codex, Hermes, NOOA, OpenClaw, OpenCode and Pi) all seed sessions on several workers, and each one's tests check a seed with two workers. Their READMEs and the Hermes SWE-bench Pro guide no longer ask for one worker. The resources server guide gains a section on state with several workers. The counter resources server gains the module-level app that multi-worker uvicorn imports. An e2e test (NEMO_GYM_MULTIWORKER_E2E=1) runs it with 4 workers behind the /run relay (`legacy_agent`) and Simple Agent, and the unit-tests workflow runs it when the routing code, or the server code it wires into, changes. An opt-in stress test (NEMO_GYM_MULTIWORKER_STRESS=1) runs thousands of concurrent episodes through single_agent_turn over 8 resources and 4 agent workers, cookieless seeds and closes, untyped seeds that never read the session, MCP sequences, a lost worker and the claims' lifetime. Signed-off-by: Ananth Subramaniam <[email protected]>
…ral workers Resources, agent, and environment servers may run several uvicorn workers with checkpointing on. Each session's requests reach the worker that holds it, and each server is one participant across its workers through a coordinator in the main process, shared with the policy model. The worker count may change between checkpoint and restore. Signed-off-by: Ananth Subramaniam <[email protected]>
… as the only restore point A commit snapshots every live session's sandbox (SupportsSandboxSnapshot: snapshot/delete_snapshot on the OpenSandbox provider, polled until Ready) and leaves it running; a restore always forks the snapshot. A finished episode deletes its snapshots; a retired attempt keeps them for the retained checkpoints. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ointer A finished episode's snapshots are deleted by the next successful export, not at verify: the controller writes the episode's result after the verify reply, so a crash in between would have restored the episode from a snapshot that was gone and, the restore being all or nothing, discarded every other session's restore with it. The record carries every snapshot of the session (`snapshot_ids`), so a fork deletes the earlier checkpoints' snapshots too, and leaves out what a fork never reads: the image and its registry credentials. The provider's snapshot capability is split into `snapshot()`, which returns the id at once, and `wait_snapshot_ready()`, so an export records the id before the wait and a wait that fails, times out, or is cancelled by the controller's resume no longer orphans the snapshot. `export` awaits every sibling before it fails. A fork releases its parallelism slot while it sleeps out a NOT_FOUND backoff. Stopping the superseded sandboxes moves off the restore's critical path, which the install deadline bounds. A stop-commit's park runs as a background task behind the deadline, like the cleanup, so the kills finish once the controller stops waiting. `add()` refuses a sandbox that owns, or is not on, the shared provider. The park hooks are optional in fact, not only in the docstring: a participant whose hooks do not define one parks nothing. OpenSandbox: `snapshot_timeout_s` defaults to 240 s, below the controller's 300 s commit deadline; a management API answer without a JSON object body or without a state fails the wait at once instead of polling until the timeout. `LegacyRun.park_requested` moves to the agent PR that implements the event it returns. The module docstring no longer names a `--retain-from` sweep that does not exist. The owner-side `/sandbox_access` route and `current_sandbox_access` hook stay here for the borrower in the later PR. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
…r no longer keeps Some participants keep part of a checkpoint outside Gym: a sandbox checkpoint is a snapshot in the sandbox service, and the record holds only its id. Deleting a checkpoint directory deletes the pointer, not the snapshot, and only the controller knows which checkpoints it may still restore. A new control operation, `release`, carries that knowledge to every participant: - `POST /ng-control/v1/checkpoint/release` with `kept_checkpoint_ids`, every checkpoint the controller may still restore. Participants free external state that only other checkpoints referred to. It states what is kept rather than what was deleted, so a controller recomputes it from its directory after a crash. - Admitted only when idle with no checkpoint open, stricter than retire and forget: a list computed before a checkpoint existed can never release it. - `coordination.release(participants, checkpoint_id, kept, *, deadline_ts)` fans out to every participant. Controllers call it after every published checkpoint, once old ones are pruned, and with an empty list only when the run is complete for good. - `CheckpointParticipant.release()` is a no-op by default. Resources and agent participants forward it to an optional server hook, `release_external_state(kept_checkpoint_ids)`. - Export learns which checkpoint it writes: `CheckpointParticipant.export(episode_ids, *, checkpoint_id)`, and the hooks become `export_session_states(session_ids, *, checkpoint_id)` and `export_agent_sessions(session_keys, *, checkpoint_id)`, so a server can tag what it creates with the checkpoint that names it. With several workers the export message carries the id to each worker. - `checkpoint.state_dir`: where servers record that external state, read at server start. Servers that checkpoint sandboxes require it. - The controller that publishes checkpoints calls it; rollout collection's checkpointing lives outside this chain (#3893) and wires the call there. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on release A snapshot must live exactly while a checkpoint the controller may restore names it. Tying its deletion to episode events got this wrong both ways: deleting a finished episode's snapshots at the next export removed the restore point of a checkpoint taken before the episode finished, and anything a process knew only in memory (a crashed process's snapshots, those of a commit that never finished, those of pruned checkpoints) was never deleted at all. The checkpointer now keeps an index on disk, one empty file per snapshot: `<state_dir>/<server>/snapshots/<checkpoint id>/<snapshot id>`. - `export(session_ids, *, checkpoint_id)` writes the file the moment the service returns the snapshot's id, before waiting for it to be ready. A snapshot that fails, times out, or outlives a cancelled export or a crash is therefore always indexed. - `release(kept_checkpoint_ids)` reads which checkpoints are dropped, returns at once, and deletes their snapshots in the background under the checkpointer's parallelism, after any earlier release. A delete that succeeds or finds the snapshot gone removes the file; one that fails keeps it for the next release. - The index outlives the process, so the replacement of a crashed process deletes what the dead one created. Several processes can share it without locks: the worst case is a snapshot deleted twice. - `checkpoint_state_dir(global_config)` resolves `checkpoint.state_dir` for a server and refuses to start when checkpointing is on without it. Removed: `stop(..., forget_snapshots=...)`, the deletions deferred to the next export, the `pending_snapshot_deletions` property, and `SandboxCheckpointState.snapshot_ids`, which a fork carried so that its episode's end could delete its ancestors' snapshots. `stop`, verify, close, retire, and restore delete no snapshot. A crashed process's sandboxes still end with the provider's lifetime (on OpenSandbox, the renewal lease); the restore stops the ones it supersedes, as before. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rocess renews
A checkpointed sandbox has two external lifetimes. The snapshot lives while a checkpoint names it (the index
and `release`). The sandbox itself should live exactly while the Gym process that created it is alive. A
process that crashes cannot stop its sandboxes, and the shipped configs give them a five-hour `ttl_s`. Those
zombies cost compute, and on cell-5 they kept calling the restarted model server, which made its restore refuse
("has served calls").
The OpenSandbox provider already renewed a sandbox's TTL from the creating process when
`create.renew_interval_s` was set; it was off and fragile. Now:
- `create.renew_ttl_s`: the sandbox is created with this TTL instead of the spec's `ttl_s`, and every renewal
sets it to now plus this TTL. The service deletes the sandbox within one TTL of the last renewal.
`sandbox_config.ttl_s` keeps its meaning for the other providers (docker and e2b read it as the whole
lifetime), so the lease lives on the provider.
- `create.renew_timeout_s` (30 s): the budget of one renewal. Before, it used the shared 300 s request timeout,
so one hung renew could eat most of the TTL.
- The renewal loop survives failures: a renew that fails after its retries is logged and the next one tries
again. Before, the first failure ended the loop, and every later operation on the sandbox, its close
included, raised "lifetime renewal failed". The interval is jittered by 10% so sandboxes created together do
not renew together.
- The shipped config sets `renew_ttl_s: 1200`, `renew_interval_s: 300`, `renew_timeout_s: 30`. A crashed
process's sandboxes are gone within 20 minutes. The API may be unreachable for 15 minutes before live
sandboxes expire. The load is under 2 renews/s at 512 sandboxes. Documented in the OpenSandbox page.
`close` cancels the renewal before the kill and `aclose` cancels every renewal, as before. Forks made by a
restore go through the same create path and get the same lease. Borrowed handles (`connect`) are not renewed.
Signed-off-by: Pranav Prashant Thombre <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…out prefix The base now refuses a cookie-only call to a restored resources session: only calls under the replacement attempt's /ng-rollout prefix reach it. Two sandbox tests called /append and /sandbox_access on the restored session with the cookie alone. A new Simple Agent test's resources server also gains the checkpoint_id keyword on export_session_states, which this series makes required. Signed-off-by: Pranav Prashant Thombre <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
| raise NotImplementedError("a coordinated participant exports its workers' records through export()") | ||
|
|
||
| async def export(self, episode_ids: Optional[list[EpisodeId]]) -> list[CheckpointRecord]: | ||
| async def export(self, episode_ids: Optional[list[EpisodeId]], *, checkpoint_id: str) -> list[CheckpointRecord]: |
There was a problem hiding this comment.
[BLOCKER] Forward parking and release to workers
This coordinator forwards export, but inherits the base no-op park_exported() and release(). With multi-worker servers the workers create the snapshots, yet a stop commit never parks their sandboxes and release never deletes their snapshots. Add coordinator broadcasts plus worker handlers for both operations, as is done for export.
| if write.cleanup is None or _failed(write.cleanup): | ||
| write.cleanup = _background(self._delete_unscoped(request.episode_ids)) | ||
| await _within(request, lambda: asyncio.shield(write.cleanup)) | ||
| if request.stop: |
There was a problem hiding this comment.
[BLOCKER] Park only after global publication
This runs independently on each participant as soon as its local write finishes. If another participant's concurrent commit fails, the checkpoint is never publishable but this participant has already destroyed the sandboxes; the controller can then resume attempts with no backing state. Have the controller issue a separate park/finalize operation only after every participant committed and the checkpoint was published.
| descriptor = await entry.sandbox.serialize() | ||
| else: | ||
| descriptor = {"sandbox_id": handle.sandbox_id} | ||
| async with self._semaphore: |
There was a problem hiding this comment.
[RISK] Release snapshot slots before readiness polling
The semaphore covers both snapshot() and wait_snapshot_ready() (up to 240 seconds). At 512 sandboxes, 16 slots, and about 20 seconds of readiness latency, commit takes at least about 640 seconds, beyond the 300-second deadline. Limit creation calls only and poll readiness outside this semaphore, with a separate short-lived poll limiter if needed.
| async with lifecycle_timeout: | ||
| while True: | ||
| status, payload = await self._management_request("GET", f"/v1/snapshots/{snapshot_id}") | ||
| if status >= 400: |
There was a problem hiding this comment.
[RISK] Retry transient readiness lookup errors
A newly created snapshot can temporarily return 404, and 429/5xx or transport failures are transient. Failing on the first one aborts the entire checkpoint. Retry 404/429/5xx and transport failures within snapshot_timeout_s; keep terminal snapshot states and permanent 4xx responses as immediate failures.
| ): | ||
| raise ValueError("create.renew_interval_s requires a longer, explicit sandbox ttl_s") | ||
| # With a lease the provider's TTL replaces the spec's, which other providers read as the whole lifetime. | ||
| ttl_s = self._create.renew_ttl_s if self._create.renew_ttl_s is not None else spec.ttl_s |
There was a problem hiding this comment.
[RISK] Keep ttl_s as an absolute lifetime cap
The shipped lease config replaces every SandboxSpec.ttl_s with 1200 and renews that forever, including workloads that are not checkpointing. A leaked session can therefore run for the server's lifetime instead of the configured maximum. Keep the short renewable lease for crash cleanup, but stop or shorten renewals at the original spec.ttl_s deadline, or do not enable the lease globally.
| async def delete_snapshot(self, snapshot_id: str) -> None: | ||
| """Delete a snapshot over the management API; one that is already gone (404) is not an error.""" | ||
| status, _ = await self._management_request("DELETE", f"/v1/snapshots/{snapshot_id}") | ||
| if status >= 400 and status != 404: |
There was a problem hiding this comment.
[RISK] Do not unindex after a single delete 404
OpenSandbox's default snapshot metadata store is local SQLite, so a request routed to another replica can return 404 even though the creating replica still holds the snapshot (source). Treating that as success makes Gym forget its only deletion record. Retry 404s for a bounded interval before accepting already gone.
| if self._connection.domain is None: | ||
| raise RuntimeError("OpenSandbox snapshot operations require connection.domain") | ||
| # The connection config keeps the scheme in ``protocol`` and the host (with any path prefix) in ``domain``. | ||
| base_url = f"{self._connection.protocol or 'https'}://{self._connection.domain.rstrip('/')}" |
There was a problem hiding this comment.
[RISK] Use the SDK's effective protocol
For a bare domain with no explicit protocol, the SDK defaults to HTTP while this path defaults to HTTPS. Creation then works, but readiness checks and releases use the wrong scheme. Build this URL from the effective SDK connection configuration or match its HTTP default (SDK source).
| description="The episodes the controller continues from this checkpoint. Participants that keep " | ||
| "state for every episode they ever served, such as the model ledger, export only these.", | ||
| ) | ||
| stop: bool = Field( |
There was a problem hiding this comment.
[RISK] Include stop in commit idempotency
_commit() records only (checkpoint_dir, scope) as its arguments. If a controller repeats this checkpoint with stop=True after an earlier stop=False call, _recorded() returns the old response and this request never parks. Include stop in the recorded arguments so differing requests conflict, or make stop finalization a separate idempotent operation.
| sandbox_id=handle.sandbox_id, | ||
| timeout_s=self._create.renew_timeout_s, | ||
| ) | ||
| except Exception as error: |
There was a problem hiding this comment.
[RISK] End renewal after definitive sandbox deletion
This catches every error and loops forever. If the service has deleted the sandbox, the provider issues a doomed renewal and warning roughly every five minutes until shutdown. Treat a definitive sandbox-not-found response as terminal and finish the renewal task; continue retrying only transient failures.
| if not self.root.is_dir(): | ||
| return {} | ||
| return { | ||
| folder.name: sorted(path.name for path in folder.iterdir()) |
There was a problem hiding this comment.
[RISK] Make the index scan race-safe
release() scans before the prior background release finishes, so the previous task can remove this folder between is_dir() and iterdir(), raising FileNotFoundError and returning 500. Move the scan behind the previous release and still tolerate per-folder FileNotFoundError for cross-process deletion races.
|
Heads-up for whichever of this PR and #4792 lands second. #4792 makes #4792 targets async def export_session_states(self, session_ids: list[str], *, checkpoint_id: str) -> dict[str, JsonValue]:GenRM's |
…ly just created The OpenSandbox management API can answer 404 for a snapshot it created moments ago. wait_snapshot_ready treated any lookup error as a failed snapshot, so the export failed and the snapshot retry took a replacement snapshot, although the original became Ready shortly after. In a 16-node full-SWE run (job 8143368) 14 first attempts across 13 sandboxes failed this way; the sampled snapshots later showed Ready. Until a lookup first finds the snapshot, a 404 is now waited out for operations.snapshot_lookup_grace_s (default 60 s, within snapshot_timeout_s), polling every create.connect_poll_s. A snapshot that did not appear by then, or a 404 after it appeared, fails as before; other lookup errors are not waited out, and a grace of 0 keeps the old behavior. A snapshot that was waited out logs a warning with how long it took to appear. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
What changed and why
Partial-rollout checkpointing (#3882 and the stack on it) lets a controller such as NeMo RL checkpoint Gym while rollouts are in flight and, after a crash, continue each rollout from its last safe point instead of starting it over. Each server checkpoints the state it holds in its own process. An agentic environment also keeps state outside Gym: a sandbox per session, a container whose filesystem holds the repository an agent is editing. This PR lets the server that owns a sandbox take part in checkpoints, and gives the two objects outside Gym that a checkpointed sandbox involves an explicit lifecycle:
ttl_s, so a harness left running in one keeps calling the model server for hours. On OpenSandbox every sandbox now lives on a lease that its creating process renews, so the service deletes a dead process's sandboxes within one lease TTL.releasecall, in which the controller names the checkpoints it still keeps, deletes the rest.What this PR adds:
SandboxSessionCheckpointer(nemo_gym/sandbox/checkpoint.py), which a resources server or an agent delegates its checkpoint hooks to:create,getandaccessmanage the sandboxes of live sessions.export(session_ids, *, checkpoint_id)runs at commit. It snapshots every live session's sandbox, at mostparallelismat a time, records each snapshot in the index as soon as the service returns its ID, and waits until each snapshot is ready. The sandbox keeps running. A snapshot that fails or is not ready in time fails the commit. Each record (SandboxCheckpointState) holds the snapshot to fork, the source sandbox, and the spec to create the fork from, without its files, image, or registry credentials.restore(states)runs in a fresh process. It validates every state, then forks every snapshot into a new sandbox, all or nothing. A snapshot the service cannot find yet is retried. The crashed process's sandboxes that the forks supersede are stopped in the background.stop(session_id)frees a sandbox when its episode is verified, closed, or retired, andpark(session_ids)frees the exported ones after a commit the controller stops after (on_stop:killornone). Neither deletes a snapshot.release(kept_checkpoint_ids)deletes, in the background, every indexed snapshot of a checkpoint outsidekept, including those a crashed predecessor created.releaseprotocol (nemo_gym/_checkpoint):POST /ng-control/v1/checkpoint/releasewithkept_checkpoint_ids, admitted only when the participant is idle with no checkpoint open, so a list computed before a checkpoint existed can never release it, andcoordination.release(participants, checkpoint_id, kept, *, deadline_ts), which sends it to every participant. Resources and agent participants forward it to an optional server hook,release_external_state(kept_checkpoint_ids).checkpoint_idonCheckpointParticipant.export,export_session_states, andexport_agent_sessions.CommitRequest.stoptells participants that the controller stops after this commit, so the optionalpark_session_statesandpark_agent_sessionshooks free the exported sandboxes once the commit is durable.checkpoint.state_dir, says where servers keep the index. With checkpointing on, a server that checkpoints sandboxes refuses to start without it.release. Rollout collection's checkpointing lives outside this chain (feat(checkpoint): checkpoint evaluation runs from rollout collection #3893) and wires the call there.SupportsSandboxSnapshotcapability (snapshot(),wait_snapshot_ready(), anddelete_snapshot(), which tolerates 404), implemented byOpenSandboxProviderwith a 240 s readiness bound (operations.snapshot_timeout_s).wait_snapshot_readywaits out a 404 foroperations.snapshot_lookup_grace_s(default 60 s, within the readiness bound), and logs a warning with how long the snapshot took to appear. A 404 after the grace, or after the snapshot appeared, fails as before; other lookup errors are never waited out; a grace of 0 keeps the old behavior. Without this, the export failed, and the retry in feat(sandbox): take a failed checkpoint snapshot again before failing the export #4779 took a replacement snapshot although the first one became Ready seconds later.OpenSandboxProvider): withcreate.renew_ttl_sset, each sandbox is created with that TTL instead of the spec'sttl_s, and the creating process renews it everycreate.renew_interval_s, each renewal bounded bycreate.renew_timeout_s. Forks get the same lease. A failed renewal is logged and retried at the next interval. The shippedopensandbox.yamlsets 1200 s, 300 s, and 30 s.POST /sandbox_accesson resources servers, backed by acurrent_sandbox_access(session_id)hook: an agent that runs in a sandbox the resources server owns asks which sandbox is current, because a restore forks the sandbox under a new ID.release(kept)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"] CO["Coordination<br/>prepare, commit, restore, resume,<br/>retire, and now release"] subgraph G["One participant per Gym server"] E["Environment server"] M["Policy model"] A["Agent"] R["Resources server<br/>a sandbox per session"] end CK["SandboxSessionCheckpointer<br/>export, restore, stop, park, release"] S[("Sandbox service<br/>sandboxes on a lease, snapshots")] I[("Snapshot index<br/>checkpoint.state_dir")] D[("Checkpoint directory<br/>records name snapshot IDs")] C --> CO CO --> E & M & A & R R --> CK A -. "an agent that owns its sandboxes" .-> CK CK -- "snapshot at commit, fork at restore,<br/>renew, stop, delete on release" --> S CK -- "one file per snapshot" --> I G --> D classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937 class CK,I thisOne checkpoint, a crash, and the restore of a sandbox
sequenceDiagram participant C as Controller participant R as Sandbox owner participant I as Snapshot index participant S as Sandbox service R->>S: create sandbox A on a lease loop every renew_interval_s while the process lives R->>S: renew the lease of A end C->>R: prepare Note over R: no tool call is in flight C->>R: commit c1 R->>S: snapshot A S-->>R: snapshot ID s1 R->>I: write c1/s1 R->>S: wait until s1 is Ready R-->>C: the record names s1, the source sandbox, and the spec C->>R: resume Note over R,S: the episode keeps changing sandbox A Note over C,S: crash - every Gym process dies, and nobody renews A C->>R: restore c1 in a fresh process R->>S: create sandbox B from s1, on a lease of its own R->>S: stop A, in the background C->>R: resume Note over R,S: the replacement attempt continues in BReleasing snapshots
The two lifecycles
A sandbox:
A snapshot:
Using
releasefrom a controllercheckpoint.state_dirper Gym instance across restarts, outside anything the controller deletesreleaseafter every successful save, after publish and prune, listing every checkpoint it could restore, including the one just publishedkeptcomplete, or no callrelease([])only when the run is truly complete, never on a signal or time-limit stopWhere this sits in the stack
This PR is the first of a series that adds sandbox checkpointing on top of the partial-rollout checkpointing stack, whose top is #4197 (
ananthsub/partial-ckpt-fault-tests). Each PR's base is the branch of the PR before it, so each diff shows only that PR's change.pthombre/partial-ckpt-sandbox-core): this PRpthombre/partial-ckpt-sandbox-resources): process-level evidence for resources-owned sandbox checkpoints, their release, and lease expirypthombre/partial-ckpt-sandbox-agent): the park request for long-running agent harnesses, with process-level evidencepthombre/partial-ckpt-sandbox-swebench): the sandbox owner base, with the SWE-bench resources server on itpthombre/partial-ckpt-sandbox-opencode): the harness driver, with the OpenCode agent on itpthombre/partial-ckpt-sandbox-capture): calls a checkpoint abandoned stay out of the capture ledgeramahishi/opencode-resume-tool-call-lineage): wake sandbox command polls while a harness launch is stopped, and hold them while it is pausedpthombre/partial-ckpt-sandbox-prepared-verify): prepared verification, so a checkpoint never waits for SWE-bench gradingpthombre/partial-ckpt-sandbox-snapshot-retry): take a failed checkpoint snapshot again before failing the exportpthombre/lineage-renamed-tool-call): match a tool call OpenCode rewrote as unavailableIssue
No tracking issue; this follows the partial-rollout checkpointing design doc and the discussion on the #3882 stack.
Validation
The snapshot 404 grace (
ff8684472, the last commit of this PR).test_opensandbox_provider.pygains 6 tests:These ran with the whole stack in the
rl-gym.nightlycontainer on Slurm: 1379 passed and 0 failed at the top of the stack (job 8281677), and every level from #4274 up passed.ruff checkandruff format --checkare clean.Earlier heads. Run in the r3Run nemo-rl+Gym container on Slurm, with the series on
ananthsub/partial-ckpt-fault-tests8947bb2ca: job 1289959 ran the sandbox, checkpoint, pilot and extra suites on each head, jobs 1289960 and 1289961 the e2e suite, and job 1290388 the provider suite on this head and the tip."provider" is
tests/unit_tests/test_opensandbox_provider.pyandtest_opensandbox_documented_config.py, run with the OpenSandbox SDK andtenacityinstalled. The hook implementers this PR changes pass on every head:resources_servers/example_session_state_mgmt/tests2,environment_servers/single_agent_turn/tests50,tests/unit_tests/test_rollout_collection.py463. The sandbox suite's 31 skips need the OpenSandbox SDK, and the 12 e2e skips are the real-model and scale cases.What the new tests cover:
test_opensandbox_provider.py(lease): validation ofrenew_ttl_s,renew_interval_s, andrenew_timeout_s; the lease TTL replaces the spec'sttl_sat create (also with no spec TTL) and in every renewal; every renewal usesrenew_timeout_s; a failed renewal is logged, the next one renews, and neither other operations nor the close are affected by it; the interval is jittered within 10%; the close cancels the renewal before the kill, andaclosecancels all.test_sandbox_checkpoint.py: an index file appears when the ID is returned, before readiness;release(kept)deletes exactly the checkpoints outsidekeptand keeps the sandboxes;release([])empties the index; a 404 removes the file; a failed delete keeps its file and the next release retries it; a release returns before its deletes and waits for the previous one; a second checkpointer over the samestate_dir(a crash) deletes what the first created, including a checkpoint whose export was cancelled mid-wait; two servers sharing astate_dirtouch only their own snapshots; a snapshot ID that cannot name a file fails the export; stop never deletes a snapshot; with nostate_dir, sessions are tracked but never exported.test_checkpoint_sandbox_resources.py: verify keeps the snapshots, and a release through the route deletes only the dropped checkpoints'; a restarted server releases its crashed predecessor's snapshots; a server withoutstate_dirfails at startup.checkpoint_idin-process and in each uvicorn worker; an invalidkept_checkpoint_idsis a 4xx.e2e on this head alone: 51 failed, 1 passed, 13 skipped. Ananth's base alone fails the same 51 in this container (job 1253295): the deployment helper on these heads overwrites
PYTHONPATH, so the spawned servers import the container's older baked Gym (on this base, the policy model server fails to importresponses_api_models.vllm_model.tar_audio). #4221 carries the fix to the helper, and every head from #4221 up passes e2e.ruff checkandruff format --checkwith CI's ruff 0.9.9 are clean on every changed file at every head. Every commit carriesSigned-off-by.Rollout evidence
The snapshot 404 grace, in 16-node full-SWE runs (2,048 rollouts in flight, every live sandbox snapshotted at each checkpoint, about 1,600–2,000 per burst):
Live on the OpenSandbox cell-5 at the series tip (job 1253315), with the shipped lease config, SWE-bench Verified rows 24 to 31, the OpenCode agent from #4274, and nano-3.5 SWE SFT on vLLM with TP=4:
checkpoint.state_dir. Arelease(["B1"])right after the resume deleted nothing.opencode run --continueand verified.release([])from the restarted Gym, which never took them, deleted both from the cell (HTTP 404 afterwards) and emptied the index. The end-of-job sweep found no sandboxes left.Compatibility
export_session_statesandexport_agent_sessionsgain a keyword-onlycheckpoint_id, and so doesCheckpointParticipant.export. Every in-tree implementer is updated: the base classes,example_session_state_mgmt, Simple Agent, and the test servers. Out-of-tree implementers on the unmerged checkpoint stack need the keyword.release. A controller that never calls it leaves snapshots in place.operations.snapshot_lookup_grace_s(default 60 s; 0 keeps the old behavior): a snapshot lookup that answers 404 before the snapshot first appears is retried instead of failing.checkpoint.state_dirand fail at startup without it.ttl_s. An OpenSandbox API outage longer than 15 minutes expires live sandboxes, which then fail their episodes. Removecreate.renew_ttl_sandcreate.renew_interval_sto get the old fixed lifetime.create.renew_interval_swithoutrenew_ttl_sbehaves as before, except that failed renewals no longer end the renewal loop or affect later operations on the sandbox.snapshots.pyCLI skips certificate verification unless--tls-verifyis given ortls_verify: trueis configured, matching the provider.🤖 Generated with Claude Code