Where #4508's 1,740 added lines go, and the ~255 that can go without changing behavior

NVIDIA-NeMo/RL #4508, part 10 of 11 in the partial-checkpointing stack. Line counts are the PR against its real base f06773e (#4612). Permalinks pin the PR head 507a670. The review comments are in a pending review; their links work once it is published.

Before
The PR started at +2,802 lines. An earlier review took out the benchmark scripts, a second save loop and repeated defaults, and the author fixed all 7 of those comments. It is now two commits, +1,740/โˆ’334.
This PR
About 812 product lines (the row encoding in them is moved, not new) and about 928 test lines.
Status
Proposed, not in the PR. The cuts below are pending review comments C8โ€“C11, C13, C15 and C16. Only C8 changes behavior, and only after an interruption, where it matches what the code did before this PR. Not run on GPU.

Two pages on this PR. Read 1 ยท how it works first for what the batching does. This one: the code that can still go.

Most of the source change is reuse: the row encoding is the old single-row body moved into _encode_record. What is left over comes from earlier versions of this PR. The batch used to succeed or fail as a whole. Now each call fails on its own, but code that only the all-or-nothing version needed is still there: a two-step seal, grouping rows before a put, and checks that other code already makes. Tests repeat each other in a few places.

Lines added per file, and what each comment removes

gray = added by this PR ยท orange = what the review comments remove test_vllm_token_capture_hosting.py +451 โˆ’16 (C16) tq_token_sink.py +294 โˆ’15 (C9) โˆ’30 (C15) prefix_recovery/recovery.py +288 โˆ’28 (C8) โˆ’25 (C13) test_prefix_read_batcher.py +257 โˆ’81 (C11) prefix_read_batcher.py +175 โˆ’16 (C10) test_tq_token_sink.py +172 โˆ’25 (C11) โˆ’20 (C15) vllm_worker_async.py +13 config plumbing, other tests +90 Total about โˆ’115 product lines (C8โ€“C10 and C15 โ‰ˆ โˆ’90, C13 โ‰ˆ โˆ’25) and โˆ’140 test lines (C11, C15, C16).
CommentWhat goesWhy behavior stays
C8The second yield in _cut_transaction, the second loop in flush(), and a copy of the one-row write in stage()Each call already fails on its own. At the previous head, no test reached the two branches that go: both were made to raise, and 144 tests still passed. Not re-run at this head.
C9_stage_at_key (now one caller) and a one-line _discard_failed_write wrapperLeftovers from deleting the one-row save. Nothing in the product code needs them.
C10In PrefixReadBatcher: max_pending, which no caller sets, and the unique-keys and short-read guards (L53, L92). The key-by-key retry stays: after C13 it is the only retry.The only read function already raises on a short read, and Gym rejects duplicate keys.
C11Repeated test helpers, and two batcher tests that repeat othersTest-only. A trimmed batcher file passed 12/12 at an earlier head, and the file has not changed since.
C13read_restore_chunks, the chunks= argument and _fetch_chunks; resolve_restore does the shared read itselfSame rows from the same shared read; the caller's second read goes. It also keeps the batching after the rebase onto Dynamo (page 1).
C15Grouping rows by column signature in stage_generation_prefix_batch, plus two length checks and a duplicate-key check. One put per batch, plus one column check.All rows in a cut come from one worker, so they always fall in one group. Mixed types or sizes already raise before any write.
C16test_worker_failed_batch_put_is_retried_row_by_row and the fake sink's fail_multi_row flagTest-only. An existing test already fails a 2-row put and checks the one-row retry.

C8 โ€” recovery.py:657 C9 โ€” tq_token_sink.py:532 C10 โ€” prefix_read_batcher.py:95 C11 โ€” test_prefix_read_batcher.py:23 C13 โ€” recovery.py:995 C15 โ€” tq_token_sink.py:780 C16 โ€” test_vllm_token_capture_hosting.py:3953

The two biggest source cuts as diffs (C8, C15) โ€” proposed, not in the PR

Where the fixes land: RL only, two files. C8: _cut_transaction and flush() in prefix_recovery/recovery.py. C15: stage_generation_prefix_batch in data_plane/tq_token_sink.py; it returns the same keys in the same order, so no caller changes. No Gym change: Gym already takes one acknowledgement per call.

@@ recovery.py L654-L661 ยท _cut_transaction
                     terminal_stop_reason=progress.terminal_stop_reason,
                 )
-                if frozen.chunk_token_ids:
-                    # Every acknowledgement in a batch is built before any of
-                    # its calls seals; a failed one leaves its cut to roll back.
-                    yield acknowledgement
                 owned.seal(checkpoint_id, staged_key)
@@ recovery.py L871-L896 ยท _cut_batched.flush
                 keys = stage(batch)
-                ready = []
                 for (transaction, _, _, _, prefix), key in zip(
                     batch, keys, strict=True
                 ):
                     handed += 1
                     if key is None:
                         transaction.close()
                         continue
                     try:
-                        # A failure here rolls the call back and clears its row.
-                        ready.append((transaction, prefix, transaction.send(key)))
-                    except Exception:
-                        fail(prefix)
-                for transaction, prefix, acknowledgement in ready:
-                    try:
-                        transaction.send(None)
-                    except StopIteration:
-                        acknowledgements.append(acknowledgement)
-                    except Exception:
-                        fail(prefix)
-                    else:
-                        transaction.close()
-                        acknowledgements.append(
-                            self._failed_ack(prefix, reason="cut_error", uncut=uncut)
-                        )
+                        # Builds the ack and seals; a failure rolls back and clears the row.
+                        transaction.send(key)
+                    except StopIteration as done:
+                        acknowledgements.append(done.value)
+                    except Exception:
+                        fail(prefix)

What each piece does: the generator now builds the acknowledgement and seals in one step, as the code before this PR did for every call (base _cut_active). send(key) then ends with StopIteration, which carries the acknowledgement. A failure still rolls the call back, through the generator's own except BaseException. The one change: if the batch is interrupted partway (for example by KeyboardInterrupt), calls earlier in that batch stay saved instead of rolling back. Batch size 1 already behaves this way today, and so did the code before this PR. One test, test_worker_batch_interruption_clears_rows_no_call_received, needs its expectation updated. Not run.

C8 โ€” recovery.py:657

@@ tq_token_sink.py L789-L838 ยท stage_generation_prefix_batch (shortened with ...; docstring edit not shown)
-        if len(records) != len(chunk_sequences):
-            raise ValueError("records and chunk_sequences must have equal lengths")
+        if not records:
+            return []
         if attachments is None:
             attachments = [None] * len(records)
-        if len(records) != len(attachments):
-            raise ValueError("records and attachments must have equal lengths")
-        keys = [ generation_cut_staging_key(...) for ... ]
-        if len(set(keys)) != len(keys):
-            raise ValueError("generation-prefix batch contains duplicate staging keys")
-        groups = {}
-        for index, (record, row_attachments) in enumerate(zip(...)):
-            fields, tags = self._encode_record(...)
-            signature = tuple((name, fields[name].dtype, tuple(fields[name].shape[2:])) ...)
-            groups.setdefault(signature, []).append((index, fields, tags))
-        try:
-            for group in groups.values():
-                fields = TensorDict({...}, batch_size=[len(group)])
-                self._store.put_many([keys[item[0]] for item in group], fields, ...)
+        keys, encoded = [], []
+        for record, sequence, row_attachments in zip(
+            records, chunk_sequences, attachments, strict=True
+        ):
+            keys.append(generation_cut_staging_key(...))
+            encoded.append(self._encode_record(...))
+        # Columns come from row 0, so a column only some rows have would be dropped.
+        if any(fields.keys() != encoded[0][0].keys() for fields, _ in encoded):
+            raise ValueError("generation-prefix batch rows have different columns")
+        fields = TensorDict({...}, batch_size=[len(encoded)])
+        try:
+            self._store.put_many(keys, fields, tags=[tags for _, tags in encoded])
         except Exception:
             self._discard_failed_writes(keys)
             raise

What each piece does: zip(..., strict=True) raises on mismatched lengths before anything is written, so the two length checks go. Duplicate keys cannot reach here: _cut_batched already rejects duplicate model calls, and each key contains the model call's ID. The one case grouping did guard is a column that some rows have and others lack: the batch takes its column names from row 0 and would drop it with no error. The new column check covers that. The review comment has the full block that applies with one click. It parses and passes ruff. Not run on GPU.

C15 โ€” tq_token_sink.py:780

So what. Nothing here is a bug in normal use, and the design is sound: the review looked for a smaller design and found none. But this is part 10 of a stack past 20k lines. About 115 source lines and 140 test lines can go without changing what the code does, and C13's share also keeps restore batching working after the rebase onto Dynamo. Two smaller items are in the same review: aclose() can wait forever on a stopped event loop (C12, a one-line fix). And before merge the PR still needs CI on this head, the end-to-end save time, and the size of the largest put with routes on.

C12 โ€” prefix_read_batcher.py:156