Skip to content

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

Merged
marcromeyn merged 22 commits into
mainfrom
alexandery/capture-engine-refusal-record
Oct 26, 2026
Merged

marcromeyn merged 22 commits into
mainfrom
alexandery/capture-engine-refusal-record

Conversation

@alexandery-nvidia

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

Copy link
Copy Markdown
Contributor

Stacked PR, bases merged. This branch was built on #3973 (the finish reason and the incomplete terminal), which it needs for the delivered status, and on #3978 (the context-overflow error envelope) for the single propagate branch. Both merged on 2026-10-15 (c7b1bdf, d5b2892), #4366 (the finish reason through worker-custody staging) merged on 2026-10-16 (949198c), and main is merged in after each squash, most recently as 10a8852, so the diff is this pull request's own changes; the commit list still shows #3973's commits (9c8bdf2, ec2f7c3, 744e198, 652a174), whose content is on main now. Review the commits that are this branch's: feat(token-capture): resolve a refused call's capture intent and report the refusal, feat(token-capture): name the ledger failure reasons of a call that served no completion, fix(token-capture): count a refusal as the rollout's ending only when it continued the delivered chain for the context window (the 2026-10-13 review follow-up), fix(token-capture): let a retained retry twin served after a refusal supersede it (the 2026-10-15 follow-up), refactor(token-capture): name engine refusals apart from OpenAI refusals and tighten the rules (ananthsub's review of 2026-10-15), fix(token-capture): order a refusal against the whole twin group; test the verdict composition and the streaming paths (83c4c2e, yaoyu-33's re-review of 2026-10-16), fix(token-capture): report the missing refusal extension and name the reason constants (985efe0), and docs(token-capture): match the comments and the docs page to the twin-group refusal rule; pin the package-root reason names (a36f24a, yaoyu-33's re-review of 2026-10-22).

What does this PR do?

A model call the engine refuses (HTTP 400 because the prompt no longer fits the context window) generates nothing, so the training-token capture holds no record of it. Two things went wrong with that. The rebuilt response of a rollout that ended on such a refusal looked exactly like one whose harness stopped on its own, so a trainer counting truncated samples missed every session that ran into the window, which is the common ending of an agent session under a token budget. And because register_call_intent had written the call's capture intent before dispatch, the refused call looked like a lost call at freeze: the rollout froze incomplete and was masked, so nothing that reached the window was trained on at all.

This PR makes the refusal the resolution of that intent.

  1. The store resolves the intent. TokenCaptureStore.record_engine_refusal(rollout_id, *, model_call_id, code, parent_call_id=None, parent_resolution=None) (nemo_gym/token_id_capture/store.py) records an EngineRefusalRecord (the refused call's id, the error code the client received, a timestamp, and the request-time lineage decision: the recorded call the refused request continued and that decision's status) in the rollout's state file, which is written atomically and fsynced. _dangling_intents treats an intent as resolved by an entry or by a refusal, so freeze_now returns incomplete=False and the snapshot reports the refusal in TokenCaptureSnapshot.engine_refusals. There is no separate refusal file. A refusal after freeze raises TokenCaptureFrozenError and leaves the version alone, so it never stales the retirement of a consumed snapshot.
  2. An optional sink extension, like begin_call. record_engine_refusal is documented beside begin_call in protocols.py and is not part of TokenSink, so existing sinks keep working. The conformance suite gains engine_refusal_resolution, gated on the method like begin_call_custody: a refusal must resolve the intent and appear on the snapshot, and after freeze the sink must either raise TokenCaptureFrozenError or leave the frozen snapshot unchanged, which a second freeze confirms by reporting the same snapshot, version and refusals. A negative test shows a store that acknowledges a refusal without recording it fails the check.
  3. One contract for both custodies. capture_engine_refusal(code) (sink.py) writes through the in-flight capture context and never raises. It passes along the lineage decision resolve_parent made for the request before dispatch (CaptureContext.parent_resolution), so a refusal is placed on the branch it continued exactly as a served call's entry is. On the local capture path it calls the sink's record_engine_refusal; a sink without the extension is logged once per worker and the rollout is masked as a lost call would be. Under worker custody it records the ledger failure row with the new ENGINE_REFUSED_CALL_REASON for the admitted call, and _fail_uncommitted_external_call skips a call recorded this way, so the ledger states the definite outcome (the engine refused before the worker could stage anything) instead of the ambiguous uncommitted-call row. That row carries the call id and the reason only, no code and no lineage, so a rollout rebuilt from staged records is not poisoned but reports no truncation verdict for the refusal; token-capture: an engine refusal under worker custody reports no truncation verdict #4647 tracks carrying both. Framework coupling: NeMo RL's receipt builder (nemo_rl/environments/nemo_gym.py, _assemble_receipt) already treats a failure row with the uncommitted reason as off-chain rather than poisoning, because such a call served no completion and can never be a lineage parent; the refused reason needs the same treatment, so UNSERVED_CALL_FAILURE_REASONS (records.py) names both reasons for the receipt builder to import, and fix(nemo-gym): keep unserved-call ledger reasons off the receipt poison list RL#4749 makes NeMo RL read that set with a pin-agnostic fallback, so it lands before any pin bump that carries this change. The rollout is still masked when the refused call was the one the harness kept (the missing-terminal-row check).
  4. The builder counts a refusal only when it ended the delivered chain. project_main_chain_response receives the snapshot's refusals and marks the rebuilt response incomplete with incomplete_details.reason: "max_output_tokens" only for a refusal that meets two conditions (_engine_refusal_ended_the_chain): its code is context_length_exceeded, because an output-token parameter the engine rejected says nothing about the conversation's length; and its request continued the delivered terminal call, by the lineage decision recorded with it, either the terminal call itself or a token-identical retry twin of it, and no other call with that token sequence was served at or after the moment the refusal was recorded (the records' created_at order the refusal against the whole twin group, whichever twin attribution retained, so the verdict does not depend on which twin drew the smaller call id; a twin served at or after the refusal is a successful re-serving that superseded it; the projection reads the calls' token sequences from BuildOutput.entries on demand, so a build without refusals compares nothing). Known limitation: an auxiliary request sent after the session completed (a summary or title call, or an end-of-session compaction) can carry the terminal call's history and so continues it in lineage; refused for the context window, it marks the rollout incomplete and delivery then replaces a harness completed. The capture cannot tell such a request from the harness's next turn. A refusal the harness recovered from (its request continued an earlier call and a later call was served), a refusal on an auxiliary branch, and a refusal whose parent could not be resolved leave the verdict alone, however late they were recorded. The consumer puts the records on metrics["engine_refusals"] on every build, masked and failed ones included, and that field is what distinguishes a refusal from a served length stop, which produces the same status. Delivery (feat(token-capture): preserve finish reasons and terminal truncation #3973) copies the verdict onto a harness response that said completed or nothing.
  5. The vLLM model server records it. Inside fix(model): return OpenAI context-overflow error envelopes #3978's single propagate branch on both routes, _mark_propagated_overflow returns the envelope code it chose and capture_engine_refusal stores it: context_length_exceeded when the body names the context window (including vLLM's "'max_tokens' or 'max_completion_tokens' is too large: N. This model's maximum context length is M tokens ..."), None for a 400 that names only the output-token parameter, which is still a refusal that resolves the intent. An absorbed overflow (propagate_context_overflow_errors: false) records nothing, and a request outside a captured rollout records nothing. The code string, CONTEXT_LENGTH_EXCEEDED_ERROR_CODE, is defined next to the refusal record in records.py and imported by the model base, so the builder and the servers read one constant.

Review follow-up (2026-10-13)

yaoyu-33's two questions on builder.py changed the rule in point 4: a refusal is placed by the lineage decision recorded with it rather than by its timestamp, so a later refusal on an auxiliary branch no longer truncates a completed main chain, and only a context_length_exceeded refusal sets the verdict, so a code=None parameter refusal resolves its intent and is listed in metrics["engine_refusals"] without becoming a truncation. The branch also carries a merge of main 3d2e970.

Review follow-up (2026-10-15)

yaoyu-33's question on builder.py: a refusal that continued call A, followed by a fresh serving B with A's exact tokens that the harness kept by response id, still marked B incomplete, because the retry-twin rule compared digests alone. _engine_refusal_ended_the_chain now also requires the retained twin's entry to precede the refusal record (TokenEntry.created_at against RefusalRecord.created_at); a twin served after the refusal is the successful re-serving that superseded it, so B's own ending stands. A refusal that continued the terminal call itself is unchanged. test_a_refusal_of_a_retry_twin_counts_only_when_the_retained_twin_preceded_it covers both orders (03a0692). tests/unit_tests/test_terminal_attribution.py, test_trajectory_builder.py, test_token_id_capture.py, test_token_capture_conformance.py: 331 passed.

ananthsub's review of 2026-10-15 (0fa5fb5): the names changed from refusal and record_engine_refusal to engine refusal throughout (EngineRefusalRecord, record_engine_refusal, capture_engine_refusal, engine_refusals, engine_refusal_resolution, the state-file key), because refusal is OpenAI's content part for a model declining to answer, which openai_utils, the converters and rollout health already use, while the ledger said engine_refused_request. The per-build sequence digests are gone: 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; the protocol text says the same. A retire test asserts the fence clears the recorded refusals. The post-completion auxiliary request is documented as a known limitation (point 4), and the worker-custody row's missing verdict is documented in the sink, the docs and point 3, with the follow-up #4647. NeMo RL's side of the reasons set is NVIDIA-NeMo/RL#4749. After #3973's squash, main was merged in as 8e6fdca (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 refusal tests. Validation of the merge head 8e6fdca: the unit suite (test_collect_downstream_junit.py excluded) gave 9163 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 537 passed), with genrm_model and local_vllm_model erroring at collection as before. Gate on 0fa5fb5: the unit suite (8758 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 529 passed; genrm and local_vllm collect errors for missing local packages, as on main); the five token-capture unit files together: 438 passed. After #4366's squash (949198c), main was merged in again as a642822: #4366 moved the finish-reason table of the rebuilt response into records.incomplete_reason_for_finish_reason, which project_main_chain_response now calls in place of this branch's local table, with this branch's engine-refusal rule kept beside it, and the projection's docstring describes both custodies as #4366 left them; #4366's apply_capture_incomplete_verdict tests sit next to this branch's refusal tests. Validation of a642822: the unit suite (test_collect_downstream_junit.py excluded) gave 9243 passed, 56 skipped, 28 failed, 20 errors, the failures and errors identical to the environmental set main shows here (telemetry and opensandbox tests that need packages this machine lacks); every responses_api_models/*/tests session passed (vllm_model 541 passed), with genrm_model and local_vllm_model erroring at collection as before; ruff 0.9.9 format --check and check are clean on the two resolved files.

Review follow-up (2026-10-16)

yaoyu-33's re-review of a642822 (83c4c2e): _engine_refusal_ended_the_chain orders the refusal against the whole twin group instead of short-circuiting when the refusal's parent is the retained terminal call, so a token-identical twin served at or after the refusal supersedes it whichever twin attribution retained, and 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 merged projection line (content_filter keeps its reason, length and stop give max_output_tokens, 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 runs over both stream settings. 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. Gate on 83c4c2e: responses_api_models/vllm_model/tests 547 passed, the four token-capture unit files 352 passed, ruff check and ruff format --check clean on the six changed files.

Review follow-up (2026-10-22)

985efe0 (yaoyu-33's follow-up notes on 83c4c2e, after a merge of main as 10a8852): the conformance kit issues a ConformanceWarning for the skipped engine_refusal_resolution check when a sink implements begin_call without record_engine_refusal, naming the consequence (the refused call's intent stays dangling, so the rollout freezes incomplete and is masked by default); a sink with neither method stays quiet and the return value is unchanged. CONTEXT_LENGTH_EXCEEDED_ERROR_CODE and MAX_OUTPUT_TOKENS_INCOMPLETE_REASON replace the string literals in the kit and the builder, so neither can drift from records.py. The staging records module no longer re-exports the refusal reason and the unserved-call set, which no staging reader used (neither NeMo RL main nor NVIDIA-NeMo/RL#4749 imports them). The builder docstring states the known limitation of point 4 in its final form. No behavior change apart from the opt-in warning. Gate on 985efe0: test_token_id_capture.py 204, test_token_capture_conformance.py 10, test_terminal_attribution.py 92, test_base_responses_api_model.py 88, responses_api_models/vllm_model/tests 575, all passing.

a36f24a (yaoyu-33's re-review of 985efe0): text only. The parent_call_id field comment on EngineRefusalRecord and the projection docstring state the twin-group rule _engine_refusal_ended_the_chain applies; the store module docstring again says the refusal transition is fsynced because it cannot be rebuilt from the JSONL tail; ENGINE_REFUSED_CALL_REASON's comment covers the output-token-parameter refusal the custody row also records; capture_engine_refusal's docstring states the custody fallback for a refusal that cannot be recorded (the sweep's uncommitted-call row); 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; the reasons test pins the package-root exports NeMo RL reads through getattr. Gate on a36f24a: the four token-capture unit files 361 passed; ruff check and ruff format --check clean on the changed files.

Issue

No issue filed; observed while training with the OpenCode and Codex harnesses under token-id capture with propagate_context_overflow_errors: true, where sessions that reached the window were indistinguishable from completed ones in the rebuilt responses, and, once the capture intents were introduced, were masked altogether.

Validation

  • New tests. Store: a refused call resolves its intent and the snapshot reports the record from the state file, idempotent repeats and a conflicting code, a refusal after freeze raises and leaves the snapshot unchanged, the retired guard, delete removes the refusal with the state file. Sink: capture_engine_refusal passes the capture context's lineage decision to the optional extension and records no parent without one, a sink without the extension warns once and leaves the intent dangling, a raising sink never fails the call. Builder and delivery: a six-case table (continues-terminal, continues-terminal-twin, recovered, auxiliary-branch, parameter-error, unresolved-parent) and the five-case twin test test_a_refusal_of_a_retry_twin_counts_only_when_every_twin_preceded_it (both retained twins, a twin served before, with and after the refusal) show the verdict set only for a context-window refusal whose request continued the delivered terminal call or a token-identical retry twin of it with no twin served at or after the refusal; two composition tests, test_a_terminal_refusal_only_fills_a_verdict_the_finish_reason_left_empty and test_twins_that_disagree_on_the_finish_reason_still_take_a_terminal_refusals_verdict, pin how the finish-reason verdict and the refusal compose on the projection line (content_filter keeps its reason, length and stop give max_output_tokens, and twins that disagree on the finish reason still take the refusal's verdict); and a finalized rollout carries the verdict and metrics["engine_refusals"] with the lineage fields on the result without being masked. Conformance: the file store passes engine_refusal_resolution, which now requires the lineage fields on the frozen record; a sink with begin_call but without the extension skips it and passes with a ConformanceWarning that names the gap; a sink with neither method passes quietly; and a store whose record_engine_refusal acknowledges without recording fails it. Model server: a captured rollout records the propagated refusal through the real dispatch (the intent is registered by register_call_intent, and the record carries the root lineage decision the dispatch made for it) and freezes complete on six routes (chat-completions, completions, chat-stream-before-headers, chat-stream-after-keepalive, where the refusal arrives as a 200 with an SSE error event, responses, and responses-stream, which raises the 400 before any event), a max_tokens-only 400 is recorded without a code, an absorbed overflow and an uncaptured request record nothing, and under worker custody the ledger carries ENGINE_REFUSED_CALL_REASON alone, on both worker backends and with streaming on and off.

  • Unit suite (pytest tests/unit_tests, with test_collect_downstream_junit.py excluded for a missing local package), run on the branch tip 2cfbb64 after the merge of main 3d2e970: 8469 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: vllm_model 455 passed; the other nine directories match main (two of them have a collection error for a missing local package on main too).

  • ruff check and ruff format --check on the changed files: clean.

  • Harness conformance (the opencode, codex and pi probes, the P0 publish and the P0 check) is red on this head and on main since fix(conformance): prefer agent sessions #4489 (dc2c341): both merge parents fail identically, and the check is not required for merge.

  • Rollout evidence on this shape (2026-10-16, one GB300 node, vLLM 0.29.0 serving Qwen3.5-9B with --max-model-len 2048, this branch at 83c4c2e with propagate_context_overflow_errors: true and a file capture store): a two-call rollout driven through the vllm_model server's /ng-rollout/<id>/training-token-capture/v1/chat/completions route as a harness drives it. Call 1 (22 prompt tokens, 48 generated) was served. Call 2 continued the conversation with a user turn that did not fit; the engine answered This model's maximum context length is 2048 tokens. However, you requested 48 output tokens and your prompt contains at least 2001 input tokens, for a total of at least 2049 tokens., and the server propagated it as HTTP 400 with code: context_length_exceeded. The harness stopped with the served response, as OpenCode and Codex do, and finalize_rollout_token_capture rebuilt the record:

    "response": {"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}, ...},
    "_ng_token_capture": {"n_calls": 1, "delivered_fraction": 1.0,
      "terminal_attribution": {"method": "response_id", "call_id": "733127f9...", "chain": "delivered"},
      "engine_refusals": [{"model_call_id": "0239bea8...", "code": "context_length_exceeded",
                            "parent_call_id": "733127f9...", "parent_resolution": "resolved"}]}

    mask_sample is unset: the refused call resolved its intent, so the snapshot froze complete. The previous shape of this change ran for several weeks of GRPO training in a downstream fork with the OpenCode and Codex harnesses under token-id capture.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 3, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ananthsub ananthsub 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.

Early feedback while this is a draft, reviewing only the last two commits as the description asks. The motivation is sound: a rollout that ends on a context-window refusal should be distinguishable from one the harness ended on its own. The store-side locking, fsync ordering, and cleanup in _drop are careful. Most of the inline findings, though, trace back to a few design choices, so this summary leads with those.

Design implications

1. One call now has two records that disagree about its fate.
The capture store already models a call that never commits. register_call_intent records the intent before dispatch, and at freeze an intent with no matching entry is read as a lost call, which marks the rollout incomplete. This PR adds a separate refusal file instead of resolving that intent. So a refused call is both a refusal in refused.jsonl and a lost call in tokens.intents, and freeze trusts the intent.

That is why every refused rollout still freezes incomplete and is masked under the default mask_incomplete_when_attributed: true. The new status: "incomplete" therefore never reaches training. The model server test misses it because it reads the state flag, not the frozen snapshot.

2. It changes the sink protocol instead of extending it.
TokenSink is deliberately minimal. Optional capabilities such as begin_call live outside the protocol, and their conformance checks are gated. Adding mark_refused to the runtime-checkable protocol makes every existing configured sink fail at startup, and makes previously conformant sinks fail conformance. The other entry points (install_token_sink, record_refusal) still treat it as optional, so the three paths now disagree.

3. New state without a guaranteed end of life.
The refusal file follows the existing cleanup paths, but a refusal that lands after freeze bumps the version. That stales the consumer's retirement, and nothing in production calls the sweeps, so that capture is never removed. A torn line in the file also fails every later freeze, so that capture is never retired either.

4. Local capture and worker custody diverge.
Only the local file store learns about refusals. Under worker custody, the receipt path upstream NeMo RL uses, the refused call is recorded on the ledger as an uncommitted failure and the rollout is rejected. The same event therefore has opposite outcomes depending on capture placement. The store and the ledger should share one contract for how a call ends.

5. The verdict has no agreed way out of Gym.
The rebuilt response's status is dropped at delivery, because finalize_rollout_token_capture copies only output. #3973 has the same gap, and its review lays out two options: copy the verdict into the harness response, which changes the delivery contract, or publish it under _ng_token_capture, which keeps the contract. This PR already puts refusals under _ng_token_capture, which argues for the second. The two PRs should settle this together.

Recommended shape

Make "refused" a reason that resolves the call intent, rather than a parallel record:

  • An optional sink extension next to begin_call that closes an intent as refused. Implement it in both the file store and the ledger.
  • Freeze then sees a resolved intent, so the rollout is not incomplete and not masked.
  • No change to TokenSink, so existing sinks keep working.
  • No separate file, and no post-freeze version bump.
  • The builder can order the refusal against the delivered terminal call. Today any refusal marks the response incomplete, even when the session continued and finished normally.

On the question you raised: we would keep the signal in the capture layer rather than the observability record. Training-only capture writes no evaluation record, and a propagated overflow appears there only as an upstream 400. The capture layer already knows the call never committed; what it lacks is the reason.

flowchart LR
    A["register_call_intent"] --> B["vLLM 400 names context length"]
    B --> C{"this PR"}
    C --> D["refused.jsonl"]
    C --> E["intent left dangling"]
    E --> F["freeze reports incomplete, build masked"]
    B --> G{"recommended"}
    G --> H["intent resolved as refused, in store and ledger"]
    H --> I["freeze complete, refusal reason on snapshot"]
    I --> J["builder counts the refusal only if terminal"]
Loading

Other items (inline)

  • Messages that mention max_tokens: the comment implies vLLM's "'max_tokens' ... is too large ... maximum context length" error is not recorded as a refusal, but it is, and no test covers it.
  • Status assertion: a test asserts a status code that #3978 will change.
  • Missing tests: nothing checks refusal cleanup in delete and the sweeps, the never-raise path, or a negative conformance case.

Sequencing

  • #3978 first. It rewrites the same vLLM classification block. Landing it first keeps one classifier and one error-code constant.
  • #3973 alongside. It sets the same status line in the builder and owns the delivery question in item 5.
  • Then rebase this PR. Doing it after both land keeps the stack consistent.

Comment thread nemo_gym/token_id_capture/store.py Resolved
Comment thread nemo_gym/token_id_capture/builder.py Resolved
Comment thread nemo_gym/token_id_capture/protocols.py Resolved
Comment thread nemo_gym/token_id_capture/store.py Resolved
Comment thread nemo_gym/token_id_capture/store.py Resolved
Comment thread nemo_gym/token_id_capture/store.py Resolved
Comment thread nemo_gym/token_id_capture/sink.py Resolved
Comment thread responses_api_models/vllm_model/app.py Resolved
@alexandery-nvidia
alexandery-nvidia force-pushed the alexandery/capture-engine-refusal-record branch from 8c9ce21 to 3141467 Compare October 10, 2026 04:09
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Thanks for the review; it changed the design. The PR is reworked now, in the shape you recommended, rather than after the compaction PRs (#3368, #4124): their landing date is open, the rework is independent of them once the intent is the anchor, and they will rebase over this change. Why it matters now: the fork trains with propagate_context_overflow_errors: true, and under the old shape every rollout that hit the window froze incomplete and was masked, so the feature was inert exactly where it was meant to work.

What changed in 3141467, one commit on top of the rebased #3978 (d55e48a) and #3973 (57ec9b7):

  • A refusal resolves the call's capture intent: TokenCaptureStore.refuse_call records it in the state file, _dangling_intents treats the call as resolved, and the snapshot freezes complete with the refusal in refusals. No separate file, no post-freeze version bump (a late refusal raises TokenCaptureFrozenError).
  • refuse_call is an optional sink extension beside begin_call, keyword-only, with a gated conformance check and a negative test; TokenSink is unchanged.
  • Worker custody shares the contract: the ledger row carries ENGINE_REFUSED_CALL_REASON and the uncommitted-call sweep skips the call. The framework's receipt consumer still rejects any failure row, so the trainable outcome under worker custody is the ledger-level follow-up, paired with feat(token-capture): preserve finish reasons and terminal truncation #3973's staging follow-up.
  • The builder counts a refusal only when it came after the delivered terminal call, and metrics["refusals"] is documented as what distinguishes it from a served length stop.
  • record_refusal sits inside fix(model): return OpenAI context-overflow error envelopes #3978's single propagate branch and records the envelope code the client received; a max_tokens-only 400 is recorded with no code.

The delivery question (item 5) is settled by #3973 as rebased: delivery copies the builder's status and incomplete_details onto a harness response that said completed or nothing, so the refusal verdict reaches the result through the same path. The description is rewritten.

@alexandery-nvidia alexandery-nvidia changed the title feat(token-capture): record an engine's context-window refusal for the rollout feat(token-capture): resolve a refused call's capture intent and report the refusal Oct 10, 2026
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Addendum: the summary above said the framework's receipt consumer still rejects any failure row. That is not what NeMo RL does: its receipt builder already treats the uncommitted reason as off-chain (see the correction on the sink.py thread). A second commit, 09ad64b, therefore exports UNSERVED_CALL_FAILURE_REASONS so the refused reason joins that carve-out with a one-line NeMo RL change, which must land before NeMo RL bumps its Gym pin. Review the last two commits; the description is updated.

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-engine-refusal-record branch from 09ad64b to f7e94ed Compare October 10, 2026 08:32
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (on the rebased #3973 head ec2f7c3) over this morning's token-capture retire/delete changes (#3938, #3939). Three adjustments came with it, all in the two commits of this PR: refuse_call raises TokenCaptureRetiredError for a retired rollout like every other write, the retirement fence clears the refusals with the rest of the state, and the conformance kit's unconditional_retirement check also requires a late refuse_call to be fenced. Full unit suite matches main's baseline; vllm_model/tests 446 passed.

@yaoyu-33 yaoyu-33 added area:core Shared APIs, servers, telemetry, health, and registries complexity:high Cross-component or shared-contract change with a large 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
alexandery-nvidia and others added 5 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]>
…velope

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]>
… 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]>
…rt 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]>
…erved 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]>
@alexandery-nvidia
alexandery-nvidia force-pushed the alexandery/capture-engine-refusal-record branch from f7e94ed to e40ae25 Compare October 13, 2026 01:09

@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 and reproduced both cases below.

Comment thread nemo_gym/token_id_capture/builder.py Resolved
Comment thread nemo_gym/token_id_capture/builder.py Resolved
alexandery-nvidia and others added 2 commits October 14, 2026 00:23
The checkpoint-gate series (#3883) and this branch both extended
CaptureContext (main's admission_hook, publish_on_delivery and
deferred_commit beside this branch's intent_registered and
refusal_recorded) and the not-poisoned condition in
base_responses_api_model.py (a deferred commit, a recorded refusal). Both
sides are kept.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
… 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]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 2cfbb64

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Pushed 2cfbb64 for the 10/13 review (both questions answered in their threads): a refusal is now placed by the lineage decision resolve_parent made for its request before dispatch (RefusalRecord.parent_call_id / parent_resolution), and only a context_length_exceeded refusal whose request continued the delivered terminal call, or a token-identical retry of it, sets the truncation verdict; a later refusal on an auxiliary branch, a recovered one, a code=None parameter refusal, and one with an unresolved parent leave it alone and stay listed in metrics["refusals"]. main 3d2e970 is merged into the branch first (the checkpoint-gate series added CaptureContext fields and a not-poisoned condition next to this branch's; both sides kept), so the branch merges cleanly again. Local gate on the tip: the unit suite's failures are exactly main's 47 environmental ones (telemetry, opensandbox), vllm_model 455 passed. The description's stack note, point 4 and validation are updated.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Re-review follow-ups are in 83c4c2e; each of the four threads has its answer, and the description has a 2026-10-16 section with the gate (vllm_model tests 547 passed, the four token-capture unit files 352 passed, ruff clean).

On the process notes: the description now states that Harness conformance is red on this head and on main since #4489 (dc2c341), identically on both merge parents, and that the check is not required. The smoke rollout with propagate_context_overflow_errors: true runs next; I will add the record showing _ng_token_capture.engine_refusals and the incomplete verdict to the description when it is in. The two classifier follow-ups you listed are filed as #4703, since they predate this PR in #3978's classifier.

@linj-glitch @yaoyu-33 @ananthsub: 83c4c2e is one follow-up commit on top of the re-reviewed a642822, so the diff since the re-review is that commit alone.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

The smoke rollout is in the description (Validation, the rollout-evidence bullet). On one GB300 node with vLLM 0.29.0 serving Qwen3.5-9B at a 2048-token window, and this branch at 83c4c2e with propagate_context_overflow_errors: true, a two-call rollout went through the vllm_model server's capture route: the first call was served, the second continued the conversation past the window and the engine refused it with This model's maximum context length is 2048 tokens. However, you requested 48 output tokens and your prompt contains at least 2001 input tokens ... (HTTP 400, code: context_length_exceeded). The finalized record carries response.status: incomplete with incomplete_details.reason: max_output_tokens, is not masked, and _ng_token_capture.engine_refusals lists the refusal with parent_call_id naming the served call and parent_resolution: resolved.

alexandery-nvidia and others added 2 commits October 19, 2026 17:37
… 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]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Pushed 985efe0a9 on top of a merge of main (10a885250). It is a self-review cleanup of this PR's own hunks, no behavior change to the refusal path:

  • The builder docstring now states the known limitation plainly: a context-window refusal of an auxiliary request that continues the terminal call marks the rollout incomplete, and delivery replaces a harness completed with that verdict. The earlier sentence about a harness ending signal described a mechanism that does not exist in code.
  • The conformance kit issues a ConformanceWarning for the skipped engine_refusal_resolution check when a sink implements begin_call without record_engine_refusal, naming the consequence (a refused call leaves its intent dangling and the rollout is masked). A sink with neither method stays quiet; the return value is unchanged.
  • CONTEXT_LENGTH_EXCEEDED_ERROR_CODE and a new MAX_OUTPUT_TOKENS_INCOMPLETE_REASON constant replace the string literals in the kit and the builder.
  • The staging records module no longer carries re-exports nothing in staging/ reads; comments describe the current contract only; the comment-only edits to upstream lines are reverted.

Tests: test_token_id_capture.py 204, test_token_capture_conformance.py 10, test_terminal_attribution.py 92, test_base_responses_api_model.py 88, responses_api_models/vllm_model/tests 575, all passing locally.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 985efe0

@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 985efe0, with a consistency check of the code against your replies, the docstrings, the description and the docs page.

All four threads from the a642822 review are resolved, and the code matches each reply.

  • Twin-group ordering. The call-id-order flip reproduces at a642822 and is gone at head for content, shared-id and declared-id attribution. Restoring the old shortcut, or changing >= to >, fails the new five-case test.
  • Composition tests. Both mutations we named fail them: gating the refusal on finish_reason_resolved, and letting a refusal override content_filter. The projection docstring states the scope of the withholding.
  • Docstrings. apply_capture_incomplete_verdict and finalize_rollout_token_capture name the refusal and qualify the same-verdict claim.
  • Streaming. All six model-server routes really exercise their path: the after-keepalive case is a 200 with an SSE error event, and responses-stream raises the 400 before any event. Running the chat stream task in an empty context now fails the tests. The custody test covers both stream settings.

The rest of the delta is consistent too.

  • 10a8852's tree is byte-identical to git merge-tree of its parents, and main's #4014 and checkpoint changes don't interact with the refusal path.
  • 985efe0 changes no behavior apart from the opt-in ConformanceWarning. The constants hold the same values, and the dropped staging re-exports never shipped; neither RL main nor RL#4749 imports them.
  • RL#4749 (58b8bcc8) reads names and values that match this head exactly.
  • Locally at head: test_token_id_capture 204, test_terminal_attribution 92, test_token_capture_conformance 10, test_trajectory_builder 55, test_base_responses_api_model 88, vllm_model tests 575, all passing. The new branch rule costs 0.13 s for 2k entries and 200 refusals in the worst case.

No BLOCKER or RISK remains. The inline comments are stale text: the parent_call_id field comment, the store module docstring, and the docs page's worker-custody sentence. There is also an optional test pinning the package-root names RL reads.

Could you refresh the description before merge? Your squash commits take the PR body, so it will likely become the commit message.

  • Point 4: the twin clause still describes the earlier rule ("served before the refusal was recorded … only for a refusal whose parent is not the terminal itself"). Something like: "either the terminal call itself or a token-identical retry twin of it, and no other call with that token sequence was served at or after the moment the refusal was recorded (the records' created_at order the refusal against the whole twin group, whichever twin attribution retained)."
  • Point 4 known limitation: "The harness's own ending signal is what tells the two apart." describes the mechanism you removed from the docstring in 985efe0. Perhaps "The capture cannot tell such a request from the harness's next turn."
  • Header: the latest merge of main is 10a8852, and the commit list doesn't include 83c4c2e or 985efe0.
  • Validation: it still lists "a two-case table on the retained twin's serving order" and the model-server test "on both the chat-completions and the completions API". It could name the five-case twin test, the two composition tests, the six routes, the custody test over both stream settings, and the ConformanceWarning case. The 985efe0 gate numbers are only in a PR comment so far.

Optional wording nits, your call:

  • records.py#L73-L75: under custody, ENGINE_REFUSED_CALL_REASON also covers an output-parameter refusal (code=None).
  • builder.py#L710-L711: "served after the refusal" should be "served at or after", matching >= and the tie test.
  • sink.py#L377-L378: under custody, a refusal that can't be recorded falls back to the uncommitted-call row rather than a dangling intent.
  • conformance.py#L198-L199: "the rollout is masked" holds only by default; mask_incomplete_when_attributed: false keeps a delivered-chain rollout.
  • The docs' conformance section could mention the new ConformanceWarning.

Possible follow-up. The verdict now compares TokenEntry.created_at, stamped by the model server (sink.py#L516), with the refusal's created_at, stamped by the sink implementation (store.py#L358). The protocol doesn't ask a sink to stamp it, and records.py#L195 still calls the entry timestamp "non-semantic". Stamping the refusal time in capture_engine_refusal would put both on one clock. Any error today is conservative: a dropped verdict, and only for retry twins.

Merge ordering is unchanged: this still lands after NVIDIA-NeMo/RL#4749. Harness conformance is red the same way as on main since #4489, and it isn't required.

Generated by Claude Code

Comment thread nemo_gym/token_id_capture/records.py Outdated
Comment on lines +151 to +153
# ``None`` for a root request or an unresolved continuation. The builder counts a refusal as
# the rollout's ending only when this names the delivered terminal call, or a call whose
# token sequence is identical to it and whose entry's ``created_at`` precedes this record's.

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.

nemo_gym/token_id_capture/records.py:151

NOTE · Thanks for 83c4c2e. The whole-twin-group ordering in _engine_refusal_ended_the_chain resolves the earlier thread, and the builder docstring describes it accurately. This field comment still states the earlier rule, though: a refusal of the terminal itself counts unconditionally, and only the parent is ordered against the refusal. A framework author reading the wire model reads this comment, so could it match the builder?

Suggested change
# ``None`` for a root request or an unresolved continuation. The builder counts a refusal as
# the rollout's ending only when this names the delivered terminal call, or a call whose
# token sequence is identical to it and whose entry's ``created_at`` precedes this record's.
# ``None`` for a root request or an unresolved continuation. The builder counts a refusal as
# the rollout's ending only when this names the delivered terminal call or a token-identical
# twin of it, and no other call with that token sequence has an entry ``created_at`` at or
# after this record's.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied in a36f24a: the field comment now states the twin-group rule the builder applies (the delivered terminal call or a token-identical twin of it, and no other call with that token sequence has an entry created_at at or after this record's).

Comment thread nemo_gym/token_id_capture/store.py Outdated
Every entry line is ``fsync``ed before ``put`` returns — that is the durability
guarantee. The state index is written atomically but fsynced only on lifecycle
transitions (freeze, mark, drop); it is reconstructible from the JSONL tail.
transitions (freeze, mark, drop, refusal); it is reconstructible from the JSONL tail.

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.

nemo_gym/token_id_capture/store.py:22

NOTE · Small one: the revert in 985efe0 dropped the qualifier, so this line now lists refusal among the transitions while saying the state index "is reconstructible from the JSONL tail". _record_engine_refusal (L333-L334) says the refusal is fsynced because it "cannot be rebuilt from the JSONL tail". Restoring the qualifier keeps the two consistent:

Suggested change
transitions (freeze, mark, drop, refusal); it is reconstructible from the JSONL tail.
transitions (freeze, mark, drop, refusal); it is reconstructible from the JSONL tail
except for those transitions, which is why they are fsynced.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Restored in a36f24a: the module docstring again says the state index is reconstructible from the JSONL tail except for those transitions, which is why they are fsynced.


`mask_incomplete_when_attributed` (default `true`) decides what happens when a model call registered its capture intent but never committed a record, which is what a harness killed at its timeout leaves behind. By default such an incomplete capture always sets `mask_sample: true`. Set it to `false` to keep the rollout when terminal attribution delivered the verifier-scored chain whole: a call with no record cannot sit inside a delivered chain, so the uncaptured call lies outside the scored trajectory. Without a delivered attribution the rollout is still masked.

A call the engine refuses because the prompt does not fit the context window is not a lost call. When the vLLM model server propagates the refusal (`propagate_context_overflow_errors: true`), it records the refusal in place of a token record, so the rollout is not incomplete and the harness can compact its history and continue. The record names the call the refused request continued (its request-time lineage, resolved before dispatch like a served call's). A context-window refusal of the request that continued the delivered terminal call marks the rebuilt response `incomplete` with reason `max_output_tokens`; a refusal on another branch of the rollout, one the harness recovered from, or one that named only an output-token parameter (no `code`) does not. `_ng_token_capture.engine_refusals` lists every refused call either way. Under worker custody (`external_staging: true`) the refusal is a capture-ledger failure row that carries the call id and the reason `engine_refused_request` only, so a rollout rebuilt from staged records is not masked for it but reports no truncation verdict either; NVIDIA-NeMo/Gym#4647 tracks carrying the code and the lineage on that row.

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.

fern/versions/latest/pages/training-tutorials/external-agent-harnesses.mdx:82

NOTE · The worker-custody sentence holds when the framework's receipt builder treats engine_refused_request as off-chain, as NeMo RL will with NVIDIA-NeMo/RL#4749. A framework-owned receipt builder written to the earlier contract, where only the uncommitted reason was exempt, would poison these rows and mask the rollout; before this PR the same refusal got the exempt uncommitted row. Nothing on this page mentions UNSERVED_CALL_FAILURE_REASONS yet, so one clause for framework authors would cover it (only the custody sentence changes):

Suggested change
A call the engine refuses because the prompt does not fit the context window is not a lost call. When the vLLM model server propagates the refusal (`propagate_context_overflow_errors: true`), it records the refusal in place of a token record, so the rollout is not incomplete and the harness can compact its history and continue. The record names the call the refused request continued (its request-time lineage, resolved before dispatch like a served call's). A context-window refusal of the request that continued the delivered terminal call marks the rebuilt response `incomplete` with reason `max_output_tokens`; a refusal on another branch of the rollout, one the harness recovered from, or one that named only an output-token parameter (no `code`) does not. `_ng_token_capture.engine_refusals` lists every refused call either way. Under worker custody (`external_staging: true`) the refusal is a capture-ledger failure row that carries the call id and the reason `engine_refused_request` only, so a rollout rebuilt from staged records is not masked for it but reports no truncation verdict either; NVIDIA-NeMo/Gym#4647 tracks carrying the code and the lineage on that row.
A call the engine refuses because the prompt does not fit the context window is not a lost call. When the vLLM model server propagates the refusal (`propagate_context_overflow_errors: true`), it records the refusal in place of a token record, so the rollout is not incomplete and the harness can compact its history and continue. The record names the call the refused request continued (its request-time lineage, resolved before dispatch like a served call's). A context-window refusal of the request that continued the delivered terminal call marks the rebuilt response `incomplete` with reason `max_output_tokens`; a refusal on another branch of the rollout, one the harness recovered from, or one that named only an output-token parameter (no `code`) does not. `_ng_token_capture.engine_refusals` lists every refused call either way. Under worker custody (`external_staging: true`) the refusal is a capture-ledger failure row that carries the call id and the reason `engine_refused_request` only. A framework that assembles receipts from the ledger must treat the reasons in `nemo_gym.token_id_capture.UNSERVED_CALL_FAILURE_REASONS` as off-chain rather than poisoning (NeMo RL does as of NVIDIA-NeMo/RL#4749); a rollout rebuilt from staged records is then not masked for the refusal but reports no truncation verdict either. NVIDIA-NeMo/Gym#4647 tracks carrying the code and the lineage on that row.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in a36f24a with only the custody sentence changed: a framework that assembles receipts from the ledger must treat the reasons in nemo_gym.token_id_capture.UNSERVED_CALL_FAILURE_REASONS as off-chain rather than as poisoning (NeMo RL's receipt builder does, through NVIDIA-NeMo/RL#4749). The conformance section of the same page now also describes the ConformanceWarning a sink without the extension receives.

Comment on lines +517 to +519


def test_the_unserved_call_reasons_are_the_refusal_and_the_uncommitted_call():

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.

tests/unit_tests/test_token_id_capture.py:517

NOTE (optional) · NVIDIA-NeMo/RL#4749 reads UNSERVED_CALL_FAILURE_REASONS and ENGINE_REFUSED_CALL_REASON from the package root through getattr with fallbacks. If the root export were ever dropped, refused calls' receipts would silently go back to being poisoned instead of failing an import. Since 985efe0 moved this test's import to .records, no test pins the root names. Two asserts would:

Suggested change
def test_the_unserved_call_reasons_are_the_refusal_and_the_uncommitted_call():
def test_the_unserved_call_reasons_are_the_refusal_and_the_uncommitted_call():
"""Pin the set a framework's receipt builder treats as off-chain rather than poisoning."""
import nemo_gym.token_id_capture as token_id_capture
assert UNSERVED_CALL_FAILURE_REASONS == frozenset({UNCOMMITTED_CALL_REASON, ENGINE_REFUSED_CALL_REASON})
# NeMo RL reads both names from the package root with a getattr fallback, so a dropped export
# would silently poison refused calls' receipts rather than fail an import.
assert token_id_capture.UNSERVED_CALL_FAILURE_REASONS is UNSERVED_CALL_FAILURE_REASONS
assert token_id_capture.ENGINE_REFUSED_CALL_REASON == ENGINE_REFUSED_CALL_REASON

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in a36f24a: the reasons test also asserts that the package root exports UNSERVED_CALL_FAILURE_REASONS (the same object) and ENGINE_REFUSED_CALL_REASON, so a dropped root export fails the test instead of silently poisoning refused calls' receipts.

…-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]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test a36f24a

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review. a36f24a applies the four inline notes and the optional wording nits, text only:

  • The parent_call_id field comment and the projection docstring state the twin-group rule (the delivered terminal call or a token-identical twin of it, with no twin served at or after the refusal).
  • The store module docstring has the reconstructibility qualifier back.
  • ENGINE_REFUSED_CALL_REASON's comment covers the output-token-parameter refusal; capture_engine_refusal's docstring states the custody fallback (the sweep's uncommitted-call row); the conformance warning and the missing-extension log line say the rollout is masked by default.
  • The docs page's custody sentence tells framework authors to treat UNSERVED_CALL_FAILURE_REASONS as off-chain, and its conformance section describes the ConformanceWarning.
  • The reasons test pins the package-root exports NeMo RL reads.

Gate on a36f24a: the four token-capture unit files 361 passed; ruff check and ruff format --check clean on the changed files.

The description is refreshed: point 4 states the twin-group rule and the known limitation in the docstring's words, the header names 10a8852 and lists 83c4c2e, 985efe0 and a36f24a, and Validation names the five-case twin test, the two composition tests, the six model-server routes, the custody test over both stream settings and the ConformanceWarning case, with the 985efe0 gate numbers in a dated follow-up section.

On the clock note: agreed that stamping the refusal time in capture_engine_refusal would put both timestamps on the model server's clock. It changes the sink extension's call signature, so it is not in this PR.

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

LGTM at a36f24a.

@marcromeyn

Copy link
Copy Markdown
Contributor

/ok to test e7a3135

@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/40363263395

This branch was previously deployed

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

Labels

area:core Shared APIs, servers, telemetry, health, and registries complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work ready-to-merge PR is approved, current, and waiting for final CI or merge 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.

5 participants