Skip to content

feat(token-id-capture): attribute terminal model calls - #2676

Merged
ananthsub merged 4 commits into
mainfrom
ansubramania/terminal-attribution-resolution
Aug 27, 2026
Merged

ananthsub merged 4 commits into
mainfrom
ansubramania/terminal-attribution-resolution

Conversation

@ananthsub

@ananthsub ananthsub commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

This PR identifies the captured model call that produced the response scored by the verifier, then anchors trajectory selection to that call. It depends on #2675.

  • Normalizes model-authored content across Responses, Chat Completions, and Anthropic message shapes.
  • Resolves the terminal model call from an explicit call ID, the served response ID, and content fingerprints.
  • Requires independent witnesses to agree and abstains when evidence is missing, duplicated, or contradictory.
  • Selects the root-to-terminal token chain, excluding auxiliary calls, sub-agent branches, and later retries.
  • Preserves the existing strict single-chain behavior when no terminal call can be attributed.
  • Records the attribution result and masking reason in rollout metrics.

Terminal attribution flow

flowchart TD
    Result["Completed /run result<br/>response scored by verifier"] --> Finalize["finalize_rollout_token_capture"]
    Store["Frozen TokenEntry snapshot<br/>one entry per captured model call"] --> Finalize
    Finalize --> Resolve["resolve_terminal"]

    Explicit["Explicit terminal model_call_id<br/>when supplied"] --> Agreement
    ResponseId["Response ID witness<br/>result.response.id = TokenEntry.response_id"] --> Agreement
    Content["Content witness<br/>cross-dialect fingerprint match"] --> Agreement
    Resolve --> Explicit
    Resolve --> ResponseId
    Resolve --> Content

    Agreement{"Do all available witnesses<br/>identify the same token sequence?"}
    Agreement -- Yes --> Terminal["Resolved terminal model_call_id"]
    Agreement -- No witnesses or disagreement --> Abstain["No attribution"]

    Terminal --> Builder["Build token-prefix forest<br/>and select root-to-terminal chain"]
    Builder --> Intact{"Is the terminal chain intact?"}
    Intact -- Yes --> Deliver["Deliver verified chain unmasked<br/>exclude auxiliary calls and sibling branches"]
    Intact -- No --> Mask["Mask rollout<br/>known terminal is not safely deliverable"]

    Abstain --> Strict["Use existing strict single-chain policy"]
    Strict --> Unique{"Exactly one unambiguous chain?"}
    Unique -- Yes --> Deliver
    Unique -- No --> Mask
Loading

The response ID does not directly determine a trajectory. It identifies a captured TokenEntry, whose model_call_id anchors selection in the token-prefix forest. Content and explicit-ID witnesses independently check that join. A disagreement fails closed instead of allowing one witness to override another.

Known limitations

  • Agent observation bundles are not yet consumed as an additional terminal witness.
  • Token-prefix reconstruction can still split legitimate multi-call tool loops when a harness reserializes structured turns. Terminal attribution chooses the verified root; it does not restore missing token continuity.
  • Hermes currently sends auxiliary model-server requests through the capture prefix. The middleware treats those requests as missing generation captures and masks an otherwise complete rollout. fix(token-id-capture): ignore auxiliary model-server requests when tracking completeness #2678 tracks that separate completeness bug.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format/copyright pass).
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

@copy-pr-bot

copy-pr-bot Bot commented Aug 23, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@ananthsub ananthsub changed the title ansubramania/terminal attribution resolution feat(token-id-capture): attribute terminal model calls Aug 23, 2026
@ananthsub
ananthsub requested review from Glorf and pthombre August 24, 2026 03:39
@ananthsub
ananthsub force-pushed the ansubramania/terminal-attribution-resolution branch from f028522 to 3494141 Compare August 24, 2026 03:45
@ananthsub
ananthsub marked this pull request as ready for review August 24, 2026 04:03
@ananthsub
ananthsub requested a review from cmunley1 August 24, 2026 14:02
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Aug 25, 2026
@ananthsub
ananthsub force-pushed the ansubramania/terminal-attribution-resolution branch from 3494141 to aa17a2a Compare August 25, 2026 18:19
@ananthsub
ananthsub force-pushed the ansubramania/terminal-attribution-resolution branch from aa17a2a to ebd2a71 Compare August 25, 2026 18:27
@ananthsub
ananthsub force-pushed the ansubramania/terminal-attribution-resolution branch from ebd2a71 to 3e114f8 Compare August 27, 2026 19:21
@ananthsub

Copy link
Copy Markdown
Contributor Author

/claude review

@claude

claude Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

SHIP — no reliability concerns found. This is a careful, fail-closed change to a training-signal-critical path; I reviewed it for the one thing that matters here: can it deliver wrong tokens to a trainer? It cannot.

What I verified

  • Correctness of the delivered chain. Terminal attribution only ever selects a chain; the builder still verifies it independently (chain.validate(), project_main_chain_response, assert_prefix_contiguity). A fingerprint collision or a mis-attributed call cannot smuggle non-contiguous tokens past those checks. terminal_ancestry is computed before retry resolution (builder.py:226-232), so the terminal path's nodes are never silently quarantined out from under it; an ambiguous-parent boundary on the path correctly yields terminal_chain="broken" → mask.

  • The mask-semantics change is sound. The new mask=False branch (consumer.py:183-196) fires only on terminal_chain == "delivered", i.e. an attributed and built-and-verified root-to-terminal chain. Off-path calls (aux, sub-agent forks, abandoned retries) are excluded from delivery, not trained on — the delivered chain is terminal_chain, and off-path chains become branches. Attribution-succeeded-but-undeliverable → mask=True. No attribution → the legacy bool(unresolved) or roots!=1 or chains!=1 policy is preserved bit-for-bit. Every witness abstains on ambiguity and disagreeing witnesses attribute nothing, so the fallback is always the strict old behavior.

  • API compatibility. All three touched public entry points (run_builder, trajectories_from_source, finalize_rollout_token_capture) gained only keyword args with defaults; prefix_merging gained a defaulted positional. No caller in the tree breaks, and the added consumer path is transparent when no witness lands.

  • Async / deps / hygiene. No httpx, no ray.get, no dropped await. trajectories_from_source wraps _assemble in a lambda for asyncio.to_thread closing over a local list copy — no shared-state hazard. orjson is already declared in pyproject.toml; SPDX headers present on both new files. Tests assert real behavior across witnesses, builder, mask semantics, and end-to-end delivery.

NOTE (not blocking). The reader-side lineage fields — continuation_fingerprint/fingerprint_version (terminal.py:235-236) and digest/cum_len (terminal.py:160-163) — have no producer in this PR; nothing writes them today. They're forward-looking scaffolding for a "lineage-aware writer," exercised only via synthetic extra fields in tests. So in production now, only the explicit, response_id, and content_output witnesses actually fire; content_cumulative and the digest-based identity are inert until that writer lands. Fine as guarded scaffolding, but worth confirming the follow-up writer is tracked.

Per the repo's own bar ("run real rollouts… green unit tests alone are not enough"): the unit coverage is strong, but since this newly unmasks multi-root rollouts that were previously dropped, validate the attribution join against a real multi-agent / retry-heavy rollout before relying on the reclaimed samples.

Base automatically changed from ansubramania/terminal-attribution-response-id to main August 27, 2026 21:24
ananthsub added a commit that referenced this pull request Aug 27, 2026
## What does this PR do?

This PR records the response envelope ID on each captured model call.
The ID is a lightweight receipt that an agent can retain while token IDs
and log probabilities remain in the configured token sink.

- Adds the optional `TokenEntry.response_id` field to the existing
version 1 record schema.
- Records the top-level ID returned by the Responses, Chat Completions,
or Messages endpoint.
- Reuses the underlying Responses ID in the Anthropic conversion so the
client-visible ID matches the captured ID.

## Response ID flow

```mermaid
sequenceDiagram
    participant Agent as Agent harness
    participant Capture as Capture middleware
    participant Route as Model API route
    participant Model as Model server
    participant Sink as Token sink

    Agent->>Capture: Request /ng-rollout/{rollout_id}/training-token-capture/v1/{dialect}
    Capture->>Capture: Strip prefix and set rollout_id + model_call_id
    Capture->>Route: Forward dialect request with capture context
    Route->>Model: Generate response
    Model-->>Route: NeMoGymResponse(id, output, token metadata)
    Route->>Sink: TokenEntry(model_call_id, response_id=id, token arrays, output items)
    alt Responses or Chat Completions
        Route-->>Agent: Client response carries the recorded id
    else Anthropic Messages
        Route->>Route: Convert response and preserve response.id as message.id
        Route-->>Agent: Message response carries the recorded id
    end
```

The response ID and token arrays are written to the same `TokenEntry`.
The agent only needs to retain the response ID; later code can use it to
locate the corresponding captured model call.

This is the first PR in the terminal-attribution stack. #2676 uses the
recorded ID as one witness when resolving the model call that produced
the verified response.

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

Signed-off-by: Ananth Subramaniam <[email protected]>
kajalj22 and others added 4 commits August 27, 2026 14:27
…2810)

## Why
`container_build`, `gpu_e2e_tests`, `provider_e2e_tests`, and the full
test suite were queuing indefinitely on every PR push against the shared
`nemo-ci-aws-gpu-x2` runner pool (follow-up to #2801).

## Before → After

| | Before | After |
|---|---|---|
| Heavy CI trigger | Every PR push + every merge to `main` | Every 4
hours (`0 */4 * * *`) or manual `workflow_dispatch` |
| `Nemo_CICD_Test` gate | Docs-only shortcut could bypass checking the
heavy jobs entirely | Single gate, branches on `event_name`, always
checks the right jobs with proper `needs.*.result` gating |
| Slack alerts | None for these jobs | Fire on failure, but only for
`main`/release-branch runs; show all upstream results, not just the 3
nightly ones |
| Alert gating | N/A | Keyed directly on `event_name` — can't silently
disappear if an earlier job in the chain gets skipped |
| Ref-check / notify logic | N/A | Deduped into a shared
`.github/actions/is-main-or-release-ref` action; job renamed
`notify-failure` to match `full-test-suite.yml`'s convention |
| Test coverage | N/A | `tests/unit_tests/test_ci_environment.py`
extended to cover the new gating/alerting behavior (67 passing) |

Split out: the "commits since last run" alert feature is a separate
stacked PR, #2812.

## Test plan
- [ ] PR pushes skip
`container_build`/`gpu_e2e_tests`/`provider_e2e_tests`; `Nemo_CICD_Test`
still passes
- [ ] Scheduled run triggers all nightly jobs + `full-test-suite.yml` on
`main`, gated correctly
- [ ] A nightly `unit_tests` or `pre-flight` failure still sends a Slack
alert with the real cause
- [ ] Merging to `main` no longer triggers `full-test-suite.yml`
directly
- [ ] `workflow_dispatch` runs on demand; alert suppressed on
non-main/non-release refs
- [ ] `pytest tests/unit_tests/test_ci_environment.py -q` passes

---------

Signed-off-by: Kajal Jain <[email protected]>
Stateless fingerprint functions over message lists, byte-compatible with
the lineage stack's hashing (same domains, tags, canonicalization). Any
server may import them; lineage state stays confined to the capture locus.
The tests pin the dialect-blind property: the same content in Chat,
Responses, or Anthropic shape hashes identically.

Signed-off-by: ananthsub <[email protected]>
…borating witnesses

The /run result's response is the object the verifier scored. resolve_terminal
joins it to exactly one captured call via independent witnesses: an explicit
declared id, the served response_id, and the content fingerprint (final-turn,
trailing-block, and cumulative readings pooled). Witnesses corroborate, never
outrank; disagreement attributes nothing and persists the trail.

Signed-off-by: ananthsub <[email protected]>
…inal

With an attributed terminal the builder delivers the root-to-terminal chain:
auxiliary calls and sub-agent forks are excluded instead of masking, calls
served after the kept response truncate away, and final-retry groups resolve
by the terminal path. Unattributed rollouts keep the strict single-chain
policy bit-for-bit. The attribution verdict survives failed builds in metrics.

Signed-off-by: ananthsub <[email protected]>
@ananthsub
ananthsub force-pushed the ansubramania/terminal-attribution-resolution branch from 3e114f8 to 4f25ada Compare August 27, 2026 21:27
@ananthsub

Copy link
Copy Markdown
Contributor Author

/ok to test 4f25ada

@pthombre pthombre left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes LGTM

@ananthsub
ananthsub merged commit 9eeb7f0 into main Aug 27, 2026
38 checks passed
@ananthsub
ananthsub deleted the ansubramania/terminal-attribution-resolution branch August 27, 2026 21:57

This branch was previously deployed

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

Labels

sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants