Skip to content

fix(model): forward replayed reasoning without inventing an id - #5024

Merged
ffrujeri merged 2 commits into
mainfrom
ffrujeri/codex-reasoning-id
Oct 29, 2026
Merged

ffrujeri merged 2 commits into
mainfrom
ffrujeri/codex-reasoning-id

Conversation

@ffrujeri

@ffrujeri ffrujeri commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

The Codex CLI replays its reasoning items on every turn without their id. The streaming request sanitizer in nemo_gym/responses_streaming.py filled the gap with a random rs_<uuid> so the item would pass strict validation, where NeMoGymResponseReasoningItem.id is required.

Responses providers bind encrypted_content to the id of the item that produced it, so a replay under a made-up id is rejected:

invalid_encrypted_content: The encrypted content for item rs_... could not be verified.
Reason: Encrypted content item_id did not match the target item id.

On a GPT-6.1 Terminal-Bench 4 run through openai_model and the NVIDIA inference hub (LiteLLM in front of Azure OpenAI), this failed all 61 Codex rollouts on their second model call (1,740 upstream 400s). Backends behind Chat Completions (for example vLLM) never see encrypted reasoning, which is why this did not show up before.

The change:

  • NeMoGymResponseReasoningInputItem, a subclass of NeMoGymResponseReasoningItem with id: Optional[str] = None, is a member of the request-input union only. The input discriminator routes a reasoning item with no id key to it, alongside the existing function_call_output_input variant. An explicit "id": null is still rejected. Response output still requires an id, and isinstance checks against the base class keep working.
  • The sanitizer no longer invents a reasoning id. The item reaches the upstream call as the client sent it (model_dump(exclude_unset=True) omits the unset id).
  • A full model_dump() of the id-less item also omits id, rather than writing "id": null, so the dump revalidates. This matters for SimpleAgent results and AgentInvocation.conversation.
  • An id-less reasoning item with token metadata routes to NeMoGymResponseReasoningInputItemForTraining. That's a new input-only training variant, selected before training discrimination, so these replays keep their token arrays instead of failing with 422.

Issue: none; found while running TB4 Harbor harnesses with GPT-6.1. The diagnosis is below.

Validation

  • Direct probe against the inference hub (azure/openai/eccn-gpt-6.1-sol, Responses API, store=false, include=["reasoning.encrypted_content"]), replaying a turn's encrypted reasoning item 4 times per variant:

    • original id: 4/4 ok
    • no id: 4/4 ok
    • random id (what Gym sent): 4/4 item_id did not match the target item id
    • plain replays, with an x-session-id header, with prompt_cache_key, and store=true with previous_response_id: all ok, so the hub's load balancing is not the cause.
  • Review follow-up (second commit):

    • test_reasoning_input_without_id_survives_full_dumps: Python and JSON full dumps, with and without token metadata, plus an AgentInvocation round trip.
    • test_reasoning_with_id_keeps_it_and_null_or_missing_output_id_is_rejected.
    • test_token_bearing_reasoning_replay_keeps_its_tokens_and_id: sanitizer and validation, with and without an id.
    • test_streaming_token_bearing_reasoning_replay_without_id_is_accepted: the route returns 200.

    The 6 id-less cases among these fail without the second commit.

  • New openai_model test test_reasoning_replayed_without_id_is_forwarded_without_id (streaming and non-streaming) checks the upstream call receives the reasoning item unchanged. Both cases fail on main: streaming sends an invented id, non-streaming returns 422.

  • Updated streaming tests now assert the id stays absent instead of starting with rs_.

  • pytest tests/unit_tests/test_responses_api_model_streaming.py tests/unit_tests/test_openai_utils.py tests/unit_tests/test_responses_converter.py tests/unit_tests/test_base_responses_api_model.py: 787 passed before the review fixes. After rebasing on main with the fixes, the same files plus test_rollout_observability.py and test_agent_activations.py give 899 passed.

  • pytest responses_api_models/openai_model/tests/test_app.py: 101 passed. responses_api_models/vllm_model/tests/test_app.py (fresh server venv): 418 passed.

  • pytest responses_api_agents/codex_agent/tests (the agent's own venv from requirements.txt): 463 passed, 7 skipped.

  • pre-commit run on the changed files: passed.

Rollout evidence

Terminal-Bench 4 through the Harbor environment server (61 tasks, 1 repeat, GPT-6.1 via openai_model and the inference hub, OpenSandbox), with this change and without drop_input_reasoning_items:

  • Before (same setup, main behavior, JHB job 1230141): 0 graded, 61 failed; 1,740 upstream 400s with invalid_encrypted_content. Its W&B run was removed with the other failed runs; the Slurm log is slurm-logs/1230141-gpt61-codex.log in the run checkout.
  • After (JHB job 1231415): 56 graded, 20 solved, 1 masked, mean reward 0.364; 0 upstream 400s and 0 could not be verified errors in 46 minutes. The 5 rollouts with no result are unrelated: 2 tasks declare MCP servers or skills, which Codex refuses, plus 3 transient 500/502 responses from the agent server.

Reference runs:

  • After: gpt61-codex.
  • Same setup with the other harnesses, which do not replay encrypted reasoning, for comparison: nvidia/tb4-harbor-gpt61. Solve rates on graded, unmasked rollouts: mini-SWE 47.5%, Hermes 41.4%, OpenCode 38.5%, Codex 36.4%, OpenClaw 31.6%, Pi 24.6%, Terminus 2 21.4%.

Compatibility

Request validation now accepts reasoning input items without an id; previously the non-streaming route rejected them with 422 and the streaming route invented one. No response shapes change.

@ffrujeri ffrujeri added bug Something isn't working area:model Model servers, inference providers, and model adapters labels Oct 23, 2026
@copy-pr-bot

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

@ffrujeri
ffrujeri force-pushed the ffrujeri/codex-reasoning-id branch from efd1c08 to 0374ea1 Compare October 24, 2026 05:34
@ffrujeri
ffrujeri marked this pull request as ready for review October 24, 2026 05:35
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Oct 24, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

HOLD — one BLOCKER and one RISK remain: full serialization makes accepted reasoning input invalid, and token-bearing streaming replays regress to 422.

Reviewed all four changed files and traced request validation, upstream forwarding, chat conversion, and downstream serialization. The direct OpenAI forwarding change preserves omitted IDs as intended. Review was static; tests were not executed.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Comment thread nemo_gym/openai_utils.py
under any other id, so a missing id must stay missing rather than be filled in.
"""

id: Optional[str] = None

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.

BLOCKER — Keep omitted reasoning IDs omitted in ordinary dumps

Failure: The new model accepts {"type":"reasoning","summary":[],"encrypted_content":"opaque"}, but an ordinary model_dump() adds "id": null. Revalidating that dump selects the required-ID model and fails. Minimal reproduction:

p = NeMoGymResponseCreateParamsNonStreaming(
    input=[{"type": "reasoning", "summary": [], "encrypted_content": "opaque"}]
)
NeMoGymResponseCreateParamsNonStreaming.model_validate(p.model_dump())
# ValidationError: reasoning.id must be a string

This breaks downstream consumers, not just an optional serialization style: SimpleAgent._run uses full dumps to construct results and verification payloads, whose request contract validates these parameters again. Likewise, a serialized AgentInvocation.conversation containing this item cannot be loaded again. The existing dump/revalidate regression contract misses this shape because its reasoning fixture supplies an ID.

Correction: Make omission stable on the new input class, rather than accepting explicit null or changing the response model. Suggested addition immediately after this field:

    @model_serializer(mode="wrap")
    def _serialize_missing_id(self, handler):
        data = handler(self)
        if self.id is None and "id" not in self.model_fields_set:
            data.pop("id", None)
        return data

The decorator is already imported. This preserves the distinction between an omitted ID and an explicitly supplied null, while covering full dumps and inherited input variants. Please verify the suggestion before adopting it.

Preservation / acceptance — proposed checks, not executed: For the reproduction above, both Python- and JSON-mode full dumps must omit id and revalidate successfully; repeat through AgentInvocation serialization. Retain the new upstream test's exact unchanged-input assertion for both streaming modes. ID-bearing reasoning must retain its original ID; explicit id: null request dictionaries and ID-less response-output dictionaries must still fail validation. Retain the existing summary-only chat-conversion case's `` text and tool-call ordering.

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.

Fixed in 35337c8. NeMoGymResponseReasoningInputItem now has a wrap serializer that drops id from dumps unless it was set, so a full model_dump() no longer writes "id": null. The training subclass inherits it.

New test test_reasoning_input_without_id_survives_full_dumps covers both Python and JSON mode, with and without token metadata. It checks that the dump has no id, that it revalidates to the same class, and that an AgentInvocation round trip keeps the id out. test_reasoning_with_id_keeps_it_and_null_or_missing_output_id_is_rejected checks that an id-bearing item keeps its id, an explicit "id": null request item is rejected, and an id-less response-output item is rejected. The new dump test fails without the change.

Comment thread nemo_gym/openai_utils.py Outdated
else:
return None
return _training_variant_tag(tag, value)
tag = _training_variant_tag(tag, value)

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.

RISK — Preserve token-bearing reasoning replays without fabricating IDs

Failure: _training_variant_tag() runs before the missing-ID branch, so complete token metadata changes the tag to reasoning__training; the new branch then never runs. For example, a streaming request with this input item now returns 422 because NeMoGymResponseReasoningItemForTraining.id is required:

{"type":"reasoning","summary":[{"type":"summary_text","text":"think"}],"prompt_token_ids":[1],"generation_token_ids":[2],"generation_log_probs":[-0.1]}

This is a regression for the shared streaming path: the base sanitizer supplied an ID, after which this summary-only training item validated and could reach chat conversion. Removing ID generation is correct, but these previously accepted requests must not become invalid or lose their token arrays.

Correction: Add an input-only training variant and select the missing-ID shape before training discrimination. Merely moving the branch would select the non-training model, which ignores the token fields. Suggested fragments in openai_utils.py:

# Alongside the existing training classes:
class NeMoGymResponseReasoningInputItemForTraining(NeMoGymResponseReasoningInputItem, TokenIDLogProbMixin):
    pass

# Add to RESPONSES_TO_TRAIN:
    NeMoGymResponseReasoningInputItem: NeMoGymResponseReasoningInputItemForTraining,

# Add "reasoning_input" to _TRAINABLE_ITEM_TAGS.

# Replace the final four lines of _discriminate_response_input_item:
    if tag == "reasoning" and "id" not in value:
        tag = "reasoning_input"
    return _training_variant_tag(tag, value)

# Add to NeMoGymResponseInputItem's training members:
    Annotated[NeMoGymResponseReasoningInputItemForTraining, Tag("reasoning_input__training")],

Keep this variant out of the response-output union. The invariant is that complete input token metadata survives validation without inventing an ID; ID-bearing reasoning still uses the existing training variant. Please verify these suggested fragments before adopting them.

Preservation / acceptance — proposed checks, not executed: Pass the example through sanitize_streaming_responses_body() and validate_streaming_responses_params(); validation must succeed, the item must implement TokenIDLogProbMixin, and its model_dump(exclude_unset=True) must retain all three arrays with no ID. Exercise the streaming route and expect 200 rather than 422. Repeat with id: "rs_original" and retain that ID and the existing training class. Retain test_all_training_variants_preserve_fields_and_revalidate, including its ID-bearing reasoning assertions. Partial/malformed token metadata must still fail, while the new metadata-free encrypted replay test must continue forwarding the item unchanged.

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.

Fixed in 35337c8. I added the input-only NeMoGymResponseReasoningInputItemForTraining, registered it in RESPONSES_TO_TRAIN and the input union (not the output union), and added reasoning_input to _TRAINABLE_ITEM_TAGS. The discriminator now picks the id-less shape before _training_variant_tag.

New tests:

  • test_token_bearing_reasoning_replay_keeps_its_tokens_and_id: your example through sanitize_streaming_responses_body() and validate_streaming_responses_params(). Without an id it becomes the new training class and keeps all three arrays and no id. With id: "rs_original" it stays NeMoGymResponseReasoningItemForTraining and keeps the id.
  • test_streaming_token_bearing_reasoning_replay_without_id_is_accepted: the streaming route now returns 200 instead of 422.

test_all_training_variants_preserve_fields_and_revalidate and the partial-metadata tests are unchanged and pass. The id-less test and the route test fail without the change.

@ffrujeri
ffrujeri marked this pull request as draft October 24, 2026 13:38
@ffrujeri
ffrujeri force-pushed the ffrujeri/codex-reasoning-id branch from 0374ea1 to 35337c8 Compare October 28, 2026 20:39
@ffrujeri
ffrujeri marked this pull request as ready for review October 28, 2026 20:39
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 35337c8

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP — the prior BLOCKER and RISK are resolved; no eligible findings remain.

  • Serialization: the input serializer keeps omitted IDs absent in full dumps. The regression tests cover Python/JSON dumps, request revalidation, and AgentInvocation round trips, while retaining supplied IDs and rejecting explicit-null input IDs and missing output IDs. Traced the affected SimpleAgent verification/result contracts.
  • Token-bearing replay: the discriminator selects the input-only shape before training discrimination. The validation regression checks exact token preservation with and without an ID; the route regression checks HTTP 200 and unchanged backend input.

Also checked directly affected OpenAI forwarding and chat-conversion preservation, including summary text and tool-call/result ordering.

This was a scoped follow-up, not a fresh whole-PR review. The previously reviewed tree was unavailable, limiting exact inter-review comparison. No eligible introduced regression was established. Review was static; tests were inspected, not executed.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a findings-only review. Request a full review with /review reset=true.

@ffrujeri
ffrujeri enabled auto-merge October 28, 2026 22:01
@ffrujeri
ffrujeri force-pushed the ffrujeri/codex-reasoning-id branch from 35337c8 to 89a01d0 Compare October 28, 2026 22:02

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

Reviewed 89a01d0. Missing reasoning IDs stay omitted through upstream forwarding and full serialization, and token-bearing inputs retain their metadata. The two earlier review findings are fixed; no additional actionable issues found after independent review.

Validation: 1,000 focused tests passed across streaming, schemas, conversion, base model, observability, agent activations, and openai_model, with repository imports verified against this checkout. Both new forwarding regressions fail against the base revision as expected. Live provider/rollout evidence is author-reported. Full CI for this head remains outstanding.

@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Oct 28, 2026
Codex replays reasoning items without their id. The streaming request
sanitizer filled in a random rs_ id so the item passed strict
validation, but providers bind encrypted_content to the original item
id and reject the replay (invalid_encrypted_content: item_id did not
match the target item id). Every Codex rollout against an OpenAI or
Azure Responses endpoint failed on its second model call.

Accept reasoning input items without an id and forward them as sent.

Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…n metadata

A full model_dump() of an id-less reasoning input item wrote "id": null,
which selects the id-requiring reasoning model, so the dump failed to
revalidate (SimpleAgent results, AgentInvocation.conversation). Omit the
id from dumps unless it was set.

A token-bearing id-less reasoning item was routed to the training variant
before the id-less branch ran, and that variant requires an id, so the
streaming route returned 422. Add an input-only training variant and pick
the id-less shape before training discrimination.

Signed-off-by: Felipe Vieira Frujeri <[email protected]>
@ffrujeri
ffrujeri force-pushed the ffrujeri/codex-reasoning-id branch from 89a01d0 to 5246a9f Compare October 28, 2026 22:51
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 5246a9f

@ffrujeri
ffrujeri added this pull request to the merge queue Oct 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/40946543307

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

Merged via the queue into main with commit 471fa5f Oct 29, 2026
81 of 89 checks passed
@ffrujeri
ffrujeri deleted the ffrujeri/codex-reasoning-id branch October 29, 2026 21:32

This branch was previously deployed

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

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants