Skip to content

feat(token-capture): carry the finish reason through worker-custody staging - #4366

Merged
linj-glitch merged 10 commits into
mainfrom
alexandery/capture-finish-reason-through-staging
Oct 16, 2026
Merged

linj-glitch merged 10 commits into
mainfrom
alexandery/capture-finish-reason-through-staging

Conversation

@alexandery-nvidia

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

Copy link
Copy Markdown
Contributor

Stacked PR. This branch is built on #3973 (the finish reason and the incomplete terminal), whose response_finish_reason and verdict table it reuses. #3973 merged on 2026-10-15 as d5b2892 and main is merged in since (3bc2a33), so the diff is this pull request's own changes; the commit list still shows #3973's commits (9c8bdf2, ec2f7c3, 744e198, 78b05e8), whose content is on main now. Review the three commits that are this branch's: feat(token-capture): carry the finish reason through worker-custody staging, fix(token-capture): withhold the staged rebuild's truncation verdict when the finish reason is unresolved (the 2026-10-13 review follow-up), and feat(token-capture): apply the capture's truncation verdict through one shared rule (ananthsub's review of 2026-10-15). A merge of main 3d2e970 sits between them: the generation-cut staging series added fields next to this branch's in lineage.py, staging/records.py and staging/rebuild.py, and both sides are kept. It is independent of #3980, which edits neighboring lines of builder.py; whichever of the two lands second merges main once more.

What does this PR do?

#3973 records each locally captured call's finish reason and marks a rebuilt response whose terminal call stopped for length or content_filter as incomplete. Under worker custody, where a framework's inference worker keeps the tokens and the model server records a token-free ledger row per call, no finish reason was recorded, so a rollout rebuilt from staged records reported no truncation verdict: a trainer's truncation rule saw every such rollout as complete.

  1. The ledger row carries the finish reason. CallRecord (nemo_gym/token_id_capture/staging/records.py) gains finish_reason: str | None in the Chat Completions vocabulary (stop, length, tool_calls, content_filter). It is a metadata column like response_id and admitted_at, outside the staged digest, so no digest or schema version changes; a row written before the column reads None. Like every column of these wire models, it binds the model server and the framework to one Gym version: the manifest route serializes it on every row and CallRecord forbids unknown fields, so a framework whose Gym predates the column rejects every manifest row as invalid_manifest_row and masks the rollout, as capture_key (feat(token-capture): add worker staging helpers for generation cuts #3884) already does. Run the same Gym on both sides.
  2. The external capture handler stamps it. _finalize_admitted_response (nemo_gym/token_id_capture/external_capture.py) reads it from the served payload with response_finish_reason, which now also understands the Anthropic Messages shape (stop_reason, the inverse of the table the Anthropic converter applies when it serves a Responses payload as a Messages response), so the chat, Responses, and Messages dialects record the same reason.
  3. Both ledgers round-trip it. _custody_columns and _manifest_from_rows (nemo_gym/token_id_capture/lineage.py) store and rebuild the column for the file-backed and the in-memory ledger; a re-commit with a different finish reason is a conflict like any other metadata field.
  4. The rebuild reports the terminal call's reason. LinearizedRow (nemo_gym/token_id_capture/staging/rebuild.py) gains terminal_finish_reason and the property incomplete_reason, which applies feat(token-capture): preserve finish reasons and terminal truncation #3973's table through incomplete_reason_for_finish_reason, now a shared function in records.py that the local-path builder uses too. Only the terminal call decides: an earlier length stop did not end the chain, because a later call extended it. The rebuild also keeps feat(token-capture): preserve finish reasons and terminal truncation #3973's abstention: when the receipt's terminal_attribution_reason carries finish_reason_disagreement (attribution named one of several token-identical calls that recorded different finish reasons, by call-id order alone), LinearizedRow.finish_reason_resolved is False and incomplete_reason is None, so the verdict cannot flip with the call id the receipt names; the token is the shared constant FINISH_REASON_DISAGREEMENT_REASON in records.py, which resolve_terminal emits. A framework's receipt consumer puts the property on the sample's response with apply_capture_incomplete_verdict (records.py, exported from nemo_gym.token_id_capture), the one precedence rule both capture placements apply: a response that reported completed or no status takes the verdict, and a harness that reported incomplete or failed itself keeps its own, exactly as finalize_rollout_token_capture does on the local path, which now calls the same helper. The NeMo RL consumer is not open yet: it comes with the Gym pin bump that follows this merge, because NeMo RL can only exercise incomplete_reason once its pinned Gym has the column. The receipt-builder half, the switch to UNSERVED_CALL_FAILURE_REASONS from feat(token-capture): resolve a refused call's capture intent and report the refusal #3980, is fix(nemo-gym): keep unserved-call ledger reasons off the receipt poison list RL#4749 and is pin-agnostic.

Review follow-up (2026-10-13)

yaoyu-33's question on staging/rebuild.py: with content-attributed, token-identical calls whose finish reasons differ, swapping the call ids changed incomplete_reason although the receipt reported finish_reason_disagreement. The rebuild now withholds the verdict in that case, as #3973's projection does. The branch also carries a merge of main 3d2e970.

Review follow-up (2026-10-15)

ananthsub's two items (4c6c6b3): the precedence rule that keeps a harness's own verdict moved into apply_capture_incomplete_verdict, which finalize_rollout_token_capture calls on the local path and a framework consumer calls on LinearizedRow.incomplete_reason (its docstring points there), with tests for a response that reported no status, completed, incomplete for its own reason, and failed; and the version coupling of the staging wire models is stated on the finish_reason column, in the model-call capture docs, and in point 1. After #3973's squash, main was merged in as 3bc2a33 (no rebase, so the review history stands); the files both sides touched keep this branch's version, which equals #3973's final tree plus this branch's lines, and #3973's last test, test_finalize_keeps_a_harness_verdict_that_is_already_incomplete, sits next to this branch's apply_capture_incomplete_verdict tests. Validation of the merge head 3bc2a33: the unit suite (test_collect_downstream_junit.py excluded) gave 9160 passed, 56 skipped, 29 failed, 20 errors; 48 of the failures and errors are the environmental set of main (telemetry and opensandbox tests that need packages this machine lacks) and the remaining one, a docker-compose shell test, passes on rerun here and on main; every responses_api_models/*/tests suite passed (vllm_model 534 passed), with genrm_model and local_vllm_model erroring at collection as before. Gate on 4c6c6b3: the unit suite (8754 passed, 56 skipped; the 28 failures and 20 errors are identical to the main 4518db9 baseline, telemetry and opensandbox tests that need packages this machine lacks) and every responses_api_models/<server>/tests session (vllm_model 492 passed; genrm and local_vllm collect errors for missing local packages, as on main); the token-capture and staging unit files together: 561 passed.

Issue

No issue filed; found while training with NeMo RL's worker-custody capture under a token budget, where every rollout rebuilt from staged records counted as complete.

Validation

  • New tests: response_finish_reason for the Anthropic Messages shape (five stop reasons); the ledger row round-trips finish_reason on both ledgers, a row without the column reads None, and a re-commit with a different reason conflicts; the external capture handler records length for every dialect (chat completions, Responses, Messages, compaction) and stop on the existing route tests; verify_and_linearize reports the terminal row's reason and incomplete_reason for stop, length, content_filter, and an unstated reason; with two token-identical rows recording length and stop, the finish_reason_disagreement token withholds the verdict whichever row the receipt names while the recorded reason stays reported, a trail without the token keeps the verdict, and a receipt without a trail resolves as before.
  • tests/unit_tests/test_token_id_capture.py, test_token_capture_ledger.py, test_token_capture_staging_rebuild.py, test_token_capture_staging_core.py, test_trajectory_builder.py, test_terminal_attribution.py: 401 passed. responses_api_models/vllm_model/tests: 409 passed.
  • Unit suite (pytest tests/unit_tests, with test_collect_downstream_junit.py excluded for a missing local package), run on the branch tip 0067fd0 after the merge of main 3d2e970: 8463 passed, 56 skipped, 28 failed, 19 errors. The failures and errors are the same 47 as on main 3d2e970 (telemetry and opensandbox tests that need packages this machine lacks). Each responses_api_models/<server>/tests directory as its own session matches main apart from the new tests (vllm_model 418 passed).
  • ruff check and ruff format --check on the changed files: clean.

🤖 Generated with Claude Code

@copy-pr-bot

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

@alexandery-nvidia
alexandery-nvidia marked this pull request as ready for review October 10, 2026 08:13
alexandery-nvidia and others added 2 commits October 10, 2026 01:18
…ength-cut terminal as incomplete

A capture record did not say why its model call stopped, so a consumer of
the rebuilt response could not tell a trajectory that ended at the
output-token budget from one that ended on its own. The Responses
converter already marks such a served response incomplete, but the
rebuilt response, which is what a trainer reads, carried no status at all.

TokenEntry gains finish_reason in the Chat Completions vocabulary (stop,
length, tool_calls, content_filter). response_finish_reason derives it
from either served payload shape: a chat payload states it directly, and a
Responses payload is read back through the converter's incomplete_details
mapping, with a completed payload stopping at a tool call or at the end of
its text. The capture path stamps it on every record; a record written
without the field reads as None.

project_main_chain_response marks the rebuilt response incomplete, with
incomplete_details.reason max_output_tokens, when the delivered chain's
terminal call stopped for length. Only the terminal call decides, because
an earlier length stop was extended by a later call. Every other finish
reason leaves the status unset, as before.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
(cherry picked from commit 9561221)
…hrough delivery and mirror content_filter

Review follow-up on the finish-reason capture.

Delivery replaced only the result response's output with the rebuilt output,
so the builder's status: incomplete and incomplete_details never reached a
result whose harness response said completed. Delivery now carries that
verdict onto the result's response when the harness reported no status or
completed; a harness that already reported incomplete or failed keeps its own
verdict. The delivery docstring states the exception, and delivery-level tests
cover the absent, completed, and failed harness statuses.

The builder mirrors the Responses converter's other incomplete verdict: a
terminal call that stopped for content_filter is incomplete with that reason,
alongside length as max_output_tokens. The docstring states that the finish
reason is recorded by the local capture path only, so a chain built from
externally staged records reports no verdict. The conformance entry carries a
non-default finish reason so the store round trip proves the field persists,
and the record comment describes which values are consumed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@alexandery-nvidia
alexandery-nvidia force-pushed the alexandery/capture-finish-reason-through-staging branch from 8aac4fc to d043ff7 Compare October 10, 2026 08:27
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Rebased onto the rebased #3973 head (d043ff7 on ec2f7c3) after #3938/#3939 merged; no content change, full unit suite matches main's baseline.

@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 10, 2026
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 12, 2026
linj-glitch
linj-glitch previously approved these changes Oct 12, 2026

@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 incremental worker-custody change against its #3973 base ec2f7c3. The terminal call's finish reason is preserved through both ledgers and staged rebuild; the mapping matches the served response dialects. No blocking findings in this increment.

Validation: 450 capture/staging/trajectory tests, 409 vLLM model tests, and 32 additional streaming/non-streaming dialect/backend cases passed; full pre-commit passed.

This remains stacked on #3973 and must not land before that dependency. Synchronize Gym consumer versions when adopting the new manifest field: new readers accept old rows, but older strict CallRecord readers reject finish_reason, including null. The follow-on RL consumer/pin change is still needed to apply this verdict during training. Shared token-capture maintainer review and trusted runtime CI remain part of the handoff.

Reviewed with Codex, including an independent source/history pass.

@linj-glitch
linj-glitch requested a review from ananthsub October 12, 2026 20:18
@linj-glitch

Copy link
Copy Markdown
Collaborator

/ok to test d043ff7

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 12, 2026 20:19
@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 12, 2026
alexandery-nvidia and others added 2 commits October 12, 2026 17:46
…tries disagree on the finish reason

Terminal attribution collapses token-identical captures (an identical retry) to the smallest call id. That is sound for the delivered tokens but not for the finish reason recorded on each serving: one serving can be cut at the output budget and its retry under a larger budget complete, so the rebuilt response's status depended on which twin drew the smaller id.

resolve_terminal now records which calls a witness singled out (the explicit id, or a response id, item id or content fingerprint that matched exactly one entry) and reports finish_reason_resolved=False when the named call was chosen among token-identical twins by id order alone and those twins recorded different finish reasons; the reason trail carries finish_reason_disagreement. The consumer passes the flag to project_main_chain_response, which then leaves status and incomplete_details unset. Twins that agree, or a call a witness singled out, keep the verdict.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
…taging

Under worker custody a framework's inference worker keeps the tokens and
the model server records a token-free ledger row per call. No finish reason
was recorded there, so a rollout rebuilt from staged records reported no
truncation verdict and a trainer's truncation rule saw every such rollout
as complete, while the local capture path marks a length-cut terminal call
incomplete.

CallRecord gains finish_reason, a metadata column like response_id that
stays outside the staged digest, so no digest or schema version changes and
a row written before the column reads None. The external capture handler
reads it from the served payload with response_finish_reason, which now
also understands the Anthropic Messages stop_reason, so the chat,
Responses, and Messages dialects record the same chat-vocabulary reason.
Both ledgers round-trip the column, and a re-commit with a different reason
conflicts like any other metadata field.

verify_and_linearize reports the terminal row's reason on LinearizedRow,
whose incomplete_reason property applies the same table the local-path
builder uses (incomplete_reason_for_finish_reason, now shared from
records.py): only the terminal call decides, because a later call extends
a chain an earlier length stop did not end.

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

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

Rechecked the current head with digest-valid receipts and explicit-ID controls.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 13, 2026
…ging

The generation-cut staging series (#3883, #4213) and this branch added
fields next to each other: main's capture_key beside this branch's
finish_reason on CallRecord and on the ledger row read in lineage.py, and
main's EpisodeId import beside this branch's incomplete_reason_for_finish_reason
import in rebuild.py. Both sides are kept.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Pushed 4c6c6b3 for the two items: the shared apply_capture_incomplete_verdict helper and the same-Gym-version note. The stack note now lists 78b05e8, the cherry-pick of #3973's head, which drops at the rebase after #3973 merges.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 4c6c6b3

@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

linj-glitch added a commit to linj-glitch/Gym that referenced this pull request Oct 15, 2026
…VIDIA-NeMo#3973)

## What does this PR do?

Three related changes in `nemo_gym/token_id_capture`, so that a consumer
of a rollout record can tell a trajectory that ended at the output-token
budget from one that ended on its own.

1. **Each locally captured record carries its call's finish reason.**
`TokenEntry` gains `finish_reason`, usually in the Chat Completions
vocabulary (`stop`, `length`, `tool_calls`, `content_filter`; other
engine values pass through unchanged). `response_finish_reason` in
`records.py` derives it from either served payload shape: a chat payload
states it directly as `choices[0].finish_reason`; a Responses payload
carries no finish reason, so `incomplete_details.reason` is mapped back
through the converter's own mapping (`max_output_tokens` to `length`,
`content_filter` to itself), and a completed Responses payload stopped
at a tool call (`tool_calls`) or at the end of its text (`stop`).
`capture_tokens` in `sink.py` stamps it on every record written by the
local capture path. A record written without the field reads as `None`,
so existing stores stay readable, and the conformance kit's entry
carries a non-default finish reason so a store that drops the field
fails the round trip.
2. **The rebuilt response reports a cut terminal as incomplete.**
`project_main_chain_response` in `builder.py` sets `status:
"incomplete"` with `incomplete_details.reason: "max_output_tokens"` when
the delivered chain's terminal call stopped for `length`, and
`incomplete_details.reason: "content_filter"` when it stopped for
`content_filter`: the verdicts the Responses converter already gives a
served chat completion that ended the same way. Only the terminal call
decides: an earlier `length` stop was extended by a later call and does
not end the chain. Any other finish reason leaves the status unset, as
before. When terminal attribution chose the terminal call among
token-identical retries by call-id order alone and those twins recorded
different finish reasons, the verdict is withheld too
(`TerminalAttribution.finish_reason_resolved`, passed to
`project_main_chain_response`): the delivered tokens are the same either
way, but the status would otherwise depend on which twin drew the
smaller id. A witness that singles out one serving (an explicit id, or a
response id, item id or content fingerprint matching exactly one entry)
keeps that serving's verdict.
3. **Delivery carries that verdict onto the rollout record.**
`finalize_rollout_token_capture` in `delivery.py` replaced only
`response.output`, so the builder's verdict never reached the record. It
now also sets the harness response's `status` and `incomplete_details`
from the rebuilt response when the harness reported `completed` or no
status; a harness that already reported `incomplete` or `failed` keeps
its own, more specific, verdict. The readers that see it without any
change are Gym's own aggregate-metrics path, which reads
`response.incomplete_details`, and the downstream NeMo RL fork, whose
agent harness finalizes the capture in-process and reads the verdict
there. Upstream NeMo RL does not see this verdict yet: at
NVIDIA-NeMo/RL#4449's head, `NemoGym` runs capture in receipt mode
(`external_staging: true`, `rebuild_response: false`) and collects
through `run_examples`, so `finalize_rollout_token_capture` never runs
for it and NVIDIA-NeMo#4449 counts only a status the harness set itself. Upstream
RL gets the verdict once NVIDIA-NeMo#4366 carries the finish reason through
worker-custody staging and RL's receipt consumer applies it.

### Scope

The finish reason is recorded on the local capture path only. Under
external staging (worker custody) `capture_tokens` returns before
building a record, and the staged `CallRecord`, the ledger, and
`staging/rebuild.py` carry no finish reason, so a chain rebuilt from
staged records reports no verdict. Carrying the finish reason through
the staging record is the follow-up NVIDIA-NeMo#4366, stacked on this branch.

## Issue

No issue filed; the missing status was found while training with agent
harnesses under token-id capture, where a session cut at the output
budget was indistinguishable from a completed one in the rebuilt
response.

## Validation

- `tests/unit_tests/test_terminal_attribution.py`,
`tests/unit_tests/test_trajectory_builder.py`: 97 passed, including the
new tests for the `content_filter` verdict and for delivery with a
harness status that is absent, `completed`, `failed` (left untouched),
and `incomplete` for the harness's own reason (left untouched); the
earlier tests for `response_finish_reason` on both payload shapes, the
recorded reason on the `/v1/responses` and `/v1/chat/completions`
capture routes, the store round trip with an older record lacking the
field, and the terminal-versus-earlier `length` rule stay.
- Full `tests/unit_tests` and every `responses_api_models/*/tests` suite
on this branch: the only failures (opensandbox, telemetry, and the two
servers that import `vllm`) are the same as on `main` f128d43 in the
same environment.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Rollout evidence: these changes have run for several weeks in a
downstream fork training with OpenCode and Codex harnesses under
token-id capture; the rebuilt responses of sessions cut at the output
budget carry `status: "incomplete"`, and the trainer's truncation count
reflects them.

### Review follow-up

Rebased onto `main` f128d43. The dependency edits that the validation
merges had added to this branch live in NVIDIA-NeMo#4362 now.

yaoyu-33's follow-up of 2026-10-12 (744e198): the finish-reason rule
for token-identical retries described in item 2, with regression tests
at the attribution level (both id orders; the explicit and response-id
witnesses), through `_assemble` (both orders; twins that agree keep the
verdict), and on the builder.
`tests/unit_tests/test_terminal_attribution.py`,
`test_trajectory_builder.py`, `test_token_id_capture.py`: 290 passed.

ananthsub's notes of 2026-10-15 (5ed1608): item 3 now names the
readers that see the delivered verdict and the one that does not
(upstream NeMo RL's receipt mode, which needs NVIDIA-NeMo#4366 plus a
receipt-consumer change on the RL side), the Scope section links NVIDIA-NeMo#4366,
and a delivery test where the harness reports `incomplete` for its own
reason (`result_missing`) pins the second half of the guard.
`tests/unit_tests/test_terminal_attribution.py`: 65 passed.

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

---------

Signed-off-by: alexandery <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Lin Jia <[email protected]>
…nish-reason-through-staging

#3973 merged on main as d5b2892. The files both sides touched keep this branch's version,
which equals #3973's final tree plus this branch's lines, and #3973's last test sits next to
this branch's tests of the shared verdict helper.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Merged main after #3973's squash (d5b2892) as 3bc2a33, a merge commit rather than a rebase, so the review history stands. The files both sides touched keep this branch's version, which is #3973's final tree plus this branch's lines, and #3973's last test, test_finalize_keeps_a_harness_verdict_that_is_already_incomplete, now sits beside this branch's apply_capture_incomplete_verdict tests. The diff is this pull request's own changes, 15 files. Validation of the merge head 3bc2a33: the unit suite (test_collect_downstream_junit.py excluded) gave 9160 passed, 56 skipped, 29 failed, 20 errors; 48 of the failures and errors are the environmental set of main (telemetry and opensandbox tests that need packages this machine lacks) and the remaining one, a docker-compose shell test, passes on rerun here and on main; every responses_api_models/*/tests suite passed (vllm_model 534 passed), with genrm_model and local_vllm_model erroring at collection as before.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 3bc2a33

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

Re-reviewed 3bc2a33: no blocking code findings. The shared helper preserves harness verdicts, and the consumer precedence/version notes address the review. Validation: 504 focused tests plus 144 local/staged boundary cases passed. Harness-conformance/P0 CI remains outstanding; downstream RL consumer adoption is still a separate follow-up.

@linj-glitch
linj-glitch 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/38849251339

Merged via the queue into main with commit 949198c Oct 16, 2026
49 of 54 checks passed
@linj-glitch
linj-glitch deleted the alexandery/capture-finish-reason-through-staging branch October 16, 2026 04:29
alexandery-nvidia added a commit that referenced this pull request Oct 16, 2026
…gine-refusal-record

Gym #4366 merged on main as 949198c and moved the finish-reason table of the rebuilt
response into records.incomplete_reason_for_finish_reason. The projection calls that helper
in place of this branch's local table, keeps this branch's engine-refusal rule beside it, and
its docstring describes both custodies as #4366 left them. #4366's
apply_capture_incomplete_verdict tests and this branch's refusal tests both stay in the
terminal-attribution test file.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
alexandery-nvidia added a commit that referenced this pull request Oct 16, 2026
…t the verdict composition and the streaming paths

Review follow-ups on the a642822 re-review of #3980.

_engine_refusal_ended_the_chain no longer short-circuits when the refusal's parent
is the retained terminal call. Whichever twin attribution retained, a token-identical
twin served at or after the refusal superseded it, so the verdict no longer depends
on which twin drew the smaller call id when _collapse_identical could only name the
twins by content. The retry-twin test runs over both retained calls and a timestamp
tie.

New tests pin how the finish-reason verdict and the refusal fallback compose on the
projection line that #4366's merge produced: content_filter keeps its own reason,
length and stop give max_output_tokens, and twins that disagree on the finish reason
still take the refusal's verdict. The model-server refusal test runs over the chat
before-headers, chat after-keepalive, Responses and Responses-streaming paths, and
the worker-custody ledger test over both stream settings, since Codex and OpenCode
stream by default.

Docstrings: apply_capture_incomplete_verdict and finalize_rollout_token_capture name
the refusal as a second source of the local verdict and qualify the same-verdict
claim (worker custody reports no refusal verdict until #4647), and the projection
docstring says the finish-reason withholding does not reach the refusal.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
aroshanghias-nvd pushed a commit to aroshanghias-nvd/Gym that referenced this pull request Oct 26, 2026
…rt the refusal (NVIDIA-NeMo#3980)

* feat(token-capture): record each call's finish reason and rebuild a length-cut terminal as incomplete

A capture record did not say why its model call stopped, so a consumer of
the rebuilt response could not tell a trajectory that ended at the
output-token budget from one that ended on its own. The Responses
converter already marks such a served response incomplete, but the
rebuilt response, which is what a trainer reads, carried no status at all.

TokenEntry gains finish_reason in the Chat Completions vocabulary (stop,
length, tool_calls, content_filter). response_finish_reason derives it
from either served payload shape: a chat payload states it directly, and a
Responses payload is read back through the converter's incomplete_details
mapping, with a completed payload stopping at a tool call or at the end of
its text. The capture path stamps it on every record; a record written
without the field reads as None.

project_main_chain_response marks the rebuilt response incomplete, with
incomplete_details.reason max_output_tokens, when the delivered chain's
terminal call stopped for length. Only the terminal call decides, because
an earlier length stop was extended by a later call. Every other finish
reason leaves the status unset, as before.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
(cherry picked from commit 9561221)

* fix(token-capture): carry the rebuilt response's incomplete verdict through delivery and mirror content_filter

Review follow-up on the finish-reason capture.

Delivery replaced only the result response's output with the rebuilt output,
so the builder's status: incomplete and incomplete_details never reached a
result whose harness response said completed. Delivery now carries that
verdict onto the result's response when the harness reported no status or
completed; a harness that already reported incomplete or failed keeps its own
verdict. The delivery docstring states the exception, and delivery-level tests
cover the absent, completed, and failed harness statuses.

The builder mirrors the Responses converter's other incomplete verdict: a
terminal call that stopped for content_filter is incomplete with that reason,
alongside length as max_output_tokens. The docstring states that the finish
reason is recorded by the local capture path only, so a chain built from
externally staged records reports no verdict. The conformance entry carries a
non-default finish reason so the store round trip proves the field persists,
and the record comment describes which values are consumed.

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

* fix(token-capture): withhold the truncation verdict when identical retries disagree on the finish reason

Terminal attribution collapses token-identical captures (an identical retry) to the smallest call id. That is sound for the delivered tokens but not for the finish reason recorded on each serving: one serving can be cut at the output budget and its retry under a larger budget complete, so the rebuilt response's status depended on which twin drew the smaller id.

resolve_terminal now records which calls a witness singled out (the explicit id, or a response id, item id or content fingerprint that matched exactly one entry) and reports finish_reason_resolved=False when the named call was chosen among token-identical twins by id order alone and those twins recorded different finish reasons; the reason trail carries finish_reason_disagreement. The consumer passes the flag to project_main_chain_response, which then leaves status and incomplete_details unset. Twins that agree, or a call a witness singled out, keep the verdict.

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

* fix(model): answer a propagated context overflow in OpenAI's error envelope

With propagate_context_overflow_errors on, the vLLM model server lets the
engine's 400 reach the harness when a request no longer fits the context
window. The harness received vLLM's raw body, whose code is the integer 400,
so an OpenAI-compatible harness (Codex, OpenCode) could not recognize the
refusal as a context overflow and compact its history.

A propagated length refusal is now marked, and VLLMModel's
_should_propagate_upstream_http_error returns false for it, so the shared
error handler lets it through to the server's middleware, which answers with
OpenAI's envelope: the engine's message and param, read from the nested
"error" object of vLLM 0.10.1 and later (or the flat message of older
engines, or the raw text), and a string code. The code is chosen where the
error is marked: a body that names the context window (vLLM's two wordings,
the engine's "maximum model length", llama.cpp's type and phrases) carries
context_length_exceeded, which tells the harness to compact and retry; a body
that only names max_tokens or max_completion_tokens carries no code, because
lowering the parameter is the remedy and compaction is not. The shared
classification also recognizes max_completion_tokens and "maximum model
length", two length refusals that were answered with a 500.

A streaming /v1/responses request receives the same HTTP 400 before the
stream, as main answers it. A streaming /v1/chat/completions request that has
passed its keepalive receives the envelope in its SSE error event, logged as
one warning instead of a traceback.

The default (off) is unchanged: the refusal is absorbed into an empty
completion with finish_reason "length".

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

* refactor(model): one attribute marks a propagated refusal and carries its envelope code

The boolean marker and the code attribute set on a propagated length refusal were two attributes to keep in sync. PROPAGATED_REFUSAL_CODE_ATTRIBUTE replaces both: its presence marks the error (is_propagated_refusal), and its value is the envelope code, context_length_exceeded for a message that names the context window and None for a refusal of the request's own output-token parameter. The marking helper, the shared handler hook, the HTTP middleware and the chat-SSE path read the one attribute; the test covers the unmarked, None-code and overflow-code states.

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

* feat(token-capture): resolve a refused call's capture intent and report the refusal

A model call the engine refuses (HTTP 400 because the prompt no longer fits
the context window) generates nothing, so no token record ever resolves the
capture intent that register_call_intent wrote before dispatch. The rollout
therefore froze incomplete and was masked, which hid every session that
ended at the window from training and from the truncation counts.

The refusal is now the intent's resolution. TokenCaptureStore.refuse_call
records a RefusalRecord in the rollout's state file, _dangling_intents
treats a refused call as resolved, and the frozen snapshot is complete and
reports the refusal in `refusals`. refuse_call is an optional sink extension
beside begin_call with a gated conformance check; TokenSink is unchanged.
After freeze a refusal raises TokenCaptureFrozenError, so it never stales a
consumed snapshot's retirement. Under worker custody record_refusal writes
the ledger failure row with ENGINE_REFUSED_CALL_REASON, the definite reason,
and the uncommitted-call sweep skips that call.

The builder marks the rebuilt response incomplete (max_output_tokens) only
when a refusal came after the delivered terminal call, and the consumer
puts the records on metrics["refusals"], which is what distinguishes a
refusal from a served length stop. The vLLM model server records a
propagated refusal inside the single propagate branch on both routes, with
the envelope code the client received.

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

* feat(token-capture): name the ledger failure reasons of a call that served no completion

A framework assembling a rollout receipt from the ledger manifest has to
decide which failure rows poison the rollout. NeMo RL already treats the
uncommitted-call reason as off-chain rather than poisoning, because such a
call served no completion and can never be a lineage parent; the final call
of a rollout that exhausted the context window is the case it was written
for. A refused call now carries its own definite reason, so it needs the
same treatment, or it would start poisoning rollouts that trained before.

UNSERVED_CALL_FAILURE_REASONS names both reasons in one place, so a receipt
builder switches from the single constant to the set and the two sides
cannot drift. A rollout whose refused or lost call is the one the harness
kept is still masked by the missing terminal row.

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

* fix(token-capture): count a refusal as the rollout's ending only when it continued the delivered chain for the context window

The builder marked the rebuilt response incomplete for any refusal recorded
later than the delivered terminal call. A later refusal on an auxiliary
branch therefore truncated a completed, attributed main chain, and a
refusal of an output-token parameter (code None) counted as a context
overflow although it says nothing about the conversation's length.

record_refusal now stores the lineage decision resolve_parent made for the
refused request before dispatch: RefusalRecord gains parent_call_id and
parent_resolution, the store's refuse_call and the sink extension carry
them, and the conformance check requires them on the frozen record. The
projection counts a refusal only when its code is
CONTEXT_LENGTH_EXCEEDED_ERROR_CODE and its parent is the delivered terminal
call or a call whose full token sequence is identical to it; BuildOutput
exposes sequence_digests so a retry twin of the terminal qualifies. A
refusal the harness recovered from, one on another branch, a parameter
refusal, and one with an unresolved parent leave the verdict alone and stay
listed in metrics["refusals"]. The code string moves next to the refusal
record in records.py, imported by the model base, so the builder and the
servers read one constant.

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

* fix(token-capture): reconcile finish reasons across terminal witnesses

Signed-off-by: Lin Jia <[email protected]>

* chore(vllm_model): drop the FastAPI Response import the merge left unused

The envelope is returned as a JSONResponse, so after the merge of main
nothing in the module constructs a bare Response any more.

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

* fix(token-capture): let a retained retry twin served after a refusal supersede it

A refusal that continued call A, followed by a fresh serving B with A's exact
tokens that the harness kept, still marked the rebuilt response `incomplete`:
the retry-twin rule compared token-sequence digests alone. `_refusal_ended_the_chain`
now also requires the retained twin's entry to precede the refusal record
(`created_at` on both records). A twin served after the refusal is the successful
re-serving that superseded it, so the twin's own ending stands. A refusal that
continued the terminal call itself is unchanged, since such a continuation is
recorded after the call it continues. The regression test covers both orders.

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

* refactor(token-capture): name engine refusals apart from OpenAI refusals and tighten the rules

Naming: `refusal`, `refusals` and `refuse_call` collided with OpenAI's `refusal`
content part, which `openai_utils`, the converters and rollout health already
use for a model declining to answer, while the ledger called the same event
`engine_refused_request`. The store, sink, snapshot, builder, consumer,
conformance check, metrics and result keys now say "engine refusal"
throughout: `EngineRefusalRecord`, `TokenCaptureStore.record_engine_refusal`,
`capture_engine_refusal`, `CaptureContext.engine_refusal_recorded`,
`TokenCaptureSnapshot.engine_refusals`, `metrics["engine_refusals"]`,
`_ng_token_capture.engine_refusals`, the conformance check
`engine_refusal_resolution`, and the state-file key `engine_refusals`.

Review items: the builder no longer hashes every call's token sequence on
every build; `BuildOutput.entries` keeps the buildable entries by call id and
the projection compares two sequences only for a refusal that continued a
retry twin. The conformance check accepts only `TokenCaptureFrozenError` as the
post-freeze fence and requires a second freeze to report the same snapshot,
version and refusals, as the protocol text now states. A retire test asserts
that the fence clears the recorded refusals. The builder documents that an
auxiliary request sent after the session completed can carry the terminal
call's history and so flip the verdict. The sink and the docs state that a
worker-custody refusal is a reason-only ledger row that yields no truncation
verdict (NVIDIA-NeMo#4647).

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

* fix(token-capture): order a refusal against the whole twin group; test the verdict composition and the streaming paths

Review follow-ups on the a642822 re-review of NVIDIA-NeMo#3980.

_engine_refusal_ended_the_chain no longer short-circuits when the refusal's parent
is the retained terminal call. Whichever twin attribution retained, a token-identical
twin served at or after the refusal superseded it, so the verdict no longer depends
on which twin drew the smaller call id when _collapse_identical could only name the
twins by content. The retry-twin test runs over both retained calls and a timestamp
tie.

New tests pin how the finish-reason verdict and the refusal fallback compose on the
projection line that NVIDIA-NeMo#4366's merge produced: content_filter keeps its own reason,
length and stop give max_output_tokens, and twins that disagree on the finish reason
still take the refusal's verdict. The model-server refusal test runs over the chat
before-headers, chat after-keepalive, Responses and Responses-streaming paths, and
the worker-custody ledger test over both stream settings, since Codex and OpenCode
stream by default.

Docstrings: apply_capture_incomplete_verdict and finalize_rollout_token_capture name
the refusal as a second source of the local verdict and qualify the same-verdict
claim (worker custody reports no refusal verdict until NVIDIA-NeMo#4647), and the projection
docstring says the finish-reason withholding does not reach the refusal.

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

* fix(token-capture): report the missing refusal extension and name the reason constants

A sink that implements begin_call without record_engine_refusal passes conformance and then
masks every rollout in which the engine refused a call, because nothing resolves the refused
call's pre-dispatch intent. The kit now issues a ConformanceWarning for the skipped
engine_refusal_resolution check that names that consequence. A sink with neither extension
stays quiet, and the result is still the list of passed check names.

The context-window error code and the max-output-tokens incomplete reason are spelled through
the constants in records.py everywhere in the library, so the conformance kit and the builder
cannot drift from the records module. The staging records module no longer re-exports the
refusal reason and the unserved-call set, which no staging reader used; the test that pins the
set imports it from the records module.

The builder docstring states that the capture cannot tell an auxiliary request sent after the
session completed from the harness's next turn, so a context-window refusal of such a request
marks the rollout incomplete and delivery replaces a harness completed status. Comments
describe the current contract only and keep one fully qualified issue pointer, and upstream
lines the change does not need are left as they were.

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

* docs(token-capture): match the comments and the docs page to the twin-group refusal rule; pin the package-root reason names

The parent_call_id field comment on EngineRefusalRecord and the projection docstring
described the earlier verdict rule, under which a refusal of the terminal call itself
counted unconditionally and only the parent was ordered against the refusal. Both now
state the rule _engine_refusal_ended_the_chain applies: the refused request continued
the delivered terminal call or a token-identical twin of it, and no other call with
that token sequence was served at or after the moment the refusal was recorded.

The store module docstring says again that the refusal transition, like freeze, mark
and drop, is fsynced because it cannot be rebuilt from the JSONL tail. The
ENGINE_REFUSED_CALL_REASON comment covers the output-token-parameter refusal that the
custody row also records. The capture_engine_refusal docstring states the custody
fallback for a refusal that cannot be recorded: the custody sweep writes the
uncommitted-call row instead of leaving an intent dangling. The conformance warning
and the missing-extension log line say the rollout is masked by default, since
mask_incomplete_when_attributed: false keeps a delivered chain.

The docs page tells framework authors that a receipt builder reading the ledger must
treat UNSERVED_CALL_FAILURE_REASONS as off-chain, and describes the ConformanceWarning
a sink without the refusal extension receives. The reasons test also pins the
package-root exports of UNSERVED_CALL_FAILURE_REASONS and ENGINE_REFUSED_CALL_REASON,
which NeMo RL reads through getattr with a fallback, so a dropped export fails a test
instead of silently poisoning refused calls' receipts.

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

---------

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

This branch was previously deployed

1 inactive deployment
public — 3bc2a330 Deployed Oct 15, 2026 by copy-pr-bot[bot] via release / finalize / notify #5567
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