Skip to content

perf(checkpoint): shorten the rollout-snapshot barrier hold - #5241

Merged
terrykong merged 5 commits into
mainfrom
amahishi/snapshot-barrier-hold
Nov 20, 2026
Merged

terrykong merged 5 commits into
mainfrom
amahishi/snapshot-barrier-hold

Conversation

@macandro96

@macandro96 macandro96 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack

PR 3, based on #5139 (#5137 is merged). Review against amahishi/async-tq-rollout-snapshots-main; once #5139 merges, retarget to main. Independent of #5185, which shrinks the remaining ledger build further.

Rebased onto #5139 at 1c6f7c4d57, which is on main at bf50129f25 (2026-11-19). The only conflict with main was the tq_controller_patch.py module docstring, which #5141 rewrote; it now keeps #5141's text, adds the list_keys paragraph, and notes that list_keys has no upstream counterpart. #5139 now serializes and hashes the recovery state after resume (a211758851), has the persist(extra_metadata=...) API (12da50adad), and carries its review follow-ups: one recovery-metadata binding and separate capture logs (f053944698), trainer-sidecar and deferred-timing tests (cc5761ee46), and a short async_checkpoint usage section in place of the README's internals section (1c6f7c4d57). That serialization half of this PR's second commit was dropped here, and this PR's README changes shrink to one paragraph in the new usage section; what remains is below.

Summary

Shortens the time a rollout snapshot holds the data-plane barrier (and keeps Gym parked) with a retained SimpleStorage view. Four commits:

  • perf(data-plane): list TQ keys without their custom metadata — the replay and staging inventory checks compare key sets only, but list_sample_ids used TQ's KV_LIST, which ships every key's custom metadata. Adds nrl_list_keys to the patched controller (the perf(data_plane): cheaper TQ kv_retrieve_meta and clear on the controller #4769 patch, applied for every TQ backend) and uses it from list_sample_ids. No behavior change.
  • perf(checkpoint): overlap the rollout-snapshot capture phases
    • Inside the barrier, the replay inventory check, the recovery-state build, the staging inventory check and the TQ capture run concurrently. Every ledger mutation needs the barrier; the controller maps the build reads are copied on the event loop before it moves to a thread.
    • A view captured beside a failed or cancelled phase is released before the error propagates (CheckpointReleaseError if the release cannot be confirmed).
    • Trainer checkpoints use the same path.
  • perf(checkpoint): list the staging partition once per checkpoint cut
    • A rollout snapshot listed the staging partition twice under one barrier: in Gym's check_against_cut, which ran before the concurrent phases and so added to the hold, and again in the recovery staging check. The staging phase now lists once, then runs Gym's check and the recovery check on that listing, beside the build and the TQ capture. Restore shares one listing between its two staging checks.
    • The TQ adapter no longer sorts list_sample_ids (about 1.25 s per listing at 2.6M keys); every caller compares key sets, and the interface no longer promises an order. The staging check also skips sorting unreferenced rows it will not clear.
    • GymEnvironmentCheckpoint and the environment-checkpoint builders drop the list_staging_keys hook and dp_client parameter that only fed Gym's listing.
  • fix(checkpoint): let an unconfirmed capture release win over other phase errors (review follow-up)
    • CheckpointReleaseError means storage actors may still hold a captured view, so checkpointing must stop. With concurrent phases, _run_capture_phases could hide it: a retryable error from another phase re-raised first (tq_capture is the last phase), or a cancellation re-raised CancelledError after the capture failed its own late release. It now raises a phase's CheckpointReleaseError before any other error or the cancellation.

Flow

A rollout snapshot with a retained SimpleStorage view, with #5139 and this PR. The shaded block is the data-plane barrier: TQ mutations are drained and blocked, and Gym stays parked. Serialization after resume comes from #5139.

sequenceDiagram
    participant S as RolloutSnapshotter<br/>(controller event loop)
    participant G as Gym
    participant T as Worker threads
    participant C as TQ controller
    participant U as TQ storage units

    S->>G: Close admission, prepare, export episodes, drain replies
    rect rgba(255, 170, 0, 0.15)
        Note over S,U: Data-plane barrier held, Gym parked
        par Replay inventory
            S->>C: nrl_list_keys(replay), keys only
        and Recovery-state build
            S->>T: Walk the recovery ledger into a detached state
        and Staging inventory
            S->>C: nrl_list_keys(staging), keys only, once
            S->>S: Gym's check, then RL's staging check, on that listing
        and TQ capture
            S->>C: Serialize controller metadata to bytes
            S->>U: Retain shard views
        end
        Note over S: A failed or cancelled phase releases a captured view
    end
    S->>G: Release the barrier, resume Gym and dispatch
    Note over S,U: Rollouts run again from here
    S->>T: torch.save + sha256 of the recovery state (from PR 5139)
    par Persist TQ
        S->>C: Write controller bytes
    and
        S->>U: Write retained shards
    end
    S->>S: Write metadata.json with the recovery digest (persist extra_metadata)
    S->>C: Release views
    S->>U: Release views
    S->>S: Write sidecars and manifest, publish the snapshot
Loading

What this PR changes on top of #5139, at 131k rollouts × 20 calls (CPU measurement below; serialization after resume takes about 6.5 s in both):

flowchart LR
    subgraph base["PR 5139: one after another under the barrier (15.2 s)"]
        direction LR
        b0["Gym check<br/>KV_LIST with tags"] --> b1["Replay inventory<br/>KV_LIST with tags"] --> b2["Ledger build"] --> b3["Staging inventory<br/>KV_LIST with tags"] --> b4["TQ capture"] --> b5(["Barrier released,<br/>Gym resumes"]) --> b6["torch.save + sha256"]
    end
    subgraph after["This PR: concurrent under the barrier (9.8 s)"]
        direction LR
        a0(["Barrier taken"]) --> a1["Replay inventory<br/>keys only"] & a2["Ledger build<br/>(worker thread)"] & a3["Staging listing, once<br/>Gym + RL checks"] & a4["TQ capture"]
        a1 & a2 & a3 & a4 --> a5(["Barrier released,<br/>Gym resumes"]) --> a6["torch.save + sha256"]
    end
Loading

Behavior changes

  • A recovery-ownership mismatch can now be detected while the TQ capture is already retained; that view is released and the snapshot fails as before.
  • The GIL contention from serializing after resume (median loop lag 5 ms, p99 25 ms, one 0.37 s stall on a 308 MB state) now comes from perf(checkpoint): defer rollout and trainer data-plane persistence #5139 and is documented there.
  • The barrier phases overlap, so exclusive_hold_seconds is close to the longest phase, not their sum. The data-plane README is updated.
  • Gym's check_against_cut runs inside the concurrent staging phase, so a Gym ownership mismatch can also be found while the TQ capture is retained; that view is released and the snapshot fails as before. staging_inventory_seconds now includes Gym's check.
  • list_sample_ids returns keys in no particular order.
  • If the TQ capture raises CheckpointReleaseError, the snapshot fails with it even when another phase also failed or the snapshot was cancelled, so the pump stops checkpointing instead of retrying.

Measurements

CPU only, one node, real Ray + TQ 0.1.11 SimpleStorage (2 storage units), synthetic sealed ledger: 8,192 groups × 16 siblings × 20 model calls (131k rollouts, 2.6M staging keys, 131k replay keys), 64-byte tags per key. A script reproduces the barrier phases with the real ledger, TQ listing and capture code; it is not a GPU run. Median of 3 rounds with the variants run in rotating order; ranges in parentheses. Measured on 2026-11-18, before the review follow-ups and the rebase onto current main; not re-measured since.

Groups Staging keys Barrier hold, #5139 With this PR Recovery serialization after resume
8,192 (131k rollouts) 2.6M 15.21 s (15.15–15.40) 9.84 s (9.69–11.44) 6.57 s, 6.53 s

The hold drops 5.4 s (35%). In the same setup, before #5139's serialization commit (e95dbedb8d), the hold was 22.82 s.

Keys-only listing alone (inventory check incl. sort and comparison):

Keys Tag size KV_LIST nrl_list_keys
300k 64 B 0.41 s 0.09 s
300k 1 KB 0.72 s 0.08 s
2.6M 64 B 4.84 s 1.02 s

At 131k rollouts the remaining hold is dominated by the ledger build (~9 s on main's copier; #5185 roughly halves it). Real-run numbers come from the phase metrics in #5139.

Validation

At 540e43d73f (on main bf50129f25): 350 tests across every test file this PR touches and the Gym-marked lane (7) passed, with main's Gym pin 9e2e5d0ad0 on the path. These include the overlap, failed-phase, cancelled-phase and single-listing tests, the two release-error tests from 540e43d73f (which fail before its fix), #5139's deferred-path tests, all Gym-checkpoint tests, and the keys-only listing and SimpleStorage tests. Mutations checked earlier: making _run_capture_phases sequential fails the overlap test, and listing the staging partition twice fails the single-listing test. Ruff and Pyrefly passed. The hold benchmark does not model Gym's check.

Before the rebases:

  • 813 CPU checkpoint/restore/dispatch-race/recovery tests passed (--noconftest, pinned Gym 5911d628 on the path). The same 32 failures and 3 fixture errors occur unchanged on perf(checkpoint): defer rollout and trainer data-plane persistence #5139's head: the 32 are an environment AttributeError (capture_key) from the borrowed Gym checkout, the 3 need the skipped conftest. No new failures.
  • New tests: keys-only listing matches stock KV_LIST keys on a real in-process controller; extra_metadata reaches the completion marker and is rejected (repeated key, unserializable value) before any write; rollout snapshots serialize after resume and the published sidecar's sha256 equals the persisted digest; the trainer path binds the same digest; the build and the TQ capture provably overlap (a sequential mutation of _run_capture_phases fails this test); a failed inventory or build phase, and a cancelled capture, release the captured view.
  • test_tq_lifecycle.py and test_metrics.py with their conftest (real TQ fixtures): 82 passed.
  • tests/functional/data_plane_simple_checkpoint_cpu.py (real Ray/ZMQ, concurrent mutations, fresh-actor restore) passed, now also checking nrl_list_keys against KV_LIST on the real actor.
  • Ruff (lint, import order, format) and Pyrefly 0.24.2 passed. No GPU run.

🤖 Generated with Claude Code

@macandro96 macandro96 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 16, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 16, 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.

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please rebase first. This PR conflicts with its base. #5139 gained c98a1322fb (a recovery-metadata refactor in snapshots.py and test_checkpointing.py) after this PR was rebased. That commit does not touch _run_capture_phases, so C1 still applies.

Running the barrier phases side by side is a clean way to cut the hold, and moving the staging listing into RL removes Gym's dp_client dependency. The overlap and release tests fail if the phases run one after another or the view is never released, which is the right kind of guard.

  1. (C1) _run_capture_phases can drop the capture's CheckpointReleaseError when another phase also fails or the snapshot is cancelled. The fix and two regression tests are in the comment.

I reviewed only this PR's own commits (68bd259c70..96c48d5095). Tests ran on CPU only (no GPU run). Ruff passes on the changed files.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5241-shorter-barrier-hold.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5241-hidden-release-error.html

Generated by Claude Code

@macandro96
macandro96 force-pushed the amahishi/snapshot-barrier-hold branch from 96c48d5 to 8373572 Compare November 19, 2026 18:21
@macandro96
macandro96 removed this pull request from stack #5140 November 19, 2026 18:27
@macandro96
macandro96 added this pull request to stack #5317 November 19, 2026 18:27
@macandro96
macandro96 force-pushed the amahishi/snapshot-barrier-hold branch from 8373572 to 540e43d Compare November 19, 2026 18:42
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 540e43d

terrykong
terrykong previously approved these changes Nov 19, 2026
@macandro96

Copy link
Copy Markdown
Contributor Author

/ok to test 0c0196d

Base automatically changed from amahishi/async-tq-rollout-snapshots-main to main November 20, 2026 08:49
macandro96 and others added 5 commits November 20, 2026 00:49
The rollout-snapshot inventory checks compare key sets only, but
list_sample_ids used TQ's KV_LIST, which ships every key's custom
metadata (route plans and other tags). Add nrl_list_keys to the patched
controller, returning just one partition's keys, and use it from
list_sample_ids.

On a CPU TQ, the inventory check at 300k keys drops from 0.41s to 0.09s
with 64-byte tags and from 0.72s to 0.08s with 1 KB tags; at 2.6M keys
it drops from 4.84s to 1.02s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
Inside the barrier, run the replay and staging inventory checks, the
recovery-state build and the TQ capture concurrently. Every ledger
mutation needs the barrier; the controller maps the build reads are
copied on the event loop before it moves to a thread. A view captured
beside a failed or cancelled phase is released before the error
propagates, with CheckpointReleaseError if the release cannot be
confirmed.

The barrier phases now overlap, so the hold is close to the longest of
them rather than their sum. Serializing the recovery state after resume
is already in the base branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
A rollout snapshot listed the token-capture staging partition twice under
one barrier: once in Gym's check_against_cut, which ran before the
concurrent capture phases and so added to the hold, and again in the
recovery staging check. Restore listed it twice too.

List it once in the staging phase and pass the listing to both checks.
Gym's check now runs in that phase, beside the recovery-state build and
the TQ capture. Restore shares one listing between its two checks; only
the ledger changes between them.

The TQ adapter no longer sorts list_sample_ids: every caller compares key
sets, and sorting 2.6M staging keys took about 1.25 s per listing. The
interface no longer promises an order. The staging check also skips
sorting unreferenced rows it will not clear.

GymEnvironmentCheckpoint and the environment-checkpoint builders lose the
list_staging_keys hook and dp_client parameter that only fed the listing.

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

Review follow-up. CheckpointReleaseError means storage actors may still
hold a captured view, so checkpointing must stop. With the capture phases
running concurrently, _run_capture_phases could hide it: a retryable
error from another phase re-raised first (tq_capture is the last phase),
or a cancellation re-raised CancelledError after the capture task failed
its own late release. The snapshot pump then retried, or the failed
release went unreported.

Raise a phase's CheckpointReleaseError before any other error or the
cancellation. Tests, as proposed by the reviewer, cover both cases.

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

Listing the staging partition once per restore cut moved the
token_capture.staging_partition read above the token_capture.enabled
check, so a restore with token capture off read a setting it never uses.
Read it inside that branch again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
@terrykong
terrykong force-pushed the amahishi/snapshot-barrier-hold branch from 0c0196d to 9e6e97b Compare November 20, 2026 08:49
@terrykong
terrykong enabled stacked auto-merge (squash) November 20, 2026 08:49
@terrykong

Copy link
Copy Markdown
Collaborator

/ok to test 9e6e97b

@terrykong
terrykong merged commit 83151e7 into main Nov 20, 2026
95 checks passed
@terrykong
terrykong deleted the amahishi/snapshot-barrier-hold branch November 20, 2026 12:56
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.

2 participants