Skip to content

fix(router): strip foreign Gemini thought signatures on vertex_ai/gemini fallback - #33471

Closed
mathew-felix wants to merge 5 commits into
BerriAI:mainfrom
mathew-felix:fix-issue-32140
Closed

mathew-felix wants to merge 5 commits into
BerriAI:mainfrom
mathew-felix:fix-issue-32140

Conversation

@mathew-felix

Copy link
Copy Markdown

Relevant issues

Closes #32140

Linear ticket

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

I don't have Vertex AI and Google AI Studio credentials configured against the same Gemini model to reproduce this against live endpoints, so I verified the fix at the unit level instead. Running the reproduction snippet from the issue through _get_model_group_custom_llm_provider, _crosses_gemini_endpoint_boundary, and _remove_foreign_thought_signatures_from_messages directly shows the fallback path now substitutes the documented dummy value (skip_thought_signature_validator, base64 encoded) instead of forwarding the foreign signature. Full test output below

Type

🐛 Bug Fix
✅ Test

Changes

Gemini's tool calls carry a thought signature, an opaque token the model uses to preserve reasoning continuity across turns. That signature is only valid on the endpoint that minted it, so a signature returned by Vertex AI is rejected as corrupted if replayed to Google AI Studio, and the reverse direction fails the same way. This PR makes the Router strip that signature out of replayed tool calls whenever a fallback crosses the vertex_ai <-> gemini boundary, so the receiving endpoint treats it as missing and fills in its own dummy placeholder instead of rejecting the request

#32140 reports that a Router configured with a Vertex AI Gemini deployment and a same-model Google AI Studio fallback breaks on every mid-conversation fallback attempt. Turn one succeeds and returns a signature tied to whichever endpoint served it. When the primary fails on turn two and the Router falls back to the twin deployment, the signature from turn one gets replayed unchanged, in both the tool call's provider_specific_fields and its id suffix, and the new endpoint responds with a 400 "Corrupted thought signature" error. The existing dummy-signature fallback in _get_thought_signature_from_tool only fires when a signature is missing, and the id-stripping added in #18374 only fires when the target is not a Gemini model, so neither existing safety net catches a Gemini-to-Gemini boundary crossing

Added _get_model_group_custom_llm_provider and _crosses_gemini_endpoint_boundary to litellm/router_utils/fallback_event_handlers.py, wired into run_async_fallback so it strips foreign thought signatures from the replayed messages before making the fallback call

Added _remove_foreign_thought_signature_from_tool_call and _remove_foreign_thought_signatures_from_messages to litellm/utils.py, next to the existing sibling function #18374 added for the non-Gemini case

This PR covers the channel where the signature lives in a tool call's provider_specific_fields and id suffix. Gemini can also attach a signature to thinking_blocks on a plain assistant text message with no tool call involved, and that channel is not touched here. I scoped this PR to the tool call channel since it already has test coverage to build on, and I'm glad to open a follow-up for the thinking_blocks channel if that's wanted

@CLAassistant

CLAassistant commented Jul 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@mathew-felix

Copy link
Copy Markdown
Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a "Corrupted thought signature" 400 error that occurs when the Router falls back from a Vertex AI Gemini deployment to a Google AI Studio deployment (or vice versa) mid-conversation. Thought signatures are endpoint-bound tokens and must be stripped from replayed tool calls before the fallback call is issued.

  • Adds _get_model_group_custom_llm_provider and _crosses_gemini_endpoint_boundary to fallback_event_handlers.py, wired into run_async_fallback to strip foreign signatures before the fallback call; the original model group's provider is looked up once outside the loop to avoid redundant traversals.
  • Adds _strip_foreign_thought_signature_from_tool_call and _remove_foreign_thought_signatures_from_messages to utils.py to clear both the provider_specific_fields[\"thought_signature\"] and the __thought__-suffixed tool call id, plus the matching role=tool tool_call_id so the two stay paired.

Confidence Score: 4/5

Safe to merge with one fix: the boundary detector incorrectly fires for vertex_ai ↔ vertex_ai_beta transitions, stripping valid Vertex AI signatures unnecessarily.

The core logic in utils.py and its test coverage are solid. The single concern is in _crosses_gemini_endpoint_boundary: treating vertex_ai and vertex_ai_beta as different endpoints causes valid Vertex AI thought signatures to be stripped when falling back between the two provider variants, silently breaking reasoning continuity for that configuration. The rest of the wiring — single provider lookup outside the fallback loop, role=tool tool_call_id pairing, Pydantic object handling, and immutability — is correct and well-tested.

Files Needing Attention: litellm/router_utils/fallback_event_handlers.py — specifically _GEMINI_ENDPOINT_PROVIDERS and _crosses_gemini_endpoint_boundary

Important Files Changed

Filename Overview
litellm/router_utils/fallback_event_handlers.py Adds boundary detection and signature-stripping wiring to run_async_fallback; _crosses_gemini_endpoint_boundary returns a false positive for vertex_ai ↔ vertex_ai_beta fallbacks, causing valid Vertex AI signatures to be stripped unnecessarily.
litellm/utils.py Adds _strip_foreign_thought_signature_from_tool_call and _remove_foreign_thought_signatures_from_messages; correctly handles both dict and Pydantic tool-call objects, strips provider_specific_fields and id suffix, and strips the matching tool_call_id on role=tool messages.
tests/test_litellm/router_utils/test_fallback_event_handlers.py Adds well-structured unit tests covering provider-lookup, boundary detection, signature stripping on fallback, same-provider preservation, and single-lookup-per-original-model-group; all mocked, no real network calls.
tests/test_litellm/test_utils.py Adds TestRemoveForeignThoughtSignaturesFromMessages covering dict and Pydantic messages, role=tool pairing, immutability, and passthrough cases; no real network calls.

Reviews (5): Last reviewed commit: "test: cover remaining branches flagged b..." | Re-trigger Greptile

Comment thread litellm/utils.py Resolved
@greptile-apps

greptile-apps Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a 400 "Corrupted thought signature" error that occurs when the Router falls back between a Vertex AI Gemini deployment and a Google AI Studio Gemini deployment (or vice versa). Thought signatures are endpoint-bound tokens that the receiving endpoint rejects if they were minted by a different endpoint.

  • Adds _crosses_gemini_endpoint_boundary and _get_model_group_custom_llm_provider in fallback_event_handlers.py to detect when a fallback crosses the vertex_ai ↔ gemini boundary, and strips the foreign signature from assistant messages' tool-calls (provider_specific_fields[\"thought_signature\"] and the id suffix) before the fallback call is made.
  • Adds _remove_foreign_thought_signatures_from_messages and _strip_foreign_thought_signature_from_tool_call in utils.py, next to the existing _remove_thought_signatures_from_messages family, with unit tests covering stripping, field preservation, non-mutation, and no-op behaviour.

Confidence Score: 4/5

Safe to merge; the fix is well-targeted, the happy paths are tested, and it is purely additive with no existing call sites changed.

The core logic correctly strips thought signatures from both channels (provider_specific_fields and id suffix) on assistant messages before crossing the endpoint boundary, and factory.py already handles the corresponding tool-response messages downstream. The main nits are that original_provider is recomputed on every fallback loop iteration when it is constant for the call, the new stripping function intentionally skips role=tool messages with no comment explaining the factory.py guarantee, and new Gemini-specific helpers land outside the llms/ directory, following an existing pattern but adding more coupling to the shared utils layer.

litellm/router_utils/fallback_event_handlers.py — the original_provider lookup can be hoisted out of the fallback loop. litellm/utils.py — the new stripping function silently skips tool-response messages; a comment explaining the factory.py guarantee would prevent future confusion.

Important Files Changed

Filename Overview
litellm/router_utils/fallback_event_handlers.py Adds _get_model_group_custom_llm_provider and _crosses_gemini_endpoint_boundary helpers, and wires them into run_async_fallback to strip foreign Gemini thought signatures before making the fallback call; original_provider is recomputed on every loop iteration when it could be computed once before the loop.
litellm/utils.py Adds _strip_foreign_thought_signature_from_tool_call and _remove_foreign_thought_signatures_from_messages to remove endpoint-bound signatures from assistant tool-call messages; the new function intentionally skips role=tool messages (handled downstream by factory.py) but this gap is undocumented.
tests/test_litellm/router_utils/test_fallback_event_handlers.py Adds unit tests for the new helpers and two async integration tests verifying signature stripping across the Gemini endpoint boundary and preservation within the same provider; tests are properly mocked with no real network calls.
tests/test_litellm/test_utils.py Adds four unit tests for _remove_foreign_thought_signatures_from_messages covering signature removal, field preservation, non-mutation, and no-op on non-tool-call messages.

Reviews (2): Last reviewed commit: "fix(router): strip foreign Gemini though..." | Re-trigger Greptile

Comment thread litellm/utils.py Resolved
@mathew-felix

Copy link
Copy Markdown
Author

Pushed a follow-up commit addressing the review feedback:

  • Strip the matching tool_call_id on role="tool" messages too, not just the assistant's tool_calls[].id, so the two stay paired after a boundary crossing strips the embedded signature
  • Added vertex_ai_beta to the recognized Gemini-family providers, since it's a distinct custom_llm_provider from vertex_ai in this codebase
  • Hoisted the original model group's provider lookup out of the fallback loop since it doesn't change across candidates

Added regression tests for all three. Full suite still passes (258 tests).

…ini fallback

Thought signatures returned by Gemini tool calls are endpoint-bound: a
signature minted by Vertex AI is rejected as corrupted by Google AI
Studio, and vice versa. When the Router fell back between a Vertex AI
Gemini deployment and its Google AI Studio twin mid-conversation, the
foreign signature was replayed unchanged in both the tool call's
provider_specific_fields and its ID suffix, causing the fallback call
itself to fail with a 400 error.

run_async_fallback now detects when a fallback crosses the vertex_ai
<-> gemini boundary and strips the foreign signature from replayed
tool calls before the fallback request is sent, so the receiving
endpoint treats it as missing and fills in its own dummy placeholder,
the same way a genuinely missing signature is already handled.

Fixes BerriAI#32140
…pping

- Strip the matching tool_call_id on role=tool messages too, not just
  the assistant's tool_calls[].id, so the two stay paired after a
  vertex_ai/gemini boundary crossing strips the embedded signature.
- Add vertex_ai_beta to the recognized Gemini-family providers, since
  it is a distinct custom_llm_provider from vertex_ai in this codebase.
- Hoist the original model group's provider lookup out of the fallback
  loop; it does not change across fallback candidates.
@codecov

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 35 untouched benchmarks


Comparing mathew-felix:fix-issue-32140 (6631732) with main (d0671f7)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (953ee19) during the generation of this report, so d0671f7 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

Adds regression tests for the 9 lines Codecov flagged as uncovered in
the diff: the two early-return branches in
_get_model_group_custom_llm_provider (no model to infer from, and
get_llm_provider raising for an unrecognized model string), and the
Pydantic-object and pass-through branches in
_remove_foreign_thought_signatures_from_messages for both messages
and tool calls.
@mathew-felix

Copy link
Copy Markdown
Author

Pushed a follow-up commit adding tests for the 9 lines Codecov flagged as uncovered: two early-return branches in _get_model_group_custom_llm_provider (no model string to infer a provider from, and get_llm_provider raising for an unrecognized model), plus the Pydantic-object and pass-through branches in _remove_foreign_thought_signatures_from_messages for both messages and tool calls. Patch coverage should be clean now.

@mathew-felix

Copy link
Copy Markdown
Author

@greptileai

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:31
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:40
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:40
return exception.status_code == 400 and bool(getattr(exception, "llm_provider", ""))


_GEMINI_ENDPOINT_PROVIDERS = ("vertex_ai", "vertex_ai_beta", "gemini")

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.

do we need a hardcoded list here? this seems like it could go out of date fast

@mateo-berri

Copy link
Copy Markdown
Contributor

Closing as superseded by #49697, which resends with the placeholder thought signature after a cross-backend fallback. Thanks for the groundwork here

@mateo-berri mateo-berri closed this Nov 3, 2026
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.

[Bug]: Router fallback between vertex_ai and gemini replays endpoint-bound thought signatures -> 400 "Corrupted thought signature" (Gemini 3.x)

5 participants