Skip to content

fix(token-id-capture): fingerprint the served response dialect - #3050

Draft
ananthsub wants to merge 23 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/fix-token-capture-utility-paths
Draft

ananthsub wants to merge 23 commits into
NVIDIA-NeMo:mainfrom
ananthsub:ananthsub/fix-token-capture-utility-paths

Conversation

@ananthsub

@ananthsub ananthsub commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • defer external-staging ledger publication until API-specific Chat, Responses, or Messages conversion is complete
  • fingerprint the response representation the harness actually receives and can echo
  • normalize Anthropic thinking blocks as reasoning so they do not alter the assistant-content witness
  • retain exact captured token prefixes even when a Responses harness omits standalone reasoning on the next request

This is the follow-up identified in #2872 (comment) and is based on #2872.

Test plan

  • uv run pytest responses_api_models/vllm_model/tests/test_app.py::TestPrefixSupply::test_responses_reasoning_echo_supplies_the_exact_captured_prefix responses_api_models/vllm_model/tests/test_app.py::TestPrefixSupply::test_external_capture_fingerprints_the_served_responses_shape tests/unit_tests/test_base_responses_api_model.py -q
  • focused pre-commit checks on all changed files

pthombre and others added 19 commits September 2, 2026 10:19
A framework inference worker stages each call's token delta durably and
acknowledges with token-light commit coordinates; the process-shared
lineage store doubles as the per-rollout capture ledger, so serving
workers coordinate only through that store. Admission is the strict
tri-state of the lineage result and unresolved parents poison the call
(fail closed). Also preserves the capture route and capability in
external SWE agent clients.

Signed-off-by: Pranav Thombre <[email protected]>
The middleware stamps admitted_at once on the CaptureContext when it
admits the call; the commit hook threads it through the lineage stores'
custody columns into the token-free manifest as CallRecord.admitted_at.
Stamping at admission (not at record time) keeps retried commits
byte-identical, which the stores' idempotency-by-equality requires.
Rows written before the column carry None and still validate.

The column exists so heuristic terminal selection can order candidate
roots for harnesses that do not declare a terminal response id.

Signed-off-by: Pranav Thombre <[email protected]>
…llouts

A harness that reports the response id it kept gives receipt assembly an
authoritative terminal row; one that reports nothing previously masked
every rollout. select_terminal_call infers the terminal from the
manifest's explicit parent links alone: the earliest-admitted root (an
extended root beats an abandoned sibling), then a walk that eliminates
abandoned retries (childless child loses to an extended sibling).

Selection is token-free and fail-closed: a retry of the final call,
divergent extended branches, orphaned or cyclic rows all select nothing
and surface a reason the caller records as the failure reason. The
verifier still checks every digest on the chosen chain downstream.

RolloutReceipt.terminal_selection records which path chose the terminal
(declared vs heuristic) so consumers can meter heuristic reliance. The
README now documents the ledger (the gate it described was removed) and
the declared > heuristic > mask precedence.

Signed-off-by: Pranav Thombre <[email protected]>
Replace cumulative_token_ids in external (custody) lineage rows with a
pair of worker-computed hashes:

  chain_hash  = H(domain ‖ parent_chain_hash ‖ token_ids_delta)
  cumulative_hash = hash_token_ids(prompt + generated)

CommitCoords.token_ids_delta is removed (hard drop; gate and worker must
deploy together). The gate records token-free external rows and
verify_and_linearize checks both hashes during the terminal-chain walk.
Old rows without hashes skip verification; legacy external rows without
chain_hash are rejected at admission (fail closed).

Signed-off-by: Pranav Thombre <[email protected]>
Staged, fail-closed terminal selection: declared response id, scored
response envelope id, and content fingerprints each independently name a
manifest row; agreeing witnesses attribute, disagreement attributes
nothing, heuristic parent-link selection remains the no-witness fallback.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…e primitives

Fold four parallel constructs the external-staging stack duplicated from
the legacy capture path into single implementations:

- Terminal attribution: token_id_capture/terminal.py is now the one
  witness-corroboration engine. Custody rows are duck-typed by their
  staging_key, identify by (cumulative_hash, chain_hash, cum_len), and
  match content through recorded fingerprints; a new keyword-only
  declared_response_id witness carries the manifest path's authoritative
  declaration semantics. staging/attribution.py is removed and the
  staging package re-exports resolve_terminal/TerminalAttribution.
- Fingerprint version: drop LINEAGE_FINGERPRINT_VERSION in favor of the
  existing fingerprint.FINGERPRINT_VERSION (same value; rows unaffected).
- Ledger file plumbing: the custody ledger reuses store.validate_rollout_id
  and the per-rollout .tokens.lock instead of a private regex and a second
  .lineage.lock file. Ledger read/append semantics are unchanged.
- Reason codes: all poison-row and terminal-selection reasons become
  documented constants in staging/records.py beside the wire schemas;
  writers import them (values unchanged).

NeMo RL's single import site must switch to
`from nemo_gym.token_id_capture.staging import resolve_terminal`; its
call already matches the unified signature.

358 token-capture unit tests pass (Slurm job 6721102).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
Two completion-file parse sites referenced the stdlib json module without
importing it (ruff F821). The file is orjson-migrated everywhere else, so
parse with orjson and catch orjson.JSONDecodeError instead of adding a
second json dependency.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
chat_completion_to_response reused the backend's chat completion id as
the Responses id unconditionally, changing the public resp_* id contract
and making id uniqueness backend-dependent for all chat-backed traffic.
The reuse is only needed as the terminal-attribution join key, so it is
now opt-in via preserve_envelope_id, passed by the vLLM model servers
from their external-capture flag; every other path mints resp_* ids as
before.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
The lineage-ledger commit preserved the launcher-supplied capture URL in
ServerClient.request but never implemented the capability half stated in
its message; only the OpenHands sitecustomize overlay injected the
header, and the unit test spec'ing both halves failed in CI. Inject
x-nemo-gym-capture-capability from OPENAI_API_KEY when the overridden
base URL is capture-prefixed, mirroring the overlay.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
… table

Promote encode_routed_experts (reference pure-Python inverse of the nrlre1
decoder) and classify_route_span (the full/tail/sentinel route-linearization
decision table as a pure-metadata function) to public staging APIs. The
envelope wire format lives with Gym because extras_digest is computed over
the encoded payload; frameworks apply the decision table instead of
mirroring it. Adds codec round-trip, malformed-envelope, and
classification-boundary tests.

Signed-off-by: Pranav Thombre <[email protected]>
…-only verifier

Add StagedCallBaseSnapshot — the extras-free part of a staged call whose
validator enforces every base invariant and recomputes the call digest from
the committed extras_digest, so it verifies without materializing extras
bytes. StagedCallRecord now derives from it and layers the extras-digest
check on top.

verify_and_linearize() keeps its name but changes contract: it consumes base
snapshots, performs all receipt/graph/chain-hash/terminal-selection and
linearization checks, and returns per-call ExtrasCommitment values instead of
decoded routes. LinearizedRow drops routed_experts/routed_experts_dtype;
_decode_selected_routes is deleted. Consumers fetch extras (immediately or
deferred), verify them against the returned commitments with
compute_extras_digest, and decode with the public codec.

BREAKING CHANGE: verify_and_linearize no longer accepts extras-bearing-only
semantics nor decodes routes; StagingSource.fetch returns base snapshots.
A one-time mutation-matrix parity check (37 base-record cases) confirmed
identical success/failure codes and row payloads against the old verifier
before deletion.

Signed-off-by: Pranav Thombre <[email protected]>
The capture host's instance-wide lock covered the external
StagingSink.stage() call, so every concurrent completion on a worker
serialized behind one blocking sink round trip - and because
_claim_completion shared the same lock, even unrelated claims and
fail_call poison paths waited on in-flight network I/O.

The lock's only real content is the per-call single-completion claim:
by the time stage() runs, the claim already made the caller the sole
stager, and cross-call ordering comes from stage-before-ack (a child is
only admitted after its parent's coords produced a ledger row). Narrow
the lock to the claim, run stage() unlocked, and promote thread safety
into the StagingSink protocol contract so implementations that need
serialization synchronize internally.

Adds a regression test that completes and poisons unrelated calls while
another call is blocked mid-stage; it fails against the previous code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…ngle_task

`BaseRunRequest.capture_rollout_id` is marked `exclude=True` so it stays out
of `model_dump()`, but the tau2 agent built its `run_single_task` kwargs by
iterating `model_fields`, which ignores `exclude`. The upstream tau2-bench
runner rejected the unexpected kwarg and every rollout failed.

Filter out excluded fields so only tau2-bench arguments are forwarded.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@copy-pr-bot

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

pthombre and others added 3 commits September 3, 2026 01:01
…A-NeMo#2872)

Routing and identity
- Preserve the backend envelope id only for requests with an active
  external-capture context; uncaptured requests keep minted resp_* ids.
- Remove the x-nemo-gym-capture-capability header. Nothing in Gym or the
  RL integration validated it; authorization is the rollout-prefixed URL.
- Remove the x-nemo-gym-logical-request-id header and the always-empty
  logical_request_id ledger column. No client sent it and nothing read it.
- SWE agent resolves the capture-prefixed model URL once in the parent
  and raises when capture is enabled without a rollout id. Drop the
  derived ng_rollout_id/token_capture_enabled instance fields in favour
  of one install_openhands_capture_overlay flag.
- Keep the OpenHands sitecustomize overlay and document the real reason:
  the pinned fork calls the model through nemo_gym.ServerClient and
  ignores llm.base_url, and its pinned client predates the
  NEMO_GYM_MODEL_SERVER_BASE_URL override.

Terminal attribution
- Rename terminal_logical_request_id to terminal_response_id; it carries
  the served response.id. Gym's finalizer now honours it as
  declared_response_id, matching the RL receipt path.

Protocols
- Rename the read-only LineageStore protocol to LineageResolver and type
  ledger consumers (capture context on the external path, control-route
  installer) as CaptureLedger.
- CaptureLedger.record takes one validated CaptureLedgerCommit wrapping a
  CallRecord instead of an open keyword list.
- Document the CaptureAdapter.enter_prefix contract: the worker resolves
  the admission to exact ids; the adapter never fetches staged records.

Cleanups
- Consolidate verify_and_linearize manifest/snapshot validation into two
  passes, preserving every failure code.
- Remove the unused HttpByteCounterMiddleware and the never-shipped
  SCHEMA_VERSION/DIGEST_VERSION staging aliases.
- Move the shared failure-reason constants to token_id_capture.records
  and re-export them from staging.
- Apply reviewer docstring and comment rewrites across the capture stack.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
Resolve conflicts with the fingerprint helper dedup (NVIDIA-NeMo#2996): lineage.py keeps
the ledger custody helpers and imports the fingerprint functions from
nemo_gym.token_id_capture.fingerprint; sink.py imports assistant_fingerprint
from the new module and keeps the LineageResolver/CaptureLedger protocol names.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@ananthsub ananthsub changed the title fix(token-id-capture): preserve harness utility requests fix(token-id-capture): fingerprint the served response dialect Sep 3, 2026
@ananthsub
ananthsub force-pushed the ananthsub/fix-token-capture-utility-paths branch from cf137e9 to 7dd16b6 Compare September 3, 2026 08:18
@ananthsub
ananthsub changed the base branch from main to pthombre/tokcap/full-stack September 3, 2026 08:18
Defer external-staging ledger publication until Chat, Responses, or Messages conversion is complete so content witnesses match what the harness can echo. Preserve exact token-prefix supply when Responses clients omit standalone reasoning.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub
ananthsub force-pushed the ananthsub/fix-token-capture-utility-paths branch from 7dd16b6 to 4c67a86 Compare September 3, 2026 08:28
@ananthsub
ananthsub requested a review from pthombre September 3, 2026 08:30
@ananthsub
ananthsub marked this pull request as ready for review September 3, 2026 09:11
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Sep 4, 2026
@ananthsub
ananthsub changed the base branch from pthombre/tokcap/full-stack to main September 10, 2026 23:53
@ananthsub
ananthsub requested a review from a team as a code owner September 10, 2026 23:53
aroshanghias-nvd added a commit to aroshanghias-nvd/Gym that referenced this pull request Sep 11, 2026
Adapt the post-conversion finalization design from Ananth Subramaniam in NVIDIA-NeMo#3050, commit 4c67a86. Retain the worker acknowledgement in request-scoped context and finalize after conversion and serialization. Add refusal, failure, identity and single-commit HTTP regressions.

Co-authored-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
ananthsub added a commit to aroshanghias-nvd/Gym that referenced this pull request Sep 15, 2026
Adapt the post-conversion finalization design from Ananth Subramaniam in NVIDIA-NeMo#3050, commit 4c67a86. Retain the worker acknowledgement in request-scoped context and finalize after conversion and serialization. Add refusal, failure, identity and single-commit HTTP regressions.

Co-authored-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
raveedturing pushed a commit to turing-rlgym/Gym that referenced this pull request Sep 15, 2026
…3301)

## What does this PR do?

Fix external token-capture ancestry by recording the final API response
representation, after Chat, Responses, or Anthropic Messages conversion
and JSON serialization succeed.

The original reasoning continuation bug reproduces on main at
`9506eb87c99ffa0f736b05f76b8f20dca8fb479b`: capture fingerprints an
internal Chat assistant message with wrapped reasoning, while the
Responses client echoes separate reasoning and answer items. Generation
returns HTTP 200, but capture is poisoned with `unresolved_parent`.

Following [Ananth's
review](NVIDIA-NeMo#3301 (review)),
this revision replaces the initial URL-selected conversion workaround
with the post-conversion design from [his final commit in
NVIDIA-NeMo#3050](NVIDIA-NeMo@4c67a86):

- Retain worker commit coordinates privately in the existing
request-scoped capture context; immediately strip transport fields from
the internal response.
- Finalize once at the outer Chat, Responses, or Messages dispatch
boundary, after conversion and JSON serialization.
- Normalize served Anthropic thinking blocks into standalone reasoning
items when constructing capture output items.
- Preserve the existing worker-acknowledgement validation, token-free
ledger, response-ID association, and poison-and-serve capture behavior.

This also fixes the reviewer's refusal example: Responses refusal
content becomes ordinary text in Messages, so fingerprinting the
intermediate Responses representation is wrong. Conversion/serialization
failures now leave no successful lineage row; the existing middleware
marks the admitted call uncommitted. Finalization before HTTP send is
not a guarantee of client receipt.

No fingerprint algorithm, admission rules, token-staging protocol,
dependencies, lockfiles, or agent implementations change. Only the
finalization portion of NVIDIA-NeMo#3050 is adapted, not its inherited capture
infrastructure. Refusal-only direct Chat ambiguity under the existing
fingerprint rules is outside this change; the original direct Chat
reasoning/plain-text controls remain covered.

## Validation

- Retained the original 24 three-turn HTTP cases: Responses, Chat
Completions, and Messages; plain answers and three reasoning
representations; with and without tool calls.
- Added four refusal continuation cases for Responses and Messages, with
and without tool calls.
- Added five failure cases: Responses/Messages conversion and JSON
serialization on all three APIs. Worker staging must already have
succeeded, no lineage commit may occur, and capture must be marked
uncommitted.
- Continuation cases check exact parent IDs and cumulative prefix
lengths, one ledger commit per call, the served response ID, token-light
output, and rejection of subsequently altered history.
- Before the revision, the Messages refusal and post-staging
conversion-failure regressions failed as reported. The original
reasoning regressions also remain regression-tested against the original
main baseline (12 failed, 12 passed before the original fix).
- After the revision: **811 passed** across vLLM model tests,
Responses/base-model/Anthropic converters, and token-capture suites. The
focused integration file has **35 passing tests**.
- `pre-commit run --all-files` passes.

These tests use the real HTTP dispatch, middleware, converters, worker
capture helper, file ledger, and parent admission. Generation and
staging storage are CPU doubles; no live vLLM/GPU validation of this
revision is claimed.

```bash
python -m pytest responses_api_models/vllm_model/tests/test_token_capture_integration.py
```

## Checklist

- [x] Contributing guidelines followed; focused changes only.
- [x] Regression tests and local pre-commit checks pass.
- [x] DCO sign-off; adapted implementation credits Ananth Subramaniam.

---------

Signed-off-by: Ali Roshan Ghias <[email protected]>
Co-authored-by: Ananth Subramaniam <[email protected]>
pthombre pushed a commit that referenced this pull request Sep 16, 2026
## What does this PR do?

Fix external token-capture ancestry by recording the final API response
representation, after Chat, Responses, or Anthropic Messages conversion
and JSON serialization succeed.

The original reasoning continuation bug reproduces on main at
`9506eb87c99ffa0f736b05f76b8f20dca8fb479b`: capture fingerprints an
internal Chat assistant message with wrapped reasoning, while the
Responses client echoes separate reasoning and answer items. Generation
returns HTTP 200, but capture is poisoned with `unresolved_parent`.

Following [Ananth's
review](#3301 (review)),
this revision replaces the initial URL-selected conversion workaround
with the post-conversion design from [his final commit in
#3050](4c67a86):

- Retain worker commit coordinates privately in the existing
request-scoped capture context; immediately strip transport fields from
the internal response.
- Finalize once at the outer Chat, Responses, or Messages dispatch
boundary, after conversion and JSON serialization.
- Normalize served Anthropic thinking blocks into standalone reasoning
items when constructing capture output items.
- Preserve the existing worker-acknowledgement validation, token-free
ledger, response-ID association, and poison-and-serve capture behavior.

This also fixes the reviewer's refusal example: Responses refusal
content becomes ordinary text in Messages, so fingerprinting the
intermediate Responses representation is wrong. Conversion/serialization
failures now leave no successful lineage row; the existing middleware
marks the admitted call uncommitted. Finalization before HTTP send is
not a guarantee of client receipt.

No fingerprint algorithm, admission rules, token-staging protocol,
dependencies, lockfiles, or agent implementations change. Only the
finalization portion of #3050 is adapted, not its inherited capture
infrastructure. Refusal-only direct Chat ambiguity under the existing
fingerprint rules is outside this change; the original direct Chat
reasoning/plain-text controls remain covered.

## Validation

- Retained the original 24 three-turn HTTP cases: Responses, Chat
Completions, and Messages; plain answers and three reasoning
representations; with and without tool calls.
- Added four refusal continuation cases for Responses and Messages, with
and without tool calls.
- Added five failure cases: Responses/Messages conversion and JSON
serialization on all three APIs. Worker staging must already have
succeeded, no lineage commit may occur, and capture must be marked
uncommitted.
- Continuation cases check exact parent IDs and cumulative prefix
lengths, one ledger commit per call, the served response ID, token-light
output, and rejection of subsequently altered history.
- Before the revision, the Messages refusal and post-staging
conversion-failure regressions failed as reported. The original
reasoning regressions also remain regression-tested against the original
main baseline (12 failed, 12 passed before the original fix).
- After the revision: **811 passed** across vLLM model tests,
Responses/base-model/Anthropic converters, and token-capture suites. The
focused integration file has **35 passing tests**.
- `pre-commit run --all-files` passes.

These tests use the real HTTP dispatch, middleware, converters, worker
capture helper, file ledger, and parent admission. Generation and
staging storage are CPU doubles; no live vLLM/GPU validation of this
revision is claimed.

```bash
python -m pytest responses_api_models/vllm_model/tests/test_token_capture_integration.py
```

## Checklist

- [x] Contributing guidelines followed; focused changes only.
- [x] Regression tests and local pre-commit checks pass.
- [x] DCO sign-off; adapted implementation credits Ananth Subramaniam.

---------

Signed-off-by: Ali Roshan Ghias <[email protected]>
Co-authored-by: Ananth Subramaniam <[email protected]>
(cherry picked from commit 295e2e6)
jinglinglingling pushed a commit to jinglinglingling/Gym that referenced this pull request Oct 8, 2026
Integrate minimal CC onto NVIDIA-NeMo/Gym main 4402098. Includes post-conversion finalization from NVIDIA-NeMo#3301 (612723a), adapted from Ananth Subramaniam in NVIDIA-NeMo#3050. Preserve main retry bounds and error propagation. Accept framework attempt-scoped owner IDs without dropping their scope. No private validation machinery or lockfile changes.

Co-authored-by: Ananth Subramaniam <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
Signed-off-by: Linglin Jing <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:model Model servers, inference providers, and model adapters bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026
@yaoyu-33
yaoyu-33 marked this pull request as draft November 18, 2026 02:17
@yaoyu-33

Copy link
Copy Markdown
Contributor

We’re doing some cleanup of the open PR list. This PR has had no activity for over a month, so I’ve moved it back to draft.

If this change is still needed, please resolve any merge conflicts and mark the PR ready for review again when it’s ready to merge. Thanks!

@github-actions github-actions Bot removed the sla:review-overdue Review response is over the one-business-day SLA label Nov 18, 2026

This branch was previously deployed

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

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working 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