Skip to content

feat(swebench): checkpoint the task sandboxes of episode sessions - #5266

Merged
pthombre merged 9 commits into
mainfrom
pranav/envckpt-2b-owner-base
Nov 19, 2026
Merged

pthombre merged 9 commits into
mainfrom
pranav/envckpt-2b-owner-base

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

A resources server whose episode seed starts a task sandbox that the agent borrows (SWE-bench and the rest of the SWE family) already has its sessions on main: SandboxSessionResourcesServer seeds the session, lends the sandbox, captures the patch once at verify, closes, fences late requests and expires sessions nobody closed. What it cannot do is take part in checkpoints. Nothing saves the task sandbox, so after a crash the episode starts over.

CheckpointedSandboxSessionResourcesServer adds the checkpoint half as a subclass, on #5265's SandboxSessionCheckpointer, and leaves the session half as it is on main. An earlier version of this PR had a session base of its own; main has gained the session base since, so that is gone.

  • Commit. Snapshots each session's task sandbox and exports the seed, the agent's working directory, the patch verify captured (if it has) and the task state the server keeps. Everything a checkpoint cannot store is refused before any snapshot is taken. Each session is locked only until its own snapshot is done, so one slow snapshot does not hold up a capture or a stop of another session. A session past its deadline that still has a running task sandbox, registered or claimed by a verify, is left out, even if no request has closed it yet. One whose verify already stopped the sandbox and is still grading is kept, with its capture.
  • Restore. Forks every task sandbox from its snapshot and installs each session for the attempt that replaces the one the checkpoint saved, all or none: if a fork or an install fails, the forks already made are stopped and nothing stays installed. The restore can then be retried at once, even when a fork could not be stopped; the checkpointer stops that fork again at the next restore and at shutdown. That attempt's episode seed gets the fork without setting the task up again, and a verify after the restore grades the saved patch instead of capturing it again.
  • Release and retire. A release deletes the snapshots of checkpoints the controller no longer keeps. A retire stops the attempt's sandbox. Shutdown stops every task sandbox, including a fork that only the checkpointer still tracks.
  • new_task_sandbox(session_id, spec). A subclass starts each task sandbox through it: the sandbox goes on the provider every session shares and is registered for the session and its checkpoints. A commit never snapshots a sandbox a stop is releasing, and it fails for a task sandbox that was registered any other way.
  • Sessions without an episode seed. Only a session an episode seed started is exported. A task sandbox started for any other seed, such as the task row an agent's /run sends, is not registered for checkpoints. While the server exports sessions, that seed's reply carries x-ng-checkpoint-restart, prepare reports the episode as a restart, and a commit leaves the session out. Close, expiry and shutdown still stop its sandbox.
  • Task state. A subclass sets task_model (the model of its episode seed's task_data) and keeps what a restore needs through _export_task_sandbox_state and _restore_task_sandbox_state. A seed that passes another model than task_model is refused. A restore puts the task state back before it builds the session's seed reply. What the server passes to capture_task_sandbox_patch, and its task state, must be JSON values.
  • Saved format. A session's record has version: 1 and sandboxes, the checkpoint state of each of the session's sandboxes by name; the task sandbox is "task". The checkpointer tracks each sandbox as <session ID>/<name>. A restore refuses a version it does not know, and a sandbox name it does not restore.
  • Mode. exported only when the provider can snapshot; otherwise restart_only, with no state_dir needed. A server whose grader needs something a snapshot does not keep, such as processes the agent started, declares checkpoint_mode = "restart_only".
  • Startup check. A missing task_model fails at startup when the server exports sessions.

Changes outside resources_servers/swebench:

  • ResourcesParticipant.restart_session(): an exported server calls it from the handler of the request that starts a session it cannot export. If the request succeeds, the seed reply and prepare say the session's episode is a restart, and a commit leaves it out. It uses the existing x-ng-checkpoint-restart header.
  • SandboxSessionCheckpointer.discard(keys): gives up the sandboxes of keys and stops them. Every key can be restored again at once, whether or not the stops succeed.
  • SandboxSessionCheckpointer.stop(key) drops a key whose sandbox already stopped without waiting for a turn, and an export checks the snapshot index for unreleased checkpoints once per checkpoint.
  • nemo_gym.server_runtime exports SandboxSessionCheckpointer, SandboxCheckpointConfig, SandboxCheckpointError and checkpoint_state_dir.

Conformance kit. check_sandbox_session_checkpoints, in resources_servers/swebench/testing/checkpoint_conformance.py next to the class, checks any server on the subclass against fake providers: commit, crash, restore into a fork, a restored session's seed and saved capture, a restore whose fork fails, release of dropped snapshots, close of a running sandbox, shutdown, and restart_only without snapshots. It also takes a checkpoint before verify captured the patch, which is the usual case: the restore must install the task state the commit exported, a retire must stop the fork and forget that state, and, given the /verify body for the seed (verify_body), the server's own /verify after the restore must reply as it does without the crash. It is not exported from nemo_gym.server_runtime.

End-to-end tests. A fake sandbox backend with snapshots and a small notes server on the subclass that Simple Agent can drive, through both environment-server variants, with and without a provider that can snapshot.

This rebuilds the checkpoint half of #4576 and the end-to-end infrastructure of #4221 (earlier stack) on main's episode sessions.

How it works

Where this PR sits in the overall flow

The highlighted part is 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 OB this
Loading

This PR

One session, from seed to close, with a checkpoint during the agent's work, a crash, and a restore.

sequenceDiagram
  participant E as Environment server
  participant R as Resources server
  participant K as Checkpointer
  participant P as Provider
  E->>R: episode seed
  R->>P: new_task_sandbox, create S1, set the task up
  R-->>E: sandbox_access(S1)
  Note over E,P: checkpoint C1 while the agent works in S1
  R->>K: export, snapshot S1 and index it under C1
  Note over R: C1 holds the seed, workdir, task state and the snapshot id
  Note over E,P: crash, then restore C1 in a new process
  R->>K: restore, all sessions or none
  K->>P: create S2 from the snapshot of S1
  E->>R: episode seed of the replacement attempt
  R-->>E: sandbox_access(S2), no setup
  E->>R: verify
  R->>R: capture the patch once and grade, as on main
  R-->>E: reward
  E->>R: close session
  Note over E,P: release(kept) deletes the snapshots of dropped checkpoints
Loading

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 and #5265 have merged, and the rest of the stack is rebased onto main after them. Each PR is based on the one before it, so each diff shows only that PR's change. The stack runs parallel to the legacy_agent path of #4220 to #4936, which it does not change or depend on.

  1. feat(checkpoint): protocol for harnesses that borrow a sandbox #5264: feat(checkpoint): protocol for harnesses that borrow a sandbox (merged)
  2. feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer #5265: feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer (merged)
  3. feat(swebench): checkpoint the task sandboxes of episode sessions #5266: feat(swebench): checkpoint the task sandboxes of episode sessions (this PR)
  4. feat(swebench): typed sessions on the owner base with capture-once verify #5267: feat(swebench): typed sessions on the owner base with capture-once verify
  5. feat(opencode): pause at checkpoints and resume after a crash #5268: feat(opencode): pause at checkpoints and resume after a crash
  6. test(checkpoint): end-to-end harness scenarios, SWE-bench recipe, docs #5269: test(checkpoint): end-to-end harness scenarios, SWE-bench recipe, docs
  7. feat(swe): checkpoint the episode sessions of the repository-task servers #5331: feat(swe): repository-task servers on the sandbox owner base
  8. feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider #5410: feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider
  9. feat(checkpoint): hold-pause a harness when the sandbox snapshot keeps its processes #5411: feat(checkpoint): hold-pause a harness when the sandbox snapshot keeps its processes
  10. feat(agent-utils): resume a supervised harness in place after a restore that kept its processes #5412: feat(agent-utils): resume a supervised harness in place after a restore that kept its processes
  11. feat(opencode): resume OpenCode in place on sandboxes whose snapshots keep processes #5413: feat(opencode): resume OpenCode in place on sandboxes whose snapshots keep processes

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

Run on c277640, on a Slurm node. The head (850c812) adds a merge of main into the branch; it conflicted in one place, the public API list of nemo_gym.server_runtime, where both sides added names and both are kept. These suites were not rerun on the merged head, which CI tests.

  • pytest resources_servers/swebench/tests/test_sandbox_session_checkpoints.py resources_servers/swebench/tests/test_sandbox_sessions.py: 100 passed.
  • pytest tests/unit_tests/server_runtime tests/unit_tests/test_public_api_facades.py tests/unit_tests/test_moved_paths.py environment_servers/single_agent_turn/tests: 3393 passed, 3 failed, 2 collection errors. The failures and errors are from the test environment: its mcp package is older than the one main pins (test_mcp_auto_exposure.py, test_review_boundary_interfaces.py) and cloudpickle is not installed (test_base_environment_server_with_tools.py). None is in a file this PR changes.
  • pytest responses_api_agents/simple_agent/tests responses_api_agents/tool_simulation_agent/tests: 189 passed.
  • NEMO_GYM_CHECKPOINT_E2E=1 pytest tests/e2e/checkpoint/test_checkpoint_sandbox_e2e.py: 6 passed. These start real Gym processes against a fake snapshot backend: commit then resume, crash then continue in a fork, release, and restart on a provider without snapshots, through both environment-server variants. They are skipped without the flag, and no CI workflow sets it, so they were run by hand.
  • The core suite (tests/unit_tests, the OpenCode agent, the SWE-bench and SWE-rebench servers, both single-agent-turn environment servers): 25000 passed, 180 failed, 13 errors. The previous head (932596c) in the same environment: 24990 passed, 179 failed, 13 errors. The failing tests are the same ones and come from the environment (mostly no /usr/bin/python3 in the container, missing mlflow, PIL and cloudpickle, the older mcp, and a tree without a git checkout), except test_docker_pty.py::test_the_wait_for_a_missing_record_is_bounded_with_an_integer_only_sleep, a timing test that failed in this run only and is in no file this PR changes.
  • The suites of swe_next, swemer_v1, swemer_v2, scale_swe, genrm_compare, example_session_state_mgmt, workplace_assistant, gymnasium, Simple Agent and Tool Simulation Agent: passed.
  • lint-imports: 2 contracts kept. ruff check . and ruff format --check . (ruff 0.9.9, the pre-commit version): clean. pre-commit itself was not run.
  • Twenty of the new tests were each run against the code with the protection they cover removed, and each fails there: the cancel shield of a failed restore, the deadline of a restored session, the lock and the untrack in _release_task_sandbox, the check after a commit takes its locks, the deadline check, its exemption for a session without a task sandbox, its hold on a sandbox a verify claimed, the order of a restore's install, the per-session lock release, discard, the restart report of a session without an episode seed, the task model check, and the two participant checks, the report of a session by its request (a seed that fails, and a later seed on the same cookie), stop of a key whose sandbox already stopped (in the core suite and through a close), the index check once per checkpoint, and discard in the core suite.

What the tests of the subclass cover: the conformance kit (attempts 0 and 7, with verify_body), the kit refusing three servers that lose or keep task state, a restored session that continues with its task state, a session restored after its capture, the saved format and its version, a commit and a stop, close, capture or release in either order, per-session lock release, a snapshot that fails once or always, expiry and a deadline no request swept, a session still being graded past its deadline, retire, a session seeded without an episode seed, a restore that fails after forking and its retry, a restore cancelled by a task cancel and through a cancel scope, invalid restore input, the startup check, and the state_dir requirement with and without snapshots.

Compatibility

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 29, 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 added feature New capabilities, enhancements, or enablement work area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation complexity:high Cross-component or shared-contract change with a large review surface labels Oct 29, 2026
@pthombre
pthombre added this pull request to stack #5270 October 29, 2026 05:56
@pthombre
pthombre force-pushed the pranav/envckpt-2b-owner-base branch from bf99bf3 to e4a4266 Compare October 29, 2026 22:39
@pthombre
pthombre force-pushed the pranav/envckpt-2b-owner-base branch from e4a4266 to 8d8e770 Compare October 31, 2026 18:07
@pthombre
pthombre force-pushed the pranav/envckpt-2b-owner-base branch from 8d8e770 to b8962b1 Compare November 3, 2026 03:22
task = asyncio.ensure_future(self._release_expired(session_id))
task.add_done_callback(lambda done: done.cancelled() or done.exception())

async def _release_expired(self, session_id: str) -> None:

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.

An identical retry refreshes seeded_at while it still holds the fence, but this task was already scheduled from the check before that refresh and does not look again. It also does not take session.lock. Can it stop the sandbox the retry just returned, and fence the id so the next seed is 409? It also looks able to stop a sandbox while an export is snapshotting it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This no longer applies at the current head. The file this comment is on (sandbox_owner.py) and its background reaper are gone: the PR is now a subclass of main's SandboxSessionResourcesServer.

  • Stopping a sandbox a retry just returned. Expiry is the inherited sweep, _close_abandoned_task_sessions. It takes the session lock and checks the record and the deadline again under it before it stops anything. The deadline is set once at seed time with setdefault, so a retry does not move it.
  • Stopping a sandbox an export is snapshotting. Every stop of a task sandbox goes through _stop_released_task_sandbox, which takes the same per-session export lock the commit holds while it snapshots. Two tests cover both orders: a commit that waits for a stop in progress, and a close that waits for a commit in progress.

@pthombre

pthombre commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Being rebased onto current main, after #5264 and #5265 (already rebased). Until this branch is pushed, its diff still shows their old commits. Not ready for review yet.

Remove the before_agent_close restore policy: its seed-reply header and
reader, the participant attribute, the class setting and its startup check,
and the changes in single_agent_turn, Simple Agent and Tool Simulation
Agent. A server whose grader needs what a snapshot does not keep runs
restart_only. The mark_restart early return added for the policy goes too.

Saved format: a session record has a version and its sandboxes by name
("task" for the task sandbox); the checkpointer key is
"<session ID>/<name>".

Commit: validate captures and task state before any snapshot, release each
session's export lock once its own snapshot is done, and leave out a
session past its deadline that no request has swept yet.

Restore: put the task state back before building the seed reply. After a
failed install, hand the forks to the checkpointer's new discard(), so a
retry is not refused when a fork could not be stopped.

A task sandbox started without an episode seed, such as for the task row
an agent's /run sends, is no longer registered for checkpoints. The server
reports the session through the new ResourcesParticipant.restart_session:
its seed reply carries the restart header, prepare lists its episode as a
restart, and a commit leaves it out.

A seed with another model than the declared task_model is refused.

Conformance kit: checkpoint before verify captures the patch, check the
restored and forgotten task state, and with verify_body compare the
server's own /verify after a restore with a run without the crash.

Also: _stop_released_task_sandbox is now _stop_unclaimed_task_sandbox,
checkpoint_settings is no longer exported, new lines use "X | None", and
private helpers follow the public API.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test c277640

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 12:41
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 19, 2026
Conflict in nemo_gym/server_runtime/__init__.py: both sides added names to
the public API list; both are kept.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 850c812

@macandro96 macandro96 left a comment

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.

One remaining P2 checkpoint-recovery correctness issue, reproduced on the current head.

and not record.expired
# Past its deadline the provider may have ended the sandbox, and the sweep that marks the session expired
# runs only when a request arrives: without this, one such session would fail the commit for all.
and self._open_task_sessions.get(session_id, float("inf")) > monotonic()

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.

[P2] Keep captured resources sessions exportable past the task sandbox deadline

This deadline check also drops a session whose replayable verification has already captured the patch and stopped the task sandbox, but is still grading. The inherited expiry sweep skips busy sessions, so the session has not actually expired. Nevertheless, export omits its saved capture, and the participant treats the omitted session as released. A checkpoint taken during that grading can therefore lose the state needed to replay verification after a crash.

I reproduced this at 850c812: hold verification after capture and sandbox teardown, move the original task deadline into the past, and export while verification remains busy. The sweep preserves the session, but export returns {}. A capture-only exemption makes the same regression pass through restore and verification.

Please apply the deadline cutoff only to sessions that still require a live task sandbox snapshot, retaining captured sessions with no task sandbox unless the session is explicitly marked expired. Add a checkpoint/restore regression for grading that continues past the original task deadline.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5788aaa. The deadline now leaves out only a session that still has a task sandbox registered. A session whose verify stopped the sandbox is exported with its capture unless it is marked expired.

Test: test_a_session_still_being_graded_past_its_deadline_is_checkpointed_with_its_capture. A verify is held after its capture and the stop of the sandbox, the deadline is moved into the past, and a checkpoint is taken through the control routes. The session is not expired, the restored server returns the saved capture without capturing again, and nothing is snapshotted or forked. The test fails with the deadline check as it was at 850c812.

ananthsub
ananthsub previously approved these changes Nov 19, 2026
@ananthsub

Copy link
Copy Markdown
Contributor

Re-review at 850c812: c277640 fixes 11 of my 12 threads. The Optional thread stays open: the same commit adds three Optional[str] annotations in resources.py. The new notes are inline. None of them needs to block the merge.

Two points outside the diff:

A commit left out every session past its deadline. That also dropped a
session whose verify had captured the patch and stopped the task
sandbox but was still grading: the expiry sweep skips it while it is
busy, so it had not expired, and a checkpoint taken then lost the
capture a replayed verify needs.

The deadline now excludes only a session that still has a task sandbox
to snapshot.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 5788aaa

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 19:11
…a stopped key without a wait

Second review round of the sandbox session checkpoints.

- ResourcesParticipant.restart_session() marks the request being handled,
  not a session ID. The middleware applies the mark when the seed
  succeeds, to the ID later requests carry, so a seed that fails reports
  nothing and a later seed on the same cookie leaves an earlier report in
  place. seed_failed and session_restarts are removed.
- SandboxSessionCheckpointer.stop drops a key whose sandbox already
  stopped without waiting for a turn, so a close cancelled there no longer
  leaves the session in the checkpointer.
- An export checks the snapshot index for unreleased checkpoints once per
  checkpoint, not once per call: a commit exports each session on its own.
- Core tests for discard, and wording: "agent-run seed", and no "free"
  for a key that can be restored again.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 61ada45

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 21:28
…ommit past its deadline

The deadline check asked only the registry whether a task sandbox was
left to snapshot. A verify that claims the sandbox takes it out of the
registry while it still runs and the checkpointer still tracks it, so a
commit snapshotted it past its deadline, where a failed snapshot fails
the commit for every session. The check now asks the checkpointer too.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 270e04a

@pthombre
pthombre added this pull request to the merge queue Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44631979111

Merged via the queue into main with commit 6805282 Nov 19, 2026
78 of 82 checks passed
@pthombre
pthombre deleted the pranav/envckpt-2b-owner-base branch November 19, 2026 23:02
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
Resolve against main:
- Drop this branch's earlier copy of the shielded stop (stop_sandbox() in
  nemo_gym.sandbox.utils and its test): #6410 merged a different version that
  puts the shield and limit in AsyncSandbox.stop(timeout_s=...). The sandbox
  package, LentSandboxes, the swebench session base and deepswe_external1
  take main's code; OwnedSandboxes stops through AsyncSandbox.stop.
- #5266 exports the checkpointer under its old name: its server, conformance
  helper and test move to OwnedSandboxes in owned_sandboxes, and the public
  API serves SandboxCheckpointConfig, SandboxCheckpointError and
  checkpoint_state_dir from there. No release shipped the old name.
- The glossary keeps main's sandbox lease and capabilities rows beside the
  owner and lend/borrow rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation 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 risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants