Skip to content

feat(token-id-capture): resolve parent and terminal call by tool-call ids - #4014

Merged
ananthsub merged 8 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/token-capture-tool-call-ids
Oct 16, 2026
Merged

ananthsub merged 8 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/token-capture-tool-call-ids

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Preserve token-capture ancestry when a harness echoes a complete served model turn but rewrites its tool arguments, as Claude Code does for Bash commands and Edit defaults. The fallback requires matching tool IDs, names, order and non-tool assistant content, plus the recorded request context; inserted, missing or changed model output and ambiguous token sequences remain unresolved.

Both local token logs and external-staging custody ledgers now retain this complete-turn key, return tool_call_turn when it supplies the parent, and reuse the parent's original staged tokens. Existing custody rows without the new optional key remain strict-only, identical replays remain idempotent, and checkpoint import/export preserves new keys. This deliberately narrows #3301's rejection of edited echoes to permit argument-only rewrites while continuing to reject text, tool-name, ID and item changes.

Terminal attribution skips token-free custody rows for the argument-insensitive reading, rejects IDs reused in earlier transcript turns, and treats interleaved reasoning consistently. Strict witnesses still take precedence, conflicting witnesses fail closed, and the merge with #3973 preserves the distinction between a uniquely identified serving and token-identical retries with different finish reasons. Custody-only terminal attribution still relies on its existing IDs/fingerprints; this PR does not add output items to custody records.

The file-ledger implementation in #4553 should be updated to use this complete-turn key when that branch integrates #4014, rather than reintroducing its older ID-only match. No separate issue is needed for the defects addressed by the inline review.

Validation

  • Source-bound native Python 3.13 run: 1,425 passed, covering test_tool_call_turn_fallback.py, test_tool_call_turn_lineage_store.py, test_token_id_capture.py, test_terminal_attribution.py, test_conversation_fingerprint.py, test_external_capture_handlers.py, test_trajectory_builder.py, all test_token_capture_*.py, and the complete responses_api_models/vllm_model/tests/ suite.
  • New regression controls: 9 failed before / passed after for interleaved reasoning and reused terminal IDs; one additional finish-reason identity regression failed before the main-integration fix. Tests also exercise durable-store restart/checkpoint compatibility, strict precedence, ambiguity, identical retries, version guards, and HTTP continuations consuming the exact original staged token prefix.
  • pre-commit run --all-files and git diff --check: passed; the private guardwords catalog was unavailable, so that hook skipped its private-catalog scan. The formatter changed one test file; its 65 cases passed again on final head a791afff6f875a53908420df5198cf30a9feeab7.

Rollouts and compatibility

No fresh live-model rollout was run for this revision; HTTP routing, conversion, lineage, admission and worker capture helpers are exercised with CPU generation/staging doubles. The earlier report of several thousand Claude Code training rollouts is historical author-provided evidence, not validation of this revised head. Argument-only echoes may become trainable where they previously failed attribution; this changes sample eligibility, not verifier scores, and requires Ananth's review and required CI before merge.

@copy-pr-bot

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

@yaoyu-33 yaoyu-33 added area:training Training framework integrations and training-data interfaces complexity:medium Single-domain change with interacting parts or a moderate review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 5, 2026
@linj-glitch
linj-glitch marked this pull request as draft October 5, 2026 06:11
@linj-glitch
linj-glitch force-pushed the linj/token-capture-tool-call-ids branch from 6182009 to b933a3e Compare October 8, 2026 00:15
… ids

Lineage resolves a continuation's parent by hashing the model-authored turns
of the request (assistant text and canonicalized tool-call arguments) and
looking the hash up among committed calls. Some harnesses echo tool-call ids
verbatim but rewrite the arguments before sending history back. Claude Code's
Bash tool strips a leading `cd <cwd> && `, and its Edit tool fills schema
defaults such as `"replace_all": false`. Every such turn misses the
fingerprint (`unresolved/no_match`), a new chain root is opened, and
multi-turn rollouts fragment into several chains that cannot be delivered.
Terminal attribution fails for the same reason
(`response_id_no_match,no_content_match`).

Index each committed call by the tool-call ids in its response, on both the
entry path and the ledger `record` path. When the fingerprint lookup yields
no candidate, take the ids of the request's trailing model-authored turn and
resolve to the single call that produced them. The existing context-digest
check still rejects rewritten or compacted history, and ambiguous ids stay
unresolved.

Terminal attribution gets the same fallback inside the content witness: when
no content hash matches, the transcript's trailing block's tool-call ids must
equal exactly one captured call's ids (`method="content_tool_ids"`).
Ambiguous ids abstain with `tool_ids_ambiguous`.

Signed-off-by: Lin Jia <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@linj-glitch
linj-glitch marked this pull request as ready for review October 13, 2026 23:19
@ananthsub
ananthsub requested a review from pthombre October 14, 2026 22:24
Comment thread nemo_gym/token_id_capture/terminal.py Resolved
Comment thread nemo_gym/token_id_capture/lineage.py Resolved
Comment thread nemo_gym/token_id_capture/lineage.py Resolved
Comment thread nemo_gym/token_id_capture/lineage.py Resolved
Comment thread nemo_gym/token_id_capture/lineage.py Resolved
Comment thread nemo_gym/token_id_capture/terminal.py Resolved
Comment thread nemo_gym/token_id_capture/lineage.py Resolved
@pthombre

Copy link
Copy Markdown
Contributor

/ok to test e5a69c0

@ananthsub
ananthsub added this pull request to the merge queue Oct 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into NVIDIA-NeMo:main with commit 8618fe0 Oct 16, 2026
48 of 53 checks passed
aroshanghias-nvd pushed a commit to aroshanghias-nvd/Gym that referenced this pull request Oct 16, 2026
…partial output on CLI timeout (NVIDIA-NeMo#4015)

## What does this PR do?

Fix Claude Code's capture transcript so Gym can corroborate the parent
conversation's terminal model call. With training-token capture enabled,
thinking stays in separate reasoning items, the last non-empty
main-thread served ID becomes `response.id`, and subagent
assistant/tool-result frames are excluded from the parent transcript.
Subagent token usage is still counted.

Tool calls enter the capture transcript in model order and remain
`incomplete` until their result arrives. A timeout therefore retains
pending calls even when parallel tools finish out of order. The partial
transcript is returned with run metadata `status="incomplete"` and
`error_type="timeout"`. The internal `terminal_response_id` is not
exported as a declared terminal ID on `/run`; attribution still
corroborates the response against independent witnesses.

Without capture, thinking remains folded into `<think>` text, unmatched
tool calls remain omitted, and the response retains a generated ID.
Timeout responses now retain partial output; verifiers that inspect
assistant text can consequently score that partial work.

No separate issue is needed: this PR documents and fixes the existing
capture-attribution and timeout failures.

## Validation

Validated fix commit `2a537a91a142c842d1782d0d1df1d73b0e566a94`.

- `gym env test +entrypoint=responses_api_agents/claude_code_agent
+should_validate_data=true`: **87 passed**, reusing the validated Python
3.13.14 environment with `skip_venv_if_present=true` and `uv_venv_dir`
overrides.
- `python -m pytest -q -o addopts=
responses_api_agents/claude_code_agent/tests
tests/unit_tests/test_terminal_attribution.py
tests/unit_tests/test_conversation_fingerprint.py`: **135 passed**
(Python 3.13.14).
- The 19 capture-focused cases include real `_create_response` →
`_run_claude_code` success/timeout paths with capture on/off, with only
the subprocess boundary replaced. The timeout uses the real asyncio
timeout path.
- Converter → continuation stamping → transcript → terminal-attribution
regressions verify that pending tool-only and thinking-plus-tool calls
select the parent, including interleaved subagent events. Response-ID,
item-ID, and cumulative-content witnesses agree.
- In-memory mutation checks: seven new regressions fail on the prior PR
head; all six review-mentioned mutations are detected (both
capture-wiring call sites, first-ID-wins, dropped thinking-only event,
empty-ID overwrite, and missing ID stringification).
- `pre-commit run --all-files`: **passed**.
- Additive fix commit has DCO sign-off.

## Rollouts and remaining gates

The original author-reported evidence was internal GRPO training through
the real Claude Code CLI: with this patch's initial representation/ID
changes plus the tool-call lineage fallback, capture attribution
succeeded over several thousand rollouts. No public rollout numbers were
supplied.

That historical report does not validate this revision's subagent and
pending-tool fixes. A fresh representative real model/verifier smoke
rollout was **not run** in this review environment; the unit tests use
synthetic CLI frames. That rollout evidence, current-head CI, and
Ananth's shared capture review remain outstanding before merge. Complete
Claude Code training attribution also depends on the still-open NVIDIA-NeMo#4014.

---------

Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
pthombre added a commit that referenced this pull request Oct 25, 2026
OpenCode echoes a model call to a tool it lacks as a call to its own `invalid`
tool: it keeps the call ID and moves the original name into the arguments as
{"tool": <name>, "error": <message>}. #4014's tool-call-turn key ignores
rewritten arguments but keeps tool names, so the echo no longer matched the
served call, the next request had no parent, and every later call of the
rollout was poisoned (47 calls in one rollout of a 16-node full-SWE run, 8 in
one of the 32-node restore run).

The key now hashes the name the model emitted when the echo has exactly that
shape. Names still have to match, so two responses that share per-response
tool IDs but call different tools stay apart, and any other shape keeps its
name and stays unresolved as before. Recorded keys hash served responses,
which never carry the rewrite, so existing ledgers and checkpoints are
unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
pthombre added a commit that referenced this pull request Oct 25, 2026
OpenCode echoes a model call to a tool it lacks as a call to its own `invalid`
tool: it keeps the call ID and moves the original name into the arguments as
{"tool": <name>, "error": <message>}. #4014's tool-call-turn key ignores
rewritten arguments but keeps tool names, so the echo no longer matched the
served call, the next request had no parent, and every later call of the
rollout was poisoned (47 calls in one rollout of a 16-node full-SWE run, 8 in
one of the 32-node restore run).

The key now hashes the name the model emitted when the echo has exactly that
shape. Names still have to match, so two responses that share per-response
tool IDs but call different tools stay apart, and any other shape keeps its
name and stays unresolved as before. Recorded keys hash served responses,
which never carry the rewrite, so existing ledgers and checkpoints are
unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>

This branch was previously deployed

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

Labels

area:training Training framework integrations and training-data interfaces complexity:medium Single-domain change with interacting parts or a moderate review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants