Repository navigation
feat(token-capture): resolve a refused call's capture intent and report the refusal - #3980
Conversation
There was a problem hiding this comment.
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_callthat 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"]
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
deleteand 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
statusline in the builder and owns the delivery question in item 5. - Then rebase this PR. Doing it after both land keeps the stack consistent.
8c9ce21 to
3141467
Compare
|
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 What changed in 3141467, one commit on top of the rebased #3978 (d55e48a) and #3973 (57ec9b7):
The delivery question (item 5) is settled by #3973 as rebased: delivery copies the builder's |
|
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 |
…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]>
09ad64b to
f7e94ed
Compare
|
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: |
…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]>
f7e94ed to
e40ae25
Compare
yaoyu-33
left a comment
There was a problem hiding this comment.
Rechecked the current head and reproduced both cases below.
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]>
|
/ok to test 2cfbb64 |
|
Pushed 2cfbb64 for the 10/13 review (both questions answered in their threads): a refusal is now placed by the lineage decision |
|
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 ( On the process notes: the description now states that Harness conformance is red on this head and on @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. |
|
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 |
…gine-refusal-record
… 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]>
|
Pushed
Tests: |
|
/ok to test 985efe0 |
yaoyu-33
left a comment
There was a problem hiding this comment.
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 overridecontent_filter. The projection docstring states the scope of the withholding. - Docstrings.
apply_capture_incomplete_verdictandfinalize_rollout_token_capturename 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-streamraises 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-treeof 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_atorder 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
ConformanceWarningcase. 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_REASONalso 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: falsekeeps 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
| # ``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. |
There was a problem hiding this comment.
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?
| # ``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. |
There was a problem hiding this comment.
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).
| 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. |
There was a problem hiding this comment.
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:
| 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. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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):
| 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. |
There was a problem hiding this comment.
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.
|
|
||
|
|
||
| def test_the_unserved_call_reasons_are_the_refusal_and_the_uncommitted_call(): |
There was a problem hiding this comment.
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:
| 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 |
There was a problem hiding this comment.
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]>
|
/ok to test a36f24a |
|
Thanks for the re-review. a36f24a applies the four inline notes and the optional wording nits, text only:
Gate on a36f24a: the four token-capture unit files 361 passed; 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 On the clock note: agreed that stamping the refusal time in |
|
/ok to test e7a3135 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/40363263395 |
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_intenthad 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.
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 anEngineRefusalRecord(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_intentstreats an intent as resolved by an entry or by a refusal, sofreeze_nowreturnsincomplete=Falseand the snapshot reports the refusal inTokenCaptureSnapshot.engine_refusals. There is no separate refusal file. A refusal after freeze raisesTokenCaptureFrozenErrorand leaves the version alone, so it never stales the retirement of a consumed snapshot.begin_call.record_engine_refusalis documented besidebegin_callinprotocols.pyand is not part ofTokenSink, so existing sinks keep working. The conformance suite gainsengine_refusal_resolution, gated on the method likebegin_call_custody: a refusal must resolve the intent and appear on the snapshot, and after freeze the sink must either raiseTokenCaptureFrozenErroror 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.capture_engine_refusal(code)(sink.py) writes through the in-flight capture context and never raises. It passes along the lineage decisionresolve_parentmade 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'srecord_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 newENGINE_REFUSED_CALL_REASONfor the admitted call, and_fail_uncommitted_external_callskips 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, soUNSERVED_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).project_main_chain_responsereceives the snapshot's refusals and marks the rebuilt responseincompletewithincomplete_details.reason: "max_output_tokens"only for a refusal that meets two conditions (_engine_refusal_ended_the_chain): its code iscontext_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_atorder 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 fromBuildOutput.entrieson 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 rolloutincompleteand delivery then replaces a harnesscompleted. 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 onmetrics["engine_refusals"]on every build, masked and failed ones included, and that field is what distinguishes a refusal from a servedlengthstop, which produces the same status. Delivery (feat(token-capture): preserve finish reasons and terminal truncation #3973) copies the verdict onto a harness response that saidcompletedor nothing._mark_propagated_overflowreturns the envelope code it chose andcapture_engine_refusalstores it:context_length_exceededwhen 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 ..."),Nonefor 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 inrecords.pyand 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.pychanged 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 acontext_length_exceededrefusal sets the verdict, so acode=Noneparameter refusal resolves its intent and is listed inmetrics["engine_refusals"]without becoming a truncation. The branch also carries a merge ofmain3d2e970.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 Bincomplete, because the retry-twin rule compared digests alone._engine_refusal_ended_the_chainnow also requires the retained twin's entry to precede the refusal record (TokenEntry.created_atagainstRefusalRecord.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_itcovers 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
refusalandrecord_engine_refusalto engine refusal throughout (EngineRefusalRecord,record_engine_refusal,capture_engine_refusal,engine_refusals,engine_refusal_resolution, the state-file key), becauserefusalis OpenAI's content part for a model declining to answer, whichopenai_utils, the converters and rollout health already use, while the ledger saidengine_refused_request. The per-build sequence digests are gone:BuildOutput.entrieskeeps 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 onlyTokenCaptureFrozenErroras 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,mainwas 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.pyexcluded) gave 9163 passed, 56 skipped, 29 failed, 20 errors; 48 of the failures and errors are the environmental set ofmain(telemetry and opensandbox tests that need packages this machine lacks) and the remaining one, a docker-compose shell test, passes on rerun here and onmain; everyresponses_api_models/*/testssuite 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 themain4518db9 baseline, telemetry and opensandbox tests that need packages this machine lacks) and everyresponses_api_models/<server>/testssession (vllm_model529 passed; genrm and local_vllm collect errors for missing local packages, as onmain); the five token-capture unit files together: 438 passed. After #4366's squash (949198c),mainwas merged in again as a642822: #4366 moved the finish-reason table of the rebuilt response intorecords.incomplete_reason_for_finish_reason, whichproject_main_chain_responsenow 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'sapply_capture_incomplete_verdicttests sit next to this branch's refusal tests. Validation of a642822: the unit suite (test_collect_downstream_junit.pyexcluded) gave 9243 passed, 56 skipped, 28 failed, 20 errors, the failures and errors identical to the environmental setmainshows here (telemetry and opensandbox tests that need packages this machine lacks); everyresponses_api_models/*/testssession passed (vllm_model 541 passed), with genrm_model and local_vllm_model erroring at collection as before; ruff 0.9.9format --checkandcheckare clean on the two resolved files.Review follow-up (2026-10-16)
yaoyu-33's re-review of a642822 (83c4c2e):
_engine_refusal_ended_the_chainorders 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_identicalcould 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_filterkeeps its reason,lengthandstopgivemax_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_verdictandfinalize_rollout_token_capturename 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/tests547 passed, the four token-capture unit files 352 passed,ruff checkandruff format --checkclean on the six changed files.Review follow-up (2026-10-22)
985efe0 (yaoyu-33's follow-up notes on 83c4c2e, after a merge of
mainas 10a8852): the conformance kit issues aConformanceWarningfor the skippedengine_refusal_resolutioncheck when a sink implementsbegin_callwithoutrecord_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_CODEandMAX_OUTPUT_TOKENS_INCOMPLETE_REASONreplace the string literals in the kit and the builder, so neither can drift fromrecords.py. The staging records module no longer re-exports the refusal reason and the unserved-call set, which no staging reader used (neither NeMo RLmainnor 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.py204,test_token_capture_conformance.py10,test_terminal_attribution.py92,test_base_responses_api_model.py88,responses_api_models/vllm_model/tests575, all passing.a36f24a (yaoyu-33's re-review of 985efe0): text only. The
parent_call_idfield comment onEngineRefusalRecordand the projection docstring state the twin-group rule_engine_refusal_ended_the_chainapplies; 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, sincemask_incomplete_when_attributed: falsekeeps a delivered chain. The docs page tells framework authors that a receipt builder reading the ledger must treatUNSERVED_CALL_FAILURE_REASONSas off-chain and describes theConformanceWarning; the reasons test pins the package-root exports NeMo RL reads throughgetattr. Gate on a36f24a: the four token-capture unit files 361 passed;ruff checkandruff format --checkclean 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,
deleteremoves the refusal with the state file. Sink:capture_engine_refusalpasses 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 testtest_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_emptyandtest_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_filterkeeps its reason,lengthandstopgivemax_output_tokens, and twins that disagree on the finish reason still take the refusal's verdict); and a finalized rollout carries the verdict andmetrics["engine_refusals"]with the lineage fields on the result without being masked. Conformance: the file store passesengine_refusal_resolution, which now requires the lineage fields on the frozen record; a sink withbegin_callbut without the extension skips it and passes with aConformanceWarningthat names the gap; a sink with neither method passes quietly; and a store whoserecord_engine_refusalacknowledges without recording fails it. Model server: a captured rollout records the propagated refusal through the real dispatch (the intent is registered byregister_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, andresponses-stream, which raises the 400 before any event), amax_tokens-only 400 is recorded without a code, an absorbed overflow and an uncaptured request record nothing, and under worker custody the ledger carriesENGINE_REFUSED_CALL_REASONalone, on both worker backends and with streaming on and off.Unit suite (
pytest tests/unit_tests, withtest_collect_downstream_junit.pyexcluded for a missing local package), run on the branch tip 2cfbb64 after the merge ofmain3d2e970: 8469 passed, 56 skipped, 28 failed, 19 errors. The failures and errors are the same 47 as onmain3d2e970 (telemetry and opensandbox tests that need packages this machine lacks). Eachresponses_api_models/<server>/testsdirectory as its own session:vllm_model455 passed; the other nine directories matchmain(two of them have a collection error for a missing local package onmaintoo).ruff checkandruff format --checkon 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
mainsince 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 withpropagate_context_overflow_errors: trueand a file capture store): a two-call rollout driven through thevllm_modelserver's/ng-rollout/<id>/training-token-capture/v1/chat/completionsroute 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 answeredThis 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 withcode: context_length_exceeded. The harness stopped with the served response, as OpenCode and Codex do, andfinalize_rollout_token_capturerebuilt the record:mask_sampleis 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