Skip to content

feat(checkpoint): per-backend generation-cut URL - #3971

Closed
tdene wants to merge 23 commits into
ananthsub/partial-ckpt-policy-modelfrom
tde/partial_ckpt_generation_cut_control_url
Closed

tdene wants to merge 23 commits into
ananthsub/partial-ckpt-policy-modelfrom
tde/partial_ckpt_generation_cut_control_url

Conversation

@tdene

@tdene tdene commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Validation

Rollouts

Compatibility and benchmark impact

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass).
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

@tdene
tdene requested a review from ananthsub October 3, 2026 03:51
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 3, 2026 03:51
@yaoyu-33 yaoyu-33 added area:model Model servers, inference providers, and model adapters complexity:low Localized change in one scope with a small, straightforward review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 3, 2026
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 5, 2026
@ananthsub
ananthsub force-pushed the ananthsub/partial-ckpt-policy-model branch 7 times, most recently from 047755d to 8f936bd Compare October 8, 2026 08:06
With external staging the model server keeps a capture ledger per rollout
and never removes it, because only the training framework knows when a
rollout's manifest is no longer needed.

Give the ledger the two operations the complete-record token store already
has. CaptureLedger.retire removes a rollout's ledger and leaves an empty
<id>.lineage.retired fence, like the retired tombstone TokenSource.drop
keeps: the framework retires every rollout it is done with, finished or
abandoned, and later calls for it are discarded instead of starting a new
ledger. That covers an abandoned agent that keeps running and a client
retry that ran a finished rollout twice. CaptureLedger.delete removes the
ledger and the fence, like TokenCaptureStore.delete: the framework deletes
retired rollouts once nothing of them can still write, and deletes a
rollout ID before reusing it.

Both are batched, validate the whole batch first, reject a bare string, and
are safe to retry, behind bearer-protected POST .../rollouts/retire and
.../rollouts/delete routes with matching RolloutControlClient methods. The
ledger row cache is now bounded. Staged token data is untouched; the
framework that staged it removes it.

Signed-off-by: Ananth Subramaniam <[email protected]>
The complete-record token store could only retire a consumed snapshot
through the conditional TokenSource.drop. Masked, failed, and abandoned
captures had no removal path, and tombstones were only removable by
sweep_retired, an age-based sweep that nothing called.

Add the same two batched operations the external-staging capture ledger
has. TokenSource.retire removes records and keeps the retired tombstone
whatever the rollout's state (drop without the snapshot check): for masked
or failed captures once their evidence is no longer needed, and for
abandoned attempts. The tombstone makes later writes fail, including from a
duplicate execution of the same rollout. TokenSource.delete removes records
and tombstones: for purging once nothing can still write, and for resetting
a rollout ID before reuse. TokenCaptureStore implements both, with
retire_now and delete_now as synchronous forms, and drop shares the retire
step. delete is now batched (it was single-ID and synchronous). The
conformance suite checks both operations.

The age-based sweeps are removed: sweep_retired, and sweep_stale, which
reclaimed unretired captures once every file of them was older than a
cutoff. Nothing in Gym called either. A capture's end of life is the
training framework's explicit retire, for every attempt it finishes or
abandons, including one whose request was cancelled mid-call, and delete
once nothing can still write. A time cutoff can remove a capture that is
still in use by a long session, and leaves the rest until the cutoff.

rollout_collection still keeps masked and failed captures; callers can now
remove them.

Signed-off-by: Ananth Subramaniam <[email protected]>
…ination

The core of partial-rollout checkpointing, shared by every server. It
installs nothing on its own; the model, environment, agent, and
resources changes each add a participant on top of it.

- Identity: an episode attempt is keyed by its capture key ("r" or
  "r-aN"). ServerClient attributes model and resources calls to their
  rollout whenever checkpointing is on, not only with observability.
- Control plane (control.py): one phase machine behind bearer-protected
  routes under /ng-control/v1/checkpoint, driving one participant per
  server. The controller owns checkpoint-ID fencing, attempt fencing,
  the readiness wait, deadline-bounded I/O, manifest-last storage, and a
  lease that resumes a participant whose controller went away.
- Episode steps (steps.py): a boundary after each completed step, and a
  wait or replay mode for a step in flight when a checkpoint closes.
  Time parked for a checkpoint does not count against an episode's
  deadline.
  A resources server reports whether its /verify may be replayed in an
  x-ng-checkpoint-verify header on its /seed_session reply, so callers
  learn the mode without another request; the default is wait.
- Coordination (coordination.py): the Gym-owned participant order a
  training controller calls: prepare environment servers, the policy
  model, agents, then resources servers; resume in reverse; commit and
  retire everywhere; restore all or nothing.
- Settings: a global checkpoint block, off by default, that requires a
  control token when enabled.

- Checkpoint coordination and other control calls use a reserved aiohttp
  pool (global_aiohttp_control_connector_limit, and _per_host), so data
  calls that hold every connection to a host, such as parked /run calls,
  cannot starve prepare, commit, or resume. coordination.renew extends
  every participant's lease when publishing outlasts it.
- Participants may override async export and install hooks to keep slow
  I/O off the event loop, and may add fields to the commit reply.
- An episode woken by a resume stays parked if a new checkpoint closed
  admission before it ran.
- Records keep each participant's opaque state (an environment, a session,
  a boundary) exactly as exported: key order, NaN, and infinities round-trip.
  Payload fields are checked once with orjson for JSON-ness, then written as
  they are, instead of a deep validation and copy of large states.

Signed-off-by: Ananth Subramaniam <[email protected]>
…o longer continues

A restore installs state for every episode the controller continues, and
that state waits for the replacement attempt to claim it. If the controller
never re-dispatches an episode, nothing released its restored state, and
every later checkpoint exported it again.

A commit's scope is the controller's statement of what it continues. After
writing its records, a participant now retires every restored episode whose
replacement has not started and that the scope leaves out. Participants
report those episodes through a new restored_pending method; retire already
releases everything else.

Signed-off-by: Ananth Subramaniam <[email protected]>
…g it forever

A retire used to discard an attempt and then remember it for the life of the
process, so its late requests were refused. That record grew with every
rollout retired or restored.

A retire now replies only after the participant has stopped the attempt's
running work and freed its state. While it stops, the attempt is refused;
afterwards nothing remains of it, so the fence holds only retires in
progress. Coordination retires callers before the servers they call
(environment servers, then agents, then the model and resources servers), so
nothing upstream can still call a server for an attempt it has stopped.

A restore and a commit's scope release no longer raise fences: nothing they
replace is running.

Retire is refused while a checkpoint is preparing, prepared or committed.
Stopping an episode waits for its final cleanup, whose calls wait for
resume, so a retire during a checkpoint could deadlock. A controller with a
straggler resumes first. Rollout collection already does.

Resumed checkpoint IDs are kept for the last 64 checkpoints instead of all
of them.

Signed-off-by: Ananth Subramaniam <[email protected]>
…en commit, restore, and discovery

Review of the participant control plane found that a retire could leave
work running unrefused, and several paths that could stall or wedge a
checkpoint.

A retired attempt stays refused until the controller forgets its rollout:
- Retire stops callers before callees, but a request a caller sent just
  before its own retire travels on another connection, and can reach a
  server after that server's retire finished. RetiredAttempts replaces
  the refusal that lasted only while a retire ran: a retire raises its
  rollout's mark before it stops anything, never lowers it, and keeps it
  whether or not the retire succeeds.
- A new forget control operation, and coordination.forget, which runs
  in retire order, remove the marks once a rollout is finished for good.
  Each participant keeps one entry per rollout retired and not yet
  forgotten; status reports the count as retired_rollouts.
- EpisodeSteps.retire waits until the episode's task has ended, and the
  episode stays tracked until then. A retire cut short by its deadline
  leaves it tracked, so a retry finds it and waits again, without
  cancelling a second time, and a duplicate start of the attempt is
  refused.

Every live episode is checkpointable:
- An episode that has not recorded a boundary yet, such as one inside
  its first replay step, is exported with no boundary and starts over
  from its input after a crash, instead of being neither a blocker nor
  exported. A restored episode starts at its restored boundary.
- A replay step that ends while a checkpoint is open keeps the episode
  at the boundary before the step until its next boundary parks it, so
  the commit does not find it running again.

Commit, restore, and discovery:
- Participants export only the restored state inside the commit's
  scope, and the cleanup of state outside it runs within the deadline,
  so a commit retried after a failed cleanup writes the same records.
- Restore validates only the records in scope.
- A failed restore always resumes every participant after retiring the
  replacement attempts, and raises the restore error, not the cleanup's.
- discover caps its connection retries, so a server that is down is
  reported instead of retried forever.
- The checkpoint block is validated once, when the ServerClient is
  built, and checkpoint is a reserved top-level key.

Performance:
- EpisodeSteps keeps a running blocker count; readiness lists at most
  the reported number of blockers, and steps notify only while a
  checkpoint is open.
- The records file is encoded, hashed, and written one record at a
  time, and read the same way.

Signed-off-by: Ananth Subramaniam <[email protected]>
…n restore, steps, and discovery

A second review of the participant control plane found paths where a
timed-out write, a failed restore, or a cut-short retire could corrupt
or wedge a checkpoint.

One write per checkpoint:
- The writer runs in a thread that a deadline cannot stop. A retried
  commit started a second export and writer, and the two could leave a
  records file and a manifest from different writers, which restore
  then rejected. A retry now awaits the checkpoint's one write, and
  starts a new one only if that write failed.
- Resume sets the write's stop flag: the writer stops before its next
  record and never publishes a manifest for a checkpoint that was
  aborted.
- The records file is named after its digest, and the manifest is only
  created, never replaced, so racing writers cannot mix their files.
- The standard json writer is the real JSON check. The orjson check
  falls back to json when it rejects a value, such as an integer beyond
  64 bits, and a value orjson accepts but json cannot write fails the
  commit with a typed error naming the episode.

Restore:
- A close of admission that fails part way, for example on one of
  several workers, reopens admission, as prepare already did.
- A record that fails validation is a typed invalid_checkpoint_state
  error naming its episode, not an untyped server error.

Episode steps:
- A retired episode that is still tracked blocks a checkpoint whatever
  its state, and is never exported, so a retire cut short by its
  deadline cannot carry the episode into the next checkpoint.

Discovery and rollout IDs:
- Each discovery probe has an outer timeout, so a server that accepts a
  connection but never replies is reported instead of hanging discover.
- A participant of an unknown kind is reported as that server's
  failure.
- An explicit rollout ID that already ends with the attempt suffix
  cannot also take an attempt index: the key would decode to no
  rollout and attempt.

Signed-off-by: Ananth Subramaniam <[email protected]>
…e's lock, and type storage errors

A third review round, and new contract tests over many inputs, found
gaps in the write path, restore, and prepare.

Write and publish:
- A commit retried after its storage failed exported again, so a
  replay-step episode that moved meanwhile left the checkpoint with a
  later cut than the other participants'. The write now keeps its
  records: a retry runs the directory and scope check, then stores the
  same records again.
- Resume set the stop flag without waiting for the writer, so a writer
  past its last check could publish a manifest after resume returned.
  The final check, the rename, and the manifest creation now run under
  one lock that resume takes, in a thread, when it stops the write.
- A commit into a directory that cannot hold state is a typed
  invalid_checkpoint_state error, not a server error.

JSON check:
- The fallback after orjson rejects a value now accepts only plain JSON
  with string keys. Falling back to json accepted integer dict keys,
  which come back as strings, and failed with a recursion error on very
  deep values.

Restore:
- A manifest that is not JSON, not an object, missing fields, or naming
  a records file outside the participant directory, and a missing
  records file, are typed invalid_checkpoint_state errors.
- Restore reads, verifies, and validates in one streaming pass in a
  thread, keeping only the records in scope, so it never holds the
  whole checkpoint.
- An install can outlive its restore's deadline, as the model ledger's
  import thread does. The control plane keeps the install, and a retire
  or the next restore waits for it, so the retire that cleans up a
  failed restore cannot run before the state it frees is installed.
- The manifest must name its checkpoint, checked before anything is
  installed.

Prepare:
- The readiness wait asks the participant only whether it is ready, and
  lists blockers once, for the reply. Participants override ready()
  where counting is cheaper than listing.

New contract tests check, over many payloads, run bodies, request
bodies, and corrupt manifests, that the check and the writer agree,
that capture keys round-trip, and that every control route answers
invalid input with a typed client error.

Signed-off-by: Ananth Subramaniam <[email protected]>
…t, give install the restore scope, reopen after a late install

Three gaps from the review of the policy model participant:

- A commit freed restored state its scope left out by retiring the
  replacement attempt. For the policy model, a retire fences the
  attempt's capture ledger, but the controller may still start the
  rollout over as that attempt, and every write would then be dropped.
  The commit now calls a new participant hook, delete_restored, which
  must leave nothing that refuses the attempt later. It defaults to
  retire, which is enough for participants whose retire refuses
  nothing beyond itself.
- install now receives the restore scope, every episode the restore
  continues, including ones a participant has no record of, so a
  participant that keeps files per episode can clear them too.
- A restore that missed its deadline reopened admission while its
  install was still changing state. Admission now reopens only once
  that install has finished, unless a later restore owns it by then.

Signed-off-by: Ananth Subramaniam <[email protected]>
ananthsub and others added 13 commits October 8, 2026 07:12
A policy model server (checkpoint_policy: true) takes part in
checkpoints. The checkpoint does not wait for generations:

- Closing admission holds every response that has not been delivered,
  and new policy calls wait until resume. Only a response already
  streaming blocks readiness.
- An undelivered call is left out of the checkpoint, including its
  capture-ledger row, so after a restore the agent simply calls again.
- With checkpoint_generation_cuts, prepare asks each generation backend
  to cut its in-flight calls at a durable token prefix. The replacement
  call carries the cut in its capture admission and the backend
  continues that prefix instead of regenerating it.
- Ledger rows are restored under the replacement attempt's capture key,
  so parent resolution continues the lineage by normal fingerprint
  matching.

Every model server binds its capture context to a policy ticket, and the
restored-cut hook is per call, so two model apps in one process do not
share state.

A restored generation cut that no re-issued call has consumed yet is
exported again by the next checkpoint, so a second crash still continues
the prefix.

Signed-off-by: Ananth Subramaniam <[email protected]>
A policy model server may now run num_workers > 1 under checkpointing.
Its workers share one port, so a control call reaches an arbitrary worker;
each running its own participant would close admission on one worker,
export other workers' undelivered calls as delivered, and restore cuts
into one worker only. It is still one participant to the controller:

- A coordinator in the main process, which serves no requests, owns the
  controller (phases, fencing, lease, storage), the attempt fence, the
  restored generation cuts, and the ledger export and import through the
  process-shared capture ledger.
- Each worker runs a PolicyGate, the per-process data plane split out of
  the participant: admission, held responses, and its own generation-cut
  round. It forwards checkpoint control calls to the coordinator, closes,
  reopens, and retires when told to, and while a checkpoint is open
  reports which responses are streaming, which calls are undelivered, and
  their cuts. A re-issued call claims its restored cut from the
  coordinator before it runs, and gives it back if it is the wrong call.
- Workers reach the coordinator over a Unix socket with length-prefixed
  JSON frames and request and reply messages in both directions.

Failures close the checkpoint instead of weakening it: a worker that has
not reported for the current checkpoint, or that disconnected while it
was open, blocks prepare and commit until the controller retires or
resumes. A worker that starts or restarts during a checkpoint closes at
once and adopts the current fences and restored cuts. A worker that loses the
coordinator shuts itself down: the main process, and uvicorn's supervisor
with it, is gone, and a worker left behind would hold the port against
the server's restart.

With one worker nothing changes: the participant owns its gate in process.

Signed-off-by: Ananth Subramaniam <[email protected]>
…ge cases

Found by the scale test and the review of the old stack's follow-ups.

- Commit and restore read and write each continued episode's ledger on a
  worker thread instead of the event loop. A restore installs all ledgers
  without syncing each file (the checkpoint is the durable copy, and
  importing it again is a no-op) and syncs the directory once, after one
  directory listing instead of an existence read per episode. At 12,000
  continued rollouts these were the checkpoint costs that grew with
  scale.
- The commit reply lists staging_keys: every staged token-store key the
  checkpointed episodes still refer to, from ledger rows and generation
  cuts. The training framework keeps those rows and may clear the rest.
- A call whose decoding is constrained (tool_choice other than auto or
  none, a non-text response_format, guided or structured outputs) is not
  cut and never continues a restored cut: a token prefix cannot restore
  its structured decoder. It regenerates instead. Ported from the prefix
  recovery work (Gym #3412); vLLM reports each request to the policy
  gate.
- Generation-cut requests to inference workers use the reserved control
  connection pool, since the worker's data connections are busy with the
  very generations being cut.
- Readiness is cheap to recompute: it counts held, cut, failed, and
  skipped calls, and each cut record is built once, when the worker
  acknowledges the cut. The full list of undelivered calls and their cuts
  is taken once, at commit; with several workers the coordinator asks each
  worker for it then. At 16k rollouts, rebuilding that list on every
  readiness check and every report stretched the policy prepare stage
  from 2 s to 25 s.
- An episode keeps one cut: when a client retried a call the server was
  still running, both calls are undelivered and cut, and only the latest
  admitted one is still awaited. Exporting both made restore reject the
  episode at 16k rollouts.
- Readiness counts cut_failed and cut_skipped, and a worker that fails to
  cut some calls is logged, so cuts that silently degrade to regeneration
  are visible.

Signed-off-by: Ananth Subramaniam <[email protected]>
…e calls

Restore installs each checkpointed episode's ledger rows as the ledger of the
next attempt. The capture directory survives a Gym restart, so after one
restore, a model call by the replacement attempt, and a second crash,
restoring the same checkpoint found the replacement's ledger, refused it, and
failed the whole restore. Every rollout then restarted from its input.

The import now deletes what dead executions left for the target attempt and
for later attempts of the same rollout, using the ledger's and the
complete-record store's delete: ledgers, token records, intents, incomplete
markers, capture state, and retire fences. A fence left in place would
silently discard the restored episode's rows once it reached that attempt
again.

A model server that has served any call refuses to restore, since a ledger it
wrote may belong to a live episode. This replaces tracking every ledger the
process appended to, which grew without bound.

Signed-off-by: Ananth Subramaniam <[email protected]>
The training framework now retires and deletes capture ledgers through the
model server's control routes. Two interactions with checkpoints needed care:

- A commit reads the ledger of every episode it continues. A retire or
  delete that landed between prepare and commit would leave the checkpoint
  holding the episode with no lineage, with no error. While a checkpoint is
  open on the model server, the routes refuse with 409 and the caller retries
  after resume.
- A checkpoint retire of attempt N fences attempt N and every earlier attempt.
  The participant now also retires those attempts' ledgers, after their calls
  are cancelled, so their files are freed and no late row recreates them.

Signed-off-by: Ananth Subramaniam <[email protected]>
…laimed restored cuts

- A restore continues attempt N as attempt N+1, but left attempt N's ledger
  on disk with nothing to remove it unless the training framework retired
  that key. The restore now retires the ledgers of every attempt it
  continues, and earlier attempts, in one batch.
- A restored generation cut waits for the replacement's re-issued call. The
  model participant now reports unused restored cuts as pending, so a commit
  that no longer continues their episode retires them.

Signed-off-by: Ananth Subramaniam <[email protected]>
…s retire replies

The gate's retire now waits until the cancelled calls have exited, and with several workers each worker refuses the attempt only while its own calls stop. Workers no longer receive a copy of a lasting fence when they join or reopen.

Signed-off-by: Ananth Subramaniam <[email protected]>
…om an earlier attempt

A turn-level checkpoint restore continues an episode under its next attempt
(for example rollout-a1), but the calls made before the checkpoint stay
staged under the earlier attempt's capture key. Rebuild required every
staged call to belong to the receipt's own rollout, so it rejected the
restored episode with wrong_rollout and the trainer dropped its row.

Restore now stamps each carried-over ledger row with the capture key it was
staged under, the manifest carries it as CallRecord.capture_key, and rebuild
verifies each call against that key. Only the same or an earlier attempt of
the receipt's rollout is accepted; anything else fails as
foreign_capture_key. A chain of restores keeps each row's original stamp.

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

The controller keeps only the staged rows of episodes it continues, but the
reply listed every key flat. Attributing a key by parsing its name breaks on
generation-cut keys, which name no rollout, and on any future key format.

The policy model participant, single- or multi-worker, now also returns
staging_keys_by_episode: each committed episode's keys under its capture
key, built from the same records as the flat list. A key can appear under
several episodes, since a restored attempt's record carries the rows of the
attempt it continues. The flat staging_keys list is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
…et, on every worker

Follows the participant control plane: a retired attempt stays refused
until the controller forgets its rollout.

- PolicyGate checks RetiredAttempts. With several uvicorn workers, each
  worker marks the attempt when the coordinator tells it to retire, and
  keeps the mark after its calls stop. A worker that registers later
  receives every current mark, and the coordinator relays forget to every
  worker.
- PolicyGate.release_response is now deliver_response: it lets a
  response start, holding it while a checkpoint is open.

Signed-off-by: Ananth Subramaniam <[email protected]>
A participant's records file is now named after its digest, so the
test finds it through the commit's manifest.

Signed-off-by: Ananth Subramaniam <[email protected]>
…nt writer's encoder

Worker messages were framed with orjson, which refuses integers beyond
64 bits and silently writes NaN and infinities, such as a -inf logprob,
as null. A message the writer could store could therefore fail to
reach a worker, or arrive changed. Messages now use the standard json
encoder, as the checkpoint writer does. A reply that still cannot be
framed is answered with a typed error instead of leaving the caller
waiting until its deadline.

Signed-off-by: Ananth Subramaniam <[email protected]>
…utions on restore, and harden the policy gate

Review of the policy model participant, each reproduced first:

- The commit's cleanup of restored state its scope left out took every
  restored cut as a pending attempt and retired it. A dispatched
  replacement whose re-issued call did not match its cut kept the cut,
  so the next commit fenced and deleted the running replacement's
  ledger, losing its training rows. The model now tracks every restored
  attempt, drops one from pending at its first admitted call on any
  worker, and deletes the ones still pending without a fence, since the
  controller may still start the rollout over as that attempt. With
  several workers, an attempt any worker started is no longer pending,
  and once a worker has left none is, because what it started is
  unknown. Only the first reopen after an install gives the workers its
  targets, so a later reopen cannot make an attempt a worker started
  pending again.
- Restoring a checkpoint again left a dead execution's ledger for an
  in-scope episode the model had no record of. Install now clears
  every in-scope episode's next attempt.
- Restore cleanup rescanned the ledger directory for every restored
  rollout; it now indexes it once: 0.23 s instead of about 19 minutes
  for 16k rollouts over 96k files.
- A hung generation cut used the whole prepare deadline, leaving the
  stages after it no time. A cut now gets half of what remains.
- A call without a rollout prefix made retire fail with an untyped
  error before it cancelled anything; retire skips untagged calls, and
  a malformed rollout prefix is a typed 400 invalid_rollout_id.
- A message to the coordinator that timed out or could not be sent
  raised a plain TimeoutError past the fallbacks, so a cut claim failed
  the call instead of regenerating it. The send is bounded with the
  reply, and timeouts and transport errors are typed as the coordinator
  being unavailable. A ticket's exit reports even if giving back its
  cut fails.
- A restore passed after a worker that had served calls was replaced by
  a fresh one; a worker leaving now refuses restore until the server is
  restarted.
- In one process, a restored cut is kept until the call that uses it
  delivers its response, so a call still undelivered at the next
  checkpoint continues from it again.
- Tests no longer exercise paths production does not run:
  continue_restored_cut is gone, and restore_records raises.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub
ananthsub force-pushed the ananthsub/partial-ckpt-policy-model branch from 8f936bd to 4e7988d Compare October 8, 2026 15:08
@tdene
tdene force-pushed the tde/partial_ckpt_generation_cut_control_url branch from f7f5037 to 97f546a Compare October 8, 2026 17:30
@ananthsub
ananthsub force-pushed the ananthsub/partial-ckpt-policy-model branch from 4e7988d to ac3a78f Compare October 9, 2026 03:55
@tdene tdene closed this Oct 9, 2026
hesam-shams pushed a commit to hesam-shams/Gym that referenced this pull request Oct 13, 2026
…ith generation cuts (NVIDIA-NeMo#3883)

## What changed and why

A policy model server with `checkpoint_policy: true` becomes a
checkpoint participant. The checkpoint never waits for generations.

- **Held responses, and new calls that wait.** Closing admission holds
every response that has not been delivered yet. Only a response that is
already streaming blocks readiness.
- A new policy call that arrives while a checkpoint is open waits until
resume before it is admitted, as a resources server's requests do. It
used to get 409 `admission_closed`. A rollout that keeps running through
the checkpoint, such as a restart, would have shown that refusal to the
model or failed.
- A waiting call is not admitted, so prepare never counts it, and its
agent is still at the boundary it recorded before the call. If its
attempt is retired while it waits, it is refused with `stale_attempt` at
once instead of running after resume.
- The gate tracks the calls waiting at closed admission by capture key.
When an attempt is marked retired, each waiting call of that attempt or
an earlier one is flagged as refused for good, and woken. The flag stays
set after the controller forgets the rollout, and it is set by the mark,
which comes before any work the retire's deadline limits, so a retire
cut short by its deadline still refuses the call. Without it, a call
that had not run again by the time the controller forgot the rollout
found no mark and was served once admission reopened.
- A retire returns only after those waiting calls have left the gate
with `stale_attempt`. A waiting call leaves the tracking when it leaves
the gate, so the tracking holds only calls still waiting.
- **Undelivered calls are left out, because they have no ledger row.**
An undelivered call is excluded from the checkpoint, so after a restore
the agent simply makes the call again.
- A call's capture-ledger row is published when its response starts, at
its first answer chunk, not when the worker stages its tokens. Headers
and keep-alive comments publish nothing. Behind the gate, the capture
handler leaves the row on the call's capture context
(`deferred_commit`), and the gate writes it after `deliver_response` and
before the chunk is sent.
- Rows used to be written at staging. Each policy server left out its
own undelivered calls by `model_call_id`, but a second policy server
sharing the ledger could not see them and exported their rows; and a
call whose capture context attached after the commit's snapshot could
land its row before the export read the ledger. Either way a checkpoint
could hold the answer of a call the caller never received.
- The write cannot be cut short by a cancellation, and the call stays
tracked until the write or its failure handling is done, so a retire or
a checkpoint waits for it. A failed write poisons the call and no answer
is sent. A call that leaves before its response starts has no row and is
not poisoned; its staged tokens are left for the training framework's
cleanup, as before.
- The export still leaves out undelivered calls' rows, now only as a
guard.
- With checkpointing on, every model server named in the config of an
agent with token capture must be a checkpoint policy server, since the
capture ledger is run-wide and a server outside the gate would write
rows at staging. Otherwise the model servers refuse to start, with an
error naming the server, the agent and the policy server.
- **Generation cuts** (`checkpoint_generation_cuts: true`). Prepare asks
each inference worker to cut its in-flight calls at a durable token
prefix. The replacement call carries the cut in its capture admission,
and the worker continues the prefix instead of regenerating it. The wire
models (`GenerationCutInventory`, `GenerationCutReceipt`,
`GenerationCutPrefixAck`) keep the field layout NeMo RL already uses. A
call with constrained decoding (`tool_choice` other than `auto` or
`none`, a non-text `response_format`, guided or structured outputs) is
never cut and never continues a cut, because a token prefix cannot
restore its structured decoder. A cut gets half of the prepare time
remaining, so a worker that hangs on its cut still leaves time for the
stages after the model.
- **Token lineage.** Ledger rows are restored under the replacement
attempt's capture key, so parent resolution continues the lineage by
normal fingerprint matching, with no parent header relay.
- **Several uvicorn workers.** A policy model server may run
`num_workers > 1`. It is still one participant to the controller: a
coordinator in the main process owns the phases, lease, storage, and
restored cuts, and each worker runs a gate (admission, held responses,
its own cut round) that reports to the coordinator over a Unix socket. A
worker that has not reported, or that disconnects during a checkpoint,
blocks the checkpoint instead of weakening it. A worker can also
disconnect after the commit checked readiness but before the coordinator
collects the workers' snapshots; the rows of that worker's undelivered
calls would then be exported as delivered. The commit therefore fails
with `export_failed` if a worker was lost or fewer workers answered than
expected, and that failure is final for the checkpoint, because a later
export could take a later cut. With one worker nothing changes.
- **Generation cuts at a per-backend address** (from NVIDIA-NeMo#3971, by
Teodor-Dumitru Ene). `generation_cut_control_url` lists one control URL
per `base_url`, for backends that serve cuts somewhere other than their
OpenAI URL. It is refused alongside `endpoint_file`, and a backend
without an address fails its cut, which only costs regenerating the
call.
- **One runtime directory per server process.** The coordinator socket
of a server with several workers lives in `/tmp/ng-<pid>-<random>/`
(`nemo_gym/runtime_dir.py`), under `/tmp` because AF_UNIX paths are
limited to about 100 bytes. It used to be a socket file in the temporary
directory that nothing ever removed.
  - The directory is removed when the process exits.
- Creating one first removes directories that killed servers left
behind, but only a directory whose owning process no longer exists
**and** none of whose sockets accepts a connection. The second check
keeps a live server in another container that shares `/tmp` but not its
process namespace, and a connection that times out counts as alive.
Nothing is removed by age.
- NVIDIA-NeMo#3905 adds the same file for session routing's sockets, so either PR
can merge first.
- **Scale fixes.** Commit and restore read and write ledgers on a worker
thread. A restore installs ledgers without syncing each file (the
checkpoint is the durable copy, and importing again is a no-op), with
one directory listing and one directory sync: importing 15,686 episodes
drops from 3.2 s to 1.5 s. Readiness is cheap to recompute. An episode
keeps only its latest cut. The commit reply lists `staging_keys`, the
staged token-store keys the checkpoint still refers to, so the training
framework knows which rows to keep. Cut requests use the reserved
control connection pool, and cut failures are counted in readiness and
logged.
- **Restored attempts the controller no longer continues.** The model
tracks every attempt a restore continues. An attempt stops being pending
at its first admitted call, on any worker. With several workers, only
the first reopen after an install gives the workers its attempts, so a
later reopen cannot make an attempt a worker has started pending again.
- An unclaimed restored cut, one no re-issued call has claimed yet, is
exported again by the next checkpoint while the controller's commit
scope still continues its episode, so a second crash still continues the
prefix.
- Once the scope leaves out an attempt that never started, the commit
drops its cut and deletes its ledger without a fence
(`delete_restored`), because the controller may still start the rollout
over as that attempt. A started replacement is never touched, so its
training rows are kept.
- Several policy servers can share one run-wide capture ledger, as
`policy_model` and `policy_model_reasoning_off` do, but each tracks its
restored attempts on its own. When the first call of a restored attempt
reaches a server, before the call can write a row or be held, that
server creates a shared "started" marker next to the attempt's ledger,
`<capture key>.lineage.started` (`mark_started()`). The marker is
created with `O_CREAT|O_EXCL` under the rollout's lock. It is not synced
to the directory: other servers only need to see it, and after a crash
the next step is a restore, which deletes started markers with the other
stale capture files. The commit deletes an unscoped restored attempt
through `delete_unstarted()`, which checks for the marker under the same
lock and keeps the ledger if any server sharing it has started the
attempt. Without the marker, a server that never saw the attempt start
would delete the rows another server wrote for it, including the rows of
a call that is held and has no row yet.
- The marker ends with the attempt's ledger: a ledger retire or delete
removes it, and so does a restore that clears what a dead execution left
for the attempt. A retired attempt is never marked.
- The commit deletes the ledger first and only then drops the attempt
from its restored bookkeeping and its saved cut, in one process and with
several workers. A delete that fails therefore leaves the attempt
pending, and the retried commit deletes it again.
- In one process, a restored cut is kept until the call that uses it
delivers its response, so a call still undelivered at the next
checkpoint continues from it again if its own cut fails.
- After each cut round, the newest cut replaces the restored cut a retry
would use. For each capture key, the cut of the latest undelivered call,
by admission time, as export chooses it, takes the restored cut's place,
and that call claims it. The checkpoint exports the newer cut and keeps
only its staged rows, so a call that ends before its response starts
leaves the newer cut for its retry, not a restored cut whose staged rows
the training framework may already have deleted. Delivering the response
frees it as before.
- With several workers, a worker claims a restored cut from the
coordinator before the call runs, and a call that used it never gives it
back. A retry of that call therefore regenerates instead of continuing a
stale cut.
- **Restoring the same checkpoint again.** The capture directory
survives a Gym restart. If the replacement attempt makes model calls and
Gym crashes before the next checkpoint, restoring the same checkpoint
again finds that attempt's files.
- Install receives the restore scope and clears the target attempt of
every episode in it, including an episode the checkpoint holds no model
record for. The import first deletes what dead executions left for the
target attempt and for every later attempt of the same rollout. It uses
the `delete` operations of NVIDIA-NeMo#3938 and NVIDIA-NeMo#3939: ledgers, token records,
intents, incomplete markers, capture state, and **retire fences**.
- A fence left in place would silently discard the restored episode's
rows once the episode reached that attempt again. Attempt numbers after
a restore are deterministic, and the training framework now retires
every finished rollout, so fences are common.
- The restore then retires the ledgers of the attempts it continues, and
of earlier attempts, in one batch. Attempt N continues as attempt N+1,
so attempt N's ledger would otherwise stay on disk.
- The cleanup lists the ledger directory once and indexes it by rollout.
Rescanning it per rollout took about 19 minutes for 16k rollouts over
96k files; the index takes about 0.23 seconds.
- A model server that has served any call refuses to restore, because a
ledger it wrote may belong to a live episode. With several workers, each
worker reports this to the coordinator, and once any worker has left,
restore is refused until the server restarts, since a fresh replacement
cannot report what the old worker served. This replaces tracking every
ledger the process appended to, which grew without bound.
- **Worker messages carry what the checkpoint writer carries.** Messages
between the coordinator and its workers are framed with the standard
`json` encoder, as the checkpoint writer is. `orjson` refused integers
beyond 64 bits and silently wrote NaN and infinities, such as a `-inf`
logprob, as `null`. A reply that still cannot be framed is answered with
a typed error, so the caller does not wait until its deadline. A
message's send and reply share one timeout, and a timeout or transport
error is `CoordinatorUnavailableError`, so a cut claim against a stalled
coordinator falls back to regenerating. A ticket's exit reports to the
coordinator even if giving back its cut fails.
- **Capture-ledger cleanup stays consistent with checkpoints.** The
training framework retires and deletes ledgers through the model
server's control routes (NVIDIA-NeMo#3938).
- While a checkpoint is open on the model server, those routes refuse
with 409, and the caller retries after resume. A commit reads the ledger
of every episode it continues, so a retire landing between prepare and
commit would leave the checkpoint holding an episode with no lineage,
with no error.
- A checkpoint `retire` of attempt N cancels the calls of attempt N and
every earlier attempt, each only once, and waits for them, then retires
those attempts' ledgers, so their files are freed and no late row
recreates them. The policy gate refuses the retired attempt's late calls
until the controller forgets the rollout. A retire skips calls without a
rollout prefix, such as evaluation, judge, or health-probe calls, and a
malformed rollout prefix is a 400 `invalid_rollout_id`. With several
workers, the coordinator marks the attempt on every worker before any of
them stops its calls, relays `forget`, and gives a worker that registers
later the current marks.
- **Calls a restore carried over are verified against their own capture
key.** A restored episode continues as attempt N+1, but the calls it
made before the checkpoint stay staged under the earlier attempt's
capture key. Rebuilding the episode's rollout rejected them as
`wrong_rollout`, so the trainer dropped the row. Restore now stamps each
carried-over ledger row with the capture key it was staged under
(`CallRecord.capture_key`), and rebuild accepts the same or an earlier
attempt of the rollout; anything else fails as `foreign_capture_key`. A
chain of restores keeps each row's original stamp.
- **Staged keys per episode.** The commit reply also returns
`staging_keys_by_episode`: each committed episode's staged keys under
its capture key, built from the same records as the flat `staging_keys`
list. The controller keeps only the rows of episodes it continues, and a
key's name does not always say whose it is: generation-cut keys name no
rollout.
- **`PolicyGate.deliver_response`** lets a response start, holding it
while a checkpoint is open; it was `release_response`.
- **A response starts with its first answer data, not its headers.**
`StreamingResponse` sends `http.response.start` before it reads its
body, and the buffered chat-streaming path sends SSE keep-alive comments
while the backend is still generating.
- The admission middleware used to call `deliver_response()` on the
headers, so prepare treated a call that had produced nothing as
streaming and waited for it instead of cutting it. If the snapshot fence
held the call's terminal token write, the call could not finish and
prepare stalled.
- It now calls `deliver_response()` on the first body chunk that carries
data, skipping empty chunks and, for an event stream, `SSE_KEEPALIVE`.
`SSE_KEEPALIVE` moved to `nemo_gym/chat_streaming.py`, so the middleware
and the streaming path share one definition of a liveness frame.
- So headers and keep-alives leave the call cuttable, its first answer
chunk is held while admission is closed, and an answer that already
started still drains before prepare completes. This is the change
proposed in NVIDIA-NeMo#4555.
- **Generation cut wire names match.** The cut inventory and
acknowledgement name the attempt `attempt`, as `EpisodeId` does, and the
continuation a re-issued call carries names its prefix
`prefix_token_count` and `prefix_digest`, as the worker's
acknowledgement does.

Conflict note: `CaptureContext` on `main` gained
`external_worker_response_seen` (NVIDIA-NeMo#3670); this PR adds `admission_hook`
next to it, and both fields are kept.

## 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 M 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

A model call across a checkpoint and a crash.

```mermaid
sequenceDiagram
  participant A as Agent
  participant P as Policy model server
  participant W as Inference worker
  A->>P: model call for rollout r, attempt 0
  P->>W: generate
  Note over P: prepare closes admission - new calls park,<br/>responses not yet delivered are held
  P->>W: generation cut, if enabled - stage the prefix so far
  W-->>P: receipt with staging keys per call
  Note over P: commit exports ledger rows minus undelivered calls,<br/>plus the latest cut of each episode
  Note over A,W: crash, restore, resume
  A->>P: the same call again, as attempt 1
  P->>W: continue from the staged prefix, or generate again
```

With several uvicorn workers, one coordinator in the main process is the
participant; every worker keeps its own gate and forwards control calls
to the coordinator.

```mermaid
flowchart LR
  CO["Coordination"] -->|"control call on the shared port"| W1["uvicorn worker 1<br/>gate: tickets, held responses"]
  CO -->|"control call on the shared port"| W2["uvicorn worker 2<br/>gate: tickets, held responses"]
  W1 <-->|"Unix socket: forward, close, reports, cut claims"| C["Coordinator in the main process<br/>phases, lease, ledger, restored cuts"]
  W2 <-->|"Unix socket"| C
```

The capture ledger across checkpoints, restores and the training
framework's cleanup.

```mermaid
sequenceDiagram
  participant T as Training framework
  participant P as Policy model server
  participant L as Capture ledger
  Note over P: checkpoint open - ledger retire and delete routes answer 409
  T->>P: retry retire and delete after resume
  Note over P,L: restore - delete what dead executions left for attempt N+1 and later, fences included
  P->>L: import attempt N's rows as attempt N+1, then retire attempts 0 to N
  Note over P,L: checkpoint retire of attempt N - stop its calls, then retire the ledgers of attempts 0 to N
```

## 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 has merged too, so NVIDIA-NeMo#3883'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
**(this PR)**
3. NVIDIA-NeMo#3884 (`ananthsub/partial-ckpt-model-worker-cuts`):
feat(token-capture): add worker staging helpers for generation cuts
4. NVIDIA-NeMo#3885 (`ananthsub/partial-ckpt-environment`): feat(checkpoint):
continue environment server episodes from their boundaries
5. NVIDIA-NeMo#3886 (`ananthsub/partial-ckpt-resources`): feat(checkpoint): add the
resources server participant with asynchronous session hooks
6. NVIDIA-NeMo#3887 (`ananthsub/partial-ckpt-verifier-declarations`):
feat(checkpoint): declare five 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#2941 (policy model participant). The checkpointable ledger
wrapper and parent relay are replaced by `main`'s capture ledger plus
rows re-imported under the next attempt; admission no longer waits for
generations.
- Takes the generation-cut models from NVIDIA-NeMo#2940, under
`nemo_gym._checkpoint.generation_cut` instead of
`model_control_contracts`.
- Multi-worker support follows the shape of NVIDIA-NeMo#3563 (a companion in the
main process, a Unix socket, and a restored cut with a single owner)
with much less machinery: no proof files, evidence files, or worker
journals. The scale fixes cover the remaining needs listed in NVIDIA-NeMo#3755
(reserved control pool, restore I/O off the event loop).
Constrained-decoding restart comes from NVIDIA-NeMo#3412.

## 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`, which includes NVIDIA-NeMo#3882:

- `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider
tests/unit_tests/test_checkpoint_*.py`: passed.
- `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider
tests/unit_tests/test_token_capture_*.py
tests/unit_tests/test_token_id_capture.py
tests/unit_tests/test_base_responses_api_model.py`: passed.
- `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider
responses_api_models/vllm_model/tests`: passed.
- Among the checkpoint tests, each failing without its change:
- restoring the same checkpoint again after the replacement made a call
(without the fix: `capture ledger for roll-1-a1 already holds rows from
another execution`), with the files and fences of the target and later
attempts deleted and look-alike rollouts untouched;
  - a restore retires the ledgers of the attempts it continues;
- a model server that has served calls refuses to restore, with one
process and with two workers;
- ledger retire and delete return 409 while a checkpoint is open and
succeed after resume;
- a retire stops a running generation before it replies, and retires the
ledgers of attempts 0 to N but not N+1;
- a retire leaves no fence on any worker, including one that joins
later;
- worker messages carry NaN, infinities, and integers beyond 64 bits
unchanged;
- a commit that no longer names a started replacement leaves its ledger
alone, and deletes a restored attempt nothing started without fencing
it; with two workers, an attempt any worker started is no longer
pending, and a reopen does not make it pending again;
- restoring again clears a dead execution of an in-scope episode without
a model record;
  - untagged calls neither break a retire nor surface as untyped errors;
- a hung cut leaves the rest of the prepare deadline for the stages
after it;
- a message that cannot be sent or is never answered is a typed
unavailable error, and a ticket leaving is reported even if giving back
its cut fails;
- restore is refused after a worker left, even if its replacement is
fresh;
- a call that arrives during a checkpoint waits for resume without being
admitted, and is refused at once if its attempt is retired while it
waits;
- two policy servers sharing a ledger, one holding a completed response:
neither snapshot, nor the restored ledger, holds its row (without the
fix, the second server exported it);
- a call whose capture context attaches after the commit's snapshot
cannot land its row in the checkpoint (without the fix, it did);
- a row is published at the first answer chunk, not at headers or
keep-alives; a call that leaves first has no row and is not poisoned; a
failed write poisons the call and sends no answer; a retire or a
checkpoint during the write waits for it; each worker of a server with
several workers follows the same rule;
- a model server outside the checkpoint gate that an agent with token
capture names is refused at startup;
- a retried retire waits for a call an earlier retire cancelled without
cancelling it again (without the fix, its cleanup was cancelled a second
time);
- marking a restored attempt started does not sync the ledger directory,
and a restore after a crash removes the markers the dead execution left;
- headers, empty bodies and keep-alives do not start a response, for
JSON and event streams; a stream sending only keep-alives during a
checkpoint is cut and its output is held until resume (without the fix,
both time out); an event stream that already started finishes while
admission is closed;
- a worker that disconnects after the commit checked readiness and
before the snapshot fails the commit, and a retried commit fails the
same way;
- a restored attempt started on one policy server keeps its ledger when
a commit on another server sharing the ledger leaves it out of scope,
both once the started call's row is recorded and while the call is
admitted but not yet recorded; with several workers, a worker marks the
attempt started in the shared ledger;
- a restored attempt no server started is deleted, and no marker is left
behind;
- the started marker is removed by a ledger retire, a ledger delete, and
a restore that clears the attempt;
- a failed delete of a restored ledger keeps the attempt pending, and
the next commit attempt deletes the remaining rows, in one process and
with several workers;
- a call waits at closed admission, its attempt is marked and retired,
the controller forgets the rollout, and admission reopens; the call is
refused with `stale_attempt` and nothing is served;
- the same with a retire cut short by its deadline, in one process and
on a worker of a server with several workers, where the waiting call
also leaves the gate's tracking;
- a resumed call that continues a restored cut is cut again by the next
checkpoint, which exports the newer cut, and then ends before its
response starts; its retry continues the newer cut, not the restored
one;
- with several workers, a retry of a call that used its restored cut
gets no cut after a newer checkpoint, and the coordinator no longer
holds the restored cut.
- `RAY_TMPDIR=/tmp .venv/bin/python -m pytest -q -p no:cacheprovider
tests/unit_tests/test_runtime_dir.py`: passed. A dead server's directory
with closed sockets is removed; a live process's directory is kept; a
directory whose socket accepts is kept even when its process looks dead;
only runtime directory names are considered; and a process creates its
directory once, with mode 0700, and removes it at exit.
- 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

- **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. A real vLLM worker serving
generation cuts is not covered: stock vLLM does not serve the cut route.
- Scale, on one workstation with every Gym server and a fake inference
backend (weather rollouts through the typed `single_agent_turn` request
path, token capture and generation cuts on, each rollout's second model
call held so most rollouts are in flight at the checkpoint; checkpoint,
kill every Gym process group, restart, restore, run the replacement
attempts). After the scale fixes in this PR, measured on the branch this
stack was cut from, with the same commits:

| Rollouts | Policy workers | In flight at checkpoint (exported) |
Prepare (s) | Commit (s) | Restore (s) | Replacement failures |
  |---|---|---|---|---|---|---|
  | 8,000 | 1 | 4,201 | 0.67 | 0.60 | 0.60 | 0 |
  | 8,000 | 2 | 4,083 | 0.56 | 0.69 | 0.56 | 0 |
  | 16,000 | 2 | 14,320 | 7.57 (model 7.38) | 4.64 | 4.97 | 0 |
  | 16,000 | 2 (rerun) | 12,228 | 3.60 (model 3.53) | 1.83 | 3.23 | 0 |

In the first 16,000-rollout run, the policy model logged 8 uvloop "File
descriptor N is used by transport" errors and 16 requests failed with
"ledger lineage resolution failed". The cause is a libuv accept race
while clients disconnect, not checkpoint code; the ledger failed closed,
clients retried, and no replacement failed. The rerun and every
8,000-rollout run had none.

## Compatibility

- New model server config: `checkpoint_policy` (default `false`) makes
the server a participant, and `checkpoint_generation_cuts` (default
`false`) turns on generation cuts. Both only take effect with the global
`checkpoint:` block enabled.
- Users of the old stack's
`token_id_capture.generation_prefix_cuts_enabled` key (never on `main`)
switch to `checkpoint_generation_cuts`.
- Generation-cut models are imported from
`nemo_gym._checkpoint.generation_cut`.
- The `CheckpointableLedger` protocol gains `mark_started()` and
`delete_unstarted()`, so a custom ledger used with a checkpoint
participant must implement both. `PolicyWorkerLink` takes a `ledger=`
argument, which a worker needs to mark restored attempts started.
- A restored attempt's first call writes a `<capture
key>.lineage.started` file in the capture ledger directory. It is
removed with the attempt's ledger.
- With checkpointing off, model servers behave as before.

Signed-off-by: Ananth Subramaniam <[email protected]>
Co-authored-by: Anish Mahishi <[email protected]>
Co-authored-by: Teodor-Dumitru Ene <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 97f546a0 Deployed Oct 8, 2026 by copy-pr-bot[bot] via release / finalize / notify #4749
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters complexity:low Localized change in one scope with a small, straightforward review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants