Repository navigation
feat(swebench): typed sessions on the owner base with capture-once verify - #5267
Conversation
bce46ea to
55fd82e
Compare
55fd82e to
f3984d4
Compare
f3984d4 to
ce691e0
Compare
ce691e0 to
8e74187
Compare
8e74187 to
e38d6cd
Compare
e38d6cd to
242485c
Compare
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE — the required runtime evidence and checkpoint setup documentation are missing.
RISK — Provide current-revision rollout and reward-comparison evidence
The eval command now merges stderr into stdout, changing the output presented to grading for existing SWE-bench benchmarks. The server also enables checkpoint export and replay. The PR reports no real-model rollout on this revision, no before/after reward comparison, and checkpoint training runs only on an earlier implementation. The new unit tests don't establish that the current provider, harness and grader work together.
Could you add the validation required by the pinned rubric's baselining rule and the repository's real-smoke requirement? Keep the model, task subset, harness and settings fixed between base and head, and record resolved/scored/masked counts, aggregate reward and task-level changes. Include a provider that returns separate streams and representative stdout-reporting cases; investigate changes outside the intended stderr correction.
For the checkpoint path, record a representative model episode using the current implementation, checkpoint its work, restore into a fork and verify it. Acceptance should show that the restored episode grades the same patch digest and preserves the expected reward and masking behavior. Retain the existing distinction between an invalid model patch, which receives an unmasked zero, and an infrastructure failure, which is masked. A full training run isn't necessary for this request, but the earlier stack's runs don't validate this implementation. These are requested checks, not results I obtained.
NOTE — Suggestion: document SWE-bench's checkpoint prerequisites
Switching to the checkpoint owner base makes an enabled snapshot-capable provider select exported mode and require a durable state directory at startup. Neither the SWE-bench quickstart nor the inspected configuration guide explains this new setup. A user enabling checkpointing without that directory now encounters a startup failure rather than a restart-only server.
Please add a short SWE-bench checkpoint section under Fern and link it from the README. Show the required checkpoint.enabled, control_auth_token and absolute state_dir settings, explain that the directory must survive restarts outside controller-deleted checkpoint directories, and identify the session-capable environment/harness prerequisites. A full stack guide isn't needed here.
Static acceptance: check the example against CheckpointSettings and the server's mode selection. State that providers without snapshots and golden-patch grading remain restart_only, and preserve the ordinary checkpoint-disabled quickstart. Distinguish controller-driven session restores from evaluation resume, which restarts interrupted rollouts rather than restoring their sandbox state.
I completed static inspection of all six changed files and their affected contracts, including the three delegated topics. I found no additional implementation defects. I didn't execute tests or validate external provider SDK behavior in this read-only review.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
242485c to
f859c9c
Compare
f859c9c to
87f9841
Compare
The SWE-bench server now builds on CheckpointedSandboxSessionResourcesServer, so its episode sessions take part in partial-rollout checkpoints. Its seed, capture-once verify and close stay main's. - The task sandbox is started through new_task_sandbox: on the provider every session shares, and registered for its checkpoints. Grading sandboxes are unchanged. - The commit a session's patch is captured against (seed_head) is exported and restored with the session. - task_model is SWEBenchInstanceRequest; verify is declared replayable, since the patch is captured once and a verify after a restore grades the saved patch. - Each grading runs under its own run id, so a verify replayed after a restore never shares log files with the first. - Golden-patch grading seeds no episode sessions and runs restart_only. - The session contract test resolves a close inherited through a subclass of the shared base. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
The grader parses only the region between SWE-bench's start and end markers, from the command's stdout followed by its stderr. A provider that returns a command's stdout and stderr apart (E2B) puts every line a test runner writes on stderr after the end marker, so tests that report there grade as missing. The eval command now joins the script's stderr to its stdout, in order, before anything runs. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…e script's real shape Found in a review of the SWE-bench checkpoints. - The comment on `EVAL_SCRIPT_COMMAND` had the failure backwards. SWE-bench's start and end markers are no-op commands that reach the output only through bash's trace, on stderr, so a provider that returns the streams apart (OpenSandbox, E2B) put what the tests print on stdout before the start marker, not stderr after the end marker. The test now runs a script of that shape: markers through the trace, tests on both streams. - The run id comment gives the reason that holds: `run_instance` returns a `report.json` it finds in the run's log directory, so a verify repeated after a restore must not find an earlier grading's. - The saved test output is read with `errors="replace"`, so a log that is not UTF-8 does not fail the verify. - The RuboCop splice says it only serves a command whose stderr comes back apart. - Tests: the restored session's patch is captured in the fork against the seed's commit even though HEAD moved, and an agent's own seed replaces the task sandbox its session started before. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
87f9841 to
e156bd0
Compare
|
/ok to test e156bd0 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44798974674 |
| # The eval script's stderr joins its stdout, in order. SWE-bench's start and end markers are no-op commands that | ||
| # reach the output only through bash's trace, on stderr, and the log parser reads the region between them. A | ||
| # provider that returns a command's stdout and stderr apart (OpenSandbox, E2B) would otherwise put everything the | ||
| # tests print on stdout before the start marker. | ||
| EVAL_SCRIPT_COMMAND = "/bin/bash /eval.sh 2>&1" |
There was a problem hiding this comment.
NOTE: this commit joins stdout and stderr into one stream before grading. That is a verifier change on a fixed benchmark, and it does not depend on the checkpoint work in this PR. The description also understates what it changes.
- Which providers. Every provider that runs the command through a shell returns stdout and stderr apart. So the graded text changes on these providers too, not only on OpenSandbox and E2B:
- local
- Docker
- Apptainer
- Enroot
- OpenShell
- ECS
- What it fixes. Test output on stdout was usually not lost on
main. When the marked region holds no result, SWE-bench'sget_logs_evalparses the whole log instead (swebench 4.1.0,harness/grading.py). A verdict changes only when the stderr part of the region parses to some results but not all, for example one test result printed on stderr. - Dead code. With the streams joined, stderr is always empty here, so
patch_swebench_multilingual_log_parsing(L411-L422) never fires. The docstring offailure_only_suite_completedstill says a sandbox returns the two streams one after the other.
Joining the streams matches upstream's own Docker exec, which returns one stream in arrival order, so the direction is right.
Fix: move this commit into its own PR, so its effect on grading is reviewed apart from the checkpoint wiring. In that PR:
- delete
patch_swebench_multilingual_log_parsingand its caller's fallback - update the
failure_only_suite_completeddocstring - state the provider list and the whole-log fallback in the description
| config: SwebenchResourcesServerConfig | ||
| task_model: ClassVar[type[BaseModel]] = SWEBenchInstanceRequest | ||
| # The patch is captured once per session, so a verify repeated after a restore grades the same patch. | ||
| checkpoint_verify: ClassVar[StepType] = "replay" |
There was a problem hiding this comment.
NOTE: this makes the SandboxSessionCheckpointer module docstring untrue. _checkpoint/sandbox.py L32-L35 says a server whose /verify runs commands in the sandbox, or stops it, must keep checkpoint_verify at "wait". This server's verify does both and declares "replay".
It is safe, because CheckpointedSandboxSessionResourcesServer runs the capture and the stop under the same per-session lock the export holds (L228-L248). The next author reading that docstring will either refuse "replay" or copy it without the lock.
Fix: reword the docstring to name the exception, for example: "...must keep checkpoint_verify at "wait", unless every such command and stop holds the lock its export holds, as in CheckpointedSandboxSessionResourcesServer."
| class SwebenchResourcesServer(CheckpointedSandboxSessionResourcesServer): | ||
| config: SwebenchResourcesServerConfig | ||
| task_model: ClassVar[type[BaseModel]] = SWEBenchInstanceRequest | ||
| # The patch is captured once per session, so a verify repeated after a restore grades the same patch. |
There was a problem hiding this comment.
NOTE: with "replay", a commit can snapshot a task sandbox that verify has already captured and is about to stop.
- What happens:
- Verify runs
capture_task_sandbox_patch, which holds the session's export lock and releases it when the capture ends (L242-L248). - A commit that arrived during the capture is waiting on that lock.
asyncio.Lockwakes waiters in order, so it gets the lock beforestop_task_sandbox_after_capturetakes it again (L229-L233). - The commit snapshots the sandbox and exports it with the saved patch. Grading waits for the snapshot, and a restore forks a sandbox that the replayed verify only stops.
- Verify runs
- Blast radius: a wasted snapshot of a full SWE-bench sandbox on the commit path, and a fork on restore. The reward is correct. SWE-bench is the first server on this base with
"replay", so this PR makes it reachable.
Running seed, prepare, verify and commit against this head exports both parts of the checkpoint: capture_ready exported: True snapshot exported: True.
Fix: in CheckpointedSandboxSessionResourcesServer, leave the snapshot out of the export when the session's capture is ready. That base already restores such a session without its sandbox.
| if task_session_id is not None: | ||
| self._session_id_to_sandbox[task_session_id] = eval_sandbox | ||
| # On the provider every task sandbox shares, and registered for the session and its checkpoints. | ||
| eval_sandbox = self.new_task_sandbox(task_session_id, eval_sandbox_spec) |
There was a problem hiding this comment.
NOTE: every task sandbox now shares one provider, also with checkpoints off. On main each task sandbox built its own provider (AsyncSandbox(resolved_sandbox_provider) creates one from the mapping, api.py L515).
-
What changes: the Docker, Apptainer and Enroot providers hold one
asyncio.Semaphore(exec.concurrency)around every CLI call (docker/provider.py L312, L351). The default is 32. That coversdocker runtoo, including an image pull of up tostart_timeout_s. -
Failure case: a worker with more than 32 SWE-bench seeds in flight on Docker queues these calls behind those slots:
- the 33rd seed's create
- every session's rev-parse, capture and stop calls
Grading sandboxes and the agent's own calls are not affected. OpenSandbox, which the shipped config uses, has no such semaphore.
Fix: add one line to the description's Compatibility section: on Docker, Apptainer and Enroot, more than exec.concurrency concurrent task-sandbox operations per worker now queue, and that is the setting to raise.
| run_id = session_id | ||
| # One run id per grading: run_instance returns a report.json it finds in the run's log directory, so a verify | ||
| # repeated after a restore must not find what an earlier grading of the session left there. | ||
| run_id = f"{session_id}-{uuid4().hex[:8]}" |
There was a problem hiding this comment.
NOTE: the per-grading run id is needed, but no test shows why. The only test checks that two gradings got two different ids (test_checkpoint.py L228), so it passes for any code that builds unique strings.
The failure it protects against:
- A checkpoint is taken while the agent works, before capture.
- Verify grades,
run_instancewritesreport.json, and the process dies before thermtree. - The restored fork produces a different patch under the same resources session ID.
- With
run_id = session_id,run_instancereturns the earlierreport.jsonearly (swebench_patches.py L86-L91) and the episode gets the earlier patch's verdict.
Fix: replace the id assertion with a test of the behavior: plant a report.json that says resolved: true under logs/run_evaluation/<session id>/, then seed and verify with the real run_instance and an empty grading output, and assert resolved is false. That test passes on this head and fails with run_id = session_id.
Test that passes on this head and fails with run_id = session_id
async def test_a_verify_grades_again_instead_of_reading_an_earlier_gradings_report(
tmp_path: Path, monkeypatch: MonkeyPatch, offline: Any
) -> None:
"""A grading that wrote report.json and stopped before clearing its logs must not decide the next verify."""
monkeypatch.chdir(tmp_path)
offline.side_effect = run_instance # the real grading, on the fake grading provider's empty output
instance_id = INSTANCE["instance_id"]
stale = tmp_path / "logs/run_evaluation" / "rs-1" / "None" / instance_id / "report.json"
stale.parent.mkdir(parents=True)
stale.write_text(json.dumps({instance_id: {"resolved": True}}))
server = make_server(FakeSnapshotProvider(git_results), {})
async with http(server) as client:
await seed(client, episode_seed())
verified = await client.post("/ng-rollout/r/verify", json=VERIFY)
assert verified.status_code == 200, verified.text
assert verified.json()["resolved"] is False, verified.json()It uses the helpers and fixtures already in test_checkpoint.py, plus run_instance from swebench_patches.
| PATCH = "diff --git a/f b/f\n+fixed\n" | ||
|
|
||
|
|
||
| def git_results(command: str) -> Optional[SandboxExecResult]: |
There was a problem hiding this comment.
NOTE: this new line uses Optional, which current typing guidance replaces with X | None. Drop Optional from the import on line 12 too.
| def git_results(command: str) -> Optional[SandboxExecResult]: | |
| def git_results(command: str) -> SandboxExecResult | None: |
| await client.post("/ng-control/v1/checkpoint/resume", json=control("c1"), headers=auth(config)) | ||
| finish.set() | ||
| await verifying | ||
| # The environment server keeps the session cookie in its bookmark and sends it again after a restore. |
There was a problem hiding this comment.
NOTE: "bookmark" is not a Gym term, and nothing in nemo_gym/ or the glossary uses it. The environment server records a continuation at each checkpoint boundary (checkpoint_boundary in environment_servers/single_agent_turn/app.py), and that continuation holds the session cookie.
| # The environment server keeps the session cookie in its bookmark and sends it again after a restore. | |
| # The environment server keeps the session cookie in the continuation it records at a checkpoint boundary. | |
| # It sends the cookie again after a restore. |
|
The checkpoint wiring fits the session base from #5266, and the inline comments are notes for follow-up, not conditions of the approval. Three points sit outside the diff:
|
What changed and why
SWE-bench is the first production resources server on
CheckpointedSandboxSessionResourcesServer(#5266), so SWE-bench episodes can take part in checkpoints: the task sandbox is snapshotted with the agent's work in it, a restore continues in a fork, and grading after a restore grades the same patch.On
main, SWE-bench already serves episode sessions: its seed, its capture-once verify and its close stay as they are. This PR changes what a checkpoint needs.main's session base.new_task_sandbox, so it runs on the provider every session shares and is registered for its checkpoints. Grading sandboxes are unchanged.HEADhas moved in the fork.checkpoint_verify = "replay": the patch is captured once, and a verify that a checkpoint replays, or that runs again after a restore, grades the saved patch. Grading itself is not cached.run_instancereturns areport.jsonit finds in the run's log directory, so a verify repeated after a restore must not find an earlier grading's.restart_only.main's test that every resources server closes sessions through the base route now also accepts a close inherited through a subclass of a base, such asCheckpointedSandboxSessionResourcesServer.errors="replace", so a log that is not UTF-8 does not fail the verify.The title still says "typed sessions on the owner base with capture-once verify".
mainhas since gained the sessions and the capture-once verify, so what this PR adds is the checkpoint wiring.This carries the design of #4277 and the fixes and tests of #4778 onto
main's SWE-bench sessions.How it works
Where this PR sits in the overall flow
The highlighted part is what this PR changes.
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 R thisThis PR
What a checkpoint exports at each point of a session, and where a restore continues.
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, #5265 and #5266 have merged, and the rest of the stack is rebased onto
mainafter them. Each PR is based on the one before it, so each diff shows only that PR's change. The stack runs parallel to thelegacy_agentpath of #4220 to #4936, which it does not change or depend on.Issue
No tracking issue exists. This implements the environment-server plan for checkpointing sandboxed harnesses, on top of the merged partial-rollout checkpoint stack (#3882 to #3909, #4997).
Validation
Head
e156bd0b98, onmain12338216b4. The stack was rebased ontomainafter #5266 merged. Tests ran as Slurm jobs on one node each, in therl-gymCI container with the repository's dev dependencies; nothing ran on a login node. In that containermainitself has 179 failures and 13 errors in the core unit suite (job 9188100), so results are compared withmain's list by test id. Two test files that hang there, onmaintoo, are left out:tests/unit_tests/test_slurm_control.pyandtests/unit_tests/benchmarks/test_agentic_vbench_staging.py.3d0e643db9, which includes this PR (jobs 9188099, 9188102): import-linter clean;ruff checkandruff format --checkclean; all ten server suites pass; the core suite differs frommain's list only by tests that fail from run to run on either side.mainonly by tests that fail when the node is loaded and pass when their file runs alone (test_harness_pause.py::test_a_hold_before_the_launch_is_not_added_to_the_deadline_again_by_a_later_pause,test_exec_transport.py::test_confirmed_cleanup_cancels_stuck_transport) andtest_docker_compose.pytests that fail from run to run onmaintoo. The whole core suite was run per level on the previous base (feat(swebench): checkpoint the task sandboxes of episode sessions #5266's head before it was squash-merged), with the same result; on this base it ran on the tip only.NEMO_GYM_CHECKPOINT_E2E=1): harness scenarios 11 passed, sandbox 6, sequences 4, fake backend 1,test_checkpoint_e2e.py45 passed and 12 skipped.HEADmoved; an agent's own seed that replaces the task sandbox its session started before; golden-patch servers; an eval script of the real shape (markers through the trace, tests on both streams) with the streams returned apart./verify(verify_body) is not used. The kit compares whole replies, and this server's replies carry timings and sandbox IDs, so it needs a change in the kit first.pre-commit run --all-files; any live sandbox, real-model or training run on this head.e62ed9ca9a), not repeated on this head: 16-node full-SWE run on AgentENV, Slurm job 9048275 (2 h, five routes, 8 Gym replicas), compared with reference job 8760594 on an earlier stack. 3 training steps (2981 s, 2567 s, 670 s; reference 2948 s, 2606 s, 681 s); 8 rollout checkpoints saved, 0 failed (reference 7 / 0); checkpoint save median 57 s, Gym commit median 50 s (reference 65 s and 48 s); 351 full 16-rollout batches, median 730 s (reference 347, 720 s); no snapshot, fork, anti-cheat, base-commit or patch-extract failures. The AgentENV gateway returned about four times as many 502s as in the reference; on the servers of this stack each was a retried first attempt and none exhausted its retries. Not exercised: the run had no crash, so no restore and no resume in place ran;scale_sweis not on the checkpoint layer.Compatibility
main. The task sandbox now runs on the provider the server's sessions share.checkpoint.state_dirwhen its provider can snapshot.🤖 Generated with Claude Code