Skip to content

feat(checkpoint): add resources state participant - #2945

Closed
ananthsub wants to merge 5 commits into
ananthsub/checkpoint-gymnasium-agentfrom
ananthsub/checkpoint-resources-base
Closed

ananthsub wants to merge 5 commits into
ananthsub/checkpoint-gymnasium-agentfrom
ananthsub/checkpoint-resources-base

Conversation

@ananthsub

@ananthsub ananthsub commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Note

This checkpoint implementation is experimental. Its Python modules live under nemo_gym._checkpoint; they are not a supported public import surface yet.

Summary

  • serialize per-execution resources mutations against checkpoint export
  • bind stateful sessions only after successful creation and track revisions under stable execution identity
  • add authenticated prepare, status, commit, restore, resume, and retire operations
  • fence MCP dispatch and unknown stateful POST routes through the same mutation contract

Why resources state needs its own participant

An agent boundary is not sufficient for a stateful environment. The resources server may hold a Python object, random-number state, table, sandbox handle, or other session data that changed during the completed turn. This PR provides the shared lifecycle for exporting that state consistently.

Mutation and checkpoint ordering

sequenceDiagram
    participant A as Agent
    participant R as Resources middleware
    participant S as Environment session
    participant C as Checkpoint controller
    participant D as Controller-provided directory

    A->>R: mutation with rollout ID and attempt
    R->>R: require a bound session and acquire its lock
    R->>S: apply mutation
    S-->>R: successful response
    R->>R: increment state revision and release lock
    R-->>A: response with revision header

    C->>R: prepare(checkpoint_id)
    R->>R: close new mutation admission
    R->>R: reject untracked stateful traffic
    R->>R: acquire every live session lock
    R->>S: export each frozen session
    R-->>C: prepared snapshot set
    C->>R: commit(checkpoint_id, directory)
    R->>D: write server-namespaced snapshots, then manifest last
    R-->>C: manifest path and digest
Loading

Restore validates the complete snapshot set before calling the environment restore hook. A process that already served stateful traffic cannot accept restored state, because existing memory could be silently mixed with the checkpoint. A fresh restore process starts paused and installs all replacements under attempt N+1 before explicit resume.

/verify participates in the mutation lock because verification can consume or delete session state. A failed verification does not retire the session; a successful terminal response does. Unknown POST data routes default to mutation so a newly added stateful endpoint cannot bypass checkpoint fencing. Control, metrics, and MCP transport routes are classified separately; MCP tool dispatch re-enters the signed execution identity and mutation path.

Stack

Test plan

  • resources participant lifecycle and authenticated status tests
  • atomic restore, unsafe restore, failed start, failed verify, retirement, and stale-attempt tests
  • MCP fencing and revision-accounting tests

Generation-safe checkpoint update

  • adds durable exact-once mutation receipts and revision reconciliation
  • replays uncertain deliveries without re-executing and poisons incomplete mutations
  • hashes semantic request inputs and leaves fail-closed tombstones after bounded eviction

Layer validation: 64 tests passed.

@copy-pr-bot

copy-pr-bot Bot commented Sep 1, 2026

Copy link
Copy Markdown

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.

@ananthsub ananthsub changed the title ananthsub/checkpoint resources base feat(checkpoint): add resources state participant Sep 1, 2026
@ananthsub

Copy link
Copy Markdown
Contributor Author

Related to the performance roadmap in #2998. The resources participant adds explicit successful-session retirement and provides lifecycle groundwork for the default cleanup contract proposed in #3037.

@ananthsub
ananthsub force-pushed the ananthsub/checkpoint-resources-base branch 2 times, most recently from 5b14945 to c440ce3 Compare September 3, 2026 11:12
@ananthsub
ananthsub force-pushed the ananthsub/checkpoint-resources-base branch from c440ce3 to bda1faf Compare September 10, 2026 20:48
@ananthsub
ananthsub force-pushed the ananthsub/checkpoint-resources-base branch from bda1faf to 2a33eb4 Compare September 22, 2026 17:29
@ananthsub
ananthsub removed this pull request from stack #2947 September 22, 2026 17:31
@ananthsub
ananthsub added this pull request to stack #3623 September 22, 2026 17:32
Serialize per-attempt mutations, export all known sessions as one prepared cut, and require environments to atomically activate the complete restored state set.

Signed-off-by: Ananth Subramaniam <[email protected]>
Bind state to execution identity, serialize mutations with snapshots, and reject unsafe restore or untracked stateful traffic.

Signed-off-by: Ananth Subramaniam <[email protected]>
boundary_index = 0
invocation_status = "completed"
model_server_cookies = None
resource_revision = 0

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.

There seems to be a mismatch between this initialization of resource revision and the one created by seed_session.


while turn_index < self.config.max_steps:
if resource_request_id is None:
turn_index += 1

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.

When restoring a pending action with turn_index == max_steps, this loop never runs, so the final action is skipped.

restore_expected: bool = False,
max_receipts_per_session: int = 1024,
max_retired_receipt_sessions: int = 1024,
max_evicted_receipt_tombstones: int = 4096,

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.

Are these reasonable numbers to use? Or should we actually have a mechanism to clear those history so it won't block new requests.

# A retired session is no longer part of the cut.
if revision is None:
continue
state = await self._export_state(rollout_id, attempt_index)

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.

My agent suggests:

A tool can change state and fail while prepare() waits, but this currently exports that state and reports success.

Not sure how important this is in a real run

dims pushed a commit to dims/Nemo-Gym that referenced this pull request Oct 15, 2026
…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]>
@ananthsub

Copy link
Copy Markdown
Contributor Author

Closing: this first prototype is replaced by the environment server checkpoint stack tracked in #3024.
This PR's part is covered by #3886, the resources server participant.
The status section of #3024 lists the whole stack and what is merged.

@ananthsub ananthsub closed this Oct 19, 2026
@ananthsub
ananthsub deleted the ananthsub/checkpoint-resources-base branch October 19, 2026 20:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants