What changes when prefix saves and restores go to TransferQueue in batches, and what the rebase onto Dynamo breaks

NVIDIA-NeMo/RL #4508, part 10 of 11 in the partial-checkpointing stack, on top of #4612. Permalinks pin the PR head 507a670; "before" links pin the base f06773e; Dynamo links pin #4979 at 766f81d. The review comments are in a pending review; their links work once it is published.

Before
At a checkpoint, each unfinished model call saved its tokens with its own TransferQueue write. After a restart, each resumed request read its own saved rows on its own thread.
This PR
Groups the saves into a few large writes, and merges the reads of requests that resume together into one shared read. Two config keys set the batch limits.
Status
Works today; one open problem after the rebase. The batching works on today's head. After the planned rebase onto Dynamo support (#4979), the shared restore read is skipped on both native vLLM and Dynamo. Open, tracked in C13 and C14, fix shown below. Cut-time batched writes need no change on Dynamo.

Two pages on this PR. This one: what the PR does, and the one problem the rebase onto Dynamo causes. Next: the code that can still go.

Background. When RL saves a checkpoint in the middle of generation, each unfinished model call writes its tokens so far to TransferQueue (TQ), one row per call. After a restart, Gym sends the call back with the keys of its saved rows, and the call continues from them instead of starting over. Dotted words have a short explanation: hover or tap them.

Before, the save loop wrote one call at a time (_cut_active → stage_generation_prefix). Now _cut_batched freezes calls one by one, keeps each locked, and writes up to 256 rows in one stage_generation_prefix_batch call. On restore, the new PrefixReadBatcher waits 2 ms, merges the keys of every request that asked, and runs one get.

The two paths, on one small example

Example: 3 unfinished calls (c0, c1, c2) and a batch limit of 2 rows. On restore, c1 has 2 saved rows (one from an earlier checkpoint), so the 3 requests need 4 keys.

At a checkpoint (save) After a restart (restore) Before This PR c0 · 40 tok c1 · 700 tok c2 · 25 tok put [c0] put [c1] put [c2] 3 puts stage_generation_prefix each call is locked only for its own write c0 · 40 tok c1 · 700 tok c2 · 25 tok put [c0, c1] put [c2] 2 puts stage_generation_prefix_batch dashed = calls held locked until their group's put returns r0 · 1 key r1 · 2 keys r2 · 1 key get [k0] get [k1, k2] get [k3] 3 gets resolve_restore each request reads its own rows on its own thread r0 · 1 key r1 · 2 keys r2 · 1 key wait 2 ms get [k0,k1,k2,k3] 1 get PrefixReadBatcher rows go back to each request, then into resolve_restore(…, chunks) today only the vLLM chat handler passes chunks; see below

Both write paths build a row with _encode_record, the old single-row body moved. The per-call freeze, ack and seal logic is the old body too, now the generator _cut_transaction, so a batch can keep several calls frozen at once. Both restore paths end in resolve_restore, which checks the prefix digest and lets the call regenerate if anything is wrong. A call that finishes while its group's put runs waits for its lock (asked in the review body). A failed group put is retried one row at a time, so a bad row fails only its own call.

The same change as pseudocode

Names are shortened and error paths trimmed, but each block keeps the real threads and locks. Underlined names link to the real line. Orange says where the code runs. In the "after" blocks, green lines are new and red lines are gone; plain lines are unchanged.

Save, before

# serving event loop: Gym asks this worker to cut
async def run_cut(inventory):
    return await run_in_executor(cut_thread, cut, inventory)  # one cut thread per worker

# cut thread
def cut(inventory):
    read_progress(inventory.calls)                            # one engine read for every call
    for call in inventory.calls:                              # one call at a time
        if past_deadline(): fail(rest); break
        with call.lifecycle_lock:                             # the call cannot finish or abort meanwhile
            row = freeze(call)
            key = tq.put([row])                               # 1 TQ write per call
            ack = build_ack(call, key)
            seal(call, key)                                   # any error: roll back; this call regenerates
        acks.append(ack)

# serving threads, at the same time: a call that finishes
await to_thread(finish_capture, call)                         # waits on call.lifecycle_lock

Real code: run_cut, checkpoint_cut, _cut_active (at the base).

Save, after

# cut thread (same entry point, same thread)
def cut(inventory):
    read_progress(inventory.calls)
    group = []
    for call in inventory.calls:
        if past_deadline(): fail(group + rest); break
        with call.lifecycle_lock:
            row = freeze(call); key = tq.put([row]); ack = build_ack(call, key); seal(call, key)
        tx = cut_transaction(call)                           # a generator; it takes call.lifecycle_lock
        row = next(tx)                                       # freeze; the lock stays held
        group.append((tx, row))
        if len(group) == 256 or tokens(group) >= 4_194_304:
            flush(group)
    flush(group)

def flush(group):                                            # still on the cut thread
    if past_deadline(): roll back group; return
    try:    keys = tq.put([row for _, row in group])         # 1 TQ write for up to 256 calls
    except: keys = [tq.put([row]) or None for row in group]  # retry one row each, once
    for tx, key in zip(group, keys): ack = tx.send(key)      # build every ack first
    for tx in group: tx.send(None)                           # then seal; each lock is released
                                                             # C8: these two loops can be one; each call already fails on its own

def cut_transaction(call):                                   # the old per-call body, split at the put
    with call.lifecycle_lock:
        row = freeze(call)
        key = yield row                                      # paused, lock held, until its group is written
        ack = build_ack(call, key)
        yield ack                                            # C8: the second pause
        seal(call, key)

# serving threads, at the same time: a call that finishes
await to_thread(finish_capture, call)                        # now waits for its whole group's write

Real code: _cut_batched with its stage and flush, _cut_transaction, and the write stage_generation_prefix_batch.

Restore, before

# serving event loop: one coroutine per resumed request, many at once
async def handle_restored_request(request):
    admission, saved = await to_thread(resolve_restore, request.admission)

# a pool thread, one per request
def resolve_restore(admission):
    rows = tq.get(admission.staging_keys)  # 1 TQ read per request
    check_digests(rows)                    # any error: drop the cut; the call regenerates
    return admission, rows

Real code: chat handler, resolve_restore (at the base).

Restore, after

# serving event loop: one coroutine per resumed request, many at once
async def handle_restored_request(request):
    rows = await reader.fetch(request.admission.staging_keys)      # joins a shared read
                                                                   # on error: logged at DEBUG, rows = None
    admission, saved = await to_thread(resolve_restore, request.admission, rows)

# a pool thread, one per request
def resolve_restore(admission, rows=None):
    if rows is None:                                               # the shared read failed: read again here
        rows = tq.get(admission.staging_keys)
    check_digests(rows)
    return admission, rows

class PrefixReadBatcher:                                           # one per worker, bound to the serving loop
    async def fetch(keys):
        futures = [queue.add(key) for key in keys]
        start runner() once, as a task on this loop
        return await gather(futures)

    # background task on the serving loop
    async def runner():
        while True:
            await queue.not_empty
            await sleep(0.002)                                     # 2 ms for other requests to join
            batch = queue.take(up to 256 distinct keys)
            rows = await to_thread(tq.get, batch)                  # 1 TQ read for many requests
            on error: await to_thread(tq.get, [key]) for each key  # retry each key alone, once
            hand each row (or its error) to every request waiting on it

Real code: chat handler, read_restore_chunks, resolve_restore, PrefixReadBatcher. The shared read only happens because the chat handler calls reader.fetch first. The next section is about what happens when the rebase deletes that handler.

After the rebase onto #4979, the shared read is skipped (C13) — fix proposed, not in the PR

Merge plan: #4583 → main; #4979 (Dynamo) on #4583; #4612 on #4979; this PR on #4612. #4979 deletes the vLLM chat handler, the one place this PR calls read_restore_chunks. Native and Dynamo then share one restore path, and it passes no rows:

native chat_server Dynamo adapter start_capture resolve_restored_call resolve_restore(adm, ids) no chunks → 1 get per restore r0, r1, r2 → 3 gets, as before this PR PrefixReadBatcher is never called. Restores still work, so no test fails and no error or generation_prefix_read_batch log line appears. Each worker serves restores on one event loop in both modes.

Where the fix lands: RL only. PrefixRecovery.resolve_restore in this PR, and one call in #4979's resolve_restored_call. No Dynamo-only code: both paths call that function. Cut-time writes need no change: Dynamo calls the same run_cut.

The fix, as pseudocode (proposed, not run)

# serving event loop: native chat_server or Dynamo adapter, after #4979
async def resolve_restored_call(request):
    admission, saved = await to_thread(resolve_restore, request.admission)  # no rows: the shared read never runs
    admission, saved = await resolve_restore(request.admission)

# PrefixRecovery in this PR: the read moves inside, so no caller can skip it
def resolve_restore(admission, rows=None):
async def resolve_restore(admission):
    rows = await reader.fetch(admission.staging_keys)                       # on the serving loop; restores share the read
    if rows is None:
        rows = tq.get(admission.staging_keys)                               # the second read goes
    await to_thread(check_digests, rows)                                    # slow checks stay off the loop
    on any error: WARNING, drop the cut; the call regenerates

async def read_restore_chunks(admission): ...                               # deleted, with its DEBUG log

What each piece does: resolve_restore now does the shared read itself, so no caller can skip it. Any read failure, including a wrong-loop call, reaches the existing except: a WARNING, and the call regenerates. Before, a DEBUG log hid it and the rows were read again. The chunks= argument, _fetch_chunks and read_restore_chunks go, about −25 source lines. The return type stays the same, so the routes from #4612 C27 and the media from #4979 C92 ride on the same object. About 8 test calls gain await. C14 replaces the two fallback tests with one test of 4 concurrent restores through resolve_restored_call that asserts one read, plus one log grep in the prefix-recovery functional script, which also runs behind Dynamo. Sketch, not run.

C13 — recovery.py:995 C14 — test_vllm_token_capture_hosting.py:4145

So what. The batching itself is sound and reuses the old code well. But its restore half hangs on one call site that the Dynamo rebase deletes, and nothing would notice: restores would quietly go back to one read each. Moving the read into resolve_restore fixes that for native and Dynamo at once, and makes the PR smaller. The other size cuts are on the next page, 2 · what can shrink.