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(proxy): guard streaming deferred init with try/finally, fix test imports
michelligabriele0057452485d2
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 1db8327482d..0e3e89c5313 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -1345,76 +1345,81 @@ class ProxyBaseLLMRequestProcessing:from litellm.proxy.utils import _check_and_merge_model_level_guardrails_response = assembled_response- _unified_guardrail = UnifiedLLMGuardrails()- guardrail_data = _check_and_merge_model_level_guardrails(- data=captured_data, llm_router=_global_llm_router- )- for cb in litellm.callbacks:- if not isinstance(cb, CustomGuardrail):- continue- if not cb.should_run_guardrail(- data=guardrail_data,- event_type=GuardrailEventHooks.post_call,- ):- continue- try:- guardrail_result = None- if "apply_guardrail" in type(cb).__dict__:- guardrail_data["guardrail_to_apply"] = cb- guardrail_result = (- await _unified_guardrail.async_post_call_success_hook(+ try:+ _unified_guardrail = UnifiedLLMGuardrails()+ guardrail_data = _check_and_merge_model_level_guardrails(+ data=captured_data, llm_router=_global_llm_router+ )+ for cb in litellm.callbacks:+ if not isinstance(cb, CustomGuardrail):+ continue+ if not cb.should_run_guardrail(+ data=guardrail_data,+ event_type=GuardrailEventHooks.post_call,+ ):+ continue+ try:+ guardrail_result = None+ if "apply_guardrail" in type(cb).__dict__:+ guardrail_data["guardrail_to_apply"] = cb+ guardrail_result = (+ await _unified_guardrail.async_post_call_success_hook(+ user_api_key_dict=captured_user_api_key_dict,+ data=guardrail_data,+ response=_response,+ )+ )+ else:+ guardrail_result = await cb.async_post_call_success_hook(user_api_key_dict=captured_user_api_key_dict,data=guardrail_data,response=_response,)+ if guardrail_result is not None:+ _response = guardrail_result+ except Exception as e:+ verbose_proxy_logger.exception(+ "Error running post-call guardrail %s on streaming response: %s",+ getattr(cb, "guardrail_name", type(cb).__name__),+ e,)- else:- guardrail_result = await cb.async_post_call_success_hook(- user_api_key_dict=captured_user_api_key_dict,- data=guardrail_data,- response=_response,+ if isinstance(e, HTTPException) and hasattr(+ captured_logging_obj, "model_call_details"+ ):+ captured_logging_obj.model_call_details.setdefault(+ "metadata", {}+ )["guardrail_blocked"] = True+ except Exception as e:+ verbose_proxy_logger.exception(+ "Error in deferred streaming guardrail initialization: %s", e,+ )+ finally:+ try:+ asyncio.create_task(+ captured_logging_obj.async_success_handler(+ _response,+ cache_hit=cache_hit,+ start_time=None,+ end_time=None,)- if guardrail_result is not None:- _response = guardrail_result+ )except Exception as e:verbose_proxy_logger.exception(- "Error running post-call guardrail %s on streaming response: %s",- getattr(cb, "guardrail_name", type(cb).__name__),- e,+ "Error in deferred streaming async logging: %s", e,)- if isinstance(e, HTTPException) and hasattr(- captured_logging_obj, "model_call_details"- ):- captured_logging_obj.model_call_details.setdefault(- "metadata", {}- )["guardrail_blocked"] = True- try:- asyncio.create_task(- captured_logging_obj.async_success_handler(+ try:+ executor.submit(+ captured_logging_obj.success_handler,_response,cache_hit=cache_hit,start_time=None,end_time=None,)- )- except Exception as e:- verbose_proxy_logger.exception(- "Error in deferred streaming async logging: %s", e,- )-- try:- executor.submit(- captured_logging_obj.success_handler,- _response,- cache_hit=cache_hit,- start_time=None,- end_time=None,- )- except Exception as e:- verbose_proxy_logger.exception(- "Error in deferred streaming sync logging: %s", e,- )+ except Exception as e:+ verbose_proxy_logger.exception(+ "Error in deferred streaming sync logging: %s", e,+ )async def _handle_llm_api_exception(self,diff --git a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.pyindex f5c9eeba1c6..c4d2dce5876 100644--- a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py+++ b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py@@ -20,7 +20,6 @@ from typing import Anyfrom unittest.mock import MagicMock, patchimport pytest-from fastapi import HTTPExceptionsys.path.insert(0, os.path.abspath("../../../.."))@@ -233,6 +232,8 @@ async def test_deferred_logging_fires_on_guardrail_exception():If post_call_success_hook raises (e.g., guardrail blocks content),the deferred logging closure must still fire (via try/finally)."""+ from fastapi import HTTPException # noqa: local import for test isolation+enqueue_called = Falsedef mock_enqueue():@@ -470,6 +471,8 @@ class TestDeferredStreamingClosure:"""If a guardrail raises HTTPException, the production_run_deferred_stream_guardrails must still fire loggingand set guardrail_blocked in metadata."""+ from fastapi import HTTPException # noqa: local import for test isolation+logging_called = Falseclass BlockingGuardrail(CustomGuardrail):@@ -902,3 +905,40 @@ class TestDeferredStreamingClosure:f"{name} must be called"assert received_data_per_guardrail[name].get("_merged_marker") is True, \f"{name} must receive guardrail_data (merged), not captured_data"++ @pytest.mark.asyncio+ async def test_logging_fires_even_if_guardrail_init_raises(self):+ """If _check_and_merge_model_level_guardrails raises during+ initialization, logging must still fire via the try/finally guard.+ This prevents silent logging loss on transient init errors."""+ logging_called = False++ mock_logging_obj = MagicMock()+ mock_logging_obj.model_call_details = {"metadata": {}}++ async def track_async_success(*args, **kwargs):+ nonlocal logging_called+ logging_called = True++ mock_logging_obj.async_success_handler = track_async_success++ def exploding_merge(data, llm_router):+ raise RuntimeError("Simulated init failure")++ with patch(+ "litellm.proxy.utils._check_and_merge_model_level_guardrails",+ side_effect=exploding_merge,+ ):+ await ProxyBaseLLMRequestProcessing._run_deferred_stream_guardrails(+ captured_data={"model": "gpt-4", "metadata": {}},+ captured_user_api_key_dict=UserAPIKeyAuth(api_key="test"),+ captured_logging_obj=mock_logging_obj,+ assembled_response=MagicMock(),+ cache_hit=False,+ )++ await asyncio.sleep(0)+ await asyncio.sleep(0)++ assert logging_called is True, \+ "Logging must fire even when guardrail initialization raises"