Skip to content

feat(token-capture): attribute terminals with corroborated item IDs - #3972

Merged
linj-glitch merged 2 commits into
mainfrom
alexandery/capture-item-id-terminal-witness
Oct 5, 2026
Merged

linj-glitch merged 2 commits into
mainfrom
alexandery/capture-item-id-terminal-witness

Conversation

@alexandery-nvidia

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds a fifth witness to terminal attribution in nemo_gym/token_id_capture/terminal.py: the item-id witness.

Terminal attribution names the model call that produced the verified response by joining independent witnesses (explicit, response id, content). A harness that rebuilds its transcript from its own session files, which OpenCode and Codex both do, never records the served response id, and when the session ends on a tool result (the harness was killed while a tool ran) the content witnesses abstain because the transcript does not end on model output. Such a rollout was masked although every call was captured whole.

The item-id witness reads the served id of the response's last model-authored item: a message's id or a tool call's call_id, which the model server assigned and the harness keeps per item. The id must be recorded on exactly one entry's output, and that item's content must match (the tool's name without any namespace prefix plus its canonical arguments, or the message's content parts), so a reused or colliding id cannot name a call whose output the transcript does not end with. Tool calls nested in a chat assistant message's tool_calls list are read as well. An item whose id no entry recorded (a message the harness composed itself) abstains, a shared id abstains as ambiguous, and a disagreement with another witness still fails closed. The witness skips token-free custody rows, as the content witness does.

NAMESPACE_TOOL_DELIMITER moves from nemo_gym/responses_streaming.py to nemo_gym/token_id_capture/records.py, because the witness strips a flattened tool's group name and test_package_is_dependency_free_leaf requires the capture package not to import the server stack; responses_streaming imports the constant from there, so its value and users are unchanged.

Issue

No issue filed; the masked rollouts were observed while training with OpenCode and Codex as harnesses under token-id capture.

Validation

  • PYTHONPATH=. python -m pytest -q tests/unit_tests/test_terminal_attribution.py tests/unit_tests/test_trajectory_builder.py tests/unit_tests/test_token_id_capture.py tests/unit_tests/test_responses_api_model_streaming.py: 402 passed, including nine new tests (a transcript ending in a tool result, a served message id corroborated by content, a harness-composed message, disagreement with the response id, chat-nested tool calls, a namespaced tool name, a shared id, a last item without an id, and an id whose content differs).
  • 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): 6237 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.
  • pre-commit run --files <changed files>: passed (ruff, ruff-format, end-of-file, trailing whitespace).
  • Rollout evidence: this witness has run for several weeks in a downstream fork training with OpenCode and Codex harnesses under token-id capture; rollouts whose session ended on a tool result attribute by item_id instead of masking.

🤖 Generated with Claude Code

Maintainer validation

Reviewed the item-ID witness, content corroboration, witness disagreement, ambiguous identities, namespace handling, and dependency-free capture package against current main and recent attribution history. No blocking findings remain.

Validation: 404 tests passed across terminal attribution, trajectory building, token capture, and streaming. Full pre-commit suite and diff checks passed. Additive main merge preserves author history. No fresh model smoke was run locally; existing author-provided downstream harness evidence is retained.

…from the last model-authored item

Terminal attribution joins independent witnesses to name the model call
that produced the verified response. A harness that rebuilds its transcript
from its own session files (OpenCode and Codex both do) never records the
served response id, and when the session ends on a tool result the content
witnesses abstain, so such a rollout was masked although every call was
captured whole.

The item-id witness reads the served id of the response's last
model-authored item: a message's id or a tool call's call_id, which the
model server assigned and the harness keeps per item. The id must be
recorded on exactly one entry's output, and that item's content (the tool's
name without any namespace prefix and its canonical arguments, or the
message's content parts) must match, so a reused or colliding id cannot
name a call whose output the transcript does not end with. Tool calls
nested in a chat assistant message's tool_calls list are read as well. An
item whose id no entry recorded abstains, and a disagreement with another
witness still fails closed.

NAMESPACE_TOOL_DELIMITER moves to token_id_capture.records because the
witness strips a flattened tool's group name and the package must not
import the server stack; responses_streaming imports it from there.

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): an item-id witness attributes the terminal call from the last model-authored item feat(token-capture): attribute terminals with corroborated item IDs 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:36

@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 item-ID witness, content corroboration, witness disagreement, ambiguous identities, namespace handling, and dependency-free capture package against current main and recent attribution history. No blocking findings remain.

Validation: 404 tests passed across terminal attribution, trajectory building, token capture, and streaming. Full pre-commit suite and diff checks passed. Additive main merge preserves author history. No fresh model smoke was run locally; existing author-provided downstream harness evidence is retained.

@linj-glitch

Copy link
Copy Markdown
Collaborator

/ok to test 375cd78

@linj-glitch
linj-glitch enabled auto-merge October 5, 2026 07:36
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 5, 2026 07:36
@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/37279775241

Merged via the queue into main with commit f4e8741 Oct 5, 2026
49 checks passed
@linj-glitch
linj-glitch deleted the alexandery/capture-item-id-terminal-witness branch October 5, 2026 08:03
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 — 375cd78e Deployed Oct 5, 2026 by copy-pr-bot[bot] via release / finalize / notify #4262
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