The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(streaming): keep provider response headers on SDK streaming errors (#41528)
구동하a9e45a24d36f
diff --git a/litellm/exceptions.py b/litellm/exceptions.pyindex 65ea61c072c..31388b00554 100644--- a/litellm/exceptions.py+++ b/litellm/exceptions.py@@ -1267,6 +1267,10 @@ class MidStreamFallbackError(ServiceUnavailableError):self.message = _saved_messageself.args = (_saved_message,)+ original_headers: Final = getattr(original_exception, "litellm_response_headers", None)+ if original_headers is not None:+ self.litellm_response_headers = original_headers+def __str__(self):_message = self.messageif self.num_retries:diff --git a/tests/integration/_support/process.py b/tests/integration/_support/process.pyindex f135a091cb3..7f69f69a55f 100644--- a/tests/integration/_support/process.py+++ b/tests/integration/_support/process.py@@ -795,6 +795,45 @@ def owned_proxy_process(_stop_launch(launch)+@contextmanager+def configless_proxy_process(+ gateway: Gateway,+ directory: Path,+ overrides: Mapping[str, str],+ *,+ model: str,+ api_base: str,+ workers: int = 1,+) -> Iterator[OwnedProxy]:+ environment: Final = _proxy_environment(gateway, {**overrides, "STORE_MODEL_IN_DB": "False"}, ())+ output: Final = Path(os.environ.get("INTEGRATION_RESULTS_DIR", str(directory)))+ output.mkdir(parents=True, exist_ok=True)+ command: Final = (+ sys.executable,+ "-m",+ "integration._support.proxy",+ "--model",+ model,+ "--api_base",+ api_base,+ "--host",+ "127.0.0.1",+ "--num_workers",+ str(workers),+ "--timeout_worker_healthcheck",+ str(healthcheck_seconds(WorkerHealthcheck.STRICT)),+ *DB_PUSH,+ )+ launch: Final = _launch_until_bound(command, _proxy_root(), environment, output, _PORT_ATTEMPTS, workers)+ try:+ with httpx.Client(+ base_url=f"http://127.0.0.1:{launch.port}", timeout=15, trust_env=False, limits=GATEWAY_LIMITS+ ) as client:+ yield OwnedProxy(Gateway(client, gateway.key, gateway.upstream_url), launch.process, launch.log)+ finally:+ _stop_launch(launch)++@contextmanagerdef owned_gateway_image(gateway: Gateway, directory: Path, overrides: Mapping[str, str], *, config: Path, workers: intdiff --git a/tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py b/tests/integration/sdk/test_stream_open_error_provider_headers_sdk.pynew file mode 100644index 00000000000..1c0ccc440a7--- /dev/null+++ b/tests/integration/sdk/test_stream_open_error_provider_headers_sdk.py@@ -0,0 +1,591 @@+import asyncio+import json+import re+import time+import uuid+from collections.abc import Callable, Mapping+from queue import SimpleQueue+from types import MappingProxyType+from typing import Final, Literal, TypeAlias++import pytest+from integration._support.vertex import service_account_json+from integration._support.wire import Reply, Request, Wire, wire_server++import litellm+from litellm import Router+from litellm.exceptions import MidStreamFallbackError+from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper++Route: TypeAlias = Literal["gemini", "vertex_ai", "codestral", "predibase", "openai", "azure", "anthropic"]+Call: TypeAlias = Literal["completion", "acompletion", "responses", "aresponses", "text_completion", "atext_completion"]++_GEMINI_MODEL: Final = "gemini-3.8-flash"+_PROJECT: Final = "scripted-project"+_LOCATION: Final = "us-east5"+_TOKEN_TARGET: Final = "/_oauth/token"+_TOKEN_REPLY: Final = Reply(+ body=json.dumps({"access_token": "scripted-token", "token_type": "Bearer", "expires_in": 3600}).encode()+)+_SCRIPTED: Final = ("retry-after", "x-request-id")+_MARKER: Final = re.compile(r"marker-([0-9a-f]{32})")++_STREAM_OPEN_CASES: Final[tuple[tuple[Route, Call], ...]] = (+ ("gemini", "completion"),+ ("gemini", "acompletion"),+ ("gemini", "responses"),+ ("gemini", "aresponses"),+ ("vertex_ai", "completion"),+ ("vertex_ai", "acompletion"),+ ("vertex_ai", "responses"),+ ("vertex_ai", "aresponses"),+ ("codestral", "atext_completion"),+ ("predibase", "acompletion"),+)+_EAGER_CASES: Final[tuple[tuple[Route, Call], ...]] = (+ ("openai", "acompletion"),+ ("azure", "acompletion"),+ ("anthropic", "acompletion"),+ ("codestral", "text_completion"),+ ("predibase", "completion"),+)+_STREAM_TARGETS: Final[Mapping[Route, str]] = MappingProxyType(+ {+ "gemini": ":streamGenerateContent",+ "vertex_ai": ":streamGenerateContent",+ "codestral": "/v1/fim/completions",+ "predibase": "/scripted-tenant/deployments/v2/llms/llama-3-8b-instruct/generate_stream",+ "openai": "/chat/completions",+ "azure": "/chat/completions",+ "anthropic": "/v1/messages",+ }+)+_SYNC_TWINS: Final[Mapping[Call, Call]] = MappingProxyType(+ {+ "completion": "completion",+ "acompletion": "completion",+ "responses": "responses",+ "aresponses": "responses",+ "text_completion": "text_completion",+ "atext_completion": "text_completion",+ }+)+++def _headers(marker: str, retry_after: str = "7") -> Mapping[str, str]:+ return MappingProxyType({"retry-after": retry_after, "x-request-id": f"req-{marker}"})+++def _gemini_error(status: int) -> bytes:+ return json.dumps(+ {"error": {"code": status, "message": f"scripted provider error {status}", "status": "X"}}+ ).encode()+++def _error_body(route: Route, status: int) -> bytes:+ match route:+ case "anthropic":+ return json.dumps(+ {"type": "error", "error": {"type": "rate_limit_error", "message": "scripted provider error"}}+ ).encode()+ case "openai" | "azure" | "codestral" | "predibase":+ return json.dumps(+ {"error": {"message": "scripted provider error", "type": "requests", "code": "rate_limit_exceeded"}}+ ).encode()+ case "gemini" | "vertex_ai":+ return _gemini_error(status)+++def _failing(route: Route, status: int, headers: Mapping[str, str]) -> Callable[[Request], Reply]:+ def respond(request: Request) -> Reply:+ if request.target == _TOKEN_TARGET:+ return _TOKEN_REPLY+ assert request.method == "POST", request.method+ return Reply(status=status, body=_error_body(route, status), headers=headers)++ return respond+++def _deployment(route: Route, wire: Wire) -> dict[str, str]:+ match route:+ case "gemini":+ return {"model": f"gemini/{_GEMINI_MODEL}", "api_base": wire.url, "api_key": "scripted-key"}+ case "vertex_ai":+ return {+ "model": f"vertex_ai/{_GEMINI_MODEL}",+ "api_base": wire.url,+ "vertex_project": _PROJECT,+ "vertex_location": _LOCATION,+ "vertex_credentials": service_account_json(_PROJECT, wire.url),+ }+ case "codestral":+ return {+ "model": "text-completion-codestral/codestral-latest",+ "api_base": f"{wire.url}/v1/fim/completions",+ "api_key": "scripted-key",+ }+ case "openai":+ return {"model": "openai/gpt-6.1-sol", "api_base": wire.url, "api_key": "scripted-key"}+ case "azure":+ return {+ "model": "azure/gpt-6.1-sol",+ "api_base": wire.url,+ "api_key": "scripted-key",+ "api_version": "2025-04-01-preview",+ }+ case "anthropic":+ return {"model": "anthropic/claude-opus-5-5", "api_base": wire.url, "api_key": "scripted-key"}+ case "predibase":+ return {"model": "predibase/llama-3-8b-instruct", "api_base": wire.url, "api_key": "scripted-key"}+++def _messages(marker: str) -> list[dict[str, str]]:+ return [{"role": "user", "content": f"stream open probe marker-{marker}"}]+++def _drain_sync(response: object) -> None:+ assert not isinstance(response, (str, bytes)) and hasattr(response, "__iter__"), type(response)+ for _ in response: # pyright: ignore[reportGeneralTypeIssues] # narrowed by the hasattr assert above+ pass+++async def _drain_async(response: object) -> None:+ assert hasattr(response, "__aiter__"), type(response)+ async for _ in response: # pyright: ignore[reportGeneralTypeIssues] # narrowed by the hasattr assert above+ pass+++async def _invoke_async(call: Call, deployment: dict[str, str], marker: str, stream: bool) -> None:+ match call:+ case "acompletion":+ completion: Final = await litellm.acompletion(+ **deployment, messages=_messages(marker), stream=stream, num_retries=0+ )+ if stream:+ await _drain_async(completion)+ case "aresponses":+ responses: Final = await litellm.aresponses(+ **deployment, input=f"stream open probe marker-{marker}", stream=stream, num_retries=0+ )+ if stream:+ await _drain_async(responses)+ case "atext_completion":+ text: Final = await litellm.atext_completion(+ **deployment, prompt=f"stream open probe marker-{marker}", stream=stream, num_retries=0+ )+ if stream:+ await _drain_async(text)+ case "completion" | "responses" | "text_completion":+ raise AssertionError(call)+++def _invoke(call: Call, deployment: dict[str, str], marker: str, stream: bool) -> None:+ match call:+ case "completion":+ completion: Final = litellm.completion(+ **deployment, messages=_messages(marker), stream=stream, num_retries=0+ )+ if stream:+ _drain_sync(completion)+ case "responses":+ responses: Final = litellm.responses(+ **deployment, input=f"stream open probe marker-{marker}", stream=stream, num_retries=0+ )+ if stream:+ _drain_sync(responses)+ case "text_completion":+ text: Final = litellm.text_completion(+ **deployment, prompt=f"stream open probe marker-{marker}", stream=stream, num_retries=0+ )+ if stream:+ _drain_sync(text)+ case "acompletion" | "aresponses" | "atext_completion":+ asyncio.run(_invoke_async(call, deployment, marker, stream))+++def _raised(invoke: Callable[[], None]) -> Exception:+ try:+ invoke()+ except Exception as error:+ return error+ pytest.fail("the provider error never reached the caller")+++def _carried(error: Exception) -> Mapping[str, str]:+ headers: Final = getattr(error, "litellm_response_headers", None) or {}+ return MappingProxyType({str(name).lower(): str(value) for name, value in dict(headers).items()})+++def _scripted(error: Exception) -> Mapping[str, str | None]:+ carried: Final = _carried(error)+ return MappingProxyType({name: carried.get(name) for name in _SCRIPTED})+++def _provider_calls(wire: Wire) -> tuple[Request, ...]:+ return tuple(request for request in wire.drain() if request.target != _TOKEN_TARGET)+++def _assert_one_stream_attempt(route: Route, wire: Wire, marker: str) -> None:+ calls: Final = _provider_calls(wire)+ assert len(calls) == 1, [request.target for request in calls]+ assert marker.encode() in calls[0].body and _STREAM_TARGETS[route] in calls[0].target, calls[0]+++def _twin_and_stream_errors(+ route: Route, call: Call, status: int, headers: Mapping[str, str], marker: str+) -> tuple[Exception, Exception]:+ with wire_server(_failing(route, status, headers)) as wire:+ twin: Final = _raised(lambda: _invoke(_SYNC_TWINS[call], _deployment(route, wire), marker, stream=False))+ assert len(_provider_calls(wire)) == 1+ raised: Final = _raised(lambda: _invoke(call, _deployment(route, wire), marker, stream=True))+ _assert_one_stream_attempt(route, wire, marker)+ return twin, raised++[email protected](autouse=True)+def _predibase_tenant(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("PREDIBASE_TENANT_ID", "scripted-tenant")++[email protected](("route", "call"), _STREAM_OPEN_CASES)+def test_stream_open_rate_limit_carries_the_provider_headers_of_its_non_stream_twin(route: Route, call: Call) -> None:+ marker: Final = uuid.uuid4().hex+ headers: Final = _headers(marker)+ twin, raised = _twin_and_stream_errors(route, call, 429, headers, marker)+ assert isinstance(twin, litellm.RateLimitError), repr(twin)+ assert dict(_scripted(twin)) == dict(headers), dict(_carried(twin))+ assert isinstance(raised, MidStreamFallbackError), repr(raised)+ assert raised.status_code == 429 and raised.is_pre_first_chunk and raised.generated_content == "", repr(raised)+ assert isinstance(raised.original_exception, litellm.RateLimitError), repr(raised.original_exception)+ assert dict(_scripted(raised)) == dict(headers), dict(_carried(raised))+ assert sorted(_carried(raised)) == sorted(_carried(twin)), (dict(_carried(raised)), dict(_carried(twin)))++[email protected]("status", (500, 502, 503, 504))+def test_stream_open_server_error_carries_the_provider_headers_of_its_non_stream_twin(status: int) -> None:+ marker: Final = uuid.uuid4().hex+ headers: Final = _headers(marker)+ twin, raised = _twin_and_stream_errors("gemini", "acompletion", status, headers, marker)+ assert dict(_scripted(twin)) == dict(headers), dict(_carried(twin))+ assert isinstance(raised, MidStreamFallbackError), repr(raised)+ assert type(raised.original_exception) is type(twin), (repr(raised.original_exception), repr(twin))+ assert raised.status_code == getattr(twin, "status_code"), (raised.status_code, getattr(twin, "status_code"))+ assert dict(_scripted(raised)) == dict(headers), dict(_carried(raised))++[email protected]("status", (400, 401, 403, 404, 408))+def test_stream_open_client_error_raises_its_non_stream_twin_with_the_provider_headers(status: int) -> None:+ marker: Final = uuid.uuid4().hex+ headers: Final = _headers(marker)+ twin, raised = _twin_and_stream_errors("gemini", "acompletion", status, headers, marker)+ assert not isinstance(raised, MidStreamFallbackError), repr(raised)+ assert type(raised) is type(twin) and getattr(raised, "status_code") == status, (repr(raised), repr(twin))+ assert dict(_scripted(raised)) == dict(_scripted(twin)) == dict(headers), dict(_carried(raised))+++ ("retry_after", "request_id"),+ (+ ("", ""),+ ("abc", "scripted-request"),+ ("-5", "scripted-request"),+ ("Wed, 21 Oct 2015 07:28:00 GMT", "scripted-request"),+ ("1", "r" * 5000),+ ),+ ids=("empty", "not_a_number", "negative", "http_date", "five_kb_request_id"),+)+def test_stream_open_rate_limit_keeps_odd_provider_header_values_as_the_non_stream_twin_does(+ retry_after: str, request_id: str+) -> None:+ marker: Final = uuid.uuid4().hex+ headers: Final = MappingProxyType({"retry-after": retry_after, "x-request-id": request_id})+ twin, raised = _twin_and_stream_errors("gemini", "acompletion", 429, headers, marker)+ assert isinstance(raised, MidStreamFallbackError), repr(raised)+ assert dict(_scripted(twin)) == dict(headers), dict(_carried(twin))+ assert dict(_scripted(raised)) == dict(_scripted(twin)), (dict(_scripted(raised)), dict(_scripted(twin)))++[email protected](("route", "call"), _EAGER_CASES)+def test_eager_stream_opener_raises_the_same_error_as_its_non_stream_twin(route: Route, call: Call) -> None:+ marker: Final = uuid.uuid4().hex+ headers: Final = _headers(marker)+ twin, raised = _twin_and_stream_errors(route, call, 429, headers, marker)+ assert not isinstance(raised, MidStreamFallbackError), repr(raised)+ assert type(raised) is type(twin) and isinstance(raised, litellm.RateLimitError), (repr(raised), repr(twin))+ assert dict(_scripted(raised)) == dict(_scripted(twin)) == dict(headers), dict(_carried(raised))+++def _gemini_frame(text: str) -> bytes:+ candidate: Final = {"content": {"role": "model", "parts": [{"text": text}]}}+ usage: Final = {"promptTokenCount": 3, "candidatesTokenCount": 1, "totalTokenCount": 4}+ return b"data: " + json.dumps({"candidates": [candidate], "usageMetadata": usage}).encode() + b"\n\n"+++def _gemini_error_frame() -> bytes:+ return (+ b"data: "+ + json.dumps({"error": {"code": 503, "message": "overloaded", "status": "UNAVAILABLE"}}).encode()+ + (b"\n\n")+ )+++def _openai_frame(text: str) -> bytes:+ chunk: Final = {+ "id": "chatcmpl-scripted",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "gpt-6.1-sol",+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": None}],+ }+ return b"data: " + json.dumps(chunk).encode() + b"\n\n"+++def _openai_error_frame() -> bytes:+ error: Final = {"error": {"message": "server overloaded", "type": "server_error", "code": "server_error"}}+ return b"data: " + json.dumps(error).encode() + b"\n\n"+++def _anthropic_frame(event: str, data: Mapping[str, object]) -> bytes:+ return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()+++_ANTHROPIC_START: Final = _anthropic_frame(+ "message_start",+ {+ "type": "message_start",+ "message": {+ "id": "msg_scripted",+ "type": "message",+ "role": "assistant",+ "model": "claude-opus-5-5",+ "content": [],+ "stop_reason": None,+ "stop_sequence": None,+ "usage": {"input_tokens": 3, "output_tokens": 0},+ },+ },+)+_ANTHROPIC_TEXT: Final = (+ _anthropic_frame(+ "content_block_start",+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},+ ),+ _anthropic_frame(+ "content_block_delta",+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "partial "}},+ ),+)+_ANTHROPIC_OVERLOADED: Final = _anthropic_frame(+ "error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}+)++InBand: TypeAlias = Literal[+ "gemini_error_before_content",+ "gemini_error_after_content",+ "gemini_drop_after_content",+ "anthropic_overloaded_before_content",+ "anthropic_overloaded_after_content",+ "openai_error_after_content",+]+++def _in_band(kind: InBand, headers: Mapping[str, str]) -> tuple[Route, Reply]:+ match kind:+ case "gemini_error_before_content":+ return "gemini", Reply(content_type="text/event-stream", chunks=(_gemini_error_frame(),), headers=headers)+ case "gemini_error_after_content":+ chunks: Final = (_gemini_frame("partial "), _gemini_error_frame())+ return "gemini", Reply(content_type="text/event-stream", chunks=chunks, headers=headers)+ case "gemini_drop_after_content":+ dropped: Final = (_gemini_frame("partial "), _gemini_frame("never sent"))+ return "gemini", Reply(content_type="text/event-stream", chunks=dropped, abort_after=1, headers=headers)+ case "anthropic_overloaded_before_content":+ early: Final = (_ANTHROPIC_START, _ANTHROPIC_OVERLOADED)+ return "anthropic", Reply(content_type="text/event-stream", chunks=early, headers=headers)+ case "anthropic_overloaded_after_content":+ late: Final = (_ANTHROPIC_START, *_ANTHROPIC_TEXT, _ANTHROPIC_OVERLOADED)+ return "anthropic", Reply(content_type="text/event-stream", chunks=late, headers=headers)+ case "openai_error_after_content":+ openai_chunks: Final = (_openai_frame("partial "), _openai_error_frame())+ return "openai", Reply(content_type="text/event-stream", chunks=openai_chunks, headers=headers)+++ ("kind", "before_content"),+ (+ ("gemini_error_before_content", True),+ ("gemini_error_after_content", False),+ ("gemini_drop_after_content", False),+ ("anthropic_overloaded_before_content", True),+ ("anthropic_overloaded_after_content", False),+ ("openai_error_after_content", False),+ ),+)+def test_in_band_stream_error_wraps_without_another_requests_provider_headers(+ kind: InBand, before_content: bool+) -> None:+ marker: Final = uuid.uuid4().hex+ route, reply = _in_band(kind, _headers(marker))+ with wire_server(lambda _request: reply) as wire:+ raised: Final = _raised(lambda: _invoke("acompletion", _deployment(route, wire), marker, stream=True))+ calls: Final = _provider_calls(wire)+ assert isinstance(raised, MidStreamFallbackError), repr(raised)+ assert raised.is_pre_first_chunk is before_content, repr(raised)+ assert raised.generated_content == ("" if before_content else "partial "), raised.generated_content+ assert _scripted(raised)["x-request-id"] in (None, f"req-{marker}"), dict(_carried(raised))+ assert len(calls) == 1 and marker.encode() in calls[0].body, calls+++async def test_messages_bridge_stream_open_rate_limit_answers_an_in_band_rate_limit_error_frame() -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_failing("gemini", 429, _headers(marker))) as wire:+ stream: Final = await litellm.anthropic.messages.acreate(+ **_deployment("gemini", wire), max_tokens=16, messages=_messages(marker), stream=True+ )+ assert hasattr(stream, "__aiter__"), type(stream)+ frames: Final = [frame async for frame in stream] # pyright: ignore[reportGeneralTypeIssues] # narrowed above+ calls: Final = _provider_calls(wire)+ text: Final = b"".join(frame if isinstance(frame, bytes) else str(frame).encode() for frame in frames).decode()+ events: Final = tuple(line.removeprefix("event: ") for line in text.splitlines() if line.startswith("event: "))+ assert events[0] == "message_start" and events[-1] == "error", text+ error_data: Final = json.loads(text.strip().split("\n\n")[-1].split("data: ", 1)[1])+ assert error_data["error"]["type"] == "rate_limit_error", error_data+ assert len(calls) == 1 and marker.encode() in calls[0].body, calls+++def _router(primary: Wire, fallback: Wire | None, num_retries: int) -> Router:+ healthy: Final = (+ ({"model_name": "healthy", "litellm_params": _deployment("gemini", fallback)},) if fallback is not None else ()+ )+ return Router(+ model_list=[{"model_name": "limited", "litellm_params": _deployment("gemini", primary)}, *healthy],+ num_retries=num_retries,+ retry_after=0,+ fallbacks=[{"limited": ["healthy"]}] if fallback is not None else [],+ )+++def _healthy_stream(_request: Request) -> Reply:+ candidate: Final = {"content": {"role": "model", "parts": [{"text": "answer"}]}, "finishReason": "STOP"}+ usage: Final = {"promptTokenCount": 3, "candidatesTokenCount": 1, "totalTokenCount": 4}+ frame: Final = b"data: " + json.dumps({"candidates": [candidate], "usageMetadata": usage}).encode() + b"\n\n"+ return Reply(content_type="text/event-stream", chunks=(_gemini_frame("healthy "), frame))+++def _text_of(chunk: object) -> str:+ choices: Final = getattr(chunk, "choices", None) or ()+ return "".join(str(choice.delta.content or "") for choice in choices)+++async def _router_stream_error(router: Router, marker: str) -> Exception:+ try:+ await _drain_async(await router.acompletion(model="limited", messages=_messages(marker), stream=True))+ except Exception as error:+ return error+ raise AssertionError(f"marker-{marker} streamed without the scripted 429")+++async def test_router_async_stream_open_rate_limit_retries_then_surfaces_the_429() -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_failing("gemini", 429, _headers(marker, retry_after="1"))) as wire:+ raised: Final = await _router_stream_error(_router(wire, None, num_retries=1), marker)+ calls: Final = _provider_calls(wire)+ assert getattr(raised, "status_code", None) == 429, repr(raised)+ assert not isinstance(raised, MidStreamFallbackError), repr(raised)+ assert len(calls) == 2 and all(marker.encode() in request.body for request in calls), calls+++async def _fallback_text(router: Router, marker: str) -> str:+ response: Final = await router.acompletion(model="limited", messages=_messages(marker), stream=True)+ assert isinstance(response, CustomStreamWrapper), type(response)+ return "".join([_text_of(chunk) async for chunk in response])+++async def test_router_async_stream_open_rate_limit_falls_back_on_every_call() -> None:+ markers: Final = (uuid.uuid4().hex, uuid.uuid4().hex)+ with wire_server(_failing("gemini", 429, _headers(markers[0]))) as limited, wire_server(_healthy_stream) as healthy:+ router: Final = _router(limited, healthy, num_retries=0)+ first: Final = await _fallback_text(router, markers[0])+ first_calls: Final = (_provider_calls(limited), _provider_calls(healthy))+ second: Final = await _fallback_text(router, markers[1])+ second_calls: Final = (_provider_calls(limited), _provider_calls(healthy))+ assert first == second == "healthy answer", (first, second)+ for marker, (limited_calls, healthy_calls) in zip(markers, (first_calls, second_calls), strict=True):+ assert [marker.encode() in request.body for request in limited_calls] == [True], limited_calls+ assert [marker.encode() in request.body for request in healthy_calls] == [True], healthy_calls+++def test_router_sync_stream_open_rate_limit_falls_back_to_the_healthy_deployment() -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_failing("gemini", 429, _headers(marker))) as limited, wire_server(_healthy_stream) as healthy:+ response: Final = _router(limited, healthy, num_retries=0).completion(+ model="limited", messages=_messages(marker), stream=True+ )+ assert isinstance(response, CustomStreamWrapper), type(response)+ text: Final = "".join(_text_of(chunk) for chunk in response)+ limited_calls: Final = _provider_calls(limited)+ healthy_calls: Final = _provider_calls(healthy)+ assert text == "healthy answer", text+ assert len(limited_calls) == 1 and marker.encode() in limited_calls[0].body, limited_calls+ assert len(healthy_calls) == 1 and marker.encode() in healthy_calls[0].body, healthy_calls+++def _retry_gap_seconds(retry_after: str, stream: bool) -> float:+ marker: Final = uuid.uuid4().hex+ arrivals: Final = SimpleQueue[float]()+ failing: Final = _failing("gemini", 429, _headers(marker, retry_after=retry_after))++ def respond(request: Request) -> Reply:+ arrivals.put(time.monotonic())+ return failing(request)++ with wire_server(respond) as wire:+ router: Final = _router(wire, None, num_retries=1)++ def complete() -> None:+ router.completion(model="limited", messages=_messages(marker), stream=stream, complete_response=stream)++ raised: Final = _raised(complete)+ calls: Final = _provider_calls(wire)+ assert getattr(raised, "status_code", None) == 429, repr(raised)+ assert [marker.encode() in request.body for request in calls] == [True, True], calls+ first, second = arrivals.get_nowait(), arrivals.get_nowait()+ return second - first+++def test_router_sync_complete_response_stream_waits_the_provider_retry_after_like_its_non_stream_twin() -> None:+ retry_after: Final = 3+ gaps: Final = (+ _retry_gap_seconds(str(retry_after), stream=False),+ _retry_gap_seconds(str(retry_after), stream=True),+ )+ assert min(gaps) >= retry_after, gaps+++def _per_request_rate_limit(request: Request) -> Reply:+ found: Final = _MARKER.search(request.body.decode())+ assert found is not None, request.body+ return Reply(status=429, body=_gemini_error(429), headers=_headers(found.group(1)))+++async def _stream_error(deployment: dict[str, str], marker: str) -> Exception:+ try:+ await _invoke_async("acompletion", deployment, marker, stream=True)+ except Exception as error:+ return error+ raise AssertionError(f"marker-{marker} streamed without the scripted 429")+++async def test_concurrent_stream_open_rate_limits_each_carry_their_own_provider_request_id() -> None:+ markers: Final = tuple(uuid.uuid4().hex for _ in range(40))+ with wire_server(_per_request_rate_limit) as wire:+ deployment: Final = _deployment("gemini", wire)+ errors: Final = await asyncio.gather(*(_stream_error(deployment, marker) for marker in markers))+ calls: Final = _provider_calls(wire)+ for marker, error in zip(markers, errors, strict=True):+ assert isinstance(error, MidStreamFallbackError), repr(error)+ assert dict(_scripted(error)) == dict(_headers(marker)), (marker, dict(_carried(error)))+ forwarded: Final = sorted(+ found.group(1) for found in (_MARKER.search(call.body.decode()) for call in calls) if found+ )+ assert forwarded == sorted(markers), forwardeddiff --git a/tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py b/tests/integration/streaming/test_stream_open_error_provider_headers_proxy.pynew file mode 100644index 00000000000..f614de3aeef--- /dev/null+++ b/tests/integration/streaming/test_stream_open_error_provider_headers_proxy.py@@ -0,0 +1,567 @@+import asyncio+import json+import re+import socket+import threading+import uuid+from collections.abc import Iterator, Mapping, Sequence+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from queue import SimpleQueue+from types import MappingProxyType+from typing import Final, Literal, TypeAlias+from urllib.parse import urlsplit++import anthropic+import httpx+import openai+import psutil+import pytest+from integration._support.client import (+ JSON_OBJECT,+ Gateway,+ eventually,+ gateway_from_environment,+ object_value,+ string_value,+)+from integration._support.database import read_rows+from integration._support.process import OwnedProxy, configless_proxy_process, graceful_stop_seconds+from integration._support.wire import Reply, Request, Wire, wire_server+from openai.types.responses import ResponseFailedEvent+from pydantic import JsonValue++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 120)++_MODEL: Final = "gemini/gemini-3.8-flash"+_GEMINI_KEY: Final = "scripted-gemini-key"+_MARKER: Final = re.compile(r"marker-([0-9a-f]{32})")+_HEALTHY_PREFIX: Final = "/healthy"+_ANTHROPIC_VERSION: Final[Mapping[str, str]] = MappingProxyType({"anthropic-version": "2023-06-01"})++Serving: TypeAlias = Literal["router", "configless"]+Kind: TypeAlias = Literal["chat_stream", "chat", "messages_stream", "responses_stream"]+PassThrough: TypeAlias = Literal["gemini", "anthropic"]+_SERVINGS: Final[tuple[Serving, ...]] = ("router", "configless")+_PASS_THROUGHS: Final[tuple[PassThrough, ...]] = ("gemini", "anthropic")+_FORWARDS_PROVIDER_HEADERS: Final[frozenset[tuple[Serving, Kind]]] = frozenset(+ {("router", "chat"), ("router", "chat_stream"), ("configless", "chat")}+)+_KINDS: Final[tuple[Kind, ...]] = ("chat_stream", "chat", "messages_stream", "responses_stream")+++@dataclass(frozen=True, slots=True)+class _Rig:+ port: int+ proxy: OwnedProxy++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self.port}"+++@dataclass(frozen=True, slots=True)+class _Call:+ kind: Kind+ marker: str+++@dataclass(frozen=True, slots=True)+class _Served:+ call: _Call+ status: int+ headers: Mapping[str, str]+ text: str+ call_id: str+++def _free_port() -> int:+ with socket.socket() as reserve:+ reserve.bind(("127.0.0.1", 0))+ return reserve.getsockname()[1]+++@contextmanager+def _configless(gateway: Gateway, directory: Path, port: int) -> Iterator[_Rig]:+ url: Final = f"http://127.0.0.1:{port}"+ overrides: Final = {+ "GEMINI_API_KEY": _GEMINI_KEY,+ "GEMINI_API_BASE": url,+ "ANTHROPIC_API_BASE": url,+ "ANTHROPIC_API_KEY": "scripted-anthropic-key",+ }+ with configless_proxy_process(gateway, directory, overrides, model=_MODEL, api_base=url, workers=2) as owned:+ yield _Rig(port, owned)++[email protected](scope="module")+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:+ with (+ gateway_from_environment() as shared,+ _configless(shared, tmp_path_factory.mktemp("configless"), _free_port()) as owned,+ ):+ yield owned+++def _newest_marker(text: str) -> str | None:+ found: Final = _MARKER.findall(text)+ return found[-1] if found else None+++def _request_id(marker: str) -> str:+ return f"req-{marker}"+++def _gemini_frame(text: str, finish: str | None) -> bytes:+ candidate: Final = {+ "content": {"role": "model", "parts": [{"text": text}]},+ **({"finishReason": finish} if finish else {}),+ }+ usage: Final = {"promptTokenCount": 3, "candidatesTokenCount": 2, "totalTokenCount": 5}+ return b"data: " + json.dumps({"candidates": [candidate], "usageMetadata": usage}).encode() + b"\n\n"+++def _respond(request: Request) -> Reply:+ assert request.method == "POST", request.method+ marker: Final = _newest_marker(request.body.decode())+ assert marker is not None, request.body+ if request.target.startswith(_HEALTHY_PREFIX):+ return Reply(+ content_type="text/event-stream",+ chunks=(_gemini_frame("healthy ", None), _gemini_frame(f"marker-{marker}", "STOP")),+ )+ headers: Final = {"retry-after": "7", "x-request-id": _request_id(marker)}+ if request.target.startswith("/v1/messages"):+ error: Final = {"type": "error", "error": {"type": "rate_limit_error", "message": "scripted rate limit"}}+ return Reply(status=429, body=json.dumps(error).encode(), headers=headers)+ body: Final = {"error": {"code": 429, "message": "scripted rate limit", "status": "RESOURCE_EXHAUSTED"}}+ return Reply(status=429, body=json.dumps(body).encode(), headers=headers)+++@contextmanager+def _model_on(serving: Serving, gateway: Gateway, rig: _Rig, wire: Wire) -> Iterator[tuple[Gateway, str]]:+ match serving:+ case "router":+ with gateway.scenario() as scenario:+ yield gateway, scenario.model(model=_MODEL, api_base=wire.url, api_key=_GEMINI_KEY, num_retries=0)+ case "configless":+ yield rig.proxy.gateway, _MODEL+++def _forwarded(headers: Mapping[str, str], name: str) -> str | None:+ return headers.get(f"llm_provider-{name}") or headers.get(name)+++def _metadata(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ stored: Final = row["metadata"]+ return JSON_OBJECT.validate_json(stored) if isinstance(stored, str) else object_value(stored)+++def _provider_request_id(row: Mapping[str, JsonValue]) -> JsonValue:+ return object_value(_metadata(row).get("error_information") or {}).get("error_provider_request_id")+++def _rows(call_ids: Sequence[str]) -> Sequence[Mapping[str, JsonValue]]:+ return eventually(+ lambda: read_rows(+ 'SELECT litellm_call_id, status, metadata FROM "LiteLLM_SpendLogs" '+ "WHERE litellm_call_id = ANY(string_to_array(%s, %s))",+ (",".join(call_ids), ","),+ ),+ lambda found: len(found) >= len(call_ids),+ seconds=70,+ )+++def _rows_by_call(call_ids: Sequence[str]) -> Mapping[str, Mapping[str, JsonValue]]:+ rows: Final = _rows(call_ids)+ by_call: Final = MappingProxyType({string_value(row["litellm_call_id"]): row for row in rows})+ assert len(by_call) == len(rows) == len(call_ids), rows+ return by_call+++def _assert_failure_row_names_its_provider_request(call_id: str, marker: str) -> None:+ row: Final = _rows_by_call((call_id,))[call_id]+ assert (row["status"], _provider_request_id(row)) == ("failure", _request_id(marker)), _metadata(row)+++def _assert_one_upstream_call(received: tuple[Request, ...], marker: str, target: str) -> None:+ assert [(request.target.split("?")[0], _newest_marker(request.body.decode())) for request in received] == [+ (target, marker)+ ], [request.target for request in received]+++def _upstream_target(kind: Kind) -> str:+ match kind:+ case "chat":+ return "/models/gemini-3.8-flash:generateContent"+ case "chat_stream" | "messages_stream" | "responses_stream":+ return "/models/gemini-3.8-flash:streamGenerateContent"+++def _route(kind: Kind) -> str:+ match kind:+ case "chat_stream" | "chat":+ return "/v1/chat/completions"+ case "messages_stream":+ return "/v1/messages"+ case "responses_stream":+ return "/v1/responses"+++def _body(call: _Call, model: str) -> Mapping[str, JsonValue]:+ prompt: Final = f"{call.kind} marker-{call.marker}"+ match call.kind:+ case "chat_stream" | "chat":+ return {+ "model": model,+ "stream": call.kind == "chat_stream",+ "messages": [{"role": "user", "content": prompt}],+ "cache": {"no-cache": True},+ }+ case "messages_stream":+ return {"model": model, "stream": True, "max_tokens": 16, "messages": [{"role": "user", "content": prompt}]}+ case "responses_stream":+ return {"model": model, "stream": True, "input": prompt}+++async def _send(client: httpx.AsyncClient, key: str, model: str, call: _Call) -> _Served:+ async with client.stream(+ "POST",+ _route(call.kind),+ json=_body(call, model),+ headers={"Authorization": f"Bearer {key}", **_ANTHROPIC_VERSION},+ ) as response:+ raw: Final = await response.aread()+ return _Served(+ call,+ response.status_code,+ MappingProxyType(dict(response.headers)),+ raw.decode(),+ response.headers["x-litellm-call-id"],+ )+++async def _burst(+ gateway: Gateway, model: str, calls: tuple[_Call, ...], *, tolerate_transport_errors: bool = False+) -> tuple[_Served, ...]:+ async with httpx.AsyncClient(base_url=str(gateway.client.base_url), timeout=60, trust_env=False) as client:+ results: Final = await asyncio.gather(+ *(_send(client, gateway.key, model, call) for call in calls), return_exceptions=tolerate_transport_errors+ )+ for result in results:+ assert not isinstance(result, BaseException) or isinstance(result, httpx.TransportError), repr(result)+ return tuple(result for result in results if isinstance(result, _Served))+++def _data_frames(text: str) -> tuple[dict[str, JsonValue], ...]:+ return tuple(+ JSON_OBJECT.validate_json(line.removeprefix("data: "))+ for line in text.splitlines()+ if line.startswith("data: {")+ )+++def _delta_text(frame: Mapping[str, JsonValue]) -> str:+ choices: Final = frame.get("choices")+ if not isinstance(choices, list) or not choices:+ return ""+ return string_value(object_value(object_value(choices[0])["delta"]).get("content") or "")+++def _assert_provider_headers_forwarded(headers: httpx.Headers, marker: str) -> None:+ forwarded: Final = (_forwarded(headers, "x-request-id"), _forwarded(headers, "retry-after"))+ assert forwarded == (_request_id(marker), "7"), headers+++def _assert_answered_in_its_own_shape(served: _Served, serving: Serving) -> None:+ match served.call.kind:+ case "chat_stream" | "chat":+ error: Final = object_value(JSON_OBJECT.validate_json(served.text)["error"])+ assert (served.status, str(error["code"])) == (429, "429"), served.text+ if (serving, served.call.kind) in _FORWARDS_PROVIDER_HEADERS:+ _assert_provider_headers_forwarded(served.headers, served.call.marker)+ case "messages_stream":+ assert served.status == 200, served.text+ frame: Final = _data_frames(served.text)[-1]+ assert frame["type"] == "error", served.text+ assert object_value(frame["error"])["type"] == "rate_limit_error", frame+ case "responses_stream":+ assert served.status == 200, served.text+ failed: Final = _data_frames(served.text)[-1]+ assert failed["type"] == "response.failed", served.text+ assert object_value(object_value(failed["response"])["error"])["code"] == "rate_limit_exceeded", failed+++def _assert_forwarded_once_each(received: tuple[Request, ...], calls: Sequence[_Call]) -> None:+ upstream: Final = sorted(+ (request.target.split("?")[0], _newest_marker(request.body.decode()) or "") for request in received+ )+ assert upstream == sorted((_upstream_target(call.kind), call.marker) for call in calls), upstream+++def _assert_each_row_names_its_own_provider_request(served: Sequence[_Served]) -> None:+ by_call: Final = _rows_by_call(tuple(item.call_id for item in served))+ observed: Final = {+ item.call.marker: (by_call[item.call_id]["status"], _provider_request_id(by_call[item.call_id]))+ for item in served+ }+ assert observed == {item.call.marker: ("failure", _request_id(item.call.marker)) for item in served}, observed++[email protected]("serving", _SERVINGS)+async def test_chat_stream_open_rate_limit_answers_429_with_the_provider_request_id_like_its_non_stream_twin(+ gateway: Gateway, rig: _Rig, serving: Serving+) -> None:+ with wire_server(_respond, port=rig.port) as wire, _model_on(serving, gateway, rig, wire) as (target, model):+ (twin,) = await _burst(target, model, (_Call("chat", uuid.uuid4().hex),))+ (streamed,) = await _burst(target, model, (_Call("chat_stream", uuid.uuid4().hex),))+ _assert_answered_in_its_own_shape(twin, serving)+ _assert_answered_in_its_own_shape(streamed, serving)+ _assert_forwarded_once_each(wire.drain(), (twin.call, streamed.call))+ _assert_each_row_names_its_own_provider_request((twin, streamed))++[email protected]("serving", _SERVINGS)+def test_openai_sdk_chat_stream_open_rate_limit_raises_with_the_provider_request_id(+ gateway: Gateway, rig: _Rig, serving: Serving+) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_respond, port=rig.port) as wire, _model_on(serving, gateway, rig, wire) as (target, model):+ client: Final = openai.OpenAI(base_url=f"{target.client.base_url}/v1", api_key=target.key, max_retries=0)+ with pytest.raises(openai.RateLimitError) as raised:+ tuple(+ client.chat.completions.create(+ model=model,+ messages=[{"role": "user", "content": f"chat_stream marker-{marker}"}],+ stream=True,+ extra_body={"cache": {"no-cache": True}},+ )+ )+ _assert_one_upstream_call(wire.drain(), marker, _upstream_target("chat_stream"))+ headers: Final = raised.value.response.headers+ if (serving, "chat_stream") in _FORWARDS_PROVIDER_HEADERS:+ _assert_provider_headers_forwarded(headers, marker)+ _assert_failure_row_names_its_provider_request(headers["x-litellm-call-id"], marker)++[email protected]("serving", _SERVINGS)+def test_anthropic_sdk_messages_stream_open_rate_limit_ends_with_a_rate_limit_error_event(+ gateway: Gateway, rig: _Rig, serving: Serving+) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_respond, port=rig.port) as wire, _model_on(serving, gateway, rig, wire) as (target, model):+ client: Final = anthropic.Anthropic(base_url=str(target.client.base_url), api_key=target.key, max_retries=0)+ with pytest.raises(anthropic.APIStatusError) as raised:+ tuple(+ client.messages.create(+ model=model,+ max_tokens=16,+ messages=[{"role": "user", "content": f"messages_stream marker-{marker}"}],+ stream=True,+ )+ )+ _assert_one_upstream_call(wire.drain(), marker, _upstream_target("messages_stream"))+ assert raised.value.status_code == 200, raised.value+ error: Final = object_value(JSON_OBJECT.validate_python(raised.value.body)["error"])+ assert error["type"] == "rate_limit_error", raised.value.body+ _assert_failure_row_names_its_provider_request(raised.value.response.headers["x-litellm-call-id"], marker)++[email protected]("serving", _SERVINGS)+def test_openai_sdk_responses_stream_open_rate_limit_ends_with_a_failed_response(+ gateway: Gateway, rig: _Rig, serving: Serving+) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_respond, port=rig.port) as wire, _model_on(serving, gateway, rig, wire) as (target, model):+ client: Final = openai.OpenAI(base_url=f"{target.client.base_url}/v1", api_key=target.key, max_retries=0)+ raw: Final = client.responses.with_raw_response.create(+ model=model, input=f"responses_stream marker-{marker}", stream=True+ )+ events: Final = tuple(raw.parse())+ _assert_one_upstream_call(wire.drain(), marker, _upstream_target("responses_stream"))+ failed: Final = events[-1]+ assert isinstance(failed, ResponseFailedEvent), events+ assert failed.response.error is not None and failed.response.error.code == "rate_limit_exceeded", failed+ _assert_failure_row_names_its_provider_request(raw.headers["x-litellm-call-id"], marker)+++def test_router_stream_fallback_answers_from_the_healthy_deployment_after_the_stream_open_rate_limit(+ gateway: Gateway, rig: _Rig+) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_respond, port=rig.port) as wire, gateway.scenario() as scenario:+ limited: Final = scenario.model(model=_MODEL, api_base=wire.url, api_key=_GEMINI_KEY, num_retries=0)+ healthy: Final = scenario.model(+ model=_MODEL, api_base=f"{wire.url}{_HEALTHY_PREFIX}", api_key=_GEMINI_KEY, num_retries=0+ )+ with gateway.client.stream(+ "POST",+ "/v1/chat/completions",+ json={+ "model": limited,+ "stream": True,+ "messages": [{"role": "user", "content": f"fallback marker-{marker}"}],+ "fallbacks": [healthy],+ "cache": {"no-cache": True},+ },+ headers={"Authorization": f"Bearer {gateway.key}"},+ timeout=60,+ ) as response:+ text: Final = response.read().decode()+ received: Final = wire.drain()+ assert response.status_code == 200, text+ content: Final = "".join(_delta_text(frame) for frame in _data_frames(text))+ assert content == f"healthy marker-{marker}", text+ assert [(request.target.split("?")[0], _newest_marker(request.body.decode())) for request in received] == [+ (_upstream_target("chat_stream"), marker),+ (f"{_HEALTHY_PREFIX}{_upstream_target('chat_stream')}", marker),+ ], received+++def _pass_through(gateway: Gateway, route: PassThrough, prompt: str) -> httpx.Response:+ match route:+ case "gemini":+ return gateway.client.post(+ "/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent",+ params={"alt": "sse", "key": gateway.key},+ json={"contents": [{"role": "user", "parts": [{"text": prompt}]}]},+ timeout=60,+ )+ case "anthropic":+ return gateway.client.post(+ "/anthropic/v1/messages",+ json={+ "model": "claude-opus-5-5",+ "max_tokens": 16,+ "stream": True,+ "messages": [{"role": "user", "content": prompt}],+ },+ headers={"Authorization": f"Bearer {gateway.key}", **_ANTHROPIC_VERSION},+ timeout=60,+ )+++def _pass_through_target(route: PassThrough) -> str:+ match route:+ case "gemini":+ return "/v1beta/models/gemini-3.8-flash:streamGenerateContent"+ case "anthropic":+ return "/v1/messages"++[email protected]("route", _PASS_THROUGHS)+def test_pass_through_stream_rate_limit_relays_the_provider_status_and_headers(rig: _Rig, route: PassThrough) -> None:+ marker: Final = uuid.uuid4().hex+ with wire_server(_respond, port=rig.port) as wire:+ response: Final = _pass_through(rig.proxy.gateway, route, f"pass-through marker-{marker}")+ _assert_one_upstream_call(wire.drain(), marker, _pass_through_target(route))+ assert response.status_code == 429, response.text+ assert response.headers["x-request-id"] == _request_id(marker), response.headers+ assert response.headers["retry-after"] == "7", response.headers+ assert "scripted rate limit" in response.text, response.text+ call_id: Final = response.headers["x-litellm-call-id"]+ assert _rows_by_call((call_id,))[call_id]["status"] == "failure", call_id++[email protected]("serving", _SERVINGS)+async def test_mixed_burst_answers_and_logs_each_stream_open_rate_limit_with_its_own_provider_request_id(+ gateway: Gateway, rig: _Rig, serving: Serving+) -> None:+ calls: Final = tuple(_Call(_KINDS[index % len(_KINDS)], uuid.uuid4().hex) for index in range(32))+ with wire_server(_respond, port=rig.port) as wire, _model_on(serving, gateway, rig, wire) as (target, model):+ served: Final = await _burst(target, model, calls)+ assert len(served) == len(calls)+ for item in served:+ _assert_answered_in_its_own_shape(item, serving)+ _assert_forwarded_once_each(wire.drain(), calls)+ _assert_each_row_names_its_own_provider_request(served)+++@dataclass(frozen=True, slots=True)+class _Held:+ release: threading.Event+ markers: SimpleQueue[str]++ def respond(self, request: Request) -> Reply:+ marker: Final = _newest_marker(request.body.decode())+ assert marker is not None, request.body+ self.markers.put(marker)+ assert self.release.wait(timeout=60), "The burst was never released"+ return _respond(request)+++def _held() -> _Held:+ return _Held(threading.Event(), SimpleQueue())+++def _stream_calls(count: int) -> tuple[_Call, ...]:+ return tuple(_Call("chat_stream", uuid.uuid4().hex) for _ in range(count))+++async def _held_burst(gateway: Gateway, calls: tuple[_Call, ...], held: _Held) -> asyncio.Task[tuple[_Served, ...]]:+ burst: Final = asyncio.create_task(_burst(gateway, _MODEL, calls, tolerate_transport_errors=True))+ await asyncio.to_thread(eventually, held.markers.qsize, lambda size: size == len(calls), 60)+ return burst+++def _open_upstream_connections(pid: int, upstream: str) -> int:+ port: Final = urlsplit(upstream).port+ return sum(+ 1+ for connection in psutil.Process(pid).net_connections(kind="tcp")+ if connection.status == psutil.CONN_ESTABLISHED and connection.raddr and connection.raddr.port == port+ )+++async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering_each_stream_open_rate_limit(rig: _Rig) -> None:+ calls: Final = _stream_calls(20)+ held: Final = _held()+ with wire_server(held.respond, port=rig.port) as wire:+ workers: Final = eventually(rig.proxy.worker_pids, lambda pids: len(pids) == 2, seconds=30)+ burst: Final = await _held_burst(rig.proxy.gateway, calls, held)+ held_by: Final = MappingProxyType({pid: _open_upstream_connections(pid, wire.url) for pid in workers})+ assert sum(held_by.values()) == 20, held_by+ victim_pid, survivor_pid = sorted(workers, key=held_by.__getitem__)+ with rig.proxy.replacing_worker(victim_pid) as kill:+ kill.freeze()+ await asyncio.to_thread(kill)+ held.release.set()+ served: Final = await burst+ assert held_by[survivor_pid] >= 10, held_by+ assert len(served) == held_by[survivor_pid], (held_by, len(served))+ for item in served:+ _assert_answered_in_its_own_shape(item, "configless")+ (answered,) = await _burst(rig.proxy.gateway, _MODEL, _stream_calls(1))+ _assert_answered_in_its_own_shape(answered, "configless")+ _assert_forwarded_once_each(wire.drain(), (*calls, answered.call))+ _assert_each_row_names_its_own_provider_request((*served, answered))++[email protected](4 * graceful_stop_seconds() + 240)+async def test_proxy_sigterm_mid_burst_answers_each_in_flight_stream_and_the_restarted_proxy_serves(+ gateway: Gateway, tmp_path: Path+) -> None:+ port: Final = _free_port()+ calls: Final = _stream_calls(20)+ held: Final = _held()+ with wire_server(held.respond, port=port) as wire:+ with _configless(gateway, tmp_path, port) as owned:+ burst: Final = await _held_burst(owned.proxy.gateway, calls, held)+ owned.proxy.begin_shutdown()+ held.release.set()+ served: Final = await burst+ await asyncio.to_thread(+ eventually, owned.proxy.process.poll, lambda code: code is not None, graceful_stop_seconds()+ )+ assert len(served) == len(calls), len(served)+ for item in served:+ _assert_answered_in_its_own_shape(item, "configless")+ _assert_forwarded_once_each(wire.drain(), calls)+ _assert_each_row_names_its_own_provider_request(served)+ with _configless(gateway, tmp_path, port) as restarted:+ (answered,) = await _burst(restarted.proxy.gateway, _MODEL, _stream_calls(1))+ _assert_answered_in_its_own_shape(answered, "configless")+ _assert_forwarded_once_each(wire.drain(), (answered.call,))+ _assert_each_row_names_its_own_provider_request((answered,))diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.pyindex a604e61b9c2..07cdbc15baa 100644--- a/tests/unit/litellm_core_utils/test_streaming_handler.py+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py@@ -931,6 +931,40 @@ async def test_bridged_stream_mid_stream_fallback_error_is_rebuilt_around_the_prassert excinfo.value.generated_content == ""[email protected]("sync_mode", [True, False])+async def test_streaming_rate_limit_midstream_fallback_keeps_provider_headers(logging_obj: Logging, sync_mode: bool):+ """MidStreamFallbackError keeps the provider headers the non-streaming RateLimitError carries."""+ from litellm.exceptions import MidStreamFallbackError+ from litellm.llms.vertex_ai.common_utils import VertexAIError++ provider_headers: Final = {"retry-after": "3", "x-request-id": "req-abc123"}++ def _raise_rate_limit(**kwargs: object) -> NoReturn:+ raise VertexAIError(status_code=429, message="Resource exhausted.", headers=provider_headers)++ async def _araise_rate_limit(**kwargs: object) -> NoReturn:+ _raise_rate_limit(**kwargs)++ response: Final = CustomStreamWrapper(+ completion_stream=None,+ model="gemini-3-flash-preview",+ logging_obj=logging_obj,+ custom_llm_provider="vertex_ai_beta",+ make_call=_raise_rate_limit if sync_mode else _araise_rate_limit,+ )++ async def _read_first_chunk() -> object:+ return next(response) if sync_mode else await response.__anext__()++ with pytest.raises(MidStreamFallbackError) as excinfo:+ await _read_first_chunk()++ assert excinfo.value.status_code == 429+ assert excinfo.value.litellm_response_headers.get("retry-after") == "3"+ assert excinfo.value.litellm_response_headers.get("x-request-id") == "req-abc123"++def test_sync_streaming_bad_request_not_midstream(logging_obj: Logging):"""Ensure __next__ raises BadRequestError (400) directly, not MidStreamFallbackError.