Repository navigation
fix(gymnasium): build Gymnasium servers on the shared resources server setup - #3895
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
cf53406 to
b25ea94
Compare
87e1f0c to
207f588
Compare
b25ea94 to
c1d3223
Compare
207f588 to
afee845
Compare
afee845 to
6a3c667
Compare
8cee79e to
dc25a06
Compare
f3ade85 to
ca27fd2
Compare
dc25a06 to
01cfa55
Compare
ca27fd2 to
f98be7a
Compare
c3fbf5f to
6bd5512
Compare
f98be7a to
beab099
Compare
c9f11b1 to
1470889
Compare
beab099 to
56eb43b
Compare
3baed96 to
726383b
Compare
b4bfe35 to
4d51770
Compare
726383b to
009480a
Compare
009480a to
a354cb3
Compare
2dd08b3 to
6bccbb0
Compare
3a8ddf3 to
dc6f470
Compare
6bccbb0 to
4b8212a
Compare
dc6f470 to
d83a4e0
Compare
4b8212a to
8a0c514
Compare
d83a4e0 to
9fd69f4
Compare
8a0c514 to
15bfbc3
Compare
9fd69f4 to
31ad088
Compare
…ous session hooks (NVIDIA-NeMo#3886) ## What changed and why Every resources server takes part in checkpoints once checkpointing is on, in one of three modes, declared with the `checkpoint_mode` class attribute: - `restart_only` (the default): nothing of a session is saved, so its rollout is a restart. It never blocks prepare, keeps running through the checkpoint, and is reported in prepare's `restarts`; the seed reply carries `x-ng-checkpoint-restart` so the environment server knows. After a crash the controller retires the rollout and starts it over from its input. Only a new session start waits while a checkpoint is open, so the restarts a prepare reported cannot change before its commit. A seed already in flight when admission closes is reported as a restart too, without waiting for it, because its reply will say restart; otherwise it would register during the checkpoint and the commit would fail with `restart_in_scope`. A waiting seed checks again each time it wakes, so a new checkpoint that closes admission before it runs keeps it waiting. - `stateless`: tool results depend only on the request, so nothing is exported. The weather example server uses it. - `exported`: the server implements the session hooks. The counter example server (`example_session_state_mgmt`) uses it. It exports only the sessions it still holds, so a dropped session is left out and the participant stops tracking it, instead of being exported as a new counter at zero. The session hooks are coroutines, and export takes every session at once: `export_session_states(session_ids)`, `restore_session_states(states)`, and `retire_session_state(session_id)`. A server whose session state lives outside the process, such as a sandbox per session, can snapshot all of it concurrently within the commit. A session missing from the export result is treated as already dropped (for example, after a failed verification) and is no longer tracked, instead of failing the commit. With `checkpoint_mode = "exported"`, a server that leaves any of these hooks as the base stub fails at startup; hooks from an intermediate base class or mixin count. `retire_session_state` is called in every mode, and its base version does nothing, so a `restart_only` or `stateless` server that keeps per-session state can free it on retire by overriding it. `checkpoint_mode` and `checkpoint_verify` are checked against their allowed values at startup, whether or not checkpointing is on. A typo such as `"exportd"` raises a `ValueError` naming the attribute, the value, and the allowed values, instead of acting as a fourth mode that exports nothing and reports no restarts. The session lifecycle comes from the server's session-start routes, `/close_session`, and `/verify`, keyed by the rollout attempt, so no request body is inspected. - **Declared session starts.** A server lists its session-start routes in `checkpoint_session_starts`, which defaults to `("/seed_session",)`; a Gymnasium-style server declares `/reset`. The checkpoint middleware treats every declared route as it treats `/seed_session`, before the handler runs: it waits out an open checkpoint in every mode, `restart_only` included, counts as a seed from admission, carries the seed reply headers, and binds the session when it succeeds. There is no other way to start a tracked session, so no start can slip in after a commit has fixed its scope. Sessions end through `/close_session`, or `checkpoint_session_ended` for a server that ends them elsewhere. - **A session start needs a rollout ID.** With checkpointing on, a session start without the `/ng-rollout/<id>` prefix is refused with 400 `rollout_id_required` before its handler runs, so no session can exist that the participant does not track. - **A resources server that bypasses the shared setup fails closed.** `SimpleServer.setup_checkpoint_participant(app)` runs for every server after `setup_webserver`. With checkpointing on, a resources server whose app did not install the checkpoint participant refuses to start, naming its class, instead of being silently left out of every checkpoint. Gymnasium servers on `main` build their own app, so they refuse to start with checkpointing on until NVIDIA-NeMo#3895 moves them onto the shared setup; with checkpointing off nothing changes. - **A session belongs to its attempt.** Any request on an existing session whose rollout prefix names an episode other than the session's is refused with `stale_attempt`, seeds excepted, so after a restore a replaced attempt's `/close_session` or `/verify` cannot end the replacement's session. A close from the owning attempt, including a retired attempt freeing its own session, still goes through. With checkpointing on, `/close_session` and `/verify` need the `/ng-rollout/<id>` prefix, as session starts do. - **A restored session needs its attempt named.** A request on a session a restore installed that names no attempt, with no rollout prefix and no MCP token, is refused with 400 `rollout_id_required`. The cookie alone cannot tell the replacement from the attempt the restore replaced. The refusal comes before the participant takes the session out of the restored sessions no request has used yet, so a refused call never claims one. Sessions seeded in the running process are not affected, and neither are restart-only servers, which never restore a session. - **Marking an attempt retired fences its sessions at once.** A retire or a restore that marks an attempt refuses the attempt's existing sessions before anything awaits, so a retire cut short by its deadline, or one that arrives after it and only marks, still leaves them refused, holding up readiness, and out of every export until a retried retire frees them. `forget` is refused while any tracked session of the rollout is at or below the retired mark. - **MCP tokens name their attempt.** With checkpointing on, the session token minted at seed carries an `episode` claim with the seeding attempt's capture key; with checkpointing off the token is unchanged. A call whose token names a fenced attempt, an attempt other than the session's, or no attempt gets 409 `stale_attempt` before its tool runs, and never claims a restored session. A restore therefore no longer lets the replaced attempt's harness keep using its token: the replacement gets a token by seeding under its own attempt with the session's cookie. `ResourcesParticipant.is_open(session_id)` reports whether a session is tracked and not fenced, for revocation at session close. - **Calls on closed or unknown sessions are out of scope.** A tool call that creates or changes state on a session that is closed or was never seeded is a session-lifecycle bug with checkpointing off as well, so it will be fixed on `main` for MCP and direct HTTP alike. - **Restarts reported by earlier prepare stages carry forward.** Coordination prepares stages in order (environment, model, agent, resources) and sends each later stage the restarts every earlier stage reported, as capture keys in a new optional `restarts` field of the prepare request. The commit leaves those episodes out, so a participant keeps them in `carried_restarts` until the checkpoint resumes, aborts or expires, and leaves them out of its blockers and its export. The resources participant no longer waits for requests in flight on their sessions, so an episode the environment server reported as a restart, for example from an MCP grant, keeps running through the checkpoint. Coordination sends the field only when an earlier stage reported a restart, and a prepare without it behaves as before. - **Commit cleanup after a restore costs as much as each rollout's own sessions**, through the rollout index, instead of scanning every restored session per episode. The `checkpoint_verify` class attribute declares whether `/verify` may run again after a crash (`replay`) or must finish before a checkpoint (`wait`, the default). The server reports it in the `x-ng-checkpoint-verify` header on every `/seed_session` reply and in its checkpoint status. A replayable `/verify` is admitted even after admission closes, because the checkpoint does not wait for the episode step that sends it. A `/seed_session` that arrives while a checkpoint is open waits for resume instead, and a seed already in flight holds up prepare and is exported. If the seed handler replaces the session ID, the session is tracked under the new one. The participant applies a seed, close, or verify to its session tracking as soon as the response starts, before the rest of the response is sent. A client that disconnects after the handler ran cancels the request, as an environment server's retire does to its calls in flight, and that cancellation can no longer leave a created session untracked or an ended one tracked. The environment server seeds inside a replay step that can finish while the checkpoint is open, so the session must match whichever boundary the environment server records. **Tools called over MCP** (`expose_tools_over_mcp: true`). A CLI agent harness calls tools over MCP with a signed session token and no session cookie. Before this change, such a server failed at startup with checkpointing on: MCP auto-exposure refuses middleware that direct MCP dispatch would skip, and the checkpoint middleware was one of them. - The checkpoint middleware works on the whole MCP request, so MCP auto-exposure accepts it. Admission and in-flight counting apply to the one POST that carries each tool call. - The middleware reads the session from the MCP session token, so a retire drains and refuses MCP calls like any other request on the session. The token key is deterministic, and the token's `episode` claim decides whether its attempt may still use it after a restore. - A request made while a checkpoint is open, over HTTP or MCP, waits for resume instead of getting a 409. It comes from a restart, which keeps running through a checkpoint, often a third-party harness that would pass the refusal to the model as a tool error. A waiting request is not in flight, so it does not hold up prepare. A replayable `/verify` is still admitted at once. - Checkpoint control routes are no longer harvested as MCP tools. **Ending sessions.** - `/close_session` is never refused. Closing is how a server frees a session's state. A close that arrives while a checkpoint is open, from an episode that ended during it, waits for resume as an MCP call does; a refusal would leave the session unfreed, since the environment server closes once. - A retire refuses the attempt's sessions, waits until no request is in flight on them (over HTTP or MCP), then frees them through `retire_session_state`, in every mode. A session stays tracked until its state is freed: a retire cut short by its deadline leaves it for a retry, and meanwhile it blocks the next checkpoint and is not exported. `retire_session_state` can therefore run again for the same session, and must tolerate state it already freed. The refusal lasts until the controller forgets the rollout: - a request that carries the rollout prefix is checked against the retired attempts, so a late `/seed_session` cannot create state nothing frees; - a tool call over MCP names only its session, so the retired session IDs are kept by rollout until `forget`, and counted in status as `retired_sessions`. - Every mode, `stateless` and `restart_only` included, records which attempt each session belongs to, so a retire drains and refuses their sessions too. Export and readiness still depend on the mode. - A retire waits for any `/seed_session` of the same rollout, up to the retired attempt, that is already admitted, then frees the session that seed created. A seed is counted at its admission, with no await in between, so a seed still waiting for resume cannot hold up the retire, and the retire's mark refuses it once it is admitted. Retire visits only the rollout's own sessions, through an index from rollout to sessions. - A seed can finish after its attempt was marked retired, for example when a retire's deadline passed while it waited for that seed. The session the seed created is then registered as retired at once instead of live: requests on it are refused, including MCP calls that carry only the session token, it is never exported, and it blocks checkpoints until a retried retire frees it. - `forget` is refused with `retire_incomplete`, changing nothing, while a retired session it targets is still tracked, or while a seed of a retired attempt of that rollout is still in flight; the controller retires again first. Forgetting during such a seed would clear the mark before the seed finished, and its session would then be bound as live. - A replayable `/verify` whose caller closes the session afterwards does not end it. The caller says so with the `x-ng-checkpoint-close-follows: 1` header, and the session stays tracked and exported until the `/close_session` that follows, a declared end, or a retire. A checkpoint can keep the environment server's boundary from before the verification even when the verification finishes before the resources server prepares, so the session must still be exported, and a restore runs the verification again against the restored state. `single_agent_turn`, the UserSim environment server, and the sandboxed Hermes agent send the header, since each closes the session in its final cleanup; Simple Agent's legacy `/run` sends it in NVIDIA-NeMo#3888. A `/verify` without the header, and a wait-mode `/verify`, end the session at once, so a caller that never closes cannot leave it tracked. - Unclaimed restored sessions, ones no request has used yet, are reported as pending, so a commit whose scope no longer continues their episode does not export them. It deletes them through `retire_session_state` without refusing anything later, since the controller may still start the rollout over as that attempt. A restored session that the server drops before any request uses it does not break the commit. - A commit exports only the live sessions whose episode is inside its scope, as it already did for restored sessions. The controller leaves every participant's restarts out of the scope, so a session another server reports as a restart is not exported here either. - The participant answers the readiness wait's `ready()` without building its blocker list, and admission refusals are the shared `AdmissionClosedError`. The MCP session token helpers live in `base_resources_server.py` and are shared with MCP auto-exposure. ## How it works ### Where this PR sits in the overall flow The highlighted part is what this PR adds. ```mermaid flowchart LR C["Controller<br/>NeMo RL, or rollout collection"] CO["Coordination<br/>prepare, commit, restore, resume,<br/>retire, forget"] K["Control plane on every server<br/>phases, lease, storage,<br/>retire: refuse, stop, free;<br/>forget"] subgraph G["One participant per Gym server"] E["Environment server<br/>episode steps"] M["Policy model<br/>held responses, generation cuts"] A["Agent<br/>sessions parked at boundaries"] R["Resources server<br/>session state"] end W["Inference worker<br/>stages cut prefixes"] D[("Checkpoint directory<br/>records, then manifest")] L[("Capture ledger<br/>retire and delete from NVIDIA-NeMo#3938, NVIDIA-NeMo#3939")] C --> CO --> K K --> E & M & A & R M --> W M --> L G --> D classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937 class R this ``` One checkpoint, a crash, and the restore, end to end: ```mermaid sequenceDiagram participant C as Controller participant G as Gym participants participant D as Checkpoint directory C->>G: prepare, in order environment, model, agent, resources Note over G: admission closes, in-flight work parks at a boundary,<br/>undelivered model responses are held G-->>C: prepared, or blockers at the deadline C->>G: commit with the episodes the controller continues G->>D: each participant writes its records, then its manifest Note over G: restored state the commit's scope leaves out is deleted C->>C: publish the checkpoint with the controller's own state C->>G: resume, in order resources, agent, model, environment Note over C,G: crash - every Gym process dies C->>G: restore the checkpoint in fresh processes, all or nothing D-->>G: records installed under attempt N+1, attempt N's capture ledger retired C->>G: resume C->>G: /run as attempt N+1 continues each episode from its boundary Note over C,G: retiring an episode, only while no checkpoint is open C->>G: retire - environment, then agent, then model and resources Note over G: each server marks the attempt, stops its work, waits, frees its state, then replies C->>G: forget, once the rollout is done for good - same order Note over G: the mark refusing the retired attempt goes away ``` ### This PR How a resources server takes part, chosen by a class attribute. ```mermaid flowchart TD M{"checkpoint_mode"} -->|stateless| S["Nothing to export.<br/>Never blocks a checkpoint."] M -->|exported| X["export_session_states at commit<br/>restore_session_states after a crash<br/>retire_session_state on retire"] M -->|"restart_only, the default"| O["Its rollout is a restart: reported in prepare,<br/>never blocks, starts over after a crash"] ``` A session's lifecycle, as the participant learns it from the routes that already define it. ```mermaid sequenceDiagram participant E as Environment server or agent participant R as Resources server E->>R: /seed_session for rollout r R-->>E: session cookie, plus x-ng-checkpoint-verify - wait or replay E->>R: tool calls - wait while a checkpoint is open E->>R: /verify, with x-ng-checkpoint-close-follows if replayable E->>R: /close_session from final cleanup, which waits for resume if a checkpoint is open ``` Retire drains a session before freeing it. ```mermaid sequenceDiagram participant C as Controller participant R as Resources server C->>R: retire(r, N) Note over R: refuse the attempt's sessions, except /close_session Note over R: wait until no request is in flight on them, over HTTP or MCP Note over R: retire_session_state for exported servers, stop tracking R-->>C: stopped and freed ``` ## Where this sits in the stack This is one PR in a stack of draft PRs that re-cut partial-rollout checkpointing onto environment servers. Each PR is one commit, and its base is the branch of the PR before it, so each diff shows only that PR's change. The stack builds on the token-capture cleanup PRs NVIDIA-NeMo#3938 (capture ledger `retire` and `delete`) and NVIDIA-NeMo#3939 (complete-record `retire` and `delete`), which have merged. NVIDIA-NeMo#3882 to NVIDIA-NeMo#3885 have merged too, so NVIDIA-NeMo#3886's base is `main`. The checkpoint stack uses those operations to free the ledgers of retired attempts and to clear a dead execution's capture files before a restore. The capture-ledger cache bound (NVIDIA-NeMo#4268) and the striped lock files (NVIDIA-NeMo#3937) are independent of the stack. 1. NVIDIA-NeMo#3882 (`ananthsub/partial-ckpt-core`): feat(checkpoint): add the participant control plane, episode steps, and coordination (merged) 2. NVIDIA-NeMo#3883 (`ananthsub/partial-ckpt-policy-model`): feat(checkpoint): make policy model servers checkpoint participants with generation cuts (merged) 3. NVIDIA-NeMo#3884 (`ananthsub/partial-ckpt-model-worker-cuts`): feat(token-capture): add worker staging helpers for generation cuts (merged) 4. NVIDIA-NeMo#3885 (`ananthsub/partial-ckpt-environment`): feat(checkpoint): continue environment server episodes from their boundaries (merged) 5. NVIDIA-NeMo#3886 (`ananthsub/partial-ckpt-resources`): feat(checkpoint): add the resources server participant with asynchronous session hooks **(this PR)** 6. NVIDIA-NeMo#3887 (`ananthsub/partial-ckpt-verifier-declarations`): feat(checkpoint): declare twenty training verifiers stateless with replayable verification 7. NVIDIA-NeMo#3888 (`ananthsub/partial-ckpt-agent`): feat(checkpoint): add the agent session participant and Simple Agent continuation 8. NVIDIA-NeMo#3889 (`ananthsub/partial-ckpt-e2e`): test(checkpoint): add a process-level end-to-end suite driven by coordination 9. NVIDIA-NeMo#3893 (`ananthsub/partial-ckpt-rollout-collection`): feat(checkpoint): checkpoint evaluation runs from rollout collection 10. NVIDIA-NeMo#3903 (`ananthsub/partial-ckpt-telemetry`): feat(checkpoint): spans and metrics for partial-rollout checkpoints 11. NVIDIA-NeMo#3909 (`ananthsub/partial-ckpt-multi-worker`): feat(checkpoint): resources, agent, and environment servers with several workers 12. NVIDIA-NeMo#4197 (`ananthsub/partial-ckpt-fault-tests`): test(checkpoint): check checkpoint invariants over random sequences of operations Partial-rollout checkpointing lets a training controller, such as NeMo RL, checkpoint Gym while rollouts are in flight and, after a crash, continue those rollouts from their last safe point instead of starting them over. Checkpointing is off by default; with the `checkpoint:` block unset, no server installs any checkpoint routes or behavior. ## Relationship to the old stack (NVIDIA-NeMo#2939 to NVIDIA-NeMo#2946) - Supersedes NVIDIA-NeMo#2945 (resources state participant). Route classification, mutation receipts, revision reconciliation, and the terminal context variable are gone; the prepare order (agents park before resources servers close) makes them unnecessary. - Takes the counter adapter from NVIDIA-NeMo#2946. The Blackjack and Workplace Assistant adapters are not carried: Blackjack moves to a separate Gymnasium PR, and Workplace Assistant can be ported onto these hooks later. ## Issue No tracking issue exists for this re-cut. The design and the mapping from the old stack are described in this PR series, and the old stack's PRs (NVIDIA-NeMo#2939 to NVIDIA-NeMo#2946) carry the original discussion. ## Validation Run on this branch, on the current `main`: - `test_each_prepare_stage_carries_the_restarts_every_earlier_stage_reported` and `test_a_request_in_flight_for_a_restart_an_earlier_stage_reported_does_not_hold_up_prepare`, each failing without its change: later stages get the earlier stages' restarts, the restarts are cleared at resume, and a resources request in flight for such an episode no longer holds up prepare. - This round's tests, each failing without its change: `test_a_retire_cut_short_while_a_seed_is_in_flight_still_fences_the_attempt_s_existing_session`, `test_a_retire_that_arrives_after_its_deadline_still_fences_the_attempt_s_sessions`, `test_after_a_restore_a_close_from_the_replaced_attempt_is_refused_and_keeps_the_session`, `test_a_request_on_a_session_from_another_rollout_is_refused`, `test_a_session_end_without_a_rollout_prefix_is_refused_before_its_handler_runs`, `test_deleting_one_rollout_s_restored_sessions_does_not_scan_every_restored_session`, `test_a_restore_refuses_the_replaced_attempt_s_token_and_a_seed_of_the_replacement_gets_one_that_works`, `test_a_stale_harness_cannot_create_state_for_a_session_the_fresh_process_never_saw`, `test_a_token_without_an_attempt_is_refused_when_checkpointing_is_on`, `test_a_second_restore_refuses_the_first_replacement_s_token`, `test_a_refused_stale_call_does_not_claim_a_restored_session`, `test_a_token_minted_with_checkpointing_names_the_attempt_that_seeded_it`, and the `is_open` tests; `test_a_token_minted_without_checkpointing_names_only_its_session_and_tools` guards the unchanged token with checkpointing off. - `test_a_declared_session_start_during_a_commit_s_export_waits_for_resume`, in all three modes: a declared `/reset` arriving while the commit is in export waits for resume, and the commit has no record for it (without the fix, the `restart_only` reset finished during the checkpoint); `test_a_restart_only_declared_session_start_in_flight_is_reported_as_a_restart` (without the fix, prepare reported no restart). - `test_a_session_start_without_a_rollout_prefix_is_refused_before_its_handler_runs`, for `/seed_session` and `/reset` (without the fix, a 200 that created untracked state). - `test_a_resources_server_whose_app_left_out_the_checkpoint_participant_refuses_to_start` and `test_a_resources_server_whose_app_installs_the_participant_passes_the_startup_check`, including a server with its own app starting with checkpointing off. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit_tests/test_checkpoint_*.py`: passed, including, each failing without its change: - a `/close_session` during a checkpoint waits for resume, then ends the session; - a retire waits for the session's request in flight, and refuses a new one meanwhile; - a commit whose scope leaves out a restored session retires it through the server's hook; - a session whose retire was cut short in the server's hook stays until a retry frees it, and blocks prepare meanwhile; - a seed arriving during an open checkpoint waits for resume, and a seed in flight when admission closes holds up prepare and is exported; - a retire waits for an admitted seed of its attempt and frees the session it creates, and a seed still waiting out a restore does not hold up the retire; - `forget` is refused while a retire has not freed its sessions; - a replayable `/verify` whose caller closes afterwards keeps the session tracked and exported until the close, including one that finishes between environment and resources prepare, after which a restore verifies again and closes it; - a replayable `/verify` without the close-follows header, and a wait-mode `/verify` with or without it, end the session at once; - after a restore, a call under the replaced attempt's prefix is refused with `stale_attempt` and a cookie-only call with `rollout_id_required`, across two restores, and neither changes the restored state or claims the session; - a stateless server drains and refuses a retired session; - deleting an unclaimed restored session refuses nothing later, and a restored session the server drops does not break the commit; - a request cancelled while notifying is no longer counted; - a session whose ID the seed replaces is tracked under its new ID; - an exported server without its hooks fails at startup; - retiring one rollout does not scan every session, and `ready()` does not list blockers; - in `restart_only` mode, a seed in flight when admission closes is reported as a restart by prepare, its reply says restart, and the commit of the remaining scope succeeds; - in `restart_only` mode, a seed waiting for resume waits again when a new checkpoint closes admission before it runs; - a seed, close, or verify whose reply has started still updates the session tracking when the request is cancelled before the reply finishes: the seeded session is tracked, and the closed or verified one is not; - an unknown `checkpoint_mode` or `checkpoint_verify` fails at startup; - a retire frees the sessions of `restart_only` and `stateless` servers through `retire_session_state`; - a commit does not export live sessions outside its scope; - a seed that finishes after its retire was cut short while waiting for it leaves a retired session: a request with only the session cookie is refused with `stale_attempt`, a checkpoint does not export it, `forget` is refused with `retire_incomplete`, and a retried retire frees it, after which `forget` succeeds; - `forget` is refused with `retire_incomplete` while a seed of a retired attempt is in flight, and the session that seed creates is refused afterwards. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider tests/unit_tests/test_mcp_auto_exposure.py tests/unit_tests/test_checkpoint_resources_mcp.py`: passed. The MCP checkpoint tests go through the real control routes and MCP JSON-RPC: - a tool call during a checkpoint waits and runs after resume, and the checkpoint holds the state from before it; - a tool call in flight holds up prepare; - a retire waits for a tool call in flight over MCP; - a restored server refuses the replaced attempt's token, and a seed under the replacement gets one that continues the session; - control routes are not tools. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider resources_servers/example_session_state_mgmt/tests`: passed, including a new test that the counter example leaves a session it no longer holds out of its export. - `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider resources_servers/example_single_tool_call/tests`: passed. - `environment_servers/single_agent_turn/tests`, `environment_servers/nemo_user_sim/tests` (in its own environment, with the UserSim package) and `responses_api_agents/hermes_sandboxed_agent/tests`: passed, including that `/verify` says the session is closed afterwards. - The Codex, OpenClaw, OpenCode, and Pi agent tests, each in its own environment: passed, except one Pi test that needs a newer Node.js than this machine has and fails the same way on `main`. - The full core unit suite (`tests/unit_tests`, eight processes, without `test_opensandbox_compose.py`, which needs the optional `opensandbox` package): passed except a sandbox retry test, which fails the same way on `main` in this development environment. - `pre-commit run --files <files changed by this PR>`: all hooks passed, and no hook modified a file. - Every commit carries a `Signed-off-by` line. ## Rollout evidence - Process-level evidence is in the top PR: restored counter state is required for the right reward, with a negative control that skips the resources restore and gets reward 0.0. - **Real model:** see the rollout evidence in NVIDIA-NeMo#3889, whose opt-in tests drove this PR's code with `Qwen/Qwen3-4B-Instruct-2507` on vLLM: saved rollouts continued after a kill and restore, restarts started over, and every rollout finished with reward 1.0. Its restart test uses a `restart_only` resources server. ## Compatibility - New resources server hooks and class attributes: `checkpoint_mode`, `checkpoint_verify`, `export_session_states`, `restore_session_states`, `retire_session_state`, `checkpoint_session_starts`, `checkpoint_session_ended`, and the `setup_checkpoint_participant` startup check. All are new; existing servers need no change and default to `restart_only` with `wait` verification. - An unknown `checkpoint_mode` or `checkpoint_verify` value raises a `ValueError` at startup, even with checkpointing off. - With checkpointing on, a retire calls `retire_session_state` in every mode, not only `exported`, and the base hook does nothing. A `restart_only` or `stateless` server that already overrides it must expect the call. - The prepare control request has a new optional `restarts` field. A participant from an older Gym build would refuse a prepare that carries it, which coordination sends only when an earlier stage reported a restart; within one deployment every server runs the same build. - A commit exports only the live sessions inside its `episode_ids` scope. A commit request without `episode_ids` still exports every live session. - `/seed_session` replies carry a new `x-ng-checkpoint-verify` header when checkpointing is on. - With checkpointing on, a caller that runs a replayable `/verify` and then closes the session should send `x-ng-checkpoint-close-follows: 1` on `/verify`; without it the session ends at the verification, as before. - With checkpointing on, a request on a restored session must carry its attempt's rollout prefix or MCP token; a cookie-only request is refused with `rollout_id_required`. - Nothing changes unless the global `checkpoint:` block sets `enabled: true`. Signed-off-by: Ananth Subramaniam <[email protected]>
31ad088 to
53aa609
Compare
cb18c76 to
7d6dbc2
Compare
…r setup GymnasiumServer built its own FastAPI app and copied part of the shared resources server setup, so it never served /reverify_mode and, with checkpointing on, never installed the checkpoint participant. Split SimpleResourcesServer.setup_webserver into create_resources_app (middleware, checkpoint participant, /aggregate_metrics, /reverify_mode) and register_protocol_routes (/seed_session, /close_session, /verify). GymnasiumServer now overrides only the protocol routes with /reset and /step. GymnasiumServer declares /reset in checkpoint_session_starts, so a reset passes the same checkpoint admission boundary as /seed_session. A terminal /step reports the session's end through checkpoint_session_ended, as does OpenAir's optional /close. Gymnasium servers stay restart_only unless a subclass declares checkpoint_mode = "exported"; the base then exports and restores session_state per session through the overridable export_env_state and restore_env_state hooks. Signed-off-by: Ananth Subramaniam <[email protected]>
zyzhou5
left a comment
There was a problem hiding this comment.
Generally LGTM.
Though my agent suggests that this PR exposes an OpenAir cleanup issue: retirement can time out after deleting the session record but before releasing backend resources, causing a retry to incorrectly report success.
We should add a follow-up PR for OpenAir to fix that.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39345132753 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39351545527 |
|
Rollout evidence rerun on vLLM 0.29.0, the version Gym's The tree was
No server log had a traceback. |
ananthsub/partial-ckpt-gymnasiummainbug,area:env-infraWhat changed and why
GymnasiumServer.setup_webserverbuilt its FastAPI app from scratch and copied part ofSimpleResourcesServer.setup_webserver: the session middleware,RolloutContextMiddleware, and/aggregate_metrics. Every Gymnasium environment inherited that copy (blackjack, example_multi_turn_gymnasium, grl_sokoban, grl_tetris, indian_banking, openair_congestion, tales, wordle), so anything added to the shared setup skipped them:GET /reverify_modereturned 404, so reverification failed with an HTTP error instead of reporting these servers.This PR:
SimpleResourcesServer.setup_webserverintocreate_resources_app()(session and rollout middleware, the checkpoint participant,/aggregate_metrics,/reverify_mode) andregister_protocol_routes(app)(/seed_session,/close_session,/verify).setup_webservercalls both, so servers that callsuper().setup_webserver()and add routes are unchanged.GymnasiumServeroverride onlyregister_protocol_routes, registering/resetand/step. It still exposes no/seed_sessionor/verify./resetincheckpoint_session_starts, so a reset passes the same checkpoint admission boundary as/seed_session: it needs a rollout prefix, waits out an open checkpoint in every mode,restart_onlyincluded, and binds its session when it succeeds. A terminal or truncated/stepcallscheckpoint_session_ended(request)afterclose_session. Building on the shared setup is also what lets Gymnasium servers pass feat(checkpoint): add the resources server participant with asynchronous session hooks #3886's startup check, which refuses a resources server that left out the checkpoint participant. OpenAir's optional/closeroute also ends the session, since the agent calls it after a failed episode.restart_onlyby default, so a live session's rollout is a restart: it never blocks prepare, keeps running through the checkpoint, and starts over after a crash. A retire still frees the session: the base'sretire_session_statecallsclose_session, and feat(checkpoint): add the resources server participant with asynchronous session hooks #3886 calls that hook in every mode. Without it, a restart-only session would never be released, because the late terminal/stepthat would have closed it is refused withstale_attempt. A subclass opts in withcheckpoint_mode = "exported". The base then implements the session hooks oversession_state, one session at a time, through two overridable methods:export_env_state(state)returns JSON for one session. The default copies state that is already JSON and fails the commit otherwise.restore_env_state(state)rebuilds one session and raises on invalid input. All sessions are converted before any is installed.close_session, in every mode, so subclass cleanup still runs.Servers that keep per-session state outside
session_state(grl_sokoban and grl_tetris keep it insession_id_to_state) must override the three session hooks themselves before opting in. No environment opts in here; Blackjack does in the next PR./reverify_modereports the configured mode,unknownby default. Reverification treatsunknownandunsupportedthe same way, so this PR does not change the Gymnasium config./stepwithstale_attempt; after that, the step can reach the server. The test environment answers it with 404. Other Gymnasium-based servers onmainthat index their state by session ID can still fail with a server error on such a step; making the shared base answer it is a follow-up.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, restore, resume,<br/>retire, forget"] K["Control plane on every server<br/>phases, lease, storage,<br/>retire: refuse, stop, free;<br/>forget"] subgraph G["One participant per Gym server"] E["Environment server<br/>episode steps"] M["Policy model<br/>held responses, generation cuts"] A["Agent<br/>sessions parked at boundaries"] R["Resources server<br/>session state"] end W["Inference worker<br/>stages cut prefixes"] D[("Checkpoint directory<br/>records, then manifest")] L[("Capture ledger<br/>retire and delete from #3938, #3939")] C --> CO --> K K --> E & M & A & R M --> W M --> L G --> D classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937 class R thisOne checkpoint, a crash, and the restore, end to end:
This PR
Gymnasium servers built their app from scratch and skipped the shared setup, so they had no checkpoint participant and no
/reverify_mode. They now build on the shared setup and only add their own routes.A Gymnasium session's lifecycle, reported to the participant. Environments are restart-only unless they opt in to
exported.Where this sits in the stack
This PR uses the resources server checkpoint participant from #3886, which has merged, and needs nothing else from the open part of the partial-rollout checkpointing stack. It is one of five PRs that port the environments the old stack checkpointed onto the new hooks. Workplace Assistant and the Gymnasium fix target
main, and Blackjack builds on the Gymnasium fix. Indirect prompt injection and proof refinement are still based on the end-to-end suite (#3889):ananthsub/partial-ckpt-workplace-assistant): feat(checkpoint): checkpoint Workplace Assistant sessionsananthsub/partial-ckpt-gymnasium): fix(gymnasium): build Gymnasium servers on the shared resources server setup (this PR)ananthsub/partial-ckpt-blackjack): feat(checkpoint): export Blackjack game state for partial-rollout checkpoints (on the Gymnasium PR)ananthsub/partial-ckpt-indirect-prompt-injection): feat(checkpoint): export indirect prompt injection session stateananthsub/partial-ckpt-proof-refinement): feat(checkpoint): continue proof refinement agent turns from their boundariesRelationship to the old stack
The old stack's Gymnasium base called
super().setup_webserver()and so also exposed/seed_sessionand/verify. It mapped routes to lifecycle kinds, kept an execution-to-session map, and exported each attempt's state by rollout ID. This PR drops the route classification and the execution map: the v2 participant keys sessions by the cookie session ID, and/resetand the terminal/stepreport the lifecycle explicitly. The JSON-copy default export and the overridable per-session conversion carry over.Issue
No separate issue. The shared-setup split follows the earlier Gymnasium proposal in the checkpoint design; the checkpoint participant needs one place to install itself on every resources server.
Validation
Run on this branch, on the current
main:/resetarriving while a checkpoint is open waits for resume, that a/resetwithout a rollout prefix is refused, and that the startup check finds the participant; the first two fail without feat(checkpoint): add the resources server participant with asynchronous session hooks #3886's declared session starts.RAY_TMPDIR=/tmp python -m pytest -q resources_servers/gymnasium/tests: passed. New tests pin the route table (protocol routes plus/aggregate_metricsand/reverify_mode), check that/reverify_modeis served, that the participant is installed, that arestart_onlysession is reported as a restart, neither blocks prepare nor waits during it, and, for an exported test environment, commit and restore into a fresh server, continue to the same reward, invalid state installs nothing, a retired session is closed, so a later step is refused withstale_attemptrather than recreating the episode, and a session the server dropped is left out of the export. A new test retires a Blackjack and an ExampleMultiTurn session, bothrestart_onlyhere, and then sends the terminal step that would have released them: the step is refused, and the retire has already released the session's state.db.jsondataset file is not present)python -m pytest -q responses_api_agents/gymnasium_agent/tests: passed.RAY_TMPDIR=/tmp python -m pytest -q tests/unit_tests/test_checkpoint_*.py: passed.RAY_TMPDIR=/tmp python -m pytest -q tests/unit_tests: passed, except one OpenSandbox compose test, which needs the optionalopensandboxpackage that is not installed locally, and is unrelated.ruff check,ruff format, andpre-commit run --fileson the changed files.Rollout evidence
Setup
The model was
Qwen/Qwen3-4B-Instruct-2507, served by vLLM 0.24.0 with thehermestool-call parser on one NVIDIA RTX 6000 Ada Generation (48 GB).Gym's
vllm_modelserver ran withuses_reasoning_parser=false, because the served model is an instruct model without a reasoning parser.Every rollout sampled at temperature 1.0.
Each tree ran in its own worktree, with server venvs created by
gym env start.Before and after, checkpointing off
Blackjack and Wordle ran through
gymnasium_agentwith their own configs and example data, once onmainat717c04a3b3and once with this change on top of it.Both runs of each environment used the same command:
gym env start --config resources_servers/blackjack/configs/blackjack.yaml --model-type vllm_model \ --model Qwen/Qwen3-4B-Instruct-2507 --model-url http://127.0.0.1:8100/v1 --model-api-key dummy \ ++policy_model.responses_api_models.vllm_model.uses_reasoning_parser=false gym eval run --no-serve --config resources_servers/blackjack/configs/blackjack.yaml --model-type vllm_model \ --model Qwen/Qwen3-4B-Instruct-2507 --model-url http://127.0.0.1:8100/v1 --model-api-key dummy \ ++policy_model.responses_api_models.vllm_model.uses_reasoning_parser=false \ --agent blackjack_gymnasium_agent --input resources_servers/blackjack/data/example.jsonl \ --output rollouts.jsonl --num-repeats 20 --concurrency 16 --temperature 1.0Wordle used
resources_servers/wordle/configs/wordle.yaml,--agent wordle_gymnasium_agent, itsexample.jsonland--num-repeats 6.Its word lists are not committed, so
python resources_servers/wordle/generate_data.pyran first; it leftexample.jsonlunchanged.mainmainBlackjack deals from an unseeded random number generator, so the two runs play different hands and only their distributions can be compared.
A chi-square test on the four Blackjack outcomes gives p = 0.86, so the distributions are consistent with each other.
The trajectories have the same shape: a game takes one to four model turns, with 2.0 output items per rollout on
mainand 1.8 with this change.Wordle pins each row's target word, so both runs played the same five words six times each.
The model lost every game in both runs, and the trajectories match closely: 180
submit_guessand 45get_game_statecalls in each run.Every rollout in all four runs ended with
terminatedset and no failure or masked sample.The server logs show no tracebacks and no error responses.
With the servers up, the Blackjack resources server answers
GET /reverify_modewith 404 onmainand with 200 with this change./resetand/aggregate_metricsbehave the same on both trees, and/seed_sessionand/verifystay unregistered.Checkpointing on
The checkpoint hooks of this change ran with Blackjack in the restart test described in the #3896 evidence.
That run used this change and #3896 cherry-picked onto the checkpoint stack (
ananthsub/partial-ckpt-e2e), with real server processes and the same model.The Blackjack resources server tracked a session for every game from its
/reset: it reported 66 sessions while 66 games were in flight at the checkpoint.After 120 games, including the 66 that were retired and played again, it held no sessions, so every terminal
/stepand every retire ended its session.What is not covered
Its change only reports the session's end after its optional
/close.It stays
restart_only, the same mode Blackjack's games take throughgymnasium_agent.gymnasium_agentcannot continue an episode, so every Gymnasium episode caught by a checkpoint restarts from its input.Unit tests cover the base class's export and restore of
session_state.Compatibility
GET /reverify_mode; reverification now reports these servers instead of failing with a 404.SimpleResourcesServer.setup_webserverkeeps its behavior and route set. Subclasses may now overrideregister_protocol_routesinstead of rebuilding the app.