Skip to content

fix(streaming): keep provider response headers on SDK streaming errors - #41528

Merged
mateo-berri merged 5 commits into
BerriAI:mainfrom
Acacian:fix-midstream-fallback-provider-headers
Oct 15, 2026
Merged

mateo-berri merged 5 commits into
BerriAI:mainfrom
Acacian:fix-midstream-fallback-provider-headers

Conversation

@Acacian

@Acacian Acacian commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A streaming Gemini 429 reaches SDK callers with no provider response headers
  • The same call without streaming exposes them on litellm_response_headers

How it solves it:

  • The streaming error wrapper copies the provider headers of the error it wraps
  • Nothing is added when the wrapped error has no headers
  • A config-less proxy now logs the provider request id on a stream-open failure's spend row
  • Router.completion(stream=True, complete_response=True) now honors the provider's retry-after on a stream-open 429
  • The proxy's HTTP answers stay the same

User 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

  1. They call litellm.completion(model="gemini/gemma-4-31b-it", messages=[...]) with a prompt over its per-minute token quota, and Gemini answers 429
  2. The raised RateLimitError lists Gemini's response headers (date, server-timing, content-type, ...) on litellm_response_headers
  3. They repeat the call with stream=True, through litellm.completion, litellm.acompletion, or litellm.responses
  4. The raised MidStreamFallbackError still reports 429, but its litellm_response_headers is empty

After: the streaming error carries Gemini's response headers too

  1. They call litellm.completion(model="gemini/gemma-4-31b-it", messages=[...]) with a prompt over its per-minute token quota, and Gemini answers 429
  2. The raised RateLimitError lists Gemini's response headers (date, server-timing, content-type, ...) on litellm_response_headers
  3. They repeat the call with stream=True, through litellm.completion, litellm.acompletion, or litellm.responses
  4. The raised MidStreamFallbackError reports 429 and lists the same date, server-timing, content-type, ... headers on litellm_response_headers

Relevant 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings 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

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-it has 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 commits

Case Before (a2f7926) After (1760034)
completion, no stream 429, headers present 429, headers present
completion, stream=True 429, no headers 429, headers present
acompletion, stream=True 429, no headers 429, headers present
responses, stream=True 429, no headers 429, headers present
Script used on both sides
import asyncio

import litellm

MODEL = "gemini/gemma-4-31b-it"
BIG_PROMPT = "lorem ipsum dolor sit amet " * 9000 + "Say hi."


def show(case, e):
    headers = dict(getattr(e, "litellm_response_headers", None) or {})
    names = sorted(k.lower() for k in headers)
    print(f"{case}: {type(e).__name__} {getattr(e, 'status_code', None)} provider_headers={names}")


def run_sync(stream):
    try:
        response = litellm.completion(model=MODEL, messages=[{"role": "user", "content": BIG_PROMPT}], stream=stream)
        for _ in response if stream else ():
            pass
        print(f"completion stream={stream}: no error")
    except Exception as e:
        show(f"completion stream={stream}", e)


async def run_async():
    try:
        response = await litellm.acompletion(model=MODEL, messages=[{"role": "user", "content": BIG_PROMPT}], stream=True)
        async for _ in response:
            pass
        print("acompletion stream=True: no error")
    except Exception as e:
        show("acompletion stream=True", e)


def run_responses(stream):
    try:
        response = litellm.responses(model=MODEL, input=BIG_PROMPT, stream=stream)
        for _ in response if stream else ():
            pass
        print(f"responses stream={stream}: no error")
    except Exception as e:
        show(f"responses stream={stream}", e)


def run_messages(stream):
    try:
        response = litellm.anthropic.messages.create(
            model=MODEL, max_tokens=64, messages=[{"role": "user", "content": BIG_PROMPT}], stream=stream
        )
        for _ in response if stream else ():
            pass
        print(f"anthropic messages stream={stream}: no error")
    except Exception as e:
        show(f"anthropic messages stream={stream}", e)


run_sync(False)
run_sync(True)
asyncio.run(run_async())
run_responses(False)
run_responses(True)
run_messages(False)
run_messages(True)

Before (a2f7926)

  1. Run python - < stream_429_headers.py from the merge base checkout
  2. Output for completion with stream=True, identical on a second run:
completion stream=True: MidStreamFallbackError 429 provider_headers=[]
Before full output, every case
completion stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
completion stream=True: MidStreamFallbackError 429 provider_headers=[]
acompletion stream=True: MidStreamFallbackError 429 provider_headers=[]
responses stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
responses stream=True: MidStreamFallbackError 429 provider_headers=[]
anthropic messages stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
anthropic messages stream=True: no error

After (1760034)

  1. Run the same script from the PR checkout
  2. Output for completion with stream=True, identical on a second run:
completion stream=True: MidStreamFallbackError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'vary', 'x-content-type-options', 'x-frame-options', 'x-xss-protection']
After full output, every case
completion stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
completion stream=True: MidStreamFallbackError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'vary', 'x-content-type-options', 'x-frame-options', 'x-xss-protection']
acompletion stream=True: MidStreamFallbackError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'vary', 'x-content-type-options', 'x-frame-options', 'x-xss-protection']
responses stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
responses stream=True: MidStreamFallbackError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'vary', 'x-content-type-options', 'x-frame-options', 'x-xss-protection']
anthropic messages stream=False: RateLimitError 429 provider_headers=['content-length', 'content-type', 'date', 'server', 'server-timing', 'transfer-encoding', 'vary', 'x-content-type-options', 'x-frame-options', 'x-gemini-service-tier', 'x-xss-protection']
anthropic messages stream=True: no error

Observations:

  • Real Gemini 429s send no retry-after or x-request-id
  • Streaming 429s lack x-gemini-service-tier, a Gemini-side difference
  • Anthropic messages streaming ends silently on 429, unchanged by this PR

Audit 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

Rows Surface Before After
P7, P8, C2 to C4 config-less proxy failure row request id null provider request id
R4 Router sync retry wait backoff, about 0.8 s provider retry-after
What 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/completions or /v1/responses call whose provider fails at stream open now records the provider's request id in the failure spend row, under error_information.error_provider_request_id. The HTTP answers stay the same. The second change is Router.completion(stream=True, complete_response=True), where a stream-open 429 now waits the provider's retry-after before the retry, the same as the non-stream call already does

Two 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 VertexAIError with a bytes message, a TypeError on 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, because async_data_generator builds its ProxyException from the message and status only. Both are filed as internal tickets

Base 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 sdk group with 1 worker and the providers group 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 its req-<marker> request id. The R4 cell was added after the round, so it ran at a0cb919 on both legs, twice on the head

Row Cell Base Head Result Ran at
S1 429 at stream open, gemini completion red green x2 PASS 412a747
S2 429 at stream open, gemini acompletion red green x2 PASS 412a747
S3 429 at stream open, gemini responses red green x2 PASS 412a747
S4 429 at stream open, gemini aresponses red green x2 PASS 412a747
S5 429 at stream open, vertex ai completion red green x2 PASS 412a747
S6 429 at stream open, vertex ai acompletion red green x2 PASS 412a747
S7 429 at stream open, vertex ai responses red green x2 PASS 412a747
S8 429 at stream open, vertex ai aresponses red green x2 PASS 412a747
S9 429 at stream open, codestral atext completion red green x2 PASS 412a747
S11 429 at stream open, predibase acompletion red green x2 PASS 412a747
S17 500 at stream open, gemini red green x2 PASS 412a747
S17 502 at stream open, gemini red green x2 PASS 412a747
S17 503 at stream open, gemini red green x2 PASS 412a747
S17 504 at stream open, gemini red green x2 PASS 412a747
S16 400 raised directly, gemini green green x2 PASS 412a747
S16 401 raised directly, gemini green green x2 PASS 412a747
S16 403 raised directly, gemini green green x2 PASS 412a747
S16 404 raised directly, gemini green green x2 PASS 412a747
S16 408 raised directly, gemini green green x2 PASS 412a747
X1 odd header value, empty red green x2 PASS 412a747
X1 odd header value, not a number red green x2 PASS 412a747
X1 odd header value, negative red green x2 PASS 412a747
X1 odd header value, http date red green x2 PASS 412a747
X1 odd header value, five kb request id red green x2 PASS 412a747
S12 eager opener, openai acompletion green green x2 PASS 412a747
S12 eager opener, azure acompletion green green x2 PASS 412a747
S12 eager opener, anthropic acompletion green green x2 PASS 412a747
S10 eager opener, codestral text completion green green x2 PASS 412a747
S11b eager opener, predibase completion green green x2 PASS 412a747
S14 in-band error, gemini error before content green green x2 PASS 412a747
S15 in-band error, gemini error after content green green x2 PASS 412a747
S15 in-band error, gemini drop after content green green x2 PASS 412a747
S14 in-band error, anthropic overloaded before content green green x2 PASS 412a747
S15 in-band error, anthropic overloaded after content green green x2 PASS 412a747
S15 in-band error, openai error after content green green x2 PASS 412a747
S13 messages bridge, in-band 429 green green x2 PASS 412a747
R1 Router async retry green green x2 PASS 412a747
R3 Router async fallback, twice green green x2 PASS 412a747
R2 Router sync fallback green green x2 PASS 412a747
C1 40 concurrent streams red green x2 PASS 412a747
R4 Router sync retry wait red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review a0cb919
P1, P3 chat stream and twin, router green green x2 PASS 412a747
P7 chat stream and twin, config-less red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747
P2 OpenAI SDK chat stream, router green green x2 PASS 412a747
P7 OpenAI SDK chat stream, config-less red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747
P4 Anthropic SDK messages, router green green x2 PASS 412a747
P8 Anthropic SDK messages, config-less green green x2 PASS 412a747
P5 OpenAI SDK responses, router green green x2 PASS 412a747
P8 OpenAI SDK responses, config-less red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747
P6 chat stream fallback, router green green x2 PASS 412a747
P9 pass-through stream, gemini green green x2 PASS 412a747
P9 pass-through stream, anthropic green green x2 PASS 412a747
C2 32-call mixed burst, router green green x2 PASS 412a747
C2 32-call mixed burst, config-less red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747
C3 worker SIGKILL mid burst red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747
C4 SIGTERM mid burst, restart red green x2 FAIL, approved to ship by mateo-berri in this PR's approving review 412a747

Not 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
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[gemini-completion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[gemini-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[gemini-responses]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[gemini-aresponses]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[vertex_ai-completion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[vertex_ai-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[vertex_ai-responses]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[vertex_ai-aresponses]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[codestral-atext_completion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin[predibase-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_server_error_carries_the_provider_headers_of_its_non_stream_twin[500]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_server_error_carries_the_provider_headers_of_its_non_stream_twin[502]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_server_error_carries_the_provider_headers_of_its_non_stream_twin[503]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_server_error_carries_the_provider_headers_of_its_non_stream_twin[504]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers[400]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers[401]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers[403]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers[404]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers[408]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does[empty]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does[not_a_number]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does[negative]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does[http_date]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does[five_kb_request_id]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin[openai-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin[azure-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin[anthropic-acompletion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin[codestral-text_completion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin[predibase-completion]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[gemini_error_before_content-True]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[gemini_error_after_content-False]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[gemini_drop_after_content-False]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[anthropic_overloaded_before_content-True]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[anthropic_overloaded_after_content-False]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_in_band_stream_error_wraps_without_another_requests_provider_headers[openai_error_after_content-False]
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_messages_bridge_stream_open_rate_limit_answers_an_in_band_rate_limit_error_frame
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_router_async_stream_open_rate_limit_retries_then_surfaces_the_429
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_router_async_stream_open_rate_limit_falls_back_on_every_call
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_router_sync_stream_open_rate_limit_falls_back_to_the_healthy_deployment
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_concurrent_stream_open_rate_limits_each_carry_their_own_provider_request_id
tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py::test_router_sync_complete_response_stream_waits_the_provider_retry_after_like_its_non_stream_twin
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_chat_stream_open_rate_limit_answers_429_with_the_provider_request_id_like_its_non_stream_twin[router]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_chat_stream_open_rate_limit_answers_429_with_the_provider_request_id_like_its_non_stream_twin[configless]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_openai_sdk_chat_stream_open_rate_limit_raises_with_the_provider_request_id[router]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_openai_sdk_chat_stream_open_rate_limit_raises_with_the_provider_request_id[configless]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_anthropic_sdk_messages_stream_open_rate_limit_ends_with_a_rate_limit_error_event[router]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_anthropic_sdk_messages_stream_open_rate_limit_ends_with_a_rate_limit_error_event[configless]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_openai_sdk_responses_stream_open_rate_limit_ends_with_a_failed_response[router]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_openai_sdk_responses_stream_open_rate_limit_ends_with_a_failed_response[configless]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_router_stream_fallback_answers_from_the_healthy_deployment_after_the_stream_open_rate_limit
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_pass_through_stream_rate_limit_relays_the_provider_status_and_headers[gemini]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_pass_through_stream_rate_limit_relays_the_provider_status_and_headers[anthropic]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_mixed_burst_answers_and_logs_each_stream_open_rate_limit_with_its_own_provider_request_id[router]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_mixed_burst_answers_and_logs_each_stream_open_rate_limit_with_its_own_provider_request_id[configless]
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_worker_sigkill_mid_burst_leaves_the_sibling_answering_each_stream_open_rate_limit
tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py::test_proxy_sigterm_mid_burst_answers_each_in_flight_stream_and_the_restarted_proxy_serves
Controls on the head, all green
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_sync_completion_stream_in_stream_rate_limit_wraps_the_provider_exception_once
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_async_completion_stream_in_stream_rate_limit_wraps_the_provider_exception_once
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_sync_stream_in_stream_rate_limit_with_fallbacks_disabled_surfaces_the_provider_exception
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_async_stream_in_stream_rate_limit_without_fallbacks_surfaces_the_provider_exception
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_async_stream_in_stream_rate_limit_with_fallbacks_disabled_surfaces_the_provider_exception
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_sync_completion_stream_openai_error_event_raises_the_provider_code_and_message
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_async_stream_openai_error_event_rate_limit_surfaces_the_provider_exception
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_async_completion_stream_top_level_rate_limit_wraps_the_provider_exception_once
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_sync_stream_top_level_rate_limit_with_fallbacks_disabled_surfaces_the_provider_exception
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_router_async_stream_top_level_rate_limit_falls_back_to_the_healthy_deployment
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_sync_responses_stream_top_level_rate_limit_raises_the_provider_rate_limit
tests/integration/sdk/test_responses_bridge_stream_errors_sdk.py::test_async_responses_stream_top_level_insufficient_quota_raises_a_rate_limit
tests/integration/sdk/test_anthropic_messages_bridge_mid_stream_failure_sdk.py::test_sdk_bridged_stream_failing_after_content_reports_the_provider_error_once
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_stream_raises_at_the_request_timeout[sync-vertex_ai]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_stream_raises_at_the_request_timeout[sync-gemini]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_stream_raises_at_the_request_timeout[async-vertex_ai]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_stream_raises_at_the_request_timeout[async-gemini]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_body_raises_at_the_request_timeout[sync]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stalled_body_raises_at_the_request_timeout[async]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stream_with_a_request_timeout_still_completes[sync]
tests/integration/sdk/test_vertex_gemini_stream_timeout_wire.py::test_stream_with_a_request_timeout_still_completes[async]
tests/integration/streaming/test_responses_bridge_stream_chaos.py::test_mixed_burst_of_bridged_streams_answers_each_call_in_its_own_shape_and_logs_each_once[nested]
tests/integration/streaming/test_responses_bridge_stream_chaos.py::test_mixed_burst_of_bridged_streams_answers_each_call_in_its_own_shape_and_logs_each_once[top_level]
tests/integration/streaming/test_responses_bridge_stream_chaos.py::test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams[nested]
tests/integration/streaming/test_responses_bridge_stream_chaos.py::test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams[top_level]
tests/integration/streaming/test_responses_bridge_stream_chaos.py::test_proxy_sigterm_mid_burst_drains_the_spend_log_queue_and_the_restarted_proxy_serves
tests/integration/streaming/test_stream_contracts.py::test_generated_tcp_partitions_preserve_unicode_text_identity_and_final_usage
tests/integration/streaming/test_stream_contracts.py::test_fragmented_tool_names_and_arguments_keep_each_call_identity
tests/integration/streaming/test_stream_contracts.py::test_proxy_stream_usage_visibility_keeps_exact_persisted_charge
tests/integration/streaming/test_stream_contracts.py::test_messages_stream_completes_through_trailing_empty_choices_usage_chunk
tests/integration/streaming/test_stream_contracts.py::test_messages_stream_opens_thinking_block_at_index_zero_for_reasoning_content_only_chunks
tests/integration/streaming/test_stream_contracts.py::test_responses_stream_completes_through_empty_choices_metadata_and_usage_chunks
tests/integration/streaming/test_stream_contracts.py::test_perplexity_stream_with_cost_breakdown_object_completes_and_bills_total_cost
tests/integration/streaming/test_stream_contracts.py::test_primary_stream_with_empty_first_chunk_then_disconnect_falls_back_and_bills_the_fallback
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[messages-non-streaming]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[messages-before-first-byte]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[messages-mid-stream]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[messages-request-body-fallbacks]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[responses-non-streaming]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[responses-before-first-byte]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[responses-mid-stream]
tests/integration/streaming/test_stream_contracts.py::test_native_messages_and_responses_routes_fall_back_and_bill_the_fallback[responses-request-body-fallbacks]
tests/integration/streaming/test_stream_contracts.py::test_truncated_http_stream_is_an_error_and_next_stream_succeeds
tests/integration/streaming/test_stream_contracts.py::test_client_cancellation_releases_the_actual_provider_connection
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_bridged_stream_failing_after_content_writes_one_failure_row[drop_after_content]
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_bridged_stream_failing_after_content_writes_one_failure_row[error_frame_after_content]
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_anthropic_sdk_sync_stream_failing_after_content_raises_and_writes_one_failure_row
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_anthropic_sdk_async_stream_failing_after_content_raises_and_writes_one_failure_row
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_bridged_request_rejected_before_any_body_keeps_its_error_and_failure_row
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_bridged_stream_served_from_the_response_cache_keeps_its_success_bookkeeping
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_client_leaving_a_bridged_stream_before_its_failure_leaves_the_proxy_serving
tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_mid_stream_failure_bookkeeping_wire.py::test_concurrent_bridged_streams_failing_after_content_each_land_one_row

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Sync litellm.anthropic.messages.create(stream=True) still ends silently on a Gemini 429
    • Same on main, this PR does not touch that adapter, tracked separately
  • Proxy streaming 429s still lack the llm_provider-* headers non-streaming 429s carry
    • Same on main, the proxy answers identically before and after this PR
  • Router stream-open errors on Gemini and Vertex still reach the caller unmapped, with a bytes message
    • Same on main, this PR does not touch the Router's first-chunk read, tracked separately

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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 copy litellm_response_headers from the wrapped provider error, matching non-streaming calls where headers like retry-after and x-request-id were already exposed.

Integration coverage adds configless_proxy_process for --model / --api_base proxy 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 in test_streaming_handler.py asserts 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.

  • a0cb919 passes /audit, behavior changes approved in review
  • 412a747 passes /live-pr-risk

@Acacian
Acacian requested a review from a team September 17, 2026 00:55
@greptile-apps

greptile-apps Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Preserves provider response headers when streaming failures are wrapped in MidStreamFallbackError

  • Copies litellm_response_headers only when the original exception provides them
  • Adds regression coverage for preserved rate-limit headers and headerless exceptions
  • Removes the redundant source comment identified in the previous review

Confidence Score: 5/5

The 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
Filename Overview
litellm/exceptions.py Preserves normalized provider headers on wrapped mid-stream fallback errors without changing headerless behavior
tests/test_litellm/litellm_core_utils/test_streaming_handler.py Covers streaming rate-limit header preservation and the absence of a header attribute when none exists

Reviews (2): Last reviewed commit: "refactor(streaming): drop explanatory co..." | Re-trigger Greptile

Comment thread litellm/exceptions.py Resolved
@codspeed

codspeed Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing Acacian:fix-midstream-fallback-provider-headers (a0cb919) with main (56dad90)1

Open in CodSpeed

Footnotes

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

@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@Acacian

Acacian commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

@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.
@Acacian
Acacian force-pushed the fix-midstream-fallback-provider-headers branch from 3cdfbed to 7a373a3 Compare September 28, 2026 08:56
@Acacian Acacian changed the title fix(streaming): keep provider headers on MidStreamFallbackError fix(gemini): keep retry-after and x-request-id on SDK streaming 429s Sep 29, 2026
@Acacian Acacian changed the title fix(gemini): keep retry-after and x-request-id on SDK streaming 429s fix(gemini): expose retry-after and x-request-id on SDK streaming 429s Sep 29, 2026
# Conflicts:
#	tests/unit/litellm_core_utils/test_streaming_handler.py
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

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
@mateo-berri mateo-berri changed the title fix(gemini): expose retry-after and x-request-id on SDK streaming 429s fix(streaming): keep provider response headers on SDK streaming errors Oct 15, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@litereview

litereview Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

MidStreamFallbackError now copies litellm_response_headers from the exception it wraps. That makes the headers available to SDK callers and to the existing consumers that already read the attribute: Router retry-after calculation (router.py:8505), provider request-id logging (litellm_logging.py:306) and the proxy error header fallback (common_request_processing.py:3840). When the wrapped error carries no headers, the error behaves as it did before.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/exceptions.py, tests/integration/_support/process.py, two new integration test files and tests/unit/litellm_core_utils/test_streaming_handler.py. None of these files sit under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.
  • Passed · New unit test: test_streaming_rate_limit_midstream_fallback_keeps_provider_headers (optional): Ran python -m pytest tests/unit/litellm_core_utils/test_streaming_handler.py -k keeps_provider_headers, and both the sync and async parametrizations passed. A full run of the file gave 167 passed and 5 failed. The 5 failures are test_dispatch_vertex_ai_legacy_* and test_gemini_legacy_vertex_*, which fail with ModuleNotFoundError: No module named 'proto' because an optional dependency is missing locally. They are unrelated to this change.
  • Passed · Consumer trace of litellm_response_headers (optional): Inspected the consumers that read litellm_response_headers: router.py:8505 (retry timeout), litellm_logging.py:_get_provider_request_id, exception_mapping_utils._get_response_headers and the proxy failure header fallback, which passes through get_response_headers. Each one handles a Mapping or httpx.Headers value, and none of them breaks when this attribute is now populated.
  • Not run · Integration tests (tests/integration/sdk, tests/integration/streaming) (optional): Not run. These tests need the integration gateway, Postgres spend-log harness and proxy processes, and none of that is available in this sandbox. The required rule does not apply to this PR, so not running them does not block the review.

View review · Reviewed a0cb91996335

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

Stale Bugbot comment from a previous 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
@mateo-berri

Copy link
Copy Markdown
Contributor

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

✅ 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 mateo-berri 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. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit a9e45a2 into BerriAI:main Oct 15, 2026
91 checks passed
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