Skip to content

fix(token-capture): preserve frozen snapshots when late writes arrive - #3970

Merged
linj-glitch merged 1 commit into
mainfrom
alexandery/capture-typed-frozen-store-error
Oct 5, 2026
Merged

linj-glitch merged 1 commit into
mainfrom
alexandery/capture-typed-frozen-store-error

Conversation

@alexandery-nvidia

@alexandery-nvidia alexandery-nvidia commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Two related changes in the training-token capture store.

  1. A typed error for a write after freeze. Writes to a frozen capture store raised a bare RuntimeError, so a caller could not tell "the rollout is already frozen" from any other failure of the sink. TokenCaptureFrozenError, a RuntimeError subclass so existing catchers keep working, names the condition; the TokenSink contract requires it, the file store raises it from put and register_call_intent, and the package exports it.

  2. A late record is dropped, not turned into a mark. commit_entry catches the new error: a capture that arrives after the rollout's capture was frozen (its harness was killed at a timeout backstop while the call was in flight) is dropped with one warning instead of marking the rollout incomplete. The freeze already judged completeness from the durable intent ledger, so the verdict is sealed. Marking the rollout incomplete at that point would mutate the frozen state and break the conditional retirement of the snapshot the finalize already consumed, leaving a capture that is never retired.

Issue

No issue filed; the defect showed as retirement failures ("snapshot version changed") on rollouts whose harness had been killed at the timeout backstop.

Validation

  • tests/unit_tests/test_token_id_capture.py gains test_a_late_capture_after_freeze_is_dropped_without_marking_the_frozen_rollout: a put after freeze raises the typed error, commit_entry drops it without a traceback, the rollout is not marked incomplete, a second freeze returns the identical snapshot, and the conditional drop with the original snapshot id and version still succeeds. The existing post-freeze conformance check still passes with the typed error.
  • Core unit suite on this branch (pytest tests/unit_tests, with the telemetry tests and test_collect_downstream_junit.py excluded for missing local packages): 6229 passed, 27 skipped, 1 failed. The one failure is test_slurm_script.py::test_build_vllm_ray_serve_command_single_node_model_with_space_survives_quoting, which needs a pip that this machine's externally managed Python refuses; it fails identically on main.
  • ruff check and ruff format --check on the changed files: clean.
  • Rollout evidence: this change has run for several weeks of GRPO training in a downstream fork with OpenCode and Codex harnesses under token-id capture, where timeout-killed sessions are routine; the retirement failures stopped with it.

🤖 Generated with Claude Code

Maintainer validation

Rebased onto current main and reviewed the store, sink, and protocol changes against the capture lifecycle and prior synthetic-completion constraints. The typed frozen-write error preserves RuntimeError compatibility; late writes leave the frozen snapshot identity, verdict, and conditional retirement unchanged. No remaining logical issue found in the scoped changes.

Validation on this head: 165 tests passed across test_token_id_capture.py, test_token_capture_conformance.py, and test_token_capture_golden_vectors.py; pre-commit run --all-files and git diff --check passed. A separate retired-state reproduction confirmed that a late write cannot mutate the tombstone or prevent reclamation. Existing downstream rollout evidence remains as recorded by the author; this review did not run a new GPU rollout.

@copy-pr-bot

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

…nd a late record is dropped

Writes to a frozen capture store raised a bare RuntimeError, so a caller
could not tell "the rollout is already frozen" from any other failure of the
sink. TokenCaptureFrozenError, a RuntimeError subclass so existing catchers
keep working, names the condition; the TokenSink contract requires it and
the package exports it.

commit_entry uses it: a capture that arrives after the rollout's capture was
frozen (its harness was killed at a timeout backstop while the call was in
flight) is dropped with a warning instead of marking the rollout incomplete,
which would mutate the frozen state and break the conditional retirement of
the snapshot the finalize already consumed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@linj-glitch
linj-glitch force-pushed the alexandery/capture-typed-frozen-store-error branch from b12d906 to 68edf7f Compare October 5, 2026 07:17
@linj-glitch linj-glitch changed the title fix(token-capture): a write to a frozen store raises a typed error, and a late record is dropped fix(token-capture): preserve frozen snapshots when late writes arrive Oct 5, 2026
@linj-glitch linj-glitch added area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working ready-to-merge PR is approved, current, and waiting for final CI or merge labels Oct 5, 2026
@linj-glitch
linj-glitch marked this pull request as ready for review October 5, 2026 07:17

@linj-glitch linj-glitch 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.

Rebased onto current main and reviewed the store, sink, and protocol changes against the capture lifecycle and prior synthetic-completion constraints. The typed frozen-write error preserves RuntimeError compatibility; late writes leave the frozen snapshot identity, verdict, and conditional retirement unchanged. No remaining logical issue found in the scoped changes.

Validation on this head: 165 tests passed across test_token_id_capture.py, test_token_capture_conformance.py, and test_token_capture_golden_vectors.py; pre-commit run --all-files and git diff --check passed. A separate retired-state reproduction confirmed that a late write cannot mutate the tombstone or prevent reclamation. Existing downstream rollout evidence remains as recorded by the author; this review did not run a new GPU rollout.

@linj-glitch

Copy link
Copy Markdown
Collaborator

/ok to test 68edf7f

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/37278051406

@yaoyu-33 yaoyu-33 added the complexity:low Localized change in one scope with a small, straightforward review surface label Oct 5, 2026
Merged via the queue into main with commit 1aa5dae Oct 5, 2026
49 checks passed
@linj-glitch
linj-glitch deleted the alexandery/capture-typed-frozen-store-error branch October 5, 2026 07:41
yuhezhang-ai pushed a commit to larroy/Gym that referenced this pull request Oct 6, 2026
…NVIDIA-NeMo#4092)

## Problem

`_CaptureMiddleware` awaits the capture write unshielded on the success
path while catching only `Exception`:

```python
await asyncio.to_thread(_parse_and_record)
except Exception:
```

A cancellation arriving after that await but **before the thread-pool
executor picks up the job** drops the model-call row with no log line,
no `.capture.incomplete` marker, and no trace anywhere. The error path a
few lines above already catches `CancelledError`; only the success path
does not.

The symptom is `trajectory_capture_mismatch` / `missing_captured_call`:
the agent's `ng_trajectory` references a `response_id` that
`ng_model_call_capture` never recorded.

## Evidence

Measured on AutomationBench, 600 tasks per run, oci-hsg, by
instrumenting four probe points around the finalization and the writer.

| | unshielded | shielded |
|---|---|---|
| `CAPTURE_FINALIZE` (finalizations entered) | 8989 | 9380 |
| `CAPTURE_ATTEMPT` (writer entered) | 8967 | 9380 |
| `CAPTURE_WROTE` (writer returned) | 8967 | 9380 |
| **`FINALIZE` − `ATTEMPT`** | **22** | **0** |
| `CAPTURE_FINALIZE_CANCELLED` | 4501 | 4230 |
| `missing_captured_call` findings | 22 | 2 |
| unhealthy rollouts | 30/600 (5.0%) | 3/600 (0.5%) |

Three things this pins down:

1. **The store is not the problem.** `ATTEMPT` equals `WROTE` in both
runs — every writer that started, finished. The `flock` + `fsync` path
in `CaptureStore.record` never loses a row.
2. **The loss is pre-execution cancellation.** In the unshielded run the
`FINALIZE` − `ATTEMPT` gap is 22, and that run had exactly 22
`missing_captured_call` findings. No capture-failure warnings were
logged, so these were not exceptions.
3. **Shielding closes it.** The gap goes to 0 while 4230 cancellations
still occur — cancellation is not prevented, it just no longer discards
a queued write.

Cancellation on this path is constant (~4000 per 600-task run), but only
~0.5% of cancellations lose data, because `asyncio.to_thread` cannot
cancel a thread that is already running. Only those landing in the
pre-execution window lose the row.

Before this, the rate was stable at 5.2–6.3% across four runs that
varied checkpoint, serving stack and Gym pin — including a pin carrying
NVIDIA-NeMo#3969, NVIDIA-NeMo#3970, NVIDIA-NeMo#3972 and NVIDIA-NeMo#3974, which address a different capture failure
and do not move this one.

## Residual: a different mechanism, now isolated

Three rollouts still carry a finding after the fix, down from 22. They
are **not** the same failure, and the distinction is measurable rather
than asserted.

Grepping every on-disk `*.capture.jsonl` in the run for the flagged
`response_id`s:

| | unshielded | shielded |
|---|---|---|
| flagged ids absent from disk entirely | 39 of 40 | **0 of 3** |
| flagged ids present on disk | 1 of 40 | **3 of 3** |

So before the fix the rows were overwhelmingly never written at all;
after it, every flagged row *is* on disk. What remains is a late write —
the row reaches the capture file after the rollout record has been
snapshotted, so it is absent from `ng_model_call_capture` while present
on disk.

That is a separate race with a separate fix, out of scope here. This
change closes the "never written" class completely.

## Testing

`pytest tests/unit_tests/test_base_responses_api_model.py` — 105 passed.

No unit test is added. `asyncio.to_thread` does not cancel an
already-running thread, so the defect only reproduces in the window
before the executor starts the job, which I could not schedule
deterministically. A test that cannot be made to fail without the fix
would be vacuous. The two 600-task runs above are the verification
instead.

Signed-off-by: Wojciech Prazuch <[email protected]>

This branch was previously deployed

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

Labels

area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants