Skip to content

feat(token-capture): make attributed incomplete-capture masking optional - #3974

Merged
linj-glitch merged 2 commits into
mainfrom
alexandery/capture-mask-incomplete-when-attributed
Oct 5, 2026
Merged

linj-glitch merged 2 commits into
mainfrom
alexandery/capture-mask-incomplete-when-attributed

Conversation

@alexandery-nvidia

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds the token_id_capture.mask_incomplete_when_attributed setting (default true, today's behavior) to the training-token capture layer.

An incomplete capture snapshot is one in which some model call registered its capture intent and never committed a record. A harness killed at its timeout backstop while a call is in flight leaves exactly this signature. Today the consumer masks such a rollout unconditionally (mask_sample: true), because the uncaptured call might be the trajectory's real terminal.

Terminal attribution already settles that question in one case. When the verifier-scored response is attributed to a captured call and that call's chain delivers whole (terminal_attribution.chain == "delivered"), a call with no record cannot sit inside the delivered chain, so the uncaptured call lies outside the scored trajectory. With mask_incomplete_when_attributed: false the consumer keeps such a build trainable; every other attribution outcome (no attribution, a conflicting one, an undelivered chain) still masks. Nothing else about the build changes: metrics.capture_incomplete is still reported either way.

Plumbing: the setting lives on TokenIdCaptureSettings (nemo_gym/token_id_capture/config.py), mask_incomplete_when_attributed_from_config reads it from the global config, RolloutCollectionHelper reads it once per collection and passes it to finalize_rollout_token_capture, which forwards it to trajectories_from_source; trajectories_for_rollout takes the same keyword. All new parameters default to the strict behavior. The external-agent-harness training page documents the setting next to max_mask_fraction.

Issue

No issue filed. Observed while training with external agent harnesses under a wall-clock timeout: every rollout whose harness was killed mid-call was masked even when the scored answer had been delivered and attributed turns earlier, which wasted otherwise clean samples.

Validation

  • tests/unit_tests/test_trajectory_builder.py, tests/unit_tests/test_rollout_collection.py, tests/unit_tests/test_token_id_capture.py: 565 passed. New tests cover the default (an incomplete capture masks even with a delivered attribution), the opt-out (a delivered attribution keeps the build with the setting off), the unattributed case (masks with either value), and the config reader.
  • Full core suite (tests/unit_tests, with the telemetry, opensandbox, and profiling modules excluded because their optional dependencies are not installed locally): 6234 passed, 27 skipped, 1 failed (test_slurm_script::test_build_vllm_ray_serve_command_single_node_model_with_space_survives_quoting, which runs pip into the system interpreter and fails with externally-managed-environment on this machine; unrelated to the change).
  • pre-commit run --files <changed files>: passed.
  • Rollout evidence: this setting has run for weeks in a downstream fork training with OpenCode and Codex harnesses under token-id capture, where it recovers the rollouts whose harness was killed after the scored answer was already delivered.

🤖 Generated with Claude Code

Maintainer validation

Reviewed the opt-in incomplete-capture masking policy and its configuration/callers against current capture attribution behavior. Strict masking remains the default; opting out preserves only a wholly delivered, attributed terminal chain, while other masking reasons remain intact. No blocking findings remain.

Validation: 565 focused tests passed across trajectory building, rollout collection, and token capture, including missing/ambiguous terminals and strict/default behavior. Full pre-commit suite and git diff --check passed. The additive main merge has an identical tree to the tested revision. No fresh real-model rollout was run locally; author-provided downstream evidence and synthetic integration tests cover this shared capture-consumption change.

…omplete capture trainable

An incomplete capture snapshot is one in which some model call registered
its capture intent and never committed a record; a harness killed at its
timeout backstop while a call is in flight leaves exactly this signature.
The consumer masked such a rollout unconditionally, because the uncaptured
call might be the trajectory's real terminal.

Terminal attribution settles that in one case. When the verifier-scored
response is attributed to a captured call and that call's chain delivers
whole, a call with no record cannot sit inside the delivered chain, so the
uncaptured call lies outside the scored trajectory. The new
token_id_capture.mask_incomplete_when_attributed setting (default True, the
previous behavior) lets a deployment keep such a build trainable; every
other attribution outcome still masks, and metrics.capture_incomplete is
reported either way.

The setting is read once per collection in RolloutCollectionHelper and
passed through finalize_rollout_token_capture to trajectories_from_source;
trajectories_for_rollout takes the same keyword. All new parameters default
to the strict behavior.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@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.

@linj-glitch linj-glitch changed the title feat(token-capture): a delivered terminal attribution can keep an incomplete capture trainable feat(token-capture): make attributed incomplete-capture masking optional Oct 5, 2026
@linj-glitch linj-glitch added area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work 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:26

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

Reviewed the opt-in incomplete-capture masking policy and its configuration/callers against current capture attribution behavior. Strict masking remains the default; opting out preserves only a wholly delivered, attributed terminal chain, while other masking reasons remain intact. No blocking findings remain.

Validation: 565 focused tests passed across trajectory building, rollout collection, and token capture, including missing/ambiguous terminals and strict/default behavior. Full pre-commit suite and git diff --check passed. The additive main merge has an identical tree to the tested revision. No fresh real-model rollout was run locally; author-provided downstream evidence and synthetic integration tests cover this shared capture-consumption change.

@linj-glitch

Copy link
Copy Markdown
Collaborator

/ok to test 59f886f

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

@yaoyu-33 yaoyu-33 added the complexity:medium Single-domain change with interacting parts or a moderate review surface label Oct 5, 2026
@linj-glitch
linj-glitch added this pull request to the merge queue Oct 5, 2026
@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/37279045614

Merged via the queue into main with commit f8f83f3 Oct 5, 2026
49 checks passed
@linj-glitch
linj-glitch deleted the alexandery/capture-mask-incomplete-when-attributed branch October 5, 2026 07:53
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]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Oct 13, 2026
…ough (NVIDIA-NeMo#4364)

## What does this PR do?

Pull request NVIDIA-NeMo#3974 added the setting
`token_id_capture.mask_incomplete_when_attributed` (default `true`). The
collection loop reads it once with
`mask_incomplete_when_attributed_from_config(...)`
(`nemo_gym/rollout_collection.py:2636`) and passes the value to
`finalize_rollout_token_capture(...)` as a keyword argument
(`nemo_gym/rollout_collection.py:2832-2834`), which forwards it to
`trajectories_from_source(...)`
(`nemo_gym/token_id_capture/delivery.py:171`). The finalizer defaults
that argument to `True` (`nemo_gym/token_id_capture/delivery.py:88`).
Nothing in `tests/unit_tests/test_rollout_collection.py` pinned that the
configured value reaches the finalizer: with the keyword argument
dropped at the call site, every existing test stays green while a
configured `false` never takes effect.

This PR adds one parametrized test,
`TestRolloutCollection::test_run_from_config_forwards_mask_incomplete_when_attributed_to_the_finalizer`,
next to the other collection-path token-capture tests. The test does the
following.

1. It points `get_global_config_dict` at a `token_id_capture` block with
`enabled`, `all_agents`, `rebuild_response`, and a `dir` under
`tmp_path`, plus the parametrized setting
(`mask_incomplete_when_attributed: false` in one case, absent in the
other). It patches `installed_token_source` to return `None`, so the
collection loop builds its own `TokenCaptureStore` from `dir`.
2. It replaces
`nemo_gym.rollout_collection.finalize_rollout_token_capture` with
`AsyncMock(wraps=finalize_rollout_token_capture)`, so the call arguments
are recorded while the real finalizer still runs.
3. It runs `run_from_config` over one rollout through a
`RolloutCollectionHelper` subclass whose `_run_examples_with_metadata`
returns a completed rollout, as the neighbouring tests do. The store
holds no records for the rollout, so the real finalizer masks it and
emits the `capture contains no token records` warning the test expects.
4. It asserts that the finalizer was awaited once, with
`mask_incomplete_when_attributed=False` for the configured case and
`True` for the absent case.

This PR changes no production code.

## Issue

No issue filed; the gap was found while reviewing NVIDIA-NeMo#3974's merge.

## Validation

- `pytest -q -p no:cacheprovider -o addopts=
tests/unit_tests/test_rollout_collection.py`, run from the checkout with
the checkout on `PYTHONPATH`: **431 passed, 0 failed** (12 warnings; the
new test on its own reports only pytest's `Unknown config option:
cache_dir` notice for this pytest version).
- Mutation check: with the keyword argument temporarily removed from the
call at `nemo_gym/rollout_collection.py:2832-2834`
(`finalize_rollout_token_capture(result, token_source)`), both
parameterizations fail with `KeyError:
'mask_incomplete_when_attributed'` on the recorded call arguments. The
call site was restored before committing, and the diff touches only the
test file.
- `ruff check tests/unit_tests/test_rollout_collection.py` and `ruff
format --check tests/unit_tests/test_rollout_collection.py` are both
clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: alexandery <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 59f886f6 Deployed Oct 5, 2026 by copy-pr-bot[bot] via release / finalize / notify #4260
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 complexity:medium Single-domain change with interacting parts or a moderate review surface feature New capabilities, enhancements, or enablement work 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