Skip to content

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]

fix(router): redact fallback tracebacks at the call site and cover the sync deferred stream (#35843)

Yassin Kortam54fb717de194
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 21334507d02..0b9a2d5e4c0 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -2688,7 +2688,6 @@ class ProxyBaseLLMRequestProcessing:
_response_headers: Final = getattr(_response, "headers", None)
if _response_headers:
headers = get_response_headers(dict(_response_headers))
- headers = {k: v for k, v in headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
headers.update(custom_headers)
# Call response headers hook for failure
@@ -2704,16 +2703,15 @@ class ProxyBaseLLMRequestProcessing:
except Exception:
pass
- headers = {k: v for k, v in headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
+ safe_headers: Final = {k: v for k, v in headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
- self._apply_router_cooldown_retry_after(headers, e)
+ self._apply_router_cooldown_retry_after(safe_headers, e)
if isinstance(e, ProxyException):
- merged_headers = {
- **e.headers,
- **{k: v if isinstance(v, str) else str(v) for k, v in headers.items()},
+ e.headers = {
+ **{k: v for k, v in e.headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS},
+ **{k: v if isinstance(v, str) else str(v) for k, v in safe_headers.items()},
}
- e.headers = {k: v for k, v in merged_headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
raise e
if isinstance(e, HTTPException):
@@ -2730,7 +2728,7 @@ class ProxyBaseLLMRequestProcessing:
param=getattr(e, "param", "None"),
code=getattr(e, "status_code", status.HTTP_400_BAD_REQUEST),
provider_specific_fields=merged_fields,
- headers=headers,
+ headers=safe_headers,
)
elif isinstance(e, httpx.HTTPStatusError):
# Handle httpx.HTTPStatusError - extract actual error from response
@@ -2756,7 +2754,7 @@ class ProxyBaseLLMRequestProcessing:
type="invalid_request_error",
param=None,
code=status.HTTP_400_BAD_REQUEST,
- headers=headers,
+ headers=safe_headers,
)
# Extract status_code from the exception if it carries one.
# Provider exceptions (NotFoundError, BadRequestError, GeminiError,
@@ -2775,7 +2773,7 @@ class ProxyBaseLLMRequestProcessing:
openai_code=getattr(e, "code", None),
code=_code,
provider_specific_fields=getattr(e, "provider_specific_fields", None),
- headers=headers,
+ headers=safe_headers,
)
#########################################################
diff --git a/litellm/router.py b/litellm/router.py
index a0eb6e91c0c..39d5080a33d 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -1832,6 +1832,13 @@ class Router:
llm_provider="",
)
+ if (
+ isinstance(response, CustomStreamWrapper)
+ and response.completion_stream is None
+ and response.make_call is not None
+ ):
+ response.fetch_sync_stream()
+
# Wrap streaming responses so MidStreamFallbackError (raised
# during iteration) triggers the Router's fallback chain.
if isinstance(response, CustomStreamWrapper):
@@ -6120,7 +6127,8 @@ class Router:
"""
Common utilities for async_function_with_fallbacks
"""
- verbose_router_logger.debug("Traceback", exc_info=True)
+ if verbose_router_logger.isEnabledFor(logging.DEBUG):
+ verbose_router_logger.debug("Traceback%s", redact_string(traceback.format_exc()))
original_exception: Final = e
fallback_model_group = None
original_model_group: Final[str | None] = kwargs.get("model")
@@ -6336,17 +6344,17 @@ class Router:
except Exception as new_exception:
parent_otel_span: Final = _get_parent_otel_span_from_kwargs(kwargs)
fallback_failure_exception_str = redact_string(str(new_exception))
- cooldown_info = await _async_get_cooldown_deployments_with_debug_info(
+ cooldown_info: Final = await _async_get_cooldown_deployments_with_debug_info(
litellm_router_instance=self,
parent_otel_span=parent_otel_span,
)
verbose_router_logger.error(
"litellm.router.py::async_function_with_fallbacks() - "
- "Error occurred while trying to do fallbacks - %s\n"
+ "Error occurred while trying to do fallbacks - %s\n%s\n"
"Debug Information:\nCooldown Deployments=%s",
fallback_failure_exception_str,
+ redact_string(traceback.format_exc()),
cooldown_info,
- exc_info=True,
)
if hasattr(original_exception, "message") and litellm.expose_router_debug_in_errors:
diff --git a/tests/test_litellm/test_redact_string_in_error_paths.py b/tests/test_litellm/test_redact_string_in_error_paths.py
index 4a624017ea2..d01a9da6617 100644
--- a/tests/test_litellm/test_redact_string_in_error_paths.py
+++ b/tests/test_litellm/test_redact_string_in_error_paths.py
@@ -193,13 +193,22 @@ class TestProxyStreamingDataGeneratorRedaction:
class TestRouterFallbackFailureTracebackRedaction:
- """Test the fallback-failure error log in router.py's
- async_function_with_fallbacks_common_utils. A prior version passed exc_info=True
- alongside an already-redacted message, which bypasses redact_string() entirely
- since the stdlib logging module renders exc_info separately from the message."""
+ """Test the fallback-failure logs in router.py's
+ async_function_with_fallbacks_common_utils. Both call sites must redact the
+ traceback at the call site with redact_string() rather than hand a live
+ exception to exc_info=True. SecretRedactionFilter rewrites record.exc_text,
+ but record.exc_info stays an exception object no filter can rewrite, so any
+ handler that renders exc_info itself (Datadog and OTel log bridges do) would
+ receive the unredacted secret."""
@pytest.mark.asyncio
async def test_fallback_failure_does_not_leak_secret_via_exc_info(self, caplog):
+ """The helper is driven from inside an `except` block because that is the only
+ way production reaches it, and the entry-point debug log takes its traceback
+ from the active exception. With no exception in flight sys.exc_info() is empty,
+ so an exc_info=True regression there would degrade to (None, None, None) and
+ this test would pass against it.
+ """
import litellm
router = litellm.Router(
@@ -221,24 +230,39 @@ class TestRouterFallbackFailureTracebackRedaction:
"litellm.router.run_async_fallback",
new=AsyncMock(side_effect=RuntimeError(f"boom api_key={secret}")),
):
- with caplog.at_level(logging.ERROR, logger="LiteLLM Router"):
- with pytest.raises(Exception):
- await router.async_function_with_fallbacks_common_utils(
- e=Exception("original failure"),
- disable_fallbacks=False,
- fallbacks=[{"gpt-3.5-turbo": ["claude-3-haiku"]}],
- context_window_fallbacks=None,
- content_policy_fallbacks=None,
- model_group="gpt-3.5-turbo",
- args=(),
- kwargs={"model": "gpt-3.5-turbo"},
- )
+ try:
+ raise ValueError(f"primary deployment failed api_key={secret}")
+ except ValueError as original_exception:
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM Router"):
+ with pytest.raises(Exception):
+ await router.async_function_with_fallbacks_common_utils(
+ e=original_exception,
+ disable_fallbacks=False,
+ fallbacks=[{"gpt-3.5-turbo": ["claude-3-haiku"]}],
+ context_window_fallbacks=None,
+ content_policy_fallbacks=None,
+ model_group="gpt-3.5-turbo",
+ args=(),
+ kwargs={"model": "gpt-3.5-turbo"},
+ )
+
+ debug_records = [r for r in caplog.records if r.levelno == logging.DEBUG]
+ assert debug_records, "expected the entry-point debug log, which carries the active traceback"
error_records = [r for r in caplog.records if r.levelno == logging.ERROR]
assert error_records, "expected an error log for the fallback failure"
- for record in error_records:
+ assert any(
+ "Cooldown Deployments" in r.getMessage() for r in error_records
+ ), "expected the fallback-failure log, not an unrelated error"
+
+ for record in caplog.records:
assert secret not in record.getMessage()
assert secret not in (record.exc_text or "")
+ rendered_exc_info = "".join(traceback.format_exception(*record.exc_info)) if record.exc_info else ""
+ assert secret not in rendered_exc_info, (
+ f"{record.levelname} record passed a live exception to exc_info; "
+ "no logging filter can redact record.exc_info"
+ )
def _make_mock_ingest_options():
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index 33aab1cf708..8f35597768f 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -6343,8 +6343,9 @@ async def test_acompletion_deferred_stream_skipped_when_stream_already_set():
return
yield
+ noop_stream = noop_aiter()
already_set_wrapper = CustomStreamWrapper(
- completion_stream=noop_aiter(),
+ completion_stream=noop_stream,
model="openai/gpt-4o",
logging_obj=logging_obj,
custom_llm_provider="openai",
@@ -6376,6 +6377,89 @@ async def test_acompletion_deferred_stream_skipped_when_stream_already_set():
)
assert result is not None, "should return a streaming wrapper without errors"
+ assert already_set_wrapper.completion_stream is noop_stream, "completion_stream must not be re-fetched"
+ await noop_stream.aclose()
+
+
+def test_completion_deferred_stream_error_propagates_through_completion():
+ """Regression: the sync router path needs the same eager fetch as the async one.
+
+ A deferred-stream CustomStreamWrapper hands back a wrapper whose HTTP call has
+ not happened yet, so without fetch_sync_stream() the provider error surfaces on
+ first iteration, outside _completion's except block. The deployment is then never
+ marked failed and function_with_fallbacks never sees the error.
+ """
+ import litellm as _litellm
+
+ rate_limit_err = _litellm.RateLimitError(
+ message="Resource exhausted",
+ llm_provider="vertex_ai",
+ model="gemini-2.0-flash",
+ )
+ make_call_invocations = []
+
+ def failing_make_call(**kwargs):
+ make_call_invocations.append(kwargs)
+ raise rate_limit_err
+
+ router = _make_router_with_vertex_and_fallback()
+ deferred_wrapper = _make_deferred_stream_wrapper(failing_make_call)
+
+ with patch("litellm.completion", return_value=deferred_wrapper):
+ with pytest.raises(_litellm.RateLimitError):
+ router._completion(
+ model="vertex_ai/gemini-2.0-flash",
+ messages=[{"role": "user", "content": "Hello"}],
+ stream=True,
+ specific_deployment=router.model_list[0],
+ )
+
+ assert len(make_call_invocations) == 1, (
+ "the deferred HTTP call must run inside _completion's try block; "
+ "without the eager fetch_sync_stream() fix it is deferred to first iteration"
+ )
+
+
+def test_completion_deferred_stream_skipped_when_stream_already_set():
+ """A non-deferred sync provider already has completion_stream populated, so the
+ eager fetch must be skipped and make_call left untouched.
+ """
+ from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
+
+ def would_fail(**kwargs):
+ raise RuntimeError("should not be called")
+
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {"litellm_params": {}}
+ already_set_stream = iter([])
+
+ already_set_wrapper = CustomStreamWrapper(
+ completion_stream=already_set_stream,
+ model="openai/gpt-4o",
+ logging_obj=logging_obj,
+ custom_llm_provider="openai",
+ make_call=would_fail,
+ )
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "my-model",
+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-fake"},
+ }
+ ],
+ )
+
+ with patch("litellm.completion", return_value=already_set_wrapper):
+ result = router._completion(
+ model="openai/gpt-4o",
+ messages=[{"role": "user", "content": "Hello"}],
+ stream=True,
+ specific_deployment=router.model_list[0],
+ )
+
+ assert result is not None, "should return a streaming wrapper without errors"
+ assert already_set_wrapper.completion_stream is already_set_stream, "completion_stream must not be re-fetched"
class TestAdvisorSubCallCooldown: