Skip to content

fix(core): keep lazy Iterable fields in request and response models as lists - #4323

Merged
yaoyu-33 merged 2 commits into
mainfrom
ananthsub/fix-serialization-iterator
Oct 10, 2026
Merged

yaoyu-33 merged 2 commits into
mainfrom
ananthsub/fix-serialization-iterator

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What changed

No public request or response model in nemo_gym/openai_utils.py keeps a field that Pydantic validates into a lazy iterator. Each change follows the existing Iterable overrides in that file, such as the ones for annotations, content, summary, and tools.

The first commit fixes model output that the agent sends back as input. NeMoGymResponseOutputText.logprobs now uses Gym copies of the OpenAI Logprob and LogprobTopLogprob types, with List in place of Iterable for bytes and top_logprobs.

The second commit fixes request configuration. It adds Gym copies with List fields for these SDK types:

Request model Field path
Responses tool_choice allowed tools: tools
Responses namespace tool: tools
Responses file search tool: compound filter filters
Responses shell tool: container_auto and local environment skills
Responses shell and code interpreter tools: container allowlist network policy domain_secrets
Chat Completions prediction.content
Chat Completions tool_choice allowed tools: allowed_tools.tools

The request models now use Gym copies of the SDK ToolParam, ToolChoice, and ChatCompletionToolChoiceOptionParam unions. Each copy keeps the SDK members in the SDK order and swaps in a List subclass only where the SDK member has an Iterable field. Because the member order is the same, union validation picks the same member as before.

NeMoGymResponse and NeMoGymChatCompletion had no remaining lazy fields.

Why the agent's next request fails

Since #3618, the vLLM model server copies chat-completion logprobs into output_text.logprobs. The OpenAI Logprob type declares bytes and top_logprobs as Iterable, and Pydantic validates an Iterable field into a lazy iterator that can be read only once.

When the model writes text and a tool call in the same turn, simple_agent sends that assistant message back as input on the next turn. ServerClient.request dumps the request body with model_dump(exclude_unset=True) in Python mode, which leaves the lazy iterator in the output as a SerializationIterator. orjson cannot encode that object, so the post to the model server fails and the agent's /run returns HTTP 500:

TypeError: Type is not JSON serializable: pydantic_core._pydantic_core.SerializationIterator

This happened in step 1 of a 2-step NeMo-RL GRPO smoke run with Qwen3-0.6B, vLLM with the hermes tool parser, and the workplace_assistant environment with simple_agent. An earlier run with the same code and data passed, because the failure only occurs when an assistant text message with logprobs is followed by another turn.

The lazy type also loses data without an error. Serializing the same response object a second time returns empty bytes and top_logprobs lists, and model_copy(deep=True) cannot copy the object at all because the iterator cannot be pickled.

Why the fix is in the type and not in ServerClient.request

Switching ServerClient.request to model_dump(mode="json") would make the first encode succeed, but the dump would still read the iterator to the end. Every later turn would then send empty logprobs to the model server. Storing the values as lists keeps them complete for every serialization.

Wire format

The encoded request bytes are unchanged. For a request with a user message, an assistant message with logprobs, a function call, and a function call output, the new Python-mode dump encoded by orjson is byte-identical to the previous mode="json" encoding of the same body.

Related issue

No issue is filed, because the bug was found in a smoke run and the fix is contained in one type.

Request configuration fields

The request configuration fields fail the same way when a dataset sets them. For example, this request cannot be encoded by orjson after validation:

NeMoGymResponseCreateParamsNonStreaming.model_validate(
    {"input": "q", "tools": [{"type": "namespace", "name": "ns", "description": "d",
                              "tools": [{"type": "function", "name": "f", "parameters": {}}]}]}
)

Its model_copy(deep=True) raises cannot pickle 'ValidatorIterator', and a second model_dump(mode="json") returns an empty tools list in the namespace tool.

Validation

  • tests/unit_tests/test_openai_utils.py builds a next-turn request the way simple_agent does. It validates a model response with output text logprobs and a function call, deep-copies the request body, and appends the output and a function call output. The test checks that orjson encodes the request with complete logprobs on repeated serializations.
  • tests/unit_tests/test_server_utils.py sends a request that replays an assistant message with logprobs through ServerClient.post and checks the encoded request data.
  • tests/unit_tests/test_openai_utils.py walks the Pydantic core schemas of NeMoGymResponseCreateParamsNonStreaming, NeMoGymResponse, NeMoGymChatCompletionCreateParamsNonStreaming, and NeMoGymChatCompletion, and fails if any field path reaches a generator schema. The failure message names each path. This test also catches lazy fields that a future OpenAI SDK upgrade adds.
  • A parametrized test validates a request for each fixed request configuration path. It checks that orjson encodes the Python-mode dump, that repeated dumps stay complete, and that a deep copy works.
  • A test pins each Gym union copy to its SDK union, member by member and in order, so an SDK upgrade that adds a tool or tool-choice type fails the test instead of being rejected silently.
  • All of these tests fail on the code before the matching commit. On the code before the second commit, the schema walk names the request configuration paths, and every encode, copy, and dump case fails.
  • For each fixed request configuration path, plus unchanged cases such as a code interpreter container ID and a named function tool choice, a script compared the orjson encoding of the new Python-mode dump with the previous code's first mode="json" dump. The bytes were identical, including key order. Requests that leave out a required key in the new copies still fail validation.

Commands:

uv sync --extra dev --extra sandbox --extra openshell --extra mlflow --extra wandb
pytest tests/unit_tests -n 16
pytest responses_api_agents/simple_agent/tests responses_api_models/vllm_model/tests
pre-commit run --all-files

Rollout evidence

Pending: the 2-step NeMo-RL GRPO smoke run on workplace_assistant will be repeated before this PR is marked ready for review.

@copy-pr-bot

copy-pr-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

…code

The vLLM model server copies chat-completion logprobs into `output_text.logprobs`. The vendored
OpenAI `Logprob` type declares `bytes` and `top_logprobs` as `Iterable`, and Pydantic validates
an `Iterable` field into a lazy iterator that can be read only once.

When the model writes text and a tool call in the same turn, the agent sends that assistant
message back as input on the next turn. `ServerClient.request` dumps the request body in Python
mode, which leaves the lazy iterator in place, so orjson fails with "Type is not JSON
serializable: SerializationIterator" and the agent's `/run` returns HTTP 500. Serializing the
same object twice also returns empty `bytes` and `top_logprobs` lists without any error.

Gym copies of `Logprob` and `LogprobTopLogprob` now use `List`, following the existing Iterable
overrides in `nemo_gym/openai_utils.py`. The encoded request bytes are unchanged.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub
ananthsub force-pushed the ananthsub/fix-serialization-iterator branch from 9429905 to 8ebe874 Compare October 9, 2026 20:54
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 9, 2026 20:55
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 9, 2026 20:55
@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

The OpenAI SDK types several request fields as Iterable. Pydantic validates an
Iterable into a lazy iterator that can be read only once. A request holding one
cannot be encoded by orjson in ServerClient.request, cannot be deep-copied, and
returns an empty list on its second serialization.

After the logprobs fix, these request paths still validated lazily:
- Responses tool_choice: allowed_tools.tools
- Responses tools: namespace tools, file_search compound filters,
  shell container_auto and local skills, and container allowlist domain_secrets
  (shell and code_interpreter)
- Chat Completions prediction.content and tool_choice allowed_tools.tools

Add Gym copies of those TypedDicts with List fields, and Gym copies of the
ToolParam, ToolChoice, and ChatCompletionToolChoiceOptionParam unions with the
same members in the same order. Encoded bytes match the previous first
mode="json" dump.

Add a test that walks the core schemas of the public request and response
models and fails on any generator schema, a test that pins the Gym union copies
to the SDK unions, and an encode, copy, and repeated-dump test for each path.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub ananthsub changed the title fix(core): keep output_text logprobs as lists so replayed requests encode fix(core): keep lazy Iterable fields in request and response models as lists Oct 9, 2026
@yaoyu-33 yaoyu-33 added area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface labels Oct 9, 2026
@yaoyu-33 yaoyu-33 added the needs-review PR is ready for code review and waiting on a reviewer label Oct 9, 2026

@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. Eager collections preserve replay and the wire format; 887 targeted tests and parent/head serialization checks passed.

@yaoyu-33
yaoyu-33 added this pull request to the merge queue Oct 10, 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/38079484503

Merged via the queue into main with commit da9f671 Oct 10, 2026
52 of 54 checks passed
@yaoyu-33
yaoyu-33 deleted the ananthsub/fix-serialization-iterator branch October 10, 2026 19:34

This branch was previously deployed

1 inactive deployment
public — 072e00cc Deployed Oct 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #4923
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 bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants