Repository navigation
fix(streaming): keep provider response headers on SDK streaming errors - #41528
Conversation
Greptile SummaryPreserves provider response headers when streaming failures are wrapped in
Confidence Score: 5/5The PR appears safe to merge, with the previous source-comment issue resolved and no new actionable findings The wrapper now preserves the original normalized response-header mapping when available, leaves headerless exceptions unchanged, and has focused regression coverage for both cases. The previous thread was manually resolved after the redundant source comment was removed Important Files Changed
Reviews (2): Last reviewed commit: "refactor(streaming): drop explanatory co..." | Re-trigger Greptile |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@greptileai removed the source comment you flagged in exceptions.py and narrowed the description to direct SDK streaming callers, please re-review |
A 429 raised while opening a stream is wrapped in MidStreamFallbackError, which dropped the litellm_response_headers exception_type() attaches to the wrapped error. retry-after and x-request-id reached callers on the non-streaming path but not on the streaming one, so retry backoff, provider request id logging and proxy error headers lost them.
3cdfbed to
7a373a3
Compare
# Conflicts: # tests/unit/litellm_core_utils/test_streaming_handler.py
|
Automatic reviews are disabled for this repository. |
…ckError Parametrizes the provider-header test over the sync and async stream wrappers, and drops the hasattr test, which pinned how the attribute is stored rather than what any caller observes
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings.
Checks and execution details
View review · Reviewed |
|
bugbot run |
Cover the SDK stream openers (gemini, vertex_ai, codestral, predibase and the eager providers), the Router stream retry and fallback paths, and the proxy on both the router and the config-less serving paths, including a mixed burst, a worker SIGKILL and a SIGTERM restart. Add a helper that boots a config-less proxy owned by the test
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit a0cb919. Configure here.
mateo-berri
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the contribution!
TLDR
Problem this solves:
litellm_response_headersHow it solves it:
Router.completion(stream=True, complete_response=True)now honors the provider'sretry-afteron a stream-open 429User Flow
Before: a developer streaming Gemini through the LiteLLM Python SDK gets a 429 error without Gemini's response headers, though the same call without streaming has them
litellm.completion(model="gemini/gemma-4-31b-it", messages=[...])with a prompt over its per-minute token quota, and Gemini answers 429RateLimitErrorlists Gemini's response headers (date,server-timing,content-type, ...) onlitellm_response_headersstream=True, throughlitellm.completion,litellm.acompletion, orlitellm.responsesMidStreamFallbackErrorstill reports 429, but itslitellm_response_headersis emptyAfter: the streaming error carries Gemini's response headers too
litellm.completion(model="gemini/gemma-4-31b-it", messages=[...])with a prompt over its per-minute token quota, and Gemini answers 429RateLimitErrorlists Gemini's response headers (date,server-timing,content-type, ...) onlitellm_response_headersstream=True, throughlitellm.completion,litellm.acompletion, orlitellm.responsesMidStreamFallbackErrorreports 429 and lists the samedate,server-timing,content-type, ... headers onlitellm_response_headersRelevant issues
#40645 edits status handling in the same constructor, so whichever lands second needs a small rebase
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays 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
Last updated: a0cb919. QA ran on 1760034, the last commit with a product diff, and /live-pr-risk on 412a747
Real Gemini API, no mocks.
gemma-4-31b-ithas a 16k input tokens per minute quota, so a ~45k token prompt gets a real 429 every time. The client is the LiteLLM Python SDK, since SDK callers read this error's headers and the proxy's HTTP answers match at both commitscompletion, no streamcompletion,stream=Trueacompletion,stream=Trueresponses,stream=TrueScript used on both sides
Before (a2f7926)
python - < stream_429_headers.pyfrom the merge base checkoutcompletionwithstream=True, identical on a second run:Before full output, every case
After (1760034)
completionwithstream=True, identical on a second run:After full output, every case
Observations:
retry-afterorx-request-idx-gemini-service-tier, a Gemini-side differenceAudit round 1 of 3
Every inventory row is VERIFIED. Two behavior changes follow this PR's intent and are approved to ship by mateo-berri in this PR's approving review
retry-afterWhat changed, how the cells ran, and the full matrix
The first change is on a proxy started with
litellm --model gemini/...and no--config. A streamed/v1/chat/completionsor/v1/responsescall whose provider fails at stream open now records the provider's request id in the failure spend row, undererror_information.error_provider_request_id. The HTTP answers stay the same. The second change isRouter.completion(stream=True, complete_response=True), where a stream-open 429 now waits the provider'sretry-afterbefore the retry, the same as the non-stream call already doesTwo inherited bugs are Low caveats, since the merge base and main behave the same and this PR does not touch them. The Router reads the first stream chunk outside the stream wrapper, so a stream-open error on Gemini or Vertex reaches the caller unmapped, as a raw
VertexAIErrorwith a bytes message, aTypeErroron the sync path without a fallback, and unprefixed provider headers on the proxy's router path. The config-less proxy also answers a stream-open error without the provider headers, becauseasync_data_generatorbuilds itsProxyExceptionfrom the message and status only. Both are filed as internal ticketsBase a2f7926, head 412a747, and the cells are committed in a0cb919 (tests only). Each leg had its own Postgres, Redis, scripted upstream and two-worker proxy. Lanes ran the
sdkgroup with 1 worker and theprovidersgroup with 4, with seed 41528 and order seed 93, the base once, the head twice and the controls once on the head. Every cell keys the caller's answer, the upstream request and the failure spend row by a per-call marker and itsreq-<marker>request id. The R4 cell was added after the round, so it ran at a0cb919 on both legs, twice on the headNot applicable, with the reason. A response-cache-hit twin does not apply, since a failed call is never cached. There is no regex, so no timing row. A sink stop or slow sink row does not apply, since the diff adds no destination and the config-less path that carries the changed field has no config to enable callbacks, so the Postgres failure row is its one destination. Duplicate, int and list header values do not apply, since httpx hands litellm one string per header name and the diff copies that mapping without reading a value
Cell node ids, in matrix order
Controls on the head, all green
Type
🐛 Bug Fix
Caveats (if any)
Low
litellm.anthropic.messages.create(stream=True)still ends silently on a Gemini 429llm_provider-*headers non-streaming 429s carryFinal Attestation
Note
Low Risk
Narrow change to exception wrapping on the streaming error path; no auth or request-body changes, with extensive new tests.
Overview
Streaming failures that surface as
MidStreamFallbackError(e.g. a 429 before the first chunk) now copylitellm_response_headersfrom the wrapped provider error, matching non-streaming calls where headers likeretry-afterandx-request-idwere already exposed.Integration coverage adds
configless_proxy_processfor--model/--api_baseproxy launches, plus broad SDK and proxy suites for stream-open errors (rate limits, 5xx, client errors, router retry/fallback, concurrency, and chaos scenarios). A unit test intest_streaming_handler.pyasserts header preservation on the mid-stream fallback path.Reviewed by Cursor Bugbot for commit a0cb919. Bugbot is set up for automated code reviews on this repo. Configure here.