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): lift standard_logging_object onto request_data before the logging object is popped
mateo-berrib477d0967a4b
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex a743526e975..58ac7882cb8 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -517,6 +517,34 @@ def _failure_usage_to_lift(return estimated_usage, 0.0+_EMPTY_LIFT: Final = MappingProxyType({})+++def _failure_fields_to_lift(request_data: Mapping[str, object]) -> Mapping[str, object]:+ """Failure-path callbacks run after ``litellm_logging_obj`` is popped from+ request_data (it is not serialisable), so the caller merges these fields+ onto request_data first: the first-handoff instant for preprocessing+ latency, recovered or estimated usage for token counts, and the standard+ logging object for deployment attribution on failed-request spend logs."""+ _logging_obj: Final = request_data.get("litellm_logging_obj")+ if _logging_obj is None:+ return _EMPTY_LIFT+ _model_call_details: Final = getattr(_logging_obj, "model_call_details", {})+ _first_handoff: Final = _model_call_details.get("first_api_call_start_time")+ _usage_to_lift: Final = _failure_usage_to_lift(+ model_call_details=_model_call_details,+ request_body=request_data,+ dispatched=_first_handoff is not None,+ )+ _entries: Final = (+ ("first_api_call_start_time", _first_handoff),+ ("combined_usage_object", None if _usage_to_lift is None else _usage_to_lift[0]),+ ("response_cost", None if _usage_to_lift is None else _usage_to_lift[1]),+ ("standard_logging_object", _model_call_details.get("standard_logging_object")),+ )+ return MappingProxyType({key: value for key, value in _entries if value is not None})++@dataclass(frozen=True)class _CallbackCapabilities:"""Cached per-hook capability flags derived from ``litellm.callbacks``.@@ -2294,29 +2322,7 @@ class ProxyLogging:original_exception=original_exception,)- # Lift the first-handoff instant onto request_data (top-level- # internal key, not metadata) so failure-path callbacks can still- # compute preprocessing latency after the logging object is popped.- _logging_obj: Final = request_data.get("litellm_logging_obj")- if _logging_obj is not None:- _model_call_details: Final = getattr(_logging_obj, "model_call_details", {})- _first_handoff: Final = _model_call_details.get("first_api_call_start_time")- if _first_handoff is not None:- request_data["first_api_call_start_time"] = _first_handoff-- # Lift recovered partial-stream usage, or an estimated input-side- # usage for a dispatched failure, onto request_data so the- # failure-path spend callbacks (which run after the logging object- # is popped) record real token counts instead of zero.- _usage_to_lift: Final = _failure_usage_to_lift(- model_call_details=_model_call_details,- request_body=request_data,- dispatched=_first_handoff is not None,- )- if _usage_to_lift is not None:- _lifted_usage, _lifted_cost = _usage_to_lift- request_data["combined_usage_object"] = _lifted_usage- request_data["response_cost"] = _lifted_cost+ request_data.update(_failure_fields_to_lift(request_data))# Remove before callbacks iterate — not serialisablerequest_data.pop("litellm_logging_obj", None)diff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.pyindex d6cf0e30139..c80130b44da 100644--- a/tests/test_litellm/proxy/test_proxy_utils.py+++ b/tests/test_litellm/proxy/test_proxy_utils.py@@ -478,6 +478,59 @@ class TestPostCallFailureHookLiftsRecoveredPartialSpend:assert "response_cost" not in request_data+class TestPostCallFailureHookLiftsStandardLoggingObject:+ """Failure callbacks read standard_logging_object from request_data, but+ post_call_failure_hook pops litellm_logging_obj before they run. The hook+ must lift the logging obj's standard_logging_object onto request_data so+ failed-request spend logs keep deployment attribution (LIT-5795).+ """++ async def _run(self, request_data):+ from unittest.mock import AsyncMock, patch++ from litellm.proxy._types import UserAPIKeyAuth++ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ proxy_logging_obj.alert_types = []+ with patch.object(proxy_logging_obj, "update_request_status", new=AsyncMock()):+ await proxy_logging_obj.post_call_failure_hook(+ request_data=request_data,+ original_exception=Exception("boom"),+ user_api_key_dict=UserAPIKeyAuth(),+ )++ @pytest.mark.asyncio+ async def test_lifts_standard_logging_object(self):+ sl_object = {"model_id": "mid-123", "model_group": "group-x"}+ logging_obj = MagicMock()+ logging_obj.model_call_details = {"standard_logging_object": sl_object}+ request_data = {"litellm_logging_obj": logging_obj, "metadata": {}}+ await self._run(request_data)+ assert request_data["standard_logging_object"] is sl_object+ assert "litellm_logging_obj" not in request_data++ @pytest.mark.asyncio+ async def test_logging_obj_value_overwrites_preexisting_key(self):+ authoritative = {"model_id": "from-logging-obj"}+ logging_obj = MagicMock()+ logging_obj.model_call_details = {"standard_logging_object": authoritative}+ request_data = {+ "litellm_logging_obj": logging_obj,+ "standard_logging_object": {"model_id": "client-injected"},+ "metadata": {},+ }+ await self._run(request_data)+ assert request_data["standard_logging_object"] is authoritative++ @pytest.mark.asyncio+ async def test_no_standard_logging_object_is_noop(self):+ logging_obj = MagicMock()+ logging_obj.model_call_details = {}+ request_data = {"litellm_logging_obj": logging_obj, "metadata": {}}+ await self._run(request_data)+ assert "standard_logging_object" not in request_data++class TestPostCallFailureHookEstimatesDispatchedInputTokens:"""A non-stream request that failed after dispatch (timeout, providererror) consumed provider-billed input tokens but recovered no usage.