Skip to content

feat(sandbox): sandbox and snapshot lifecycle for partial-rollout checkpoints - #4220

Open
pthombre wants to merge 10 commits into
mainfrom
pthombre/partial-ckpt-sandbox-core
Open

pthombre wants to merge 10 commits into
mainfrom
pthombre/partial-ckpt-sandbox-core

Conversation

@pthombre

@pthombre pthombre commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • The restore point is a snapshot taken at commit. A live sandbox is never a restore point: it keeps changing once the episode continues, and a paused state may be consumed on resume. At commit the owner snapshots each session's sandbox and leaves it running; after a crash the restore forks each snapshot into a new sandbox.
  • A sandbox lives while the process that created it is alive. A crashed process cannot stop its sandboxes, and the shipped configs give them a five-hour 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.
  • A snapshot lives while a checkpoint the controller may restore names it. A checkpoint record holds only a snapshot ID; the snapshot itself lives in the sandbox service, which never expires it. Deleting a checkpoint directory deletes the pointer, not the snapshot. The owner now indexes every snapshot by checkpoint on disk, and a new release call, 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, get and access manage the sandboxes of live sessions.
    • export(session_ids, *, checkpoint_id) runs at commit. It snapshots every live session's sandbox, at most parallelism at 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, and park(session_ids) frees the exported ones after a commit the controller stops after (on_stop: kill or none). Neither deletes a snapshot.
    • release(kept_checkpoint_ids) deletes, in the background, every indexed snapshot of a checkpoint outside kept, including those a crashed predecessor created.
  • The release protocol (nemo_gym/_checkpoint):
    • POST /ng-control/v1/checkpoint/release with kept_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, and coordination.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).
    • Export learns which checkpoint it writes: a keyword-only checkpoint_id on CheckpointParticipant.export, export_session_states, and export_agent_sessions.
    • CommitRequest.stop tells participants that the controller stops after this commit, so the optional park_session_states and park_agent_sessions hooks free the exported sandboxes once the commit is durable.
    • A new setting, checkpoint.state_dir, says where servers keep the index. With checkpointing on, a server that checkpoints sandboxes refuses to start without it.
    • The controller that publishes checkpoints calls release. Rollout collection's checkpointing lives outside this chain (feat(checkpoint): checkpoint evaluation runs from rollout collection #3893) and wires the call there.
  • Snapshots in the provider interface: the SupportsSandboxSnapshot capability (snapshot(), wait_snapshot_ready(), and delete_snapshot(), which tolerates 404), implemented by OpenSandboxProvider with a 240 s readiness bound (operations.snapshot_timeout_s).
    • A snapshot the service does not know yet is waited out. The management API can answer 404 for a snapshot it created moments ago. Until a lookup first finds the snapshot, wait_snapshot_ready waits out a 404 for operations.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.
  • Sandboxes on a lease (OpenSandboxProvider): with create.renew_ttl_s set, each sandbox is created with that TTL instead of the spec's ttl_s, and the creating process renews it every create.renew_interval_s, each renewal bounded by create.renew_timeout_s. Forks get the same lease. A failed renewal is logged and retried at the next interval. The shipped opensandbox.yaml sets 1200 s, 300 s, and 30 s.
  • POST /sandbox_access on resources servers, backed by a current_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.
Object Lives while Mechanism Who ends it
Sandbox its creating process is alive and has not stopped it a lease that process renews verify, close, retire, or park stops it; a restore stops the ones it supersedes; after a crash with no restore, the service when the lease lapses
Snapshot a checkpoint the controller may restore names it the on-disk index and release(kept) the release that no longer keeps its checkpoint, in this process or the next

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 this
Loading

One 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 B
Loading

Releasing snapshots

sequenceDiagram
  participant C as Controller
  participant R as Sandbox owner, this process or the next
  participant I as Snapshot index
  participant S as Sandbox service
  C->>C: publish c2, prune c1
  C->>R: release with kept = c2
  R->>I: list the indexed checkpoints: c1, c2
  R-->>C: done, the deletes continue in the background
  R->>S: delete the snapshots indexed under c1
  S-->>R: deleted, or already gone (404)
  R->>I: remove the files of c1
  Note over R,I: a failed delete keeps its file, and the next release retries it
Loading

The two lifecycles

A sandbox:

stateDiagram-v2
  [*] --> Running: created on a lease
  Running --> Running: renewed by the process that created it
  Running --> Stopped: verify, close, retire, or park
  Running --> Superseded: its process crashed and a restore forked its snapshot
  Superseded --> Stopped: stopped by that restore
  Running --> Expired: its process crashed and the lease lapsed
  Stopped --> [*]
  Expired --> [*]
Loading

A snapshot:

stateDiagram-v2
  [*] --> Indexed: export writes its file as soon as the service returns the ID
  Indexed --> Kept: Ready, and its checkpoint is one the controller keeps
  Indexed --> Dropped: not Ready in time, or its commit failed or was never published
  Kept --> Kept: verify, close, retire, and restore keep it
  Kept --> Dropped: the controller no longer keeps its checkpoint
  Dropped --> Deleted: the next release, in this process or the next
  Deleted --> [*]
Loading

Using release from a controller

Rule Why
The same checkpoint.state_dir per Gym instance across restarts, outside anything the controller deletes the index is only useful to a process that can read it
One release after every successful save, after publish and prune, listing every checkpoint it could restore, including the one just published a dropped checkpoint's snapshots are deleted only by a release that leaves it out
kept complete, or no call a short list deletes the snapshots of a checkpoint that could still be restored; a missed call is caught up by the next one
release([]) only when the run is truly complete, never on a signal or time-limit stop a stopped job is resubmitted and restores
A failed release is not fatal log it; the next save's release catches up

Where 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.

  1. feat(sandbox): sandbox and snapshot lifecycle for partial-rollout checkpoints #4220 (pthombre/partial-ckpt-sandbox-core): this PR
  2. feat(checkpoint): process-level evidence for resources-owned sandbox checkpoints, their release, and lease expiry #4221 (pthombre/partial-ckpt-sandbox-resources): process-level evidence for resources-owned sandbox checkpoints, their release, and lease expiry
  3. feat(checkpoint): ask a long-running agent harness to park when a checkpoint opens #4222 (pthombre/partial-ckpt-sandbox-agent): the park request for long-running agent harnesses, with process-level evidence
  4. feat(sandbox): sandbox owner base for resources servers, with SWE-bench on it #4576 (pthombre/partial-ckpt-sandbox-swebench): the sandbox owner base, with the SWE-bench resources server on it
  5. feat(checkpoint): harness driver for sandboxed agents that pauses them at checkpoints, with OpenCode on it #4274 (pthombre/partial-ckpt-sandbox-opencode): the harness driver, with the OpenCode agent on it
  6. fix(checkpoint): leave the calls a checkpoint abandoned out of the capture ledger #4451 (pthombre/partial-ckpt-sandbox-capture): calls a checkpoint abandoned stay out of the capture ledger
  7. fix(checkpoint): wake sandbox command polls while a harness launch is stopped #4553 (amahishi/opencode-resume-tool-call-lineage): wake sandbox command polls while a harness launch is stopped, and hold them while it is paused
  8. feat(checkpoint): prepared verification, so a checkpoint never waits for SWE-bench grading #4778 (pthombre/partial-ckpt-sandbox-prepared-verify): prepared verification, so a checkpoint never waits for SWE-bench grading
  9. feat(sandbox): take a failed checkpoint snapshot again before failing the export #4779 (pthombre/partial-ckpt-sandbox-snapshot-retry): take a failed checkpoint snapshot again before failing the export
  10. fix(token-id-capture): match a tool call OpenCode rewrote as unavailable #4936 (pthombre/lineage-renamed-tool-call): match a tool call OpenCode rewrote as unavailable

Issue

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.py gains 6 tests:

  • 404, 404, then Ready is waited out, with one warning naming the snapshot and the 404 count;
  • a snapshot still missing after the grace fails long before the snapshot timeout;
  • a 404 after the snapshot appeared fails at once;
  • a grace of 0 fails on the first 404;
  • a 403 or 500 is not waited out;
  • a negative grace is rejected, and the default is 60 s.

These ran with the whole stack in the rl-gym.nightly container on Slurm: 1379 passed and 0 failed at the top of the stack (job 8281677), and every level from #4274 up passed. ruff check and ruff format --check are clean.

Earlier heads. Run in the r3Run nemo-rl+Gym container on Slurm, with the series on ananthsub/partial-ckpt-fault-tests 8947bb2ca: 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.

Head provider sandbox checkpoint pilots e2e
#4220 (this PR) 145 passed 212 passed 736 passed Simple Agent 73 see below
#4221 212 776 Simple Agent 73 58 passed
#4222 212 783 Simple Agent 73 61 passed
#4576 227 783 SWE-bench 39 61 passed
#4274 227 811 OpenCode 79, SWE-bench 41 61 passed
#4451 145 227 812 all of the above 61 passed

"provider" is tests/unit_tests/test_opensandbox_provider.py and test_opensandbox_documented_config.py, run with the OpenSandbox SDK and tenacity installed. The hook implementers this PR changes pass on every head: resources_servers/example_session_state_mgmt/tests 2, environment_servers/single_agent_turn/tests 50, tests/unit_tests/test_rollout_collection.py 463. 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 of renew_ttl_s, renew_interval_s, and renew_timeout_s; the lease TTL replaces the spec's ttl_s at create (also with no spec TTL) and in every renewal; every renewal uses renew_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, and aclose cancels all.
  • test_sandbox_checkpoint.py: an index file appears when the ID is returned, before readiness; release(kept) deletes exactly the checkpoints outside kept and 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 same state_dir (a crash) deletes what the first created, including a checkpoint whose export was cancelled mid-wait; two servers sharing a state_dir touch only their own snapshots; a snapshot ID that cannot name a file fails the export; stop never deletes a snapshot; with no state_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 without state_dir fails at startup.
  • Control plane, coordination, and participants: a release is refused while preparing or committed (under either ID) and after a restore, and admitted when idle; it reaches every participant, and a prepare makes it fail everywhere; resources (exported mode only) and agent participants forward it to the optional hook; the export hook receives the commit's checkpoint_id in-process and in each uvicorn worker; an invalid kept_checkpoint_ids is 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 import responses_api_models.vllm_model.tar_audio). #4221 carries the fix to the helper, and every head from #4221 up passes e2e.

ruff check and ruff format --check with CI's ruff 0.9.9 are clean on every changed file at every head. Every commit carries Signed-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):

Runs Snapshot lookups that answered 404 just after create Outcome
job 8143368, before this commit 14 each failed its export; #4779's retry took a replacement snapshot
jobs 8205027, 8208396, 8213273, 8216755, 8243255, 8270615, with this commit 30 all waited out: each snapshot appeared 2.4–3.4 s after the wait began; 0 failed

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:

  • Lease. A sandbox on a 60 s lease renewed every 20 s was still running after 90 s. Once its renewals stopped without any stop call, as a crash stops them, the cell deleted it 53 s later.
  • Checkpoint. 300 s in, 6 rollouts had finished and 2 were running. Prepare took 5.6 s with no blockers, and the commit snapshotted both sandboxes in 19.4 s and indexed both snapshots under checkpoint.state_dir. A release(["B1"]) right after the resume deleted nothing.
  • Crash and restore. Three minutes later, with 1 rollout still running, every Gym process was killed, and the smoke driver deleted that rollout's sandbox before restarting Gym. The restore forked its snapshot in 6.9 s, and the replacement continued in the fork with opencode run --continue and verified.
  • Release. After verification the index still held both snapshots. A 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

  • Hook signatures change: export_session_states and export_agent_sessions gain a keyword-only checkpoint_id, and so does CheckpointParticipant.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.
  • A new control route, release. A controller that never calls it leaves snapshots in place.
  • A new OpenSandbox setting, 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.
  • With checkpointing on, servers that checkpoint sandboxes require checkpoint.state_dir and fail at startup without it.
  • The shipped OpenSandbox config puts every sandbox on the lease, with or without checkpointing. A sandbox's lifetime on OpenSandbox is now "while its process renews it", not the spec's ttl_s. An OpenSandbox API outage longer than 15 minutes expires live sandboxes, which then fail their episodes. Remove create.renew_ttl_s and create.renew_interval_s to get the old fixed lifetime.
  • create.renew_interval_s without renew_ttl_s behaves as before, except that failed renewals no longer end the renewal loop or affect later operations on the sandbox.
  • The snapshots.py CLI skips certificate verification unless --tls-verify is given or tls_verify: true is configured, matching the provider.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@pthombre

pthombre commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto the current ananthsub/partial-ckpt-fault-tests tip and appended one commit (9ab8a45): the exported state records a restore_point ("paused" or "snapshot", from a provider's snapshot_survives_resume; False on OpenSandbox, whose pause snapshot is consumed by the resume on cell-2 and leaves no listed snapshot at all on cell-3) and the TTL expiry; the snapshot lookup at export is best effort with a 15 s cap; a restore of a sandbox that resumed since, or whose TTL passed, raises a typed SandboxCheckpointError instead of a fork the backend cannot serve; the fork spec drops the image (OpenSandbox requires exactly one of image or snapshot_id); the snapshot listing and snapshots.py honour connection.tls_verify. Found against OpenSandbox cell-3; see #4274 for the rollout evidence.

@pthombre
pthombre force-pushed the pthombre/partial-ckpt-sandbox-core branch 2 times, most recently from 883f681 to 73289c8 Compare October 9, 2026 06:31
@pthombre
pthombre force-pushed the pthombre/partial-ckpt-sandbox-core branch from 73289c8 to 011c338 Compare October 9, 2026 21:52
@pthombre

pthombre commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

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, restore_point field and listing-based snapshot lookup are gone; a restore always forks the snapshot. A commit the controller stops after carries stop: true and participants park (kill) the exported sandboxes once the write is durable. Episode end deletes the snapshots; a retired attempt keeps them for the retained checkpoints and the sweep reaps the rest. No compatibility with pause-based checkpoint records. Rebased onto the current ananthsub/partial-ckpt-fault-tests. Offline suites green (sandbox 199, checkpoint 608, pilots 69, e2e 65 passed; Slurm job 1167803). Live validation waits on the cell-3 shared snapshot store (fork currently returns SNAPSHOT::NOT_FOUND).

🤖 Generated with Claude Code

@pthombre
pthombre force-pushed the pthombre/partial-ckpt-sandbox-core branch from 011c338 to 6a3c661 Compare October 11, 2026 04:43
@pthombre
pthombre force-pushed the pthombre/partial-ckpt-sandbox-core branch 2 times, most recently from e301273 to de74a72 Compare October 12, 2026 21:57
@pthombre
pthombre force-pushed the pthombre/partial-ckpt-sandbox-core branch 2 times, most recently from 6952832 to 9054f72 Compare October 13, 2026 16:27
…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]>
ananthsub and others added 8 commits October 20, 2026 13:54
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]:

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.

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

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.

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

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.

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

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.

[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

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.

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

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.

[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('/')}"

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.

[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(

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.

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

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.

[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())

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.

[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.

@macandro96

Copy link
Copy Markdown
Contributor

Heads-up for whichever of this PR and #4792 lands second.

#4792 makes genrm_compare an exported resources server, so it overrides export_session_states(self, session_ids). This PR changes the hook to export_session_states(self, session_ids, *, checkpoint_id: str), and ResourcesParticipant.export passes checkpoint_id=. The two merge without a textual conflict, but once both are in, GenRM's override raises TypeError on every commit, so no checkpoint can commit on a deployment that runs GenRM.

#4792 targets main, so it will probably land first. In that case this PR needs one line in resources_servers/genrm_compare/app.py:

async def export_session_states(self, session_ids: list[str], *, checkpoint_id: str) -> dict[str, JsonValue]:

GenRM's tests/test_checkpoint.py also calls participant.export(None) in several places, and those calls need checkpoint_id=.... If this PR lands first, I'll make the change in #4792 instead. ananthsub found it with a trial merge: #4792 (comment).

…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]>

This branch was previously deployed

1 inactive (outdated) deployment
public — 9054f724 Deployed Oct 13, 2026 by copy-pr-bot[bot] via release / finalize / notify #5188
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sandbox Sandbox providers, isolation, and sandbox runtime contracts complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants