Skip to content

feat(checkpoint): protocol for harnesses that borrow a sandbox - #5264

Merged
pthombre merged 6 commits into
mainfrom
pranav/envckpt-1-protocol
Nov 12, 2026
Merged

pthombre merged 6 commits into
mainfrom
pranav/envckpt-1-protocol

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

The partial-rollout checkpoint stack on main checkpoints environment-server episodes whose agent and resources state live in Gym processes. It cannot yet checkpoint an episode whose agent harness runs in a sandbox the resources server lends (for example OpenCode on SWE-bench):

  • after a restore, the resources server hands out a forked sandbox with a new id, but the agent session still points at the old one, and the base agent answers 409 to the replacement attempt's seed;
  • a harness running in a sandbox has no way to learn that a checkpoint wants it parked;
  • a server that keeps state outside Gym (sandbox snapshots) has no hook to learn which checkpoints are still needed, and no stable directory to index that state across restarts;
  • resources MCP grants force every episode to restart, because a restored agent keeps the old attempt's token.

This PR is every protocol change between the four server types that the rest of the stack needs. The pieces are small and only useful together, so they are reviewed together and tested with fakes. Nothing here takes a snapshot or pauses a process.

  • Control plane
    • release(kept): a new control operation, admitted only while the participant is idle with no checkpoint open. The controller calls it after saving a checkpoint, with every checkpoint it may still restore, so participants can delete external state that only dropped checkpoints need. It returns only once that state is deleted, under the control lock and the request deadline. Coordination fans it out best effort and reports failures per participant. A multi-worker server forwards it to every worker and fails unless every expected worker answered, so the controller releases again.
    • Stale releases. A release names the latest checkpoint the controller resumed. A participant refuses it as stale (checkpoint_stale) once it has committed or restored a checkpoint after the one named, so a release delayed past a later checkpoint cannot delete that checkpoint's state. A checkpoint that was aborted does not count, so the release that ends a run is still admitted after an abort. A process that holds a checkpoint also refuses a release naming one it never resumed, which covers a release from before a restart.
    • Export hooks receive the checkpoint_id they write (keyword-only), so a server can name external snapshots after the checkpoint and find them again at release. The participants refuse an export hook that cannot take it when they are built, so a server, or code that builds a participant around its own hooks, learns it at startup.
    • CheckpointSettings.state_dir: a directory stable across restarts, for servers that index external state.
    • Optional hook delete_external_state(kept) on resources servers and agents (no-op by default). Its docstring states the contract: it holds the control lock, can be cancelled at the deadline and is retried (so it must be idempotent), runs beside live traffic, runs on every worker, and keeps by reference.
    • Status and discovery report keeps_external_state: whether a server's checkpoints keep state outside Gym that only release deletes. A controller that never releases can then refuse to run or warn.
    • Prepare hands the participant an earlier stage's restarts before it closes admission, so no worker asks a restart's harness to park.
  • First seeds do not hold up prepare. When a checkpoint closes admission, a rollout whose first seed is still in flight (its agent or resources session does not exist yet) is reported as a restart of that checkpoint, by both the agent and the resources participant (exported and stateless modes; restart_only already did this). The controller leaves those rollouts out of the commit, so prepare no longer waits for sandbox creation, repository setup and harness setup. In large runs a checkpoint often lands just after a batch is dispatched, with hundreds of first seeds in flight, and waiting for them was most of the time rollouts stayed parked. The set is fixed when admission closes and cleared at resume: the seed keeps running, and its session is in the next checkpoint. A seed of a session that exists, such as the re-seed of a restored session, still blocks prepare, so restored progress stays in the checkpoint.
  • Per-instance checkpoint mode. checkpoint_mode_in_effect() on agents and resources servers, defaulting to the checkpoint_mode ClassVar. A sandbox owner (feat(swebench): checkpoint the task sandboxes of episode sessions #5266) reports restart_only when its provider cannot snapshot. Environment servers keep reading the ClassVar.
  • Park signal for agent sessions. Activation.park_requested and wait_park_requested() tell agent code running outside Gym (a harness in a sandbox) to park; a retire or close wakes the wait with StaleAttemptError. Activation.slot(semaphore) takes one of the agent's concurrency slots and gives it back on every path, and counts as parked while it waits, so an activation still waiting for a slot does not hold up prepare (queued() wraps any other such wait). An episode that will restart is never asked to park, and uses a slot or a policy reply it gets during a checkpoint at once.
  • Restored boundary. An activation keeps its restored boundary as the session's latest until it records its own, so a checkpoint taken before its first boundary exports it again instead of nothing.
  • Agent base
    • Re-bind. A replacement attempt's seed of a restored, unclaimed session calls _rebind_restored_agent_session_state instead of answering 409. The default still refuses, so Simple Agent is unchanged.
    • Seed restarts. A session the agent could not continue after a restore is a restart, decided at the seed before the session exists, so it is never exported or waited for. Two cases always apply: a session granted MCP tools, unless the agent declares rebinds_tool_accesses, and a session lent a sandbox, unless the agent overrides the re-bind hook. _seed_restarts(body) lets an agent add restarts of its own; it cannot remove those two.
    • rebinds_tool_accesses: an agent that re-renders tool grants at re-bind says so in its seed reply (x-ng-checkpoint-rebinds-tool-accesses). Startup refuses the flag without an override of the re-bind hook.
  • Environment server (single_agent_turn and its legacy variant)
    • The bookmark records borrowed_sandbox, with a default, so existing bookmarks load.
    • Re-seed after a restore. A continuation at invoke_agent or close_agent with a borrowed sandbox re-seeds the resources session and then the agent session inside a replay step, so the agent re-binds to the forked sandbox. A checkpoint does not wait for the re-seed.
    • MCP grants. An episode that grants MCP tools continues after a restore only when its agent borrows the lent sandbox and declares that it re-binds tools; otherwise it restarts, marked before the agent seed.
  • Episode budget. The environment participant records the budget an episode has spent (excluding time parked for checkpoints) when a checkpoint exports it (EpisodeRecord.elapsed_s), and charges it to the replacement attempt, so a step in flight when the checkpoint exported the episode, such as the agent's activation, counts in full. The record leaves the field out when nothing was spent, so a Gym from before the field still restores it. Environment servers need no code for this.
  • In-tree overrides of the export hooks take the new keyword.

This generalizes the control-plane part of #4220 and #4222 (legacy stack) to agent sessions.

How it works

Where this PR sits in the overall flow

The highlighted parts are 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["Sandbox owner base<br/>export, restore, capture_once"]
  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 CO,E,A this
Loading

This PR

A crash after a checkpoint, then the restore. The new parts are the re-seed in the replay step and the agent's re-bind.

sequenceDiagram
  participant C as Controller
  participant E as Environment server
  participant R as Resources server
  participant A as Agent
  Note over C,A: checkpoint C1 committed while the episode was at invoke_agent<br/>bookmark records borrowed_sandbox, record holds the budget spent
  Note over C,A: crash, every Gym process dies
  C->>E: restore C1 (the bookmark becomes unclaimed)
  C->>R: restore C1 (the sandbox is forked, S1 becomes S2)
  C->>A: restore C1 (session installed, not yet connected)
  C->>E: run, attempt N+1
  E->>E: continue at invoke_agent with the remaining budget
  rect rgb(253, 230, 138)
    Note over E: replay step, a crash here just re-seeds again
    E->>R: seed (same session, attempt N+1)
    R-->>E: sandbox_access(S2), no setup run
    E->>A: seed (same session, attempt N+1, S2, fresh grants)
    A->>A: re-bind the restored session
    A-->>E: reply declares that it re-binds tools
  end
  E->>A: activation (the harness continues in S2)
  C->>E: release(kept=[C1]) after the next save
Loading

How a restored episode continues, by the boundary it was saved at:

Restored at Environment server Resources server Agent
seed Normal seed Fresh setup Fresh seed
invoke_agent Re-seed both, then the activation Returns the forked sandbox, skips setup Re-binds, then continues
close_agent Re-seed both, then close Same Re-binds, close collects from the fork
verify, return Unchanged Unchanged Unchanged

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). Each PR is based on the one before it, so each diff shows only that PR's change. This PR and #5265 are rebased onto current main; the PRs after #5265 are being rebased and are drafts until then. The stack is based on main and 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 (this PR)
  2. feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer #5265: feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer
  3. feat(swebench): checkpoint the task sandboxes of episode sessions #5266: feat(resources): sandbox owner base for resources servers
  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

  • Unit tests for the release fan-out and stale releases, checkpoint_id in the export hooks (one and two workers), the park signal and its wake-up on retire and close, slots, restored boundaries, re-bind (including the default gate) and per-session restarts, first seeds in flight becoming restarts, and the startup checks.
  • Unit tests for the second review's fixes: a release after an aborted checkpoint, from before a restore, between a restore and its resume, and with a worker missing; keeps_external_state in status; a lent sandbox and an overridden restart hook at the seed; the export-hook check on a participant built directly; elapsed_s left out of an unspent record; and, for the resources participant, resume clearing the first-seed restarts and a seed that claims a restored session blocking prepare.
  • Environment-server tests, in both variants, for the borrowed sandbox recorded by a real seed, the re-seed after a restore and a checkpoint not waiting for it, the budget sampled at export and charged on restore, and MCP grants.
  • Each fix of both reviews was reverted in turn (32 in all): every one makes the tests written for it fail.
  • Rebased onto current main: the full unit suite fails only where main itself does, apart from three orchestration tests that depend on the test machine; lint is clean.
  • Real-model smoke rollouts (Simple Agent + single_agent_turn on Qwen3-0.6B): uninterrupted rollouts, a checkpoint held open past the episode budget, and a crash and restore mid-activation all finish with the expected reward; details in a comment below.
  • 16-node AgentENV RL training runs, before the review fixes and this rebase, commit every checkpoint, keep rollouts parked several times shorter with the first-seed restarts, and a restore from a checkpoint resumes the held sessions.
pytest tests/unit_tests/server_runtime environment_servers/single_agent_turn/tests \
  environment_servers/single_agent_turn_legacy/tests responses_api_agents/simple_agent/tests

Compatibility

  • Hook signatures: export_session_states and export_agent_sessions take a keyword-only checkpoint_id. Out-of-tree overrides must add it (startup says so); in-tree overrides are updated here.
  • New control operation release, with the same auth as the others; a controller that never calls it sees no change. A release answers 409 checkpoint_stale once the participant has committed or restored a later checkpoint, and fails on a multi-worker server while a worker is missing.
  • New optional settings and fields (checkpoint.state_dir, EpisodeRecord.elapsed_s, the bookmark's borrowed_sandbox, all with defaults), so checkpoints written before this PR restore. A Gym from before this PR restores a checkpoint written after it unless an episode record holds spent budget, which only episodes with a time limit do.
  • New status field keeps_external_state, false for every in-tree server.
  • New seed-reply header x-ng-checkpoint-rebinds-tool-accesses. Episodes with resources MCP grants still restart unless their agent borrows the lent sandbox and declares it; no in-tree agent does until the OpenCode PR.
  • Lent sandboxes. An exported agent that accepts a lent sandbox without overriding the re-bind hook now restarts those sessions instead of failing after a restore. No in-tree agent is affected.
  • Replacement attempts get the remaining budget rather than a fresh one.
  • Behaviour without opting in: the first-seed restarts, the restart rules for MCP grants, the stale-release check and the budget charge apply to every checkpoint; the rest changes nothing until a server opts in.
  • Prepare no longer waits for first seeds. After a restore, a rollout that was still in its first seed when the checkpoint was taken starts over from its input. It had no agent progress yet, so only its setup is repeated.

🤖 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:core Shared APIs, servers, telemetry, health, and registries 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-1-protocol branch from 675c3f4 to 4d55d7a Compare November 3, 2026 03:22
@pthombre
pthombre marked this pull request as ready for review November 3, 2026 03:25
@pthombre

pthombre commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 4d55d7a

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

HOLD — one BLOCKER and four RISK findings.

I reviewed all 34 changed files and traced the affected restore, grant, budget, export and release paths. A queued replacement activation can lose its saved continuation; the inline findings cover that and three other checkpoint reliability defects.

RISK — Provide representative real smoke-rollout evidence

The PR reports fake-based tests and treats real rollouts as unnecessary protocol validation. However, it also changes existing episode behavior: single-agent-turn budget charging affects replacements using existing agents, independently of a sandbox harness opting in. The trusted quality bar requires representative real model rollouts and inspection of agent and verifier behavior for behavior-changing environment or agent work.

Could you add that evidence after correcting the defects? Use a real model with an existing checkpointable agent/resources pairing, record the configuration and commands, and inspect an uninterrupted rollout plus a rollout checkpointed during activation and continued after restore. Show that the restored agent retains its progress, verification still produces the expected task result, and cleanup completes. Also exercise the remaining-budget timeout case: the replacement must receive only the unspent budget, excluding checkpoint parking. Preserve the uninterrupted pairing's reward, observations and cleanup behavior. No verifier or reward formula changed here, so this request is for smoke-rollout evidence rather than a benchmark reward-distribution comparison.

I couldn't execute tests or rollouts in this read-only review. All acceptance checks below are proposed; suggested code needs verification before adoption.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@asynccontextmanager
async def queued(self, session: _Session) -> AsyncIterator[None]:
previous = session.state
session.state = "at_boundary"

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 — Preserve a restored continuation while its activation queues.

Restore a session with boundary={"step": 4}, enter its activation, and wait for a semaphore inside activation.queued() before processing the continuation. The activation constructor moves the saved boundary into activation.continuation and clears session.continuation. This new queue context then makes the session checkpoint-ready, but export finds neither a boundary callback nor a continuation and writes boundary=None. A second restore silently loses step 4 and can replay already completed work. Queuing must preserve the latest resumable boundary, not merely readiness.

A small correction is to retain the restored boundary as the activation's initial snapshot. In Activation.__init__, immediately after moving the continuation:

if self.continuation is not None:
    saved_boundary = self.continuation
    session.boundary = lambda: saved_boundary

Source tracing shows that activation.boundary() subsequently replaces this callback, while activation teardown clears it. Fresh queued activations without a continuation should still export no loop boundary; a fresh or restored activation that records a newer boundary must export that newer boundary instead.

Proposed acceptance: install a record with {"step": 4}, start its replacement activation, block inside queued() on a zero-capacity semaphore, then prepare/export. Assert the exported boundary is exactly {"step": 4} and a further restore delivers it as the next activation's continuation. Also check fresh/no-boundary export remains None and a newly recorded {"step": 5} supersedes the restored boundary. Retain the existing queue test's assertions that prepare completes while queued and a slot granted during the checkpoint cannot start work before resume.

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.

Reproduced on 4d55d7a: restoring {"step": 4}, entering the activation and blocking in queued() leaves activation.continuation == {"step": 4}, but prepare/export writes boundary=None, because the constructor (agent.py#L181) cleared session.continuation and _export_boundary (#L785-L789) only reads session.boundary or session.continuation. Your fix works: session.boundary = lambda c=self.continuation: c keeps {"step": 4} while queued, a recorded {"step": 5} supersedes it, teardown clears it, and a further restore delivers {"step": 4}. The same hole exists today through awaiting_model().

One severity note: no in-tree agent calls queued() yet (Simple Agent calls commit_boundary() first), so I'd grade this RISK rather than BLOCKER. Since this PR introduces queued(), the fix and the restore, queue, checkpoint, restore test should land here.

@pthombre pthombre Nov 7, 2026 •

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 e048e24: an activation keeps the restored boundary as the session's latest until it records its own, so a checkpoint taken while it waits in queued() or awaiting_model() exports it again instead of nothing. Agreed with the RISK grading: no in-tree agent waits before its first boundary. Tested for both waits, alongside a fresh session that still exports none.

the agent re-binds its restored session to that sandbox and to this attempt's tool grants.
Without a borrowed sandbox nothing changed hands, and nothing is seeded.
"""
if not handles.borrowed_sandbox:

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 — Refresh MCP grants even without a borrowed sandbox.

An exported agent may declare x-ng-checkpoint-rebinds-tools: 1 while using resources MCP tools without borrowing a resources sandbox. _seed_agent now allows that episode to continue, but this guard skips both re-seeds after restore. The agent therefore keeps the previous attempt's token. Resources admission rejects that token because the restored session belongs to the replacement attempt. The new MCP capability test explicitly admits this no-sandbox combination but doesn't continue it after restore.

Could you make reseed_after_restore() cover attempt-bound MCP grants as well as borrowed sandboxes? For the current protocol, replacing the guard with the following covers both reasons to re-seed:

if not handles.borrowed_sandbox and "mcp" not in self.config.resources_tool_transports:
    return

Update its docstring/log message accordingly. This relies on the existing seed contract: resources re-seeding must preserve restored task state, and the agent rebind must take the replacement grants. Keep no-sandbox direct-HTTP continuations unseeded, borrowed-sandbox continuations re-seeded, and agents without the rebind header marked as restarts. Do not re-seed completed verify/return stages.

Proposed acceptance: for both environment variants, checkpoint a no-sandbox MCP session whose agent declares rebinding, restore at invoke_agent, and assert the replacement receives a newly minted token and a tool call succeeds against the preserved resources state. The old token must remain refused. Cover close_agent as well, and retain the existing no-sandbox/direct-HTTP no-reseed and non-rebinding MCP restart assertions.

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.

Confirmed for both environment variants: with ["mcp"], an agent that declares re-binding and no borrowed sandbox, a restore at invoke_agent makes no /seed_session or /v1/agent_sessions call (app.py#L369), and resources admission then refuses the old attempt's token (resources.py#L206-L214).

Two ways to close it. Your guard ("mcp" in resources_tool_transports) re-mints the token in both variants, but it relies on a repeat /seed_session of a restored session keeping task state without re-running setup. No docstring in this PR states that rule (only the sandbox-owner base in #5266 is meant to do it), so please document it on seed_session and sandbox_access. The alternative is to honour the rebinds header only when a sandbox is lent (seed.sandbox_access is not None); that turns the MCP-rebind cases of test_an_episode_that_grants_mcp_access_restarts_unless_its_agent_rebinds_grants into restarts, so they would need a sandbox. No in-tree agent declares the header today, so this is latent until a harness does.

@pthombre pthombre Nov 7, 2026 •

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 e048e24. An episode that grants MCP tools without lending a sandbox now restarts, even if its agent declares re-binding: only a borrowed sandbox's re-seed carries the new token, and no in-tree agent re-binds without one.

self.checkpoint_charge_elapsed(request, handles.elapsed_s)

def bookmark(next_stage: str) -> dict[str, Any]:
elapsed = self.checkpoint_elapsed(request)

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 — Capture elapsed time at the checkpoint cut, not only before the replay step.

With a 30-second episode budget, enter invoke_agent near time zero, let the agent work for 20 seconds, then checkpoint while that replay step is still running. The saved environment bookmark still has the elapsed value recorded before invocation. Environment export writes that unchanged bookmark, even though the agent's checkpoint can preserve its later progress. On restore, line 180 charges approximately zero, so the continued agent gets another 30 seconds instead of approximately 10. Long activations—the main partial-rollout use case—therefore still receive a renewed budget.

Could you arrange for the persisted elapsed value to be sampled at the actual checkpoint cut for an in-flight replay step? bookmark(), EnvironmentParticipant.export_records() and the EpisodeSteps elapsed/restore contract need to preserve the original protocol boundary while carrying the current consumed budget. Merely moving this call into the existing boundary lambda won't fix it: checkpoint_boundary() evaluates that lambda when the boundary is recorded, not at export. The exact owner/runtime representation needs a decision, so I don't have a safe local replacement block to suggest.

Preserve zero elapsed for older bookmarks, unbounded episodes, cumulative charging over repeated restores, and exclusion of checkpoint parking. Do not advance the saved stage or replay a completed state-changing verification just to refresh its time.

Proposed acceptance: use a controlled clock or held activation with a 30-second budget; spend 20 seconds inside invoke_agent, prepare/export before the invocation completes, and assert the saved budget charge is approximately 20 seconds. Restore and hold the activation for another 11 seconds: it must time out. Add a second checkpoint/restore to verify charges accumulate rather than reset, and a parked interval to verify it contributes no elapsed time. The existing budget tests cover prefilled elapsed values and completed seed work, not this in-flight case.

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.

Confirmed: with a 3 s budget and the agent held about 1.2 s inside invoke_agent, the exported bookmark carries elapsed_s of about 0.0003 while steps.elapsed(key) reads 1.2 at the same cut, so the replacement gets nearly the full budget back. The bookmark dict is built when the boundary is recorded (app.py#L239) and steps.exported() returns it as stored (steps.py#L345).

The deadline is already suspended at the cut for replay steps, so sampling at export is accurate. I'd keep the bookmark layout out of core: an optional EpisodeRecord.elapsed_s (a default keeps old checkpoints loading), filled in EnvironmentParticipant.export_records from steps.elapsed(key) and charged in begin(), keeps repeated restores cumulative and parked time excluded, and removes checkpoint_elapsed and checkpoint_charge_elapsed from every environment author. If you'd rather defer this to the OpenCode PR, please drop the budget wording from the description, including "no behavior change until a server opts in", since the charge applies to every restored single_agent_turn episode with a timeout.

@pthombre pthombre Nov 7, 2026 •

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 e048e24 with yaoyu's design: the budget spent is sampled at export (EpisodeRecord.elapsed_s) and charged on restore. The per-environment helpers are gone.

with self._operation("release", request.checkpoint_id) as span:
span.set(kept=len(request.kept))
async with self._lock:
if self.phase != CheckpointPhase.IDLE or self.checkpoint_id is not 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.

RISK — Fence obsolete release requests after a newer checkpoint resumes.

The idle check prevents release during a checkpoint, but not after it. A concrete sequence is: commit/resume C1; send a still-valid release(checkpoint_id="C1", kept=["C1"]) whose delivery is delayed; commit/resume C2; then admit the delayed C1 release before its deadline. Both phase conditions pass, and the hook receives {C1}, authorizing deletion of C2's external snapshots although the controller retains C2. This violates the safety invariant in this method's docstring. Resume clears the active identity, so no comparison here detects checkpoint progression.

Could you fence releases against subsequent checkpoint progression, retaining the necessary identity or generation across resume? A release authorized before a subsequent checkpoint must never garbage-collect that checkpoint's external state. The representation needs a protocol decision, so I don't have a compatibility-safe replacement block to suggest. Calling _admit() unchanged isn't sufficient: normal releases intentionally name an already-resumed checkpoint.

Preserve current-identity release after resume, identical retries, best-effort participant fan-out and cancellation-aware all-worker forwarding. Final empty retention must remain possible; prepared, committed-but-not-resumed and restored phases must still refuse release.

Proposed acceptance: use a fake external-state hook holding C1 and C2 snapshots. Delay C1's release until C2 has committed/resumed, keeping the old request's deadline valid; assert it is refused without invoking deletion and C2 remains restorable. Release with the current authorization and {C2}; assert C1 is deleted and C2 retained. Repeat that release, exercise final empty retention, and retain the existing phase-refusal and all-worker forwarding checks.

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.

Reproduced at the control-plane level: commit and resume c1, build release(c1, kept=[c1]) with a long deadline, commit and resume c2, then deliver it. It is admitted (control.py#L820-L832) and a hook that deletes everything outside kept removes c2's state, because resume forgets the active id (#L1179) and the request's checkpoint_id is never compared.

It needs delivery after a whole later checkpoint cycle but still within the request's deadline, so I'd grade it NOTE unless a controller can fire releases without awaiting them. Refusing a release whose checkpoint_id is not the most recently resumed id (the participant already keeps _resumed_ids in order) closes it; please keep an empty kept allowed for the end-of-run call. Either fence it, or narrow this docstring's "must never" wording and the "safe to retry" line at coordination.py#L7.

@pthombre pthombre Nov 7, 2026 •

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 e048e24: a release older than the latest resumed checkpoint is refused as checkpoint_stale.

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.

The stale-release check compares the checkpoint named in a release with the ones this process has resumed, and that misses two cases.
In the first case, a checkpoint was prepared and then aborted. The end-of-run release(c1, kept=[]) then names an id older than the last resume, so it is refused as stale every time and the end-of-run cleanup never runs.
In the second case, a process restarts after a crash. It then admits an older id that it never resumed.
Please key the check on the last checkpoint this participant committed and resumed, and have the release docstring say which id an end-of-run release names.

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 730aa9d. A release is stale only once this participant committed or restored a checkpoint after the one it names, so an aborted checkpoint no longer blocks the release that ends the run. Once a process holds a checkpoint, it also refuses an id it never resumed, which covers the restart. The docstrings say a release names the latest checkpoint the controller resumed.

I did not key it on equality with the last committed id: a participant that committed a checkpoint the controller then aborted elsewhere would refuse the next valid release.

ananthsub
ananthsub previously approved these changes Nov 12, 2026
# they keep state outside Gym.
self.kind = participant.kind
self.mode = participant.mode
self.keeps_external_state = participant.keeps_external_state

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.

No test fails if this line is removed, or if discover stops reading keeps_external_state.
A server with several workers answers status through this coordinator (participant_workers.py#L1143-L1144), so without the copy it reports false, and a controller never learns that it has to release.
Please add a test that a server with several workers whose hooks delete external state reports keeps_external_state in its status, and that discover carries the value into Participant (coordination.py#L190).

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 3d2a27b: a two-worker server's status reports keeps_external_state, and discover carries it into Participant.

@pthombre
pthombre added this pull request to the merge queue Nov 12, 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/43252654295

@pthombre
pthombre removed this pull request from the merge queue due to a manual request Nov 12, 2026
pthombre and others added 6 commits November 12, 2026 09:26
Every protocol change the environment-server checkpointing of sandboxed harnesses needs between the four
server types, reviewed together and tested with fakes:

- Control plane: `release(kept)` admitted only while idle, fanned out to every participant best effort
  (failures returned per participant) and forwarded to every worker; export hooks receive the
  `checkpoint_id` they write (keyword-only); `CheckpointSettings.state_dir` for servers that record
  external state such as snapshots; optional `release_external_state(kept)` hooks. In-tree overrides
  (genrm_compare, gymnasium, workplace_assistant, example_session_state_mgmt, simple_agent,
  tool_simulation_agent) take the new keyword.
- Per-instance checkpoint mode: `checkpoint_mode_in_effect()` on agents, resources and environment
  servers, read by participant setup, status/discovery and seed replies; defaults to the ClassVar.
- Park signal for agent sessions: `Activation.park_requested`, `Activation.wait_park_requested()` (set by
  prepare, at activation entry while closed, and by retire/close; cleared by resume; never for an episode
  that restarts) and `Activation.queued()`, so an activation waiting for the agent's own concurrency limit
  counts as parked.
- Agent base: a replacement attempt's seed of a restored, unclaimed session calls
  `_rebind_restored_agent_session_state` instead of answering 409 (the default still refuses);
  `_seed_restarts(body)` marks a session the agent cannot capture as a restart (header on the seed reply,
  never exported or waited for); `rebinds_tool_accesses` is reported with `x-ng-checkpoint-rebinds-tools`.
- single_agent_turn (and the legacy flat-row server, which inherits it): the bookmark records
  `borrowed_sandbox` and `elapsed_s`; a restore at `invoke_agent` or `close_agent` re-seeds both sessions
  in a replay step (`reseed_after_restore`), so the agent re-binds to the forked sandbox; a replacement
  attempt only has the rest of the episode budget; resources MCP grants force a restart only when the
  agent seed reply does not say it re-binds tool grants.

Provenance: the control-plane part of #4220 and #4222, generalized from LegacyRun to agent sessions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…t instead of waiting for it

A rollout checkpoint lands right after a training step dispatches its rollouts, while hundreds of first seeds are
still running: the resources server creating each sandbox and the agent setting its harness up in it. Prepare
waited for every one, 70-80 s at 16 nodes, while every rollout already running sat parked. Such a seed has done no
work of its episode worth saving.

When admission closes, the agent and resources participants now record the rollouts whose first seed is still in
flight and report their episodes as restarts of that checkpoint: prepare does not wait for them, and the commit leaves
them out, including the sessions they register before resume. After a crash those rollouts start over from their
input; the live run is unchanged, and after resume the next checkpoint captures them like any other. A seed of a
session that exists, such as one re-binding a restored session to its rebuilt sandbox, still blocks prepare, so
restored progress stays in the checkpoint.

At 16 nodes on AgentENV (runs 8639483 and 8641901 against 8634011), steady-state checkpoints park rollouts for
7-36 s instead of 79-107 s, and leave 200-370 fewer sandboxes to snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…udgets, stale releases, startup checks

- A restart's activation no longer parks when it gets a slot (`queued()`) or a policy reply (`awaiting_model()`)
  while a checkpoint is open: nothing of it is in the checkpoint, the rule `park_requested` already applies.
- `Activation.slot(semaphore)` takes one of the agent's concurrency slots in the queued scope and gives it back on
  every path, including a retire or close while the activation is parked holding it.
- An activation keeps the restored boundary as the session's latest until it records its own, so a checkpoint taken
  while it waits before its first boundary exports it again instead of nothing.
- The elapsed time budget is sampled when a checkpoint exports an episode (`EpisodeRecord.elapsed_s`) and charged when
  its replacement begins, so an agent step in flight at the cut counts in full. The per-environment
  `checkpoint_elapsed` / `checkpoint_charge_elapsed` helpers and `SessionHandles.elapsed_s` are gone, and so is the
  environment server's `checkpoint_mode_in_effect`, which nothing overrode.
- An agent that grants MCP tools and does not declare `rebinds_tool_accesses` reports the restart on its own seed
  reply, before its session exists. single_agent_turn makes an episode that grants MCP tools without lending a sandbox
  a restart before seeding the agent, since only a borrowed sandbox's re-seed carries the replacement's token; its two
  checks of the agent's seed reply are one.
- Prepare carries an earlier stage's restarts before closing admission, so no worker wakes a restart's harness first.
- A release for a checkpoint older than the latest one a participant resumed is refused as stale.
- Startup refuses an export hook that cannot take `checkpoint_id` and an agent that declares
  `rebinds_tool_accesses` without overriding the re-bind hook.
- Docs: the `release_external_state` contract on both hooks, the MCP and re-seed behaviour in the single_agent_turn
  README, and `release` among the traced checkpoint operations.

Tests cover each, plus the gaps the review found: the borrowed-sandbox flag recorded by a real seed and a checkpoint
not waiting for the re-seed, the real resources release by mode and the export's checkpoint ID (one and two workers),
the retire and close wake-up of a park wait in a task of its own, and the default re-bind gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…, stale releases, restart rules, names

- `release` returns only once the external state is deleted, under the control lock and the request deadline. The
  participant docstring no longer allows returning before.
- A release is stale once the participant committed or restored a checkpoint after the one it names. A checkpoint
  aborted there no longer counts, so the release that ends a run is admitted after an abort. Once a process holds a
  checkpoint, a release that names one it never resumed is stale too, since it dates from before a restart. A
  release names the latest checkpoint the controller resumed.
- Status and discovery report `keeps_external_state`, so a controller that never releases can refuse to run or warn.
- A session granted MCP tools the agent cannot re-bind, or lent a sandbox the agent cannot re-bind, restarts
  whatever `_seed_restarts` returns: the hook only adds restarts, and its default adds none.
- With several workers a release fails unless every expected worker answered.
- The participants check that the export hook takes `checkpoint_id` when they are built, so code that builds one
  around its own hooks learns it at startup too.
- `EpisodeRecord` leaves `elapsed_s` out when nothing was spent, so a Gym from before the field restores the record.
- Names: the hook is `delete_external_state` and the docstrings say delete; the participants' first-seed restarts
  are `_first_seed_restarts`; the header is `x-ng-checkpoint-rebinds-tool-accesses` and its reader
  `seed_rebinds_tool_accesses`; "the cut" no longer names the moment a checkpoint exports an episode.
- Docs: `release` is listed among the control operations in the metrics page and the telemetry docstrings.

Tests cover each, plus the resources participant gaps the review found: a release between a restore and its
resume, resume clearing the first-seed restarts, and a seed that claims a restored session blocking prepare.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…s not re-bind exports the session

An agent that does not re-bind restored sessions now restarts a session lent a sandbox, so the tests of its
restored sessions and of its MCP restart seed a session without one. The test of a seed that claims a restored
session reads the phase of the prepare it holds up, and the test of an overriding restart hook seeds its second
session on its own client.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…l_state, and discover carries it

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre
pthombre force-pushed the pranav/envckpt-1-protocol branch from 3d2a27b to da72850 Compare November 12, 2026 17:51
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test da72850

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 12, 2026 17:52
@pthombre
pthombre added this pull request to the merge queue Nov 12, 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/43277627011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries 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.

5 participants