Skip to content

[None][fix] Chat Completions: keep replayed tool calls in forwarded requests - #21155

Open
JunyiXu-nv wants to merge 4 commits into
NVIDIA:mainfrom
JunyiXu-nv:dev-junyix-fix-chat-replayed-tool-calls
Open

JunyiXu-nv wants to merge 4 commits into
NVIDIA:mainfrom
JunyiXu-nv:dev-junyix-fix-chat-replayed-tool-calls

Conversation

@JunyiXu-nv

@JunyiXu-nv JunyiXu-nv commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A chat request whose history replays an assistant turn with tool calls can reach a disaggregated worker without those tool calls.

  • A retry loses them. OpenAI declares an assistant message's tool_calls as an Iterable, which pydantic validates into a single-use ValidatorIterator. The disaggregated orchestrator serializes the request each time it sends it to a worker (OpenAIHttpClient._post_with_retry), and the first serialization consumes the iterator: the resend after a failed attempt carries tool_calls: [], and the worker renders the turn without its tool calls. The Anthropic /v1/messages route on a disaggregated server builds the same chat request and is affected the same way.
  • A replayed index loses them on the first attempt. A client that rebuilds an assistant turn from a streamed response keeps index on each tool call; only streamed tool-call deltas (ChoiceDeltaToolCall) have that key. The OpenAI message types reject it, but tool_calls is validated lazily, so the request is accepted. On a disaggregated server, serializing the request to forward it then leaves the call out without an error (with pydantic 2.11 and 2.13, the versions tried), and a KV-cache-aware router cannot render the turn and routes it on no token ids. The aggregated server is not affected: its chat route falls back to the raw request body.

#19964 covered only the case where a router renders the request (and the call carries no index): chat_utils writes the materialized list back into the message.

This PR fixes both in ChatCompletionRequest:

  • _drop_streaming_only_tool_call_index, a mode="before" model validator, drops index from every messages[*].tool_calls[*] before validation. The key has no meaning in a request, so it is dropped, not declared.
  • _materialize_lazy_message_fields, a mode="wrap" validator on messages, turns the validated tool_calls into lists, so every reader and every serialization sees the same calls. Tool calls that fail the OpenAI types (object-valued function.arguments, as tau2-bench sends them) are left lazy as before, so the aggregated chat route still reads them from the raw request body instead of rejecting the request at validation; they are validated afresh for that, since the failed attempt consumed the first iterators.

No API change: no field, default or YAML row changes. Behavior changes:

  • An index on a tool call of a request message is dropped.
  • The chat route now reads well-formed tool calls through the list branch of chat_utils._parse_assistant_message_content, which yields the same id, name and arguments; only the key order of the parsed call differs, which matters only to a chat template that serializes a whole call (none in this repository does). A custom (non-function) tool call in the history, which the chat route cannot render, is still answered with a 400; the message is now tool_calls[0].function is required. instead of 'function'.

Not changed: tool calls that stay lazy (object-valued arguments) are still single-use, so forwarding such a request to a disaggregated worker still loses them, as on main.

Test Coverage

  • tests/unittest/disaggregated/test_disagg_openai_client.py::TestDisaggIdRegenOnRetry::test_retry_resends_the_tool_calls_of_a_replayed_turn[no_index|streamed_index] (new): the first POST to the worker fails with aiohttp.ClientError, the second succeeds; both msgpack bodies carry the tool call, without index. On main, no_index sends tool_calls: [] on the retry and streamed_index sends tool_calls: [] on both attempts.
  • tests/unittest/llmapi/apps/test_render_callers.py::TestRouterWriteBack::test_a_replayed_tool_call_index_is_dropped_and_its_calls_are_forwarded (new): a KV-cache-aware router renders a turn whose tool call carries index to the same token ids as the turn without it and forwards them; two dumps of the request are equal and carry the call without index. On main the router renders no ids.
  • tests/unittest/llmapi/apps/test_render_callers.py::TestRouterWriteBack::test_object_valued_tool_arguments_are_routed_on_no_ids_not_on_a_partial_render (existing, unchanged) guards the lazy fallback: its request has object-valued function.arguments and must still validate.
  • tests/unittest/llmapi/apps/test_chat_template_kwargs_guard.py::test_router_and_server_tool_call_tokenization_match (existing, updated): it pins which path each function.arguments shape takes, and asserted that strictly validated tool calls stay a lazy iterator, the behavior this PR removes. It now asserts that the strict model hands validated calls through as a list and leaves object-valued ones lazy; its router/server tokenization checks are unchanged.
  • No legacy-render variant: [TRTLLM-16711][fix] Remove the legacy renderer paths #20775 removed that render path.

All three files are cpu_only and already listed in l0_cpu.yml.

Local runs with a CPU harness that stubs the compiled bindings:

  • On main the 3 new cases and the updated string_arguments_strict_path case fail; the object-valued-arguments cases pass on both. On this branch all pass.
  • Every cpu_only file of tests/unittest/llmapi/apps and tests/unittest/disaggregated (74, leaving out three that need the compiled transfer bindings) plus api_stability/test_serve_api.py: main 3203 passed; this branch 3207 passed (the 3 new cases, and test_transfer_ownership_regressions.py::test_cancel_after_publication_cannot_overtake_request_data, which failed once in the main run and passes 3 of 3 times in isolation on both). The other 211 tests fail or error on both, nearly all because the harness stubs the compiled bindings; nothing that passes on main fails here.
  • Mutations of this branch, each restored afterwards: keeping index fails streamed_index and the router test; leaving tool_calls lazy fails both retry cases; materializing without the lazy fallback fails the object-valued-arguments guard (the request is rejected at validation).

PR Checklist

  • PR description clearly explains what and why.

GitHub Bot Help

To see a list of available CI bot commands, please comment /bot help.

🤖 Generated with Claude Code

Dev Engineer Review

  • ChatCompletionRequest message validation removes the streaming-only index key from dictionary-valued tool calls before validation.
  • Validated tool_calls are materialized as lists. Repeated serialization and retries keep the calls.
  • If materialization raises ValidationError, the validator reruns message validation on the original value. The existing raw-body fallback is kept.
  • Calls with object-valued function.arguments stay lazy so the aggregated chat route can read them from the raw body. The PR reports that disaggregated forwarding can still lose these calls. This is a known gap, not a fix.
  • The error message for unsupported custom tool calls changes. Clients that match on the old text can fail. Custom non-function calls still return HTTP 400.
  • The PR reports no API, field, default, or YAML changes.
  • CI status, from PR comments and not verified on the current head:
    • Commit 5cd788e: CI job FAILURE, L0 pipeline UNSTABLE. The bot stated that multi-GPU tests require the ci: full pre-merge approved label.
    • Commit edf06b4: CI job SUCCESS, L0 pipeline FAILURE. The bot requested investigation.
    • Commit 49fe483: CI job SUCCESS, L0 pipeline UNSTABLE. The bot repeated the multi-GPU label note.
  • Reported CPU-harness results, not independently verified: 3,207 tests passed on this branch and 3,203 on main. 211 other tests failed or errored on both, mostly from compiled-binding stubs.

QA Engineer Review

Changed test files:

  • tests/unittest/disaggregated/test_disagg_openai_client.py: adds TestDisaggIdRegenOnRetry::test_retry_resends_the_tool_calls_of_a_replayed_turn, parameterized as no_index and streamed_index. Both retry attempts must serialize the tool call without index.
  • tests/unittest/llmapi/apps/test_render_callers.py: adds TestRouterWriteBack::test_a_replayed_tool_call_index_is_dropped_and_its_calls_are_forwarded. It checks token-ID parity with the call that has no index, forwarding when worker fingerprints match, and stable serialization.
  • tests/unittest/llmapi/apps/test_render_callers.py: adds TestRouterWriteBack::test_object_valued_tool_arguments_are_routed_on_no_ids_not_on_a_partial_render.
  • tests/unittest/llmapi/apps/test_chat_template_kwargs_guard.py: updates test_router_and_server_tool_call_tokenization_match. It builds a strict ChatCompletionRequest and asserts that tool_calls is a list only when the input does not take the fallback path.

Reported results:

  • The three new cases and the updated strict-path case fail on main and pass on this branch.

Test-list placement: not verified. These are unit tests under tests/unittest/. The test-db/ and qa/ lists were not checked.

Gaps:

  • No coverage for object-valued function.arguments forwarding through disaggregated workers. The PR documents this path as lossy.

Coverage verdict: sufficient for replayed tool calls with and without index. needs follow-up for object-valued function.arguments forwarding.

Per-File QA Perspective

  • tensorrt_llm/serve/openai_protocol.py: Verify that request tool calls lose index. Verify that validated calls stay stable across repeated serialization. Verify that invalid input still takes the raw-body fallback. Verify the changed error message for unsupported custom tool calls.
  • tests/unittest/disaggregated/test_disagg_openai_client.py: Covers retry resend of replayed tool calls with and without index. Test-list placement not verified.
  • tests/unittest/llmapi/apps/test_render_callers.py: Covers router write-back, index removal, token-ID forwarding, object-valued arguments routing, and stable serialization. Test-list placement not verified.
  • tests/unittest/llmapi/apps/test_chat_template_kwargs_guard.py: Covers strict-path tokenization with list-backed tool_calls and the fallback path. Test-list placement not verified.

…equests

An assistant message's tool_calls is declared as an Iterable, which
pydantic validates into a single-use iterator. The disaggregated
orchestrator serializes a chat request to forward it, which consumes the
iterator, so a resend after a failed attempt carries no tool calls.

A client that rebuilds an assistant turn from a stream also keeps the
streaming-only "index" key on each tool call. The OpenAI message types
reject it, but only when the lazy tool_calls are read: the forwarded
request silently leaves the call out, and a KV-cache-aware router cannot
render the turn.

Drop "index" from the tool calls of the request's messages before
validation, and turn the validated tool calls into lists. Tool calls
that fail the OpenAI types (object-valued function.arguments) stay lazy,
so the aggregated chat route still reads them from the raw request body.

Signed-off-by: JunyiXu-nv <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Chat completion request validation removes streaming-only index fields from dictionary-valued tool calls and materializes lazy validated message fields. Tests cover serialization across retries, strict-model representation, and router rendering.

Changes

Tool-call request normalization

Layer / File(s) Summary
Normalize and validate tool calls
tensorrt_llm/serve/openai_protocol.py
ChatCompletionRequest removes index from dictionary-valued tool calls. Its message validator materializes lazy fields and calls the handler again if materialization raises ValidationError.
Verify replay and rendering behavior
tests/unittest/disaggregated/test_disagg_openai_client.py, tests/unittest/llmapi/apps/test_chat_template_kwargs_guard.py, tests/unittest/llmapi/apps/test_render_callers.py
Tests check serialization across retries, strict-model tool-call representation, and router rendering, token forwarding, and repeated serialization with and without index.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: juney-nvidia

Merge Risk: Minimal · up to 9c689

The change keeps replayed assistant tool calls in forwarded chat requests, and the regression tests target that behavior. Object-valued tool arguments are documented as not covered for disaggregated forwarding. No merge-blocking risk is established.

Security architecture risk: Minimal · up to 9c689

The change keeps replayed tool calls in conversation history when a request is retried. It does not grant permission to execute those calls, and the reviewed change did not show a material security regression.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A caller who supplies replayed assistant history can affect the rendered prompt and the history relayed to workers for that request. The inspected change makes that history survive serialization; it does not add a worker destination or an execution permission.

Trust Boundaries and Controls

  • observed — The server still validates internal disaggregated requests before parsing the relayed history. The new normalization is in the request model and does not replace that check.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: replayed tool calls are kept in chat requests forwarded to disaggregated workers. It follows the repository template with the [None][fix] prefix and is specific and co…
Description check Passed The description explains the two causes: a single-use validator iterator consumed by retries, and a replayed streamed tool-call index that drops calls on forwarding. It names the fix in ChatCompletion…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: replayed tool calls are kept in chat requests forwarded to disaggregated workers. It follows the repository template with the [None][fix] prefix and is specific and concise.

Full details: Description check

Explanation

The description explains the two causes: a single-use validator iterator consumed by retries, and a replayed streamed tool-call index that drops calls on forwarding. It names the fix in ChatCompletionRequest, lists the behavior changes and the remaining lazy-argument limitation, and gives detailed test coverage. It omits the template's ticket-format guidance and the checklist items beyond the first, but the required content is present.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 49fe483 and 9c6893c.

Files selected for processing: 3

  • tensorrt_llm/serve/openai_protocol.py
  • tests/unittest/disaggregated/test_disagg_openai_client.py
  • tests/unittest/llmapi/apps/test_render_callers.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 9 remain after this review.

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #81082 [ run ] triggered by Bot. Commit: 5cd788e Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #81082 [ run ] completed with state FAILURE. Commit: 5cd788e
/LLM/main/L0_MergeRequest_PR pipeline #66792 completed with status: 'UNSTABLE'

CI Report

⚠️ Multi-GPU Label Required:
Multi-GPU tests require the ci: full pre-merge approved label on this PR. Either:

  • Wait for the PR to be fully approved — the label is added automatically once approval is complete. Having unresolved open comments is fine, or
  • If needed, ask a member of NVIDIA/trt-llm-ci-approvers to add the label manually.
    Then re-trigger CI with the same bot command (no rebase needed).

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

Local runtime validation remains incomplete; required matching-build and dependency CI remains pending.

Signed-off-by: JunyiXu-nv <[email protected]>
@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85151 [ run ] triggered by Bot. Commit: edf06b4 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85151 [ run ] completed with state SUCCESS. Commit: edf06b4
/LLM/main/L0_MergeRequest_PR pipeline #70486 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

Local runtime validation remains incomplete; matching-build manifest/schema/API and native CI validation remains required.

Signed-off-by: JunyiXu-nv <[email protected]>
@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85553 [ run ] triggered by Bot. Commit: 49fe483 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85553 [ run ] completed with state SUCCESS. Commit: 49fe483
/LLM/main/L0_MergeRequest_PR pipeline #70817 completed with status: 'UNSTABLE'

CI Report

⚠️ Multi-GPU Label Required:
Multi-GPU tests require the ci: full pre-merge approved label on this PR. Either:

  • Wait for the PR to be fully approved — the label is added automatically once approval is complete. Having unresolved open comments is fine, or
  • If needed, ask a member of NVIDIA/trt-llm-ci-approvers to add the label manually.
    Then re-trigger CI with the same bot command (no rebase needed).

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

@JunyiXu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87425 [ run ] triggered by Bot. Commit: 9c6893c Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87425 [ run ] completed with state SUCCESS. Commit: 9c6893c
/LLM/main/L0_MergeRequest_PR pipeline #72542 completed with status: 'UNSTABLE'

CI Report

⚠️ Multi-GPU Label Required:
Multi-GPU tests require the ci: full pre-merge approved label on this PR. Either:

  • Wait for the PR to be fully approved — the label is added automatically once approval is complete. Having unresolved open comments is fine, or
  • If needed, ask a member of NVIDIA/trt-llm-ci-approvers to add the label manually.
    Then re-trigger CI with the same bot command (no rebase needed).

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants