Skip to content

refactor(checkpoint): move rollout checkpointing out of the single controller (design proposal) - #4879

Draft
terrykong wants to merge 29 commits into
mainfrom
terryk/sc-environment-checkpoint-seam
Draft

terrykong wants to merge 29 commits into
mainfrom
terryk/sc-environment-checkpoint-seam

Conversation

@terrykong

@terrykong terrykong commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do ?

Moves rollout checkpointing out of single_controller.py into one component the controller calls, in five commits. Each commit keeps behavior the same and can be read on its own, so you can watch the file shrink.

This is a draft design proposal against #4500's branch, not a request to merge as-is. @macandro96, the goal is to agree on the shape before more recovery code lands in the controller.

Why

single_controller.py is the GRPO/PPO loop: a train pump and a rollout pump. Partial rollout checkpointing grew inside it, one level at a time: #3480, #3923, #3924, #3925, and now #4500 (+642 / −53 lines in the controller). At #4500 the file is 6,446 lines, and about 2,000 of them are checkpoint and recovery code. That causes four problems:

  1. There is no single off switch. Five settings control the feature. With checkpointing.enabled and a replay-capable sampler, save_data_plane and ledger-tracked dispatch are forced on.
  2. The loop has two copies of dispatch. _rollout_pump and _drain_reserve_into_steps each have a recovery path and a plain path, chosen by ten if self._rollout_recovery_enabled: branches.
  3. Two save paths repeat each other. _save_checkpoint_impl repeats the TQ capture and sidecar writes the rollout-snapshot path already has.
  4. The controller knows it talks to NeMo Gym. It built the coordinator, owned Gym's dispatch gate, retired and forgot Gym episodes, parsed gym_checkpoint.json, and branched on whether a Gym coordinator existed. A run on another environment backend would carry all of it. (fix(checkpoint): harden Gym turn recovery for failures and scale #4501 adds another one, _summarize_gym_episodes.)

The commits

# Commit single_controller.py
#4500's head 6,446
1 Move Gym checkpoint code behind an EnvironmentCheckpoint interface (+ design doc) 6,032 (−414)
2 Backend-neutral names in the ledger and rollout manager; interfaces become abc.ABC 6,032 (±0)
3 Snapshot writer, snapshot pump, save lock and commit window into RolloutCheckpointing 5,270 (−762)
4 Restore chain into RolloutCheckpointing.restore() 4,656 (−614)
5 One dispatch loop through reservation() 4,593 (−63)

Total: 6,446 → 4,593 lines (−1,853, −29%). if self._rollout_recovery_enabled branches: 10 → 0. The controller has no Gym checkpoint names left.

Where the code went

SingleControllerActor                          train pump + rollout pump
  └─ RolloutCheckpointing (abc.ABC)            nemo_rl/algorithms/rollout_checkpointing/
       ├─ DataPlaneRolloutCheckpointing        snapshot writer, pump, save lock, commit window
       ├─ NoRolloutCheckpointing               saves nothing; restore still runs
       ├─ RolloutRestorer                      restore chain, shared by both
       ├─ PromptDispatch                       ledger-recorded or plain reservations
       └─ EnvironmentCheckpoint (abc.ABC)      nemo_rl/experience/environment_checkpoint.py
            ├─ GymEnvironmentCheckpoint        nemo_rl/environments/
            └─ NoEnvironmentCheckpoint

New code: rollout_checkpointing/ is 2,717 lines in seven files; the environment interface, Gym implementation and backend picker are 805 lines.

What the controller calls now:

Call Replaces
restore() -> RestoreReport, applied by _apply_restore_report() the _maybe_restore_* chain and five restore-only fields
redispatch_restored(launch, admit) _redispatch_restored_rollouts
background_tasks(), stop_requested the hard-wired snapshot pump and stop event
optimizer_commit(drain_snapshot=...) the save lock, _begin_optimizer_commit and the commit flag/event
trainer_checkpoint(), save_with_trainer_checkpoint(...) the duplicated TQ capture and sidecar writes in _save_checkpoint_impl (223 → 130 lines)
reservation(kind) → PromptReservation the second dispatch loop and the _rollout_recovery_enabled branches
records_prompt_groups the _rollout_recovery_enabled flag

The component never reads or writes controller fields. It asks through a small host adapter (train_steps, trainer_version, current_epoch, rollout_state(), log_telemetry_metrics) and returns what restore found in a RestoreReport.

Things worth a look

  • Old checkpoints still restore. Step 2 renamed the ledger's fields but kept the on-disk keys (gym_instance_id, gym_attempt) and the schema version; _ATTEMPT_STATE_KEYS maps them.

  • Ledger dispatch is decided apart from which component was built. A run with NoRolloutCheckpointing still switches to ledger dispatch when it resumes from a checkpoint that needs it. Tested.

  • What stays in the controller, on purpose: the data-plane barrier (every run uses it, not only recovery), and _admit_reserved_prompt_groups / _require_unoccupied_target_step (the pump's sampler admission in both modes).

  • Small timing differences, nothing trained changes:

    • a snapshot reads controller state once at the start of its cut;
    • replay-buffer permits for restored groups are taken right after restore() returns;
    • the plain path's spare-pool drain now sets _sampler_stamps_target_steps, as the ledger path did.

    Each commit message lists its own.

  • Renamed outputs: the failure reason gym_unavailable is now environment_unavailable; the snapshot log prints restarted_rollouts; warnings and ledger errors say "environment". The Gym snapshot still logs gym_parked_seconds and gym_restarted_episodes.

  • Still open: the attempt-qualified rollout key <rollout_id>-a<attempt> (Gym's EpisodeId format) lives in the neutral EnvironmentEpisode. _summarize_gym_episodes from fix(checkpoint): harden Gym turn recovery for failures and scale #4501 should move to the Gym module.

  • One # pyrefly: ignore[bad-override] on reservation: pyrefly 0.24.2 reads a Literal parameter on an abstract method as str.

Testing

  • The checkpoint, restore, component and pump test files pass: 244 passed on the last commit. The one error is test_rollout_pump_writes_expected_tq_data, which needs 2 GPUs.
  • The step-1 fix still holds: 3 tests that fail at feat(checkpoint): add Gym turn-level rollout recovery #4500's head (their stubs yielded object()) pass here.
  • New tests in tests/unit/single_controller/test_rollout_checkpointing_component.py and test_rollout_pump.py cover the component on its own.
  • After every commit, the broader run (all of tests/unit/single_controller/, the Gym checkpoint adapter and coordinator tests, and tests/unit/experience/test_rollout_recovery.py) has no new failures. The 47 failures and 2 errors that remain also fail at feat(checkpoint): add Gym turn-level rollout recovery #4500's head on the same CPU-only macOS machine, whose Gym submodule is older than feat(checkpoint): add Gym turn-level rollout recovery #4500's pin.
  • No assertion was dropped. Where one now reads a value from the component or the restore report instead of a controller field, the commit message says so.
  • Not run: GPU and functional tests. CI not triggered.
  • ruff 0.9.9 and pyrefly 0.24.2 are clean on the changed files; every new file is in pyrefly.toml.

🤖 Generated with Claude Code

macandro96 and others added 24 commits October 22, 2026 07:52
…fast on stranded ones

A legacy_agent environment server only relays /run, so its environment
participant never holds the episode; the Simple Agent's legacy session does.
The commit summary counted only environment exports as owned, so every
in-flight Workplace episode looked unexported and the drain waited for
replies that cannot arrive while Gym is prepared. Every periodic checkpoint
timed out.

When no environment participant exported an episode, a legacy agent session
(a record with an episode step boundary) now owns it. The adapter reads the
agent's committed records through Gym's digest-checked store. A parked agent
session that nobody owns fails the checkpoint immediately instead of waiting
out the drain deadline.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…oint refusals

An attempt was marked DISPATCHED before it waited at the dispatch gate, so a
checkpoint could count an attempt that cannot reach Gym until the checkpoint
releases the gate; its drain could only time out, fatally at a trainer
checkpoint. A /run that reached Gym after prepare closed admission was
refused with 409 checkpoint_parked, charged as a data failure, and stayed
DISPATCHED while it retried behind the closed gate.

The ledger now marks an attempt DISPATCHED inside the gate admission, in the
same mutation as the Ray submission. NemoGym takes /run failures as Gym
sidecar rows so a checkpoint_parked refusal names its row without ending the
stream. The refused attempt returns to RESERVED with its identity and is
re-sent once admission reopens, spending no row attempt and no data budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Two-process crash/restore test for a Workplace Assistant turn. Phase one
publishes a bootstrap rollout snapshot that holds one turn after its
calendar mutation, then is killed; phase two restores it and must dispatch
that episode once, as Gym attempt + 1 on its original replica, and train
every step exactly once with no invalid or poisoned rows.

The turn is captured deterministically: the Gym checkpoint test agent holds
the first post-mutation boundary until a real checkpoint parks it, and the
rows force a single calendar_create_event whose sentinel the selector
requires exactly once in the saved Workplace state. The selector copies the
chosen bootstrap snapshot before step 1's trainer checkpoint prunes it, and
phase two drops every trainer checkpoint so the restore starts from that
anchor. The hook records dispatches once the ledger marks them, plus any
checkpoint refusals, and patches run_rollout so RolloutManager's NeMo-Gym
type checks still hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…kpoint

Abandoning or discarding a group drops its attempts from the recovery
ledger, but an episode Gym already admitted keeps running. Gym exports it at
the next commit, outside the candidate set, and every checkpoint fails until
the episode finishes on its own.

The ledger now records each dropped attempt Gym may still hold (dispatched,
or reserved with restored Gym state), in memory only. With dispatch closed
and before preparing Gym, while Gym is still idle (it refuses a retire once
a checkpoint is open), the controller retires them and forgets only what it
retired, so a drop recorded meanwhile waits for the next checkpoint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…ing the run

Three ways a Gym checkpoint could take the run down with it:

- Control calls had no RL-side timeout. Gym enforces deadline_ts only once
  it runs a call, so an actor with a stuck event loop, or a call Ray never
  scheduled, left the coordinator waiting forever with dispatch admission
  closed. Each call is now bounded by its own deadline plus a short reply
  grace; an unanswered instance is reported as a TimeoutError and its Ray
  call is cancelled. Giving up is safe: Gym's lease reopens a parked
  deployment if the resume is lost too.

- The periodic rollout checkpoint treated every Gym failure as a broken
  invariant and ended training. A checkpoint that could not park, went
  unanswered, hit a dead actor, or failed in Gym's control plane changed
  nothing RL holds, so it is now retried under a gym_unavailable reason,
  still bounded by max_consecutive_failures. Ownership, topology and reply
  mismatches still abort. Gym's CoordinationError cannot be pickled and
  reached RL as an untyped UnserializableException, so the adapter raises a
  picklable GymCheckpointUnavailable in its place for live checkpoint calls.

- Rollout deadlines kept ticking while Gym held rollouts parked, so a long
  checkpoint could time out healthy rollouts as soon as it resumed. The
  request-deadline registry now tracks named holders (ported from #4266),
  and a Gym checkpoint holds its own pause from closing admission until
  Gym resumes, without releasing a colocated engine's pause.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Parking a turn checkpoint waits for every in-flight agent and environment
step to reach a boundary, but the prepare deadline reused
token_capture.control_timeout_s, which bounds each control-plane call. The
only way to give long steps time to park was to loosen unrelated
token-capture RPC deadlines.

rollout_recovery.gym_prepare_timeout_s (default 300 s) now sets the prepare
deadline alone; renew, commit, retire, restore and resume keep the control
timeout. Gym extends its lease from each call's deadline, so a longer
prepare cannot let the lease lapse. The value is operational, so it is left
out of the bootstrap fingerprint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
With turn-level recovery, a trainer checkpoint parked Gym and committed its
state inside the trainer save. A Gym prepare that missed its deadline, or a
transient Gym control error, therefore failed the save and ended the run;
the periodic snapshot path already retries those.

The trainer checkpoint now saves weights, dataloader, TQ and the recovery
ledger without pausing Gym, and marks itself with gym_restart_fallback.json:
it holds no Gym state. Gym state lives only in rollout snapshots. The trainer
save wakes the snapshot pump, which waits for the checkpoint to be durable
off the training loop and then captures Gym anchored to it, with the
gym_unavailable retry and max_consecutive_failures budget it already has.
The trainer cut no longer counts as a rollout snapshot, so that snapshot is
not skipped for lack of data-plane mutations.

Restore prefers the newest rollout snapshot. A trainer checkpoint restored
on its own restarts its unfinished turn-level rollouts from their tasks; one
with neither Gym state nor the marker is refused. A reserved attempt that
continued earlier restored Gym state, and that this restart did not restore
again, starts over as well.

Ported from the trainer-boundary fallback in #4117, without its forced
boundary snapshot, which blocked training on the asynchronous weight write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…tart fallback

Turn recovery now keeps Gym state only in rollout snapshots: the trainer
checkpoint never pauses Gym, marks itself with gym_restart_fallback.json and
wakes the snapshot loop. Document that, the restore of a trainer checkpoint
without a later snapshot, and rollout_recovery.gym_prepare_timeout_s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…de key

Address review feedback on turn-level rollout recovery:

- Derive a group's recovery granularity from its persisted restore level
  instead of storing both; recovery_granularity is no longer persisted.
  Schema 4 is new in this change, so no released checkpoint carries it.
- GymCheckpointEpisode.capture_key is the single source of Gym's
  attempt-qualified key; the ledger and the controller use the wire type
  directly instead of converting tuples at each call.
- Refuse turn recovery behind an environment server other than
  legacy_agent: typed servers build EpisodeId from the restored "<id>-a<N>"
  key, which Gym rejects, so every restored turn would restart until its
  row budget ran out.
- Reject target-level overrides with target_level=turn: Gym exports every
  live episode, so a coarser route would fall outside the commit scope.
- Mint the Gym checkpoint control token per run, classify a failed
  environment-server episode by Gym's terminal flag, and keep the /run
  timing on refused rows.
- Abandon a reserved Gym attempt that this restart did not restore again.
- Pass gym_instance_id and dispatch_recorder to run_rollout explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Move the event writer and the ledger-group lookup that the turn, sibling
and rollout recovery hooks each copied into
_single_controller_hook_utils.py, drop the turn hook's unused delegate
passthrough, and forward gym_instance_id and dispatch_recorder from the
sibling hook. The sibling recovery script now checks the persisted
restore_level, since recovery_granularity is no longer saved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Note that only the current rollout_recovery.pt schema can be resumed and
that target-level overrides are rejected with target_level=turn, since a
checkpointing Gym deployment exports every live episode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
- Snapshots: abort the Gym phase when a train step commits, warn when
  snapshots keep losing to train steps, report gym_parked_seconds, and
  require stall_timeout_s to outlast a Gym park.
- Gym control: set lease_grace_seconds from control_timeout_s, retry a
  transient resume on the failed instances only, make the coordinator
  errors picklable, share one restore cleanup through coordinator.restored(),
  and route discover/restore errors through the same unavailable path.
- Adapter: drop the unused participant summaries and reply-shape checks;
  initialize adapters inside the shared spinup deadline.
- Dispatch: replace RolloutDispatchAdmissionGate with a second
  DataPlaneCheckpointBarrier; use Gym's no-result failure classes.
- Restore: pass restored_from_rollout_snapshot from setup instead of the
  gym_restart_fallback marker file; restore the trainer save to main's
  shape; name the Gym instances whose manifest disagrees with the ledger;
  require the Gym fields in v4 ledger attempts.
- Config: reject the removed *_granularity keys in check_outdated_config;
  derive target-level order from RecoveryTargetLevel.rank; document the
  turn requirements in the exemplar YAMLs and guide.
- Tests: drive the real GymCheckpointCoordinator through a shared fake Gym
  actor, test the adapter against real in-process Gym participants, and
  assert Gym restore and pre-cut model calls in the functional test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…L needs

Move the Gym pin from main's 6f295d7d to bf631d0a on NVIDIA-NeMo/Gym
amahishi/rl-gym-turn-recovery-pin:

- Gym main at 9ef5ed0f, which carries the merged checkpoint stack
  (#3882-#3889) and descends from main's pin 6f295d7d;
- NVIDIA-NeMo/Gym#3894: checkpoint Workplace Assistant sessions;
- NVIDIA-NeMo/Gym#4690: name the episodes an agent's own /run drives in
  the agent commit reply (run_episode_ids);
- the checkpoint test agent the turn-recovery functional test runs, with
  its participant installed once per app now that Gym installs it twice.
- NVIDIA-NeMo/Gym#3895-#3898: Gymnasium servers on the shared resources
  server setup, and checkpointing for Blackjack, indirect prompt
  injection and the proof refinement agent.

Gym adds requests to its core dependencies, so the lock records it for
nemo-gym; requests is already locked, and every resolved package keeps its
version.

Gym's coordination now sends each control body pre-encoded as data
rather than json, so the adapter test's in-process client forwards both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Address the review of turn-level recovery against the Gym main pin:

- Restarts: carry PrepareResult.restarts() back from each Gym actor, leave
  them out of the commit scope (Gym refuses a commit that names one), skip
  them in the drain, accept them in the cut, and record them in
  gym_checkpoint.json (schema 3) so a restore checks saved episodes plus
  restarts against the ledger and starts the restarts over from their
  tasks.
- Forget: retire leaves a mark per rollout on every Gym participant until
  the controller forgets it. Forget each rollout right after its retire,
  and each restored rollout once its continued attempt seals, before the
  next prepare; a deployment that refuses gets the retire again and then
  the forget, and one that still refuses keeps them queued.
- Resume order: Gym resumes before the snapshot is published, so new
  rollouts wait only for the Gym commit and TQ capture. A resume that still
  fails after a successful cut is reported, not raised: Gym's lease reopens
  the deployment, and the snapshot is kept.
- Ownership: read the committed episodes an agent's own /run drives from
  Gym's run_episode_ids commit reply instead of Gym's on-disk agent
  records, and name the two kinds of agent session in Gym's terms.

Document the resume order, restarts, and retire/forget in the guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…up test setup

gym_checkpoint.json is new in this PR and only RL writes it, so start its
schema at version 1 and parse it plainly. The version check and the checks
of what it means (non-empty IDs, no duplicates, matching topologies, no
episode both saved and restarting) stay; a file of the wrong shape still
fails to load, with a KeyError or TypeError instead of a tailored message.

Build the admitted, dispatched turn-level group the checkpoint race tests
use in one helper instead of seven copies, and merge the two equivalent
ledger-test helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…t agent

The Workplace turn-recovery test needs a published checkpoint holding a turn
whose calendar write was already applied. It held that boundary with a Gym
checkpoint test agent that subclassed private participant internals and was
switched by environment variables.

A test-only proxy between Gym's policy model server and vLLM now does it
through production paths. It holds the first policy call that carries a tool
result: Gym counts a session at its boundary while it waits on a policy call
made right after one, and a held call never blocks a checkpoint prepare. The
rows use the plain workplace_assistant_simple_agent, so the test needs no
Gym-side agent.

After the write, the proxy forces one calendar_search_events call and then
sends tool_choice none, so no turn writes a second event. The restored
episode's search must find the event written before the crash exactly once,
which checks that the Workplace state itself was restored, not only the
model calls; its reward must be 1.0. The selector accepts only the held
episode, since another episode also counts as at its boundary while its own
post-tool call is in flight. The proxy forwards every path, so token capture
is unaffected, and listens on the node's address so replicas on other nodes
reach it.

Passed with one Gym replica on one node and with two replicas on two nodes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
The pin no longer needs commits that exist only on an unmerged branch. The
turn-recovery test holds its boundary through a policy-call proxy, so it no
longer uses the checkpoint test agent (NVIDIA-NeMo/Gym#4773), and the agent
commit reply's run_episode_ids (NVIDIA-NeMo/Gym#4690) is on main. The other
pin-only commits, the indirect prompt injection and proof refinement
checkpoint exports (NVIDIA-NeMo/Gym#3897, #3898), are for environments RL's
tests do not use.

Gym's pyproject.toml is identical to the previous pin's, so uv.lock is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…unless allowed

A restart-only Gym server reports its in-flight rollouts as restarts at every
checkpoint, so under target_level='turn' they quietly start over from their
tasks after a crash, and nothing told the user. Restart-only is Gym's default
for resources servers that declare no checkpoint mode and for agents without
checkpoint session support.

Before the first rollout, SC reads every Gym participant's checkpoint status:
a resources server reports its mode, and an agent reports restart_only
(NVIDIA-NeMo/Gym#4957; an agent on an older Gym is not flagged). If any server
is restart-only, setup fails and names it, unless the new
rollout_recovery.allow_restart_only_gym_servers is true, which accepts it with
a warning. Setting it when no server is restart-only warns that it has no
effect, and setting it below target_level='turn' is rejected.

Each saved rollout snapshot also logs gym_restarted_episodes, the episodes
that would start over after a crash, on its save line and as a metric.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…ly reachable replies

Only typed environment servers take part in Gym checkpoints, and turn
recovery refuses those at setup; the legacy_agent relay it accepts is not a
participant. The adapter's environment-ownership branch was therefore
unreachable. It is removed, and discover() now fails, naming the server, if an
environment participant ever appears, instead of attributing its episodes
wrongly. The branch can return, tested against Gym's real participant, once
typed environment servers are supported.

The adapter tests no longer build replies for environment servers or the
participant manifest fields the adapter never reads. The stateless-resources
case runs on Gym's real participants in the save/restore test. Hand-written
replies remain for states valid participants cannot produce, plus three that
had no test: a commit from an unexpected participant set, an export outside
the requested scope, and a /run episode two agents claim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…s rollout metrics

Main now passes full_results to _compute_rollout_metrics and computes per-group
reward diagnostics from each result's full_result (#4435). This test predates
that and still stubbed the old signature and built results without
full_result, so it failed in CI's Nemo Gym unit lane after the rebase.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…heckpoint interface

The single controller built the Gym checkpoint coordinator, owned Gym's
dispatch gate, retired and forgot Gym episodes, parsed gym_checkpoint.json
and branched on whether a Gym coordinator existed. Move all of it into
GymEnvironmentCheckpoint (nemo_rl/environments/) behind a backend-neutral
EnvironmentCheckpoint interface (nemo_rl/experience/), with a
NoEnvironmentCheckpoint for backends that keep no rollout state. The
controller now pauses, snapshots, validates and restores the environment
through that interface and never names the backend.

Behavior is unchanged except for three renames:
- the rollout checkpoint failure reason gym_unavailable is now
  environment_unavailable
- the snapshot completion log prints restarted_rollouts
- warnings say environment rather than Gym

Add the design doc for the full plan: one RolloutCheckpointing component
the controller calls, of which this is step 1.

Signed-off-by: Terry Kong <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 23, 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.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 23, 2026
…and use ABCs for the environment interface

Step 2 of the rollout-checkpointing move (see
docs/design-docs/single-controller-rollout-checkpointing.md).

Interfaces:
- EnvironmentCheckpoint and EnvironmentSnapshot are now abc.ABC classes
  with @abc.abstractmethod on every member, so a backend that misses one
  fails when it is built. NoEnvironmentCheckpoint, GymEnvironmentCheckpoint,
  GymEnvironmentSnapshot and the test fakes subclass them.
- New EnvironmentEpisode (rollout_id, attempt, capture_key, next_attempt)
  in nemo_rl/experience/environment_checkpoint.py. Gym's
  GymCheckpointEpisode is now an alias of it, so the ledger no longer
  imports from the Gym adapter.

Ledger (rollout_recovery.py) renames:
- gym_checkpoint_inventory -> environment_inventory
- gym_checkpoint_retirements / mark_gym_retired ->
  environment_retirements / mark_environment_retired
- gym_checkpoint_forgets / mark_gym_forgotten ->
  environment_forgets / mark_environment_forgotten
- prepare_for_restart(restored_gym_episodes=) -> (continued_attempts=)
- record fields gym_instance_id / gym_attempt / holds_gym_state ->
  environment_instance_id / environment_attempt / holds_environment_state;
  gym_episode() -> environment_episode();
  mark_group_dispatched(gym_instance_id=) -> (environment_instance_id=)

The on-disk ledger keys stay "gym_instance_id" and "gym_attempt", and
ROLLOUT_RECOVERY_SCHEMA_VERSION is unchanged, so checkpoints written
before this change still restore. _ATTEMPT_STATE_KEYS maps the new field
names to the old keys.

Rollout manager: the checkpoint-owner argument of run_rollout (base impl,
Gym impl, RolloutManager) and _LedgerDispatchRecorder is now
environment_instance_id. The Gym impl's private _run_rollouts keeps
gym_instance_id.

Controller: passes continued_attempts=; it has no Gym checkpoint names
left. single_controller.py stays at 6,032 lines.

Behavior is the same. Some error messages in the ledger now say
"environment" instead of "Gym"; one test match string changed to follow.
test_serialized_state_fields_match_recovery_dataclasses now maps renamed
fields to their on-disk keys before comparing.

Signed-off-by: Terry Kong <[email protected]>
…eckpointing

Step 3 of the plan in docs/design-docs/single-controller-rollout-checkpointing.md.

New package nemo_rl/algorithms/rollout_checkpointing/:
- interface.py: RolloutCheckpointing and RolloutCheckpointingHost (abc.ABC,
  every member abstract) and NoRolloutCheckpointing.
- data_plane.py: DataPlaneRolloutCheckpointing. It now owns the rollout
  snapshot writer (_save_rollout_checkpoint, _capture_rollout_checkpoint_cut,
  _write_rollout_checkpoint_sidecars, _save_data_plane_checkpoint), the
  snapshot pump with its outcome logging and warnings, the save lock, the
  optimizer-commit window, and the wakeup and stop events.
- controller_state.py: ControllerRolloutState, which the controller builds
  under the data-plane cut, and write_controller_sidecars, the one writer
  that trainer checkpoints and rollout snapshots share.
- inventory.py: validate_replay_inventory, validate_rollout_recovery_inventory
  and capture_reward_settings as plain functions, because restore runs them
  too and must keep running them when rollout checkpointing is off.

The controller now calls:
- background_tasks() / stop_requested in _run_pumps
- optimizer_commit(drain_snapshot=...) in the train pump, entered on a
  per-step AsyncExitStack that closes where the flag used to be cleared
- trainer_checkpoint() around _save_checkpoint_impl (the save lock, and the
  wakeup after a trainer checkpoint)
- save_with_trainer_checkpoint(cut, path, state) and write_controller_sidecars
  in _save_checkpoint_impl, instead of its own copy of the TQ capture and
  sidecar writes (223 -> 130 lines)

The component reads no controller fields: it asks through a small host
adapter (train_steps, trainer_version, current_epoch, rollout_state(),
log_telemetry_metrics). A run with no snapshot interval whose trainer
checkpoints skip the data plane gets NoRolloutCheckpointing.

Behavior is unchanged. Small differences in timing only: the snapshot
capture reads the controller state once at the start of its cut instead of
across it (the values that matter only change under mutation cuts), and the
trainer checkpoint reads the sampler's supports_buffer_checkpoint flag even
when save_data_plane is off.

Tests: the tests of moved members now reach them through
controller._rollout_checkpointing, or build the component directly where the
test is about the component. No assertion was dropped or changed. New
test_rollout_checkpointing_component.py covers the ABC, NoRolloutCheckpointing,
the commit window, the save lock, the wakeup and the sidecar writer.

single_controller.py: 6,032 -> 5,270 lines. New package: 1,454 lines.

Signed-off-by: Terry Kong <[email protected]>
Step 4 of the rollout checkpointing move (design doc:
docs/design-docs/single-controller-rollout-checkpointing.md).

What moved: the restore chain leaves SingleControllerActor for a new
RolloutRestorer in nemo_rl/algorithms/rollout_checkpointing/restore.py:
_maybe_restore_replay_buffer, _maybe_restore_rollout_recovery,
_maybe_restore_replacement_reserve,
_queue_restored_replay_groups_for_regeneration, _load_recovery_prompt,
_rehydrate_rollout_recovery_prompts, _validate_restored_sampler_cursor,
_log_rollout_restore_metrics and _redispatch_restored_rollouts. The method
bodies moved as they were; only their reads of controller state changed.

What the controller now calls:
- RolloutCheckpointing.restore() in _run_pumps, in place of the five-call
  chain. It returns a RestoreReport, which the new
  _apply_restore_report() applies: replay-capacity permits, spare prompts,
  batch shortfall, finalizer metrics and rewards,
  sampler_stamps_target_steps, and whether ledger-tracked dispatch must
  turn on. The restorer never writes controller fields.
- RolloutCheckpointing.redispatch_restored(launch, admit) in the rollout
  pump, in place of _redispatch_restored_rollouts.

Both NoRolloutCheckpointing and DataPlaneRolloutCheckpointing hand these
to the same RolloutRestorer. A run that saves no rollout state still
restores in full, because the checkpoint it resumes from may hold buffered
rollouts, unfinished groups or spare prompts.

__init__ no longer keeps the restore-only fields (_last_checkpoint_path,
_restored_from_rollout_snapshot, _data_plane_checkpoint_metadata,
_rollout_checkpoint_load_metrics, _restored_replay_groups_to_regenerate).
It builds a CheckpointToRestore and passes it to
_build_rollout_checkpointing().

Stays in the controller for step 5: _admit_reserved_prompt_groups and
_require_unoccupied_target_step, which every new batch's admission uses.

Behavior: the same, with one ordering change. The permits for restored
replay groups are now taken right after restore() returns, not inside the
replay restore. Nothing reads the semaphore before the pumps start.

Tests: restore tests build the restorer directly (new helper
tests/unit/single_controller/_restore_helpers.py). Four assertions that
read controller fields right after _maybe_restore_rollout_recovery now
read the same values on the restorer, which reports them. The actor init
test checks the metadata and load timers on the restorer's
CheckpointToRestore. New component tests cover restore under both
implementations, a fresh run, and _apply_restore_report.

single_controller.py: 5,270 -> 4,656 lines. The package is 2,394 lines in
six files.

Signed-off-by: Terry Kong <[email protected]>
The rollout pump, _drain_reserve_into_steps, _abort_stale_inflight and the
finalizer's drop path now reserve, admit and discard prompt groups through
RolloutCheckpointing.reservation(kind). The plain-path copies of the
dataloader loop and the spare-pool drain are gone.

New in nemo_rl/algorithms/rollout_checkpointing/:
- PromptReservation (interface.py): reserve_prompt_group, admit,
  mark_prompt_group_admitted, discard_prompt_group, discard_recovery_group.
- dispatch.py: PromptDispatch hands out a LedgerReservation (one mutation
  cut, every call recorded in the ledger) or an UnrecordedReservation (no
  cut, nothing recorded; the rollout manager mints group IDs as before).
- RolloutCheckpointing gains records_prompt_groups and reservation(kind).
  Both implementations hold the same PromptDispatch.

The ledger-dispatch decision no longer depends on which component class was
built. _build_rollout_checkpointing sets it from the config and the resumed
checkpoint's recovery payload (moved from __init__), and the component's
restore() turns it on when the report says restore queued groups only the
ledger can launch (moved from _apply_restore_report). So a run with
NoRolloutCheckpointing still dispatches through the ledger after a
replay-free resume. redispatch_restored does nothing while it is off.

_admit_reserved_prompt_groups and _require_unoccupied_target_step stay in
the controller: they are the pump's sampler admission in both modes and
read and write controller state. The data-plane barrier also stays: every
run uses it, including finalizer commits, cleanup, advantage writeback and
the trainer checkpoint's cut over GRPOSaveState.

Plain-path differences (nothing trained changes): the spare-pool drain now
sets _sampler_stamps_target_steps, as the ledger path did; a transactional
sampler's gate is checked before the reservation and again inside admit;
the "substituting a spare prompt" log names the dropped step in both modes.

Tests: hand-built controllers get their dispatch mode from use_dispatch or
dispatch_for instead of setting _rollout_recovery_enabled. The
_apply_restore_report test no longer checks the flag; the switch is tested
on the component (test_restore_turns_on_ledger_dispatch_the_checkpoint_needs).
New tests cover the builder's choice, both reservations, and a
NoRolloutCheckpointing pump that restore switches to ledger dispatch.

single_controller.py: 4,656 -> 4,593 lines (6,446 at #4500's head).
_rollout_recovery_enabled branches: 10 -> 0 (nine in the pump, drain and
abort plus the one in _apply_restore_report). One records_prompt_groups
check is left, the guard in _launch.
Package: 2,394 -> 2,717 lines in seven files.

Signed-off-by: Terry Kong <[email protected]>
@terrykong terrykong changed the title refactor(checkpoint): move Gym checkpoint code out of the single controller (proposal, step 1) refactor(checkpoint): move rollout checkpointing out of the single controller (design proposal) Oct 23, 2026
@macandro96
macandro96 force-pushed the amahishi/gym-turn-recovery-pr1 branch 3 times, most recently from d1d83f1 to 70ba0c1 Compare October 28, 2026 14:58
@macandro96
macandro96 force-pushed the amahishi/gym-turn-recovery-pr1 branch 3 times, most recently from 343eaff to 789cedf Compare October 31, 2026 14:41
macandro96 added a commit that referenced this pull request Nov 1, 2026
The recovery ledger and the rollout manager still named the environment's
rollouts after Gym, and the ledger imported its episode type from the Gym
adapter. They now use neutral names:
- the ledger's queries and updates are environment_inventory,
  environment_retirements / mark_environment_retired,
  environment_forgets / mark_environment_forgotten and
  environment_episodes_still_held; prepare_for_restart takes
  continued_attempts;
- attempt records carry environment_instance_id, environment_attempt and
  holds_environment_state, and a group's environment_episode() returns an
  EnvironmentEpisode;
- EnvironmentEpisode lives in environments/checkpointing/interfaces.py,
  and the Gym adapter's GymCheckpointEpisode is an alias of it;
- the rollout manager's checkpoint-owner argument is
  environment_instance_id; the Gym rollout implementation keeps its own
  gym_instance_id.

The on-disk ledger keys keep their names (gym_instance_id, gym_attempt)
and the schema version is unchanged, so existing checkpoints restore.
Telemetry keeps the gym_unavailable reason.

Behavior is unchanged. The environment interface stays a Protocol; the
abstract-class conversion that came with these renames in #4879 is not
taken.

Source: +253 / -199. Tests: +150 / -133.
Unit: 2051 passed (default lane), 98 passed (Gym lane); the 29 forest
dispatch tests pass in the Gym lane. ruff and pyrefly
clean.

Co-authored-by: Terry Kong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@macandro96
macandro96 force-pushed the amahishi/gym-turn-recovery-pr1 branch from 789cedf to 3ca7028 Compare November 2, 2026 16:23
macandro96 added a commit that referenced this pull request Nov 2, 2026
The recovery ledger and the rollout manager still named the environment's
rollouts after Gym, and the ledger imported its episode type from the Gym
adapter. They now use neutral names:
- the ledger's queries and updates are environment_inventory,
  environment_retirements / mark_environment_retired,
  environment_forgets / mark_environment_forgotten and
  environment_episodes_still_held; prepare_for_restart takes
  continued_attempts;
- attempt records carry environment_instance_id, environment_attempt and
  holds_environment_state, and a group's environment_episode() returns an
  EnvironmentEpisode;
- EnvironmentEpisode lives in environments/checkpointing/interfaces.py,
  and the Gym adapter's GymCheckpointEpisode is an alias of it;
- the rollout manager's checkpoint-owner argument is
  environment_instance_id; the Gym rollout implementation keeps its own
  gym_instance_id.

The on-disk ledger keys keep their names (gym_instance_id, gym_attempt)
and the schema version is unchanged, so existing checkpoints restore.
Telemetry keeps the gym_unavailable reason.

Behavior is unchanged. The environment interface stays a Protocol; the
abstract-class conversion that came with these renames in #4879 is not
taken.

Source: +253 / -199. Tests: +150 / -133.
Unit: 2051 passed (default lane), 98 passed (Gym lane); the 29 forest
dispatch tests pass in the Gym lane. ruff and pyrefly
clean.

Co-authored-by: Terry Kong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Base automatically changed from amahishi/gym-turn-recovery-pr1 to main November 2, 2026 20:50
macandro96 added a commit that referenced this pull request Nov 2, 2026
The recovery ledger and the rollout manager still named the environment's
rollouts after Gym, and the ledger imported its episode type from the Gym
adapter. They now use neutral names:
- the ledger's queries and updates are environment_inventory,
  environment_retirements / mark_environment_retired,
  environment_forgets / mark_environment_forgotten and
  environment_episodes_still_held; prepare_for_restart takes
  continued_attempts;
- attempt records carry environment_instance_id, environment_attempt and
  holds_environment_state, and a group's environment_episode() returns an
  EnvironmentEpisode;
- EnvironmentEpisode lives in environments/checkpointing/interfaces.py,
  and the Gym adapter's GymCheckpointEpisode is an alias of it;
- the rollout manager's checkpoint-owner argument is
  environment_instance_id; the Gym rollout implementation keeps its own
  gym_instance_id.

The on-disk ledger keys keep their names (gym_instance_id, gym_attempt)
and the schema version is unchanged, so existing checkpoints restore.
Telemetry keeps the gym_unavailable reason.

Behavior is unchanged. The environment interface stays a Protocol; the
abstract-class conversion that came with these renames in #4879 is not
taken.

Source: +253 / -199. Tests: +150 / -133.
Unit: 2051 passed (default lane), 98 passed (Gym lane); the 29 forest
dispatch tests pass in the Gym lane. ruff and pyrefly
clean.

Co-authored-by: Terry Kong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
macandro96 added a commit that referenced this pull request Nov 5, 2026
The recovery ledger and the rollout manager still named the environment's
rollouts after Gym, and the ledger imported its episode type from the Gym
adapter. They now use neutral names:
- the ledger's queries and updates are environment_inventory,
  environment_retirements / mark_environment_retired,
  environment_forgets / mark_environment_forgotten and
  environment_episodes_still_held; prepare_for_restart takes
  continued_attempts;
- attempt records carry environment_instance_id, environment_attempt and
  holds_environment_state, and a group's environment_episode() returns an
  EnvironmentEpisode;
- EnvironmentEpisode lives in environments/checkpointing/interfaces.py,
  and the Gym adapter's GymCheckpointEpisode is an alias of it;
- the rollout manager's checkpoint-owner argument is
  environment_instance_id; the Gym rollout implementation keeps its own
  gym_instance_id.

The on-disk ledger keys keep their names (gym_instance_id, gym_attempt)
and the schema version is unchanged, so existing checkpoints restore.
Telemetry keeps the gym_unavailable reason.

Behavior is unchanged. The environment interface stays a Protocol; the
abstract-class conversion that came with these renames in #4879 is not
taken.

Source: +253 / -199. Tests: +150 / -133.
Unit: 2051 passed (default lane), 98 passed (Gym lane); the 29 forest
dispatch tests pass in the Gym lane. ruff and pyrefly
clean.

Co-authored-by: Terry Kong <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@terrykong terrykong added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 5, 2026
@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

This branch has not been deployed

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

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants