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(router): log each dropped /v1/messages attempt through its own logging copy and open the retry without its usage (#45194)
Mateo Wang820725661e86
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex a59672b5cb2..d75d35e4531 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -604,6 +604,10 @@ def _timestamp_seconds(moment: object) -> float | None:return None+def same_attempt_marker(first: object, second: object) -> bool:+ return first is second or first == second++class Logging(LiteLLMLoggingBaseClass):global \supabaseClient, \@@ -625,6 +629,7 @@ class Logging(LiteLLMLoggingBaseClass):classifier_input: Mapping[str, JsonValue] | None = Nonebaseline_cache_context: "BaselineCacheContext | None" = Nonebaseline_observation: "CapturedBaselineObservation | None" = None+ _on_failure_payload_built: "Callable[[], None] | None" = None@propertydef _defer_async_logging(self) -> bool:@@ -852,6 +857,7 @@ class Logging(LiteLLMLoggingBaseClass):"litellm_call_id": litellm_call_id,"start_time": start_time,"first_api_call_start_time": None,+ "current_attempt_api_call_start_time": None,"litellm_params": litellm_params,}new_call.streaming_chunks = []@@ -1602,7 +1608,9 @@ class Logging(LiteLLMLoggingBaseClass):# A proxy-gate failure (auth, rate limit, client disconnect) fires pre_call for its callbacks# without any provider handoff, so it must not stamp the handoff instants.if LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL not in self.model_call_details:- self.model_call_details["api_call_start_time"] = datetime.datetime.now()+ api_call_start_time: Final = datetime.datetime.now()+ self.model_call_details["api_call_start_time"] = api_call_start_time+ self.model_call_details["current_attempt_api_call_start_time"] = api_call_start_time# Set-once first provider-handoff instant. api_call_start_time# is overwritten on every retry, so it can't measure one-time# preprocessing; pinning the first attempt excludes retry loops@@ -1610,9 +1618,7 @@ class Logging(LiteLLMLoggingBaseClass):# litellm_params["metadata"] (caller request metadata, typed# Dict[str, str], echoed downstream; a datetime breaks it).if self.model_call_details.get("first_api_call_start_time") is None:- self.model_call_details["first_api_call_start_time"] = self.model_call_details[- "api_call_start_time"- ]+ self.model_call_details["first_api_call_start_time"] = api_call_start_time# Input Integration Logging -> If you want to log the fact that an attempt to call the model was madecallbacks: Final = (*self._without_replaced_global_callbacks(litellm.input_callback),@@ -2474,12 +2480,37 @@ class Logging(LiteLLMLoggingBaseClass):attempt.model_call_details = dict(self.model_call_details)return attempt+ def dispatch_attempt_failure_handlers(+ self, exception: Exception, traceback_exception: str+ ) -> Coroutine[None, None, None]:+ shared_payload: Final = self.model_call_details.get("standard_logging_object")+ attempt_marker: Final = self.model_call_details.get("current_attempt_api_call_start_time")+ attempt: Final = self.attempt_scoped_copy()++ def publish() -> None:+ attempt_payload: Final = attempt.model_call_details.get("standard_logging_object")+ current_marker: Final = self.model_call_details.get("current_attempt_api_call_start_time")+ if (+ attempt_payload is not None+ and self.model_call_details.get("standard_logging_object") is shared_payload+ and same_attempt_marker(current_marker, attempt_marker)+ ):+ self.model_call_details["standard_logging_object"] = attempt_payload++ attempt._on_failure_payload_built = publish++ async def dispatch() -> None:+ await attempt.dispatch_failure_handlers(exception, traceback_exception, prefer_async_handlers=True)++ return dispatch()+def carry_failed_attempt_usage(self) -> None:"""Move what a failed earlier attempt stashed off the retry sharing this logging object, so the retry logs itsown usage while the request's failure log still bills every attempt."""usage: Final = self.model_call_details.pop("combined_usage_object", None)response_cost: Final = self.model_call_details.pop("response_cost", None)if isinstance(usage, Usage):+ self.model_call_details["current_attempt_api_call_start_time"] = Noneself.model_call_details["failed_attempts_usage"] = (*self.model_call_details.get("failed_attempts_usage", ()),(usage, float(response_cost) if isinstance(response_cost, (int, float)) else 0.0),@@ -2593,6 +2624,10 @@ class Logging(LiteLLMLoggingBaseClass):"""returnself.model_call_details[f"has_logged_{event_type}"] = True+ if event_type == "async_failure":+ self.model_call_details["async_failure_logged_attempt"] = self.model_call_details.get(+ "current_attempt_api_call_start_time"+ )returndef has_run_logging(@@ -4410,7 +4445,8 @@ class Logging(LiteLLMLoggingBaseClass):start_time=start_time,end_time=end_time,)-+ if self._on_failure_payload_built is not None:+ self._on_failure_payload_built()callbacks: Final = self.get_combined_callback_list(dynamic_success_callbacks=self.dynamic_async_failure_callbacks,global_callbacks=litellm._async_failure_callback,diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 5e43157a55d..f994baa52b1 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -2283,12 +2283,7 @@ class CustomStreamWrapper:traceback_exception = traceback.format_exc()## ADD DEBUG INFORMATION - E.G. LITELLM REQUEST TIMEOUTtraceback_exception += f"\nLiteLLM Default Request Timeout - {litellm.request_timeout}"- if self.logging_obj is not None:- self._record_partial_usage_for_failure()- ## LOGGING- self._failure_logging = asyncio.create_task(- self.logging_obj.dispatch_failure_handlers(e, traceback_exception, prefer_async_handlers=True)- )+ self._dispatch_stream_failure(e, traceback_exception)await self.aclose()self._handle_stream_fallback_error(e)except (httpx.ReadError, httpx.RemoteProtocolError) as e:@@ -2389,16 +2384,20 @@ class CustomStreamWrapper:return processed_chunkdef _log_stream_failure_and_raise(self, e: Exception) -> NoReturn:- traceback_exception: Final = traceback.format_exc()- if self.logging_obj is not None:- self._record_partial_usage_for_failure()- ## LOGGING- self._failure_logging = asyncio.create_task(- self.logging_obj.dispatch_failure_handlers(e, traceback_exception, prefer_async_handlers=True)- )+ self._dispatch_stream_failure(e, traceback.format_exc())self._handle_stream_fallback_error(e)- async def wait_for_failure_logging(self, timeout: float) -> None:+ def _dispatch_stream_failure(self, e: Exception, traceback_exception: str) -> None:+ self._record_partial_usage_for_failure()+ self._failure_logging = asyncio.create_task(+ self.logging_obj.dispatch_attempt_failure_handlers(e, traceback_exception)+ )++ @property+ def has_dispatched_failure_logging(self) -> bool:+ return self._failure_logging is not None++ async def wait_for_failure_logging(self, timeout: float | None) -> None:"""Let this stream's failure log read its own deployment before a fallback reuses the logging object."""if self._failure_logging is None:return@@ -2412,9 +2411,9 @@ class CustomStreamWrapper:A stream that breaks mid-flight still billed the provider for the chunksalready delivered. Recover that partial usage from the chunks seen sofar and stash it, with its cost, on the logging object so the failure- handler records the real partial spend instead of zero. A request that- later recovers via a router fallback overwrites this with the combined- success log on the same request id, so this never double counts.+ handler records the real partial spend instead of zero. The router+ moves it into terminal failure usage before opening the next attempt,+ so a recovered attempt logs its own usage."""if self.logging_obj is None or not self.chunks:returndiff --git a/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.pyindex 52b836c789a..e9fd77ef441 100644--- a/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py+++ b/litellm/llms/anthropic/pass_through/adapters/streaming_iterator.py@@ -16,6 +16,7 @@ from typing import (Protocol,cast,get_args,+ runtime_checkable,)from pydantic import TypeAdapter@@ -65,6 +66,14 @@ class _ChunkStream(Protocol):def __aiter__(self) -> "AsyncIterator[ModelResponseStream]": ...+@runtime_checkable+class _FailureLoggingWaiter(Protocol):+ @property+ def has_dispatched_failure_logging(self) -> bool: ...++ async def wait_for_failure_logging(self, timeout: float | None) -> None: ...++def _optional_attr(obj: object, name: str) -> object:return getattr(obj, name, None)@@ -189,6 +198,14 @@ class _CombinedChunkSplitter:self._held_calls: Mapping[int, tuple[ModelResponseStream, _ToolCallPart]] = MappingProxyType({})self._live_call_index: int | None = None+ @property+ def has_dispatched_failure_logging(self) -> bool:+ return isinstance(self._stream, _FailureLoggingWaiter) and self._stream.has_dispatched_failure_logging is True++ async def wait_for_failure_logging(self, timeout: float | None) -> None:+ if isinstance(self._stream, _FailureLoggingWaiter):+ await self._stream.wait_for_failure_logging(timeout=timeout)+@propertydef chunks(self) -> "list[ModelResponseStream] | None":return cast( # cast-ok: chunks is a list of ModelResponseStream on the inner stream@@ -522,7 +539,9 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):# Wrap the upstream stream so chunks that carry both content and a# finish_reason (fake-streamed providers) are split into two — see# _CombinedChunkSplitter.- super().__init__(_CombinedChunkSplitter(completion_stream))+ combined_chunk_splitter: Final = _CombinedChunkSplitter(completion_stream)+ super().__init__(combined_chunk_splitter)+ self._combined_chunk_splitter: Final = combined_chunk_splitterself.model = modelself._message_id: str = f"msg_{uuid.uuid4()}"if litellm_logging_obj is not None:@@ -1244,7 +1263,10 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):if provider_error is e:raiseraise provider_error from e- if logging_obj is not None:+ stream_has_dispatched_failure_logging: Final = self._combined_chunk_splitter.has_dispatched_failure_logging+ if stream_has_dispatched_failure_logging:+ await self._combined_chunk_splitter.wait_for_failure_logging(timeout=None)+ elif logging_obj is not None:try:await logging_obj.dispatch_failure_handlers(exception=provider_error,diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.pyindex a7f3a4f84a7..23ef89b3c5c 100644--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py@@ -10,14 +10,12 @@ from pydantic import ConfigDict, TypeAdapterimport litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.constants import ANTHROPIC_BATCHES_ROUTE-from litellm.litellm_core_utils.asyncify import asyncifyfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.litellm_core_utils.litellm_logging import use_custom_pricing_for_modelfrom litellm.litellm_core_utils.prompt_templates.common_utils import (get_content_from_model_response,)from litellm.llms.anthropic import get_anthropic_config-from litellm.llms.anthropic.common_utils import anthropic_error_frame_exceptionfrom litellm.llms.anthropic.pass_through.stream_assembly import (build_complete_streaming_response,build_complete_streaming_response_legacy,@@ -256,26 +254,6 @@ class AnthropicPassthroughLoggingHandler:),)- @staticmethod- async def log_error_frame_as_failure(- attempt_logging_obj: LiteLLMLoggingObj,- request_body: Mapping[str, object],- all_chunks: Sequence[str | bytes],- error_event: tuple[str, str, int],- ) -> None:- """A stream closed at the provider's `event: error` frame is one failed attempt of the request: it logs- through the attempt-scoped copy its caller took at the close, so the usage it consumed never reaches- the success log of the attempt the router opens in its place."""- error_type, message, status_code = error_event- await asyncify(AnthropicPassthroughLoggingHandler.record_partial_usage_for_failure)(- litellm_logging_obj=attempt_logging_obj, request_body=request_body, all_chunks=all_chunks- )- await attempt_logging_obj.dispatch_failure_handlers(- anthropic_error_frame_exception(error_type, message, status_code, str(attempt_logging_obj.model)),- "",- prefer_async_handlers=True,- )-@staticmethoddef _cost_partial_stream_or_zero(partial_response: ModelResponse | TextCompletionResponse, model: str, logging_obj: LiteLLMLoggingObjdiff --git a/litellm/proxy/pass_through_endpoints/streaming_handler.py b/litellm/proxy/pass_through_endpoints/streaming_handler.pyindex 1fcfe2e279a..b6a067b7666 100644--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py@@ -1,5 +1,5 @@import traceback-from collections.abc import Coroutine, Sequence+from collections.abc import Callable, Coroutine, Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Final, Protocol@@ -12,6 +12,7 @@ from litellm.litellm_core_utils.asyncify import asyncifyfrom litellm.litellm_core_utils.core_helpers import bind_budget_reservation_to_callbacksfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER+from litellm.llms.anthropic.common_utils import anthropic_error_frame_exceptionfrom litellm.proxy._types import PassThroughEndpointLoggingResultValuesfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessingfrom litellm.proxy.common_utils.sse_keepalive import split_complete_sse_frames@@ -87,13 +88,32 @@ class PassThroughStreamingHandler:)try:GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(- async_coroutine=litellm_logging_obj.dispatch_failure_handlers(- exception, traceback.format_exc(), prefer_async_handlers=True- )+ async_coroutine=litellm_logging_obj.dispatch_attempt_failure_handlers(exception, traceback.format_exc()))except Exception as e:verbose_proxy_logger.error("Error scheduling stream failure logging: %s", e)+ @staticmethod+ async def _schedule_stream_end_logging(+ litellm_logging_obj: LiteLLMLoggingObj,+ endpoint_type: EndpointType,+ request_body: Mapping[str, object],+ raw_bytes: Sequence[bytes],+ error_event: tuple[str, str, int] | None,+ success_logging: Callable[[], Coroutine[None, None, None]],+ ) -> None:+ if error_event is None:+ GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(async_coroutine=success_logging())+ return+ error_type, message, status_code = error_event+ await PassThroughStreamingHandler.schedule_stream_failure_logging(+ litellm_logging_obj=litellm_logging_obj,+ endpoint_type=endpoint_type,+ request_body=dict(request_body),+ raw_bytes=raw_bytes,+ exception=anthropic_error_frame_exception(error_type, message, status_code, str(litellm_logging_obj.model)),+ )+@staticmethoddef _record_partial_usage_for_failure(litellm_logging_obj: LiteLLMLoggingObj,@@ -276,17 +296,13 @@ class PassThroughStreamingHandler:else PassThroughStreamingHandler._error_frame_closed_at(endpoint_type, raw_bytes))try:- GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(- async_coroutine=(- _build_logging_coroutine()- if superseded_error_event is None- else AnthropicPassthroughLoggingHandler.log_error_frame_as_failure(- attempt_logging_obj=litellm_logging_obj.attempt_scoped_copy(),- request_body=resolved_request_body,- all_chunks=tuple(raw_bytes),- error_event=superseded_error_event,- )- )+ await PassThroughStreamingHandler._schedule_stream_end_logging(+ litellm_logging_obj=litellm_logging_obj,+ endpoint_type=endpoint_type,+ request_body=resolved_request_body,+ raw_bytes=tuple(raw_bytes),+ error_event=superseded_error_event,+ success_logging=_build_logging_coroutine,)except Exception as e:verbose_proxy_logger.error("Error scheduling chunk_processor logging: %s", e)@@ -295,10 +311,6 @@ class PassThroughStreamingHandler:@staticmethoddef _error_frame_closed_at(endpoint_type: EndpointType, raw_bytes: Sequence[bytes]) -> tuple[str, str, int] | None:- """The provider `event: error` frame of a stream the router closed because a retry or fallback took the- request over. That attempt is logged as its own failure, on a copy taken now so the retry's rebinding of- the shared logging object never reaches it. A stream that ran to its end or that the client closed keeps- logging through the success route, so its usage is still billed."""from litellm.llms.anthropic.pass_through.messages.streaming_iterator import (closing_superseded_attempt,parse_anthropic_error_event,diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 6c9b23860da..2a328971817 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -1015,7 +1015,7 @@ def _billed_across_attempts()-def _failure_usage_to_lift(+def _current_failure_usage_to_lift(model_call_details: Mapping[str, object],request_body: Mapping[str, object],dispatched: bool,@@ -1037,9 +1037,6 @@ def _failure_usage_to_lift(failure stays at zero cost. Returns the(combined_usage_object, response_cost) pair to lift, or None."""recovered_usage: Final = model_call_details.get("combined_usage_object")- failed_attempts: Final = _FAILED_ATTEMPTS_USAGE.validate_python(model_call_details.get("failed_attempts_usage", ()))- if failed_attempts:- return _billed_across_attempts(failed_attempts, recovered_usage, model_call_details.get("response_cost"))if recovered_usage is not None:return recovered_usage, model_call_details.get("response_cost")if not dispatched:@@ -1281,6 +1278,29 @@ def _estimated_input_cost(return next((cost for cost in candidate_costs if cost is not None), 0.0)+def _failure_usage_to_lift(+ model_call_details: Mapping[str, object],+ request_body: Mapping[str, object],+ dispatched: bool,+ provider_billed: bool = False,+ deployment_id: str | None = None,+ base_model: str | None = None,+) -> tuple[object, object] | None:+ current_attempt: Final = _current_failure_usage_to_lift(+ model_call_details,+ request_body,+ dispatched,+ provider_billed,+ deployment_id,+ base_model,+ )+ failed_attempts: Final = _FAILED_ATTEMPTS_USAGE.validate_python(model_call_details.get("failed_attempts_usage", ()))+ if not failed_attempts:+ return current_attempt+ current_usage, current_cost = current_attempt if current_attempt is not None else (None, None)+ return _billed_across_attempts(failed_attempts, current_usage, current_cost)++_EMPTY_LIFT: Final = MappingProxyType({})@@ -1444,7 +1464,7 @@ def _failure_fields_to_lift(request_data: Mapping[str, object], provider_billed:_usage_to_lift: Final = _failure_usage_to_lift(model_call_details=_model_call_details,request_body=request_data,- dispatched=_first_handoff is not None,+ dispatched=_model_call_details.get("current_attempt_api_call_start_time", _first_handoff) is not None,provider_billed=_billed,deployment_id=_deployment_id,base_model=_base_model,diff --git a/litellm/router.py b/litellm/router.pyindex 0ac21960be1..fe418b5830b 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -260,6 +260,7 @@ from litellm.router_utils.fallback_event_handlers import (attempted_retries_for_request,carry_over_pre_routing_selection,carry_over_routed_deployment,+ carry_superseded_attempt_usage,check_non_standard_fallback_format,clear_pre_routing_selection,committed_retry_budget_for_request,@@ -6721,6 +6722,7 @@ class Router:verbose_router_logger.debug("Retrying stream that failed before content, attempt %s of %s", attempt + 1, budget)+ carry_superseded_attempt_usage(retry_kwargs)try:response = await attempt_function(**retry_kwargs)except Exception as retry_error: # noqa: BLE001 # the fallback chain judges the failed retrydiff --git a/litellm/router_utils/fallback_event_handlers.py b/litellm/router_utils/fallback_event_handlers.pyindex e1201df1a13..6c93fe6d239 100644--- a/litellm/router_utils/fallback_event_handlers.py+++ b/litellm/router_utils/fallback_event_handlers.py@@ -8,6 +8,7 @@ from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Finalimport httpx+from pydantic import TypeAdapterimport litellmfrom litellm._logging import verbose_router_logger@@ -15,6 +16,7 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs, safe_deep_copyfrom litellm.litellm_core_utils.credential_accessor import reject_api_key_secret_referencefrom litellm.litellm_core_utils.get_llm_provider_logic import inferred_provider+from litellm.litellm_core_utils.litellm_logging import Logging, same_attempt_markerfrom litellm.litellm_core_utils.sensitive_data_masker import mask_sensitive_structurefrom litellm.router_utils.add_retry_fallback_headers import (add_fallback_headers_to_response,@@ -51,6 +53,7 @@ else:# (e.g. a nonexistent file/batch/thread id), independent of the selected deployment's health._REQUEST_SCOPED_STATUS_CODES: Final = frozenset((404,))_NO_MODEL_CALL_DETAILS: Final[Mapping[str, object]] = MappingProxyType({})+_FALLBACK_KWARGS_ADAPTER: Final = TypeAdapter(dict[str, object])def _trigger_cooldown_for_failed_deployment(@@ -447,6 +450,24 @@ def mid_stream_retry_kwargs(return {key: value for key, value in hop_kwargs.items() if key not in _MID_STREAM_RETRY_STRIPPED_KEYS}+def carry_superseded_attempt_usage(kwargs: Mapping[str, object]) -> None:+ """Carry the superseded stream's partial usage into billing if the request ultimately fails."""+ logging_obj: Final = kwargs.get("litellm_logging_obj")+ if isinstance(logging_obj, Logging):+ logging_obj.carry_failed_attempt_usage()+++def _failure_callbacks_blocked_logging_object(kwargs: Mapping[str, object]) -> Logging | None:+ logging_obj: Final = kwargs.get("litellm_logging_obj")+ if not isinstance(logging_obj, Logging):+ return None+ if logging_obj.model_call_details.get("has_logged_async_failure", False) is not True:+ return None+ current_marker: Final = logging_obj.model_call_details.get("current_attempt_api_call_start_time")+ logged_marker: Final = logging_obj.model_call_details.get("async_failure_logged_attempt")+ return logging_obj if not same_attempt_marker(current_marker, logged_marker) else None++def _request_metadata_bucket(kwargs: Mapping[str, object]) -> Mapping[str, object] | None:bucket: Final = kwargs.get(get_metadata_variable_name_from_kwargs(kwargs))return bucket if isinstance(bucket, Mapping) else None@@ -869,6 +890,7 @@ async def run_async_fallback(kwargs["attempted_targets"] = attemptedif include_fallback_errors:kwargs["include_fallback_errors"] = include_fallback_errors+ carry_superseded_attempt_usage(_FALLBACK_KWARGS_ADAPTER.validate_python(kwargs))response = await litellm_router.async_function_with_fallbacks(*args, **kwargs)verbose_router_logger.info("Successful fallback b/w models.")response = add_fallback_headers_to_response(@@ -891,13 +913,16 @@ async def run_async_fallback(kwargs=kwargs,original_exception=original_exception,)- logging_obj = kwargs.get("litellm_logging_obj")- if logging_obj is not None and logging_obj.model_call_details.get("has_logged_async_failure", False):+ if (+ failure_callbacks_blocked_logging_obj := _failure_callbacks_blocked_logging_object(+ _FALLBACK_KWARGS_ADAPTER.validate_python(kwargs)+ )+ ) is not None:_trigger_cooldown_for_failed_deployment(litellm_router=litellm_router,kwargs=kwargs,exception=e,- model_call_details=logging_obj.model_call_details,+ model_call_details=failure_callbacks_blocked_logging_obj.model_call_details,)raise error_from_fallbacksdiff --git a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.pyindex e0b2e4a336f..041a0a72fdd 100644--- a/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py+++ b/tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py@@ -1,13 +1,17 @@import jsonimport osimport uuid-from collections.abc import Callable, Mapping+from collections.abc import Callable, Iterator, Mapping, Sequence+from contextlib import AbstractContextManagerfrom dataclasses import dataclass+from pathlib import Pathfrom typing import Final, Literalimport anthropicimport httpx+from pydantic import JsonValue, TypeAdapterimport pytest+import yamlfrom integration._support.anthropic_sse import (LIFECYCLE,Attempts,@@ -27,13 +31,14 @@ from integration._support.anthropic_sse import ()from integration._support.client import Gateway, eventually, object_valuefrom integration._support.database import read_rows+from integration._support.process import owned_proxyfrom integration._support.wire import Reply, Request, Wire, wire_server-from pydantic import JsonValuefrom redis import Redis_MODEL: Final = "claude-sonnet-4-5-20250929"_API_KEY: Final = "synthetic-anthropic-key"_TEXT: Final = "Hello"+_SINK_EVENT_BATCH_ADAPTER: Final = TypeAdapter(list[dict[str, JsonValue]])FirstAttempt = Literal["drop_after_headers",@@ -127,24 +132,24 @@ def _stream(gateway: Gateway, body: Mapping[str, JsonValue]) -> tuple[int, tuplereturn response.status_code, parse_sse(response.text)-def _rows(request_id: str) -> list[dict[str, JsonValue]]:- return read_rows('SELECT status, model_group FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (request_id,))+def _rows(gateway: Gateway, request_id: str) -> list[dict[str, JsonValue]]:+ return gateway.rows('SELECT status, model_group FROM "LiteLLM_SpendLogs" WHERE request_id=%s', (request_id,))-def _success_rows(request_id: str) -> list[dict[str, JsonValue]]:- return eventually(lambda: _rows(request_id), lambda rows: len(rows) >= 1, seconds=70)+def _success_rows(gateway: Gateway, request_id: str) -> list[dict[str, JsonValue]]:+ return eventually(lambda: _rows(gateway, request_id), lambda rows: len(rows) >= 1, seconds=70)def _assert_completed_by_retry(- status: int, events: tuple[SseEvent, ...], prompt: str, model: str, wire: Wire, *, attempts: int = 2+ gateway: Gateway, status: int, events: tuple[SseEvent, ...], prompt: str, model: str, wire: Wire, *, attempts: int = 2) -> None:assert status == 200, eventsassert event_types(events) == LIFECYCLE, eventsassert message_id(events) == _served_id(prompt, attempts), eventsassert delta_text(events) == _TEXT, eventsassert [request.target for request in wire.drain()] == ["/v1/messages"] * attempts- assert _success_rows(_served_id(prompt, attempts)) == [{"status": "success", "model_group": model}]- superseded_rows: Final = {attempt: _rows(_served_id(prompt, attempt)) for attempt in range(1, attempts)}+ assert _success_rows(gateway, _served_id(prompt, attempts)) == [{"status": "success", "model_group": model}]+ superseded_rows: Final = {attempt: _rows(gateway, _served_id(prompt, attempt)) for attempt in range(1, attempts)}assert not any(superseded_rows.values()), superseded_rows@@ -183,7 +188,7 @@ def test_stream_failing_before_content_is_retried_on_the_same_group_and_complete**({"num_retries": 1} if source == "deployment" else {}),)status, events = _stream(gateway, _body(model, prompt, source))- _assert_completed_by_retry(status, events, prompt, model, wire)+ _assert_completed_by_retry(gateway, status, events, prompt, model, wire)@pytest.mark.parametrize("source", ["deployment", "request"])@@ -204,7 +209,7 @@ def test_stream_rejected_before_it_opens_is_retried_and_completes(**({"num_retries": 1} if source == "deployment" else {}),)status, events = _stream(gateway, _body(model, prompt, source))- _assert_completed_by_retry(status, events, prompt, model, wire)+ _assert_completed_by_retry(gateway, status, events, prompt, model, wire)def _sdk(gateway: Gateway) -> anthropic.Anthropic:@@ -232,7 +237,7 @@ def test_anthropic_sdk_sync_stream_completes_after_a_drop_following_message_starassert final.id == _served_id(prompt, 2), finalassert [block.text for block in final.content if block.type == "text"] == [_TEXT], finalassert [request.target for request in wire.drain()] == ["/v1/messages"] * 2- assert _success_rows(final.id) == [{"status": "success", "model_group": model}]+ assert _success_rows(gateway, final.id) == [{"status": "success", "model_group": model}]async def test_anthropic_sdk_async_stream_completes_after_a_drop_following_message_start(gateway: Gateway) -> None:@@ -321,7 +326,7 @@ def test_stream_error_frame_after_content_is_not_retried_and_keeps_its_spend_rowassert message_id(events) == _served_id(prompt, 1), eventsassert delta_text(events) == _TEXT, eventsassert [request.target for request in wire.drain()] == ["/v1/messages"]- assert [row["model_group"] for row in _success_rows(_served_id(prompt, 1))] == [model]+ assert [row["model_group"] for row in _success_rows(gateway, _served_id(prompt, 1))] == [model]def test_stream_rejected_with_401_before_it_opens_is_not_retried(gateway: Gateway) -> None:@@ -393,6 +398,22 @@ def test_retry_rejected_before_it_opens_counts_against_the_same_budget(gateway:model: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)response: Final = gateway.request("POST", "/v1/messages", _body(model, prompt, "deployment"))_assert_rejected_before_content(response, wire, status=500, attempts=2, error="error")+ rows: Final = eventually(+ lambda: _request_rows(gateway, response.headers["x-litellm-call-id"]),+ lambda values: len(values) >= 1,+ seconds=70,+ )+ rejected: Final = gateway.request("POST", "/v1/messages", _body(model, prompt, "request", budget=0))+ _assert_rejected_before_content(rejected, wire, status=500, attempts=1, error="error")+ rejection_rows: Final = eventually(+ lambda: _request_rows(gateway, rejected.headers["x-litellm-call-id"]),+ lambda values: len(values) >= 1,+ seconds=70,+ )+ estimated_input: Final = rejection_rows[0]["prompt_tokens"]+ assert isinstance(estimated_input, int)+ assert rejection_rows == [{"status": "failure", "prompt_tokens": estimated_input, "completion_tokens": 0}]+ assert rows == [{"status": "failure", "prompt_tokens": 5 + estimated_input, "completion_tokens": 1}], rowsdef test_non_stream_messages_rejected_with_500_is_retried_per_the_deployment_budget(gateway: Gateway) -> None:@@ -409,7 +430,7 @@ def test_non_stream_messages_rejected_with_500_is_retried_per_the_deployment_budassert payload["id"] == _served_id(prompt, 2), response.textassert payload["content"] == [{"type": "text", "text": _TEXT}], response.textassert [request.target for request in wire.drain()] == ["/v1/messages"] * 2- assert _success_rows(_served_id(prompt, 2)) == [{"status": "success", "model_group": model}]+ assert _success_rows(gateway, _served_id(prompt, 2)) == [{"status": "success", "model_group": model}]def test_retried_stream_response_headers_name_the_attempt(gateway: Gateway) -> None:@@ -422,7 +443,7 @@ def test_retried_stream_response_headers_name_the_attempt(gateway: Gateway) -> Nmodel: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)response: Final = gateway.request("POST", "/v1/messages", _body(model, prompt, "deployment"))events: Final = parse_sse(response.text)- _assert_completed_by_retry(response.status_code, events, prompt, model, wire)+ _assert_completed_by_retry(gateway, response.status_code, events, prompt, model, wire)assert response.headers.get("x-litellm-attempted-retries") == "1", dict(response.headers)assert response.headers.get("x-litellm-max-retries") == "1", dict(response.headers)@@ -454,7 +475,7 @@ def test_retried_stream_spend_row_records_the_attempt_count(gateway: Gateway) ->):model: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)status, events = _stream(gateway, _body(model, prompt, "deployment"))- _assert_completed_by_retry(status, events, prompt, model, wire)+ _assert_completed_by_retry(gateway, status, events, prompt, model, wire)rows: Final = read_rows("SELECT metadata->>'attempted_retries' AS attempted, metadata->>'max_retries' AS budget "'FROM "LiteLLM_SpendLogs" WHERE request_id=%s',@@ -463,6 +484,114 @@ def test_retried_stream_spend_row_records_the_attempt_count(gateway: Gateway) ->assert rows == [{"attempted": "1", "budget": "1"}], rows+def _proxy_with_callback_sink(gateway: Gateway, tmp_path: Path, sink: Wire) -> AbstractContextManager[Gateway]:+ loaded_config: Final = TypeAdapter(dict[str, object]).validate_python(+ yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ )+ litellm_settings: Final = TypeAdapter(dict[str, object]).validate_python(loaded_config["litellm_settings"])+ config: Final = {+ **loaded_config,+ "litellm_settings": {+ **litellm_settings,+ "callbacks": ["generic_api"],+ "DEFAULT_FLUSH_INTERVAL_SECONDS": 1,+ },+ }+ path: Final = tmp_path / "callbacks.yaml"+ path.write_text(yaml.safe_dump(config))+ return owned_proxy(+ gateway,+ tmp_path,+ {"GENERIC_LOGGER_ENDPOINT": sink.url, "GENERIC_LOGGER_HEADERS": "Authorization=Bearer synthetic-sink-secret"},+ config=path,+ )+++def _sink_events(batches: Sequence[Request]) -> Iterator[dict[str, JsonValue]]:+ for batch in batches:+ yield from _SINK_EVENT_BATCH_ADAPTER.validate_python(json.loads(batch.body))+++class _SinkReader:+ """Reads the callback sink across polls: drain() consumes the sink's queue, so earlier batches are kept here."""++ def __init__(self, sink: Wire, model: str) -> None:+ self._sink: Final = sink+ self._model: Final = model+ self._batches: tuple[Request, ...] = ()++ def delivered_usage(self) -> tuple[tuple[str, int, int], ...]:+ self._batches = (*self._batches, *self._sink.drain())+ return tuple(+ (str(event["status"]), int(event["prompt_tokens"]), int(event["completion_tokens"]))+ for event in _sink_events(self._batches)+ if event.get("model_group") == self._model+ )+++def _request_rows(gateway: Gateway, call_id: str) -> list[dict[str, JsonValue]]:+ return gateway.rows(+ 'SELECT status, prompt_tokens, completion_tokens FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s', (call_id,)+ )+++ "failure",+ (_Failure("drop_after_message_start"), _Failure("error_frame_after_message_start", 500)),+ ids=("transport-drop", "recoverable-error-frame"),+)+def test_superseded_attempt_and_its_retry_each_log_their_own_usage(+ gateway: Gateway, tmp_path: Path, failure: _Failure+) -> None:+ prompt: Final = _prompt()+ attempts: Final = Attempts()+ with (+ wire_server(_upstream(prompt, failure, attempts)) as wire,+ wire_server(lambda request: Reply()) as sink,+ _proxy_with_callback_sink(gateway, tmp_path, sink) as candidate,+ candidate.scenario() as scenario,+ ):+ model: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)+ status, events = _stream(candidate, _body(model, prompt, "deployment"))+ _assert_completed_by_retry(candidate, status, events, prompt, model, wire)+ delivered: Final = eventually(+ _SinkReader(sink, model).delivered_usage, lambda values: len(values) >= 2, seconds=20+ )+ assert sorted(delivered) == [("failure", 5, 1), ("success", 5, 3)], delivered+++def test_every_dropped_attempt_logs_its_own_failure_and_the_request_row_still_bills_the_dropped_usage(+ gateway: Gateway, tmp_path: Path+) -> None:+ prompt: Final = _prompt()+ attempts: Final = Attempts()+ with (+ wire_server(_upstream(prompt, _Failure("drop_after_message_start"), attempts, failing_attempts=99)) as wire,+ wire_server(lambda request: Reply()) as sink,+ _proxy_with_callback_sink(gateway, tmp_path, sink) as candidate,+ candidate.scenario() as scenario,+ ):+ model: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)+ response: Final = candidate.request("POST", "/v1/messages", _body(model, prompt, "deployment"))+ _assert_stream_failed_after_message_start(response.status_code, parse_sse(response.text), wire, attempts=2)+ delivered: Final = eventually(+ _SinkReader(sink, model).delivered_usage, lambda values: len(values) >= 2, seconds=20+ )+ assert delivered == (("failure", 5, 1), ("failure", 5, 1)), delivered+ rows: Final = eventually(+ lambda: _request_rows(candidate, response.headers["x-litellm-call-id"]),+ lambda values: len(values) >= 1,+ seconds=70,+ )+ assert rows == [+ {+ "status": "failure",+ "prompt_tokens": sum(input_tokens for _, input_tokens, _ in delivered),+ "completion_tokens": sum(output_tokens for _, _, output_tokens in delivered),+ }+ ], rows++def _string_values(cache: Redis) -> tuple[bytes, ...]:keys: Final = tuple(key for key in cache.scan_iter(count=1000) if cache.type(key) == b"string")return tuple(value for value in cache.mget(keys) if value is not None) if keys else ()@@ -485,7 +614,7 @@ def test_retried_stream_is_cached_and_the_identical_request_is_served_without_thmodel: Final = scenario.model(model=f"anthropic/{_MODEL}", api_base=wire.url, api_key=_API_KEY, num_retries=1)body: Final = _body(model, prompt, "deployment")status, events = _stream(gateway, body)- _assert_completed_by_retry(status, events, prompt, model, wire)+ _assert_completed_by_retry(gateway, status, events, prompt, model, wire)eventually(lambda: _cached_somewhere(_served_id(prompt, 2)), bool, seconds=30)replay_status, replay = _stream(gateway, body)assert replay_status == 200, replaydiff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.pyindex 43190852c60..bbfae2229ce 100644--- a/tests/unit/litellm_core_utils/test_litellm_logging.py+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py@@ -1849,13 +1849,19 @@ def test_mark_logging_complete_flags_by_stream_and_event("async_failure","sync_failure",)+ attempt_marker: Final = datetime_unit_test(2026, 1, 1)logging_obj.stream = stream+ logging_obj.model_call_details["current_attempt_api_call_start_time"] = attempt_markerlogging_obj.mark_logging_complete(event_type=event)expected_to_run: Final = stream and event in ("async_success", "sync_success")assert logging_obj.should_run_logging(event_type=event) is expected_to_runassert all(logging_obj.should_run_logging(event_type=other_event) for other_event in events if other_event != event)+ if event == "async_failure":+ assert logging_obj.model_call_details["async_failure_logged_attempt"] is attempt_marker+ else:+ assert "async_failure_logged_attempt" not in logging_obj.model_call_details@pytest.mark.parametrize("stream", [False, True])diff --git a/tests/unit/litellm_core_utils/test_max_streaming_duration.py b/tests/unit/litellm_core_utils/test_max_streaming_duration.pyindex fc8daab3899..234bc83e3c3 100644--- a/tests/unit/litellm_core_utils/test_max_streaming_duration.py+++ b/tests/unit/litellm_core_utils/test_max_streaming_duration.py@@ -67,12 +67,13 @@ class TestCustomStreamWrapperMaxDuration:@pytest.mark.asyncioasync def test_should_raise_on_async_anext_when_exceeded(self):- """__anext__ should check the limit before iterating, dispatching the- same failure-callback/logging path every other stream failure goes- through (dispatch_failure_handlers is async on the real Logging class,- so the mock needs to be awaitable too)."""+ """__anext__ checks the limit before iterating and schedules failure logging."""wrapper = _make_custom_stream_wrapper()- wrapper.logging_obj.dispatch_failure_handlers = AsyncMock()++ async def _noop() -> None:+ return None++ wrapper.logging_obj.dispatch_attempt_failure_handlers = MagicMock(side_effect=lambda *_: _noop())wrapper._stream_created_time = time.time() - 20with patch("litellm.constants.LITELLM_MAX_STREAMING_DURATION_SECONDS", 10.0):with pytest.raises(litellm.Timeout):diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.pyindex 550ecd3c0f7..c13cea51183 100644--- a/tests/unit/litellm_core_utils/test_streaming_handler.py+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py@@ -13,8 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, Mock, patchimport httpximport pytestfrom openai.types.chat import ChatCompletionChunk-from pydantic import BaseModel-+from pydantic import BaseModel, TypeAdapterimport litellmfrom litellm import verbose_loggerfrom litellm._logging import session_id_var, trace_id_var@@ -36,6 +35,7 @@ from litellm.types.utils import (ModelResponseStream,PromptTokensDetailsWrapper,StreamingChoices,+ StandardLoggingPayload,Usage,)from litellm.utils import ModelResponseListIterator@@ -4265,6 +4265,68 @@ def test_record_partial_usage_for_failure_stashes_usage_and_cost():assert isinstance(logging_obj.model_call_details["response_cost"], float)+class _FailureRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.failures: tuple[tuple[int, int], ...] = ()+ self.logged: asyncio.Event = asyncio.Event()++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: datetime.datetime,+ end_time: datetime.datetime,+ ) -> None:+ payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(kwargs["standard_logging_object"])+ self.failures = (*self.failures, (payload["prompt_tokens"], payload["completion_tokens"]))+ self.logged.set()+++async def test_log_stream_failure_bills_the_dropped_attempt_even_after_the_router_discards_its_usage() -> None:+ """The dropped attempt's failure log is queued, and the router discards the stashed usage as it opens the+ fallback hop before that log runs. The log must still bill what the dropped attempt consumed, and the shared+ logging object must not be marked as already failed, since the hop's own failure still has to reach the+ integrations."""+ recorder: Final = _FailureRecorder()+ logging_obj: Final = Logging(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "Hey"}],+ stream=True,+ call_type="completion",+ start_time=datetime.datetime(2026, 1, 1),+ litellm_call_id="partial-usage-copy",+ function_id="1245",+ dynamic_async_failure_callbacks=[recorder],+ )+ logging_obj.model_call_details["custom_llm_provider"] = "openai"+ wrapper: Final = CustomStreamWrapper(+ completion_stream=None,+ model="gpt-5.6",+ logging_obj=logging_obj,+ custom_llm_provider="openai",+ )+ wrapper.chunks = [+ ModelResponseStream(+ id="chatcmpl-partial-copy",+ created=1742056047,+ model="gpt-5.6",+ object="chat.completion.chunk",+ choices=[StreamingChoices(finish_reason=None, index=0, delta=Delta(content="The", role="assistant"))],+ usage=Usage(prompt_tokens=30, completion_tokens=1, total_tokens=31),+ )+ ]++ with pytest.raises(MidStreamFallbackError):+ wrapper._log_stream_failure_and_raise(httpx.ReadError("connection dropped"))+ logging_obj.carry_failed_attempt_usage()+ await asyncio.wait_for(recorder.logged.wait(), timeout=10)++ assert recorder.failures == ((30, 1),)+ assert logging_obj.model_call_details.get("has_logged_async_failure") is not True++def test_record_partial_usage_for_failure_noop_without_chunks():"""With no chunks delivered there is nothing billed to recover, so thefailure stash must stay absent and not force a zero-usage row.diff --git a/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_mid_stream_error.py b/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_mid_stream_error.pyindex 785e1f1096b..6951253349e 100644--- a/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_mid_stream_error.py+++ b/tests/unit/llms/anthropic/pass_through/adapters/test_streaming_iterator_mid_stream_error.py@@ -19,12 +19,14 @@ import jsonimport osimport sysimport threading+from collections.abc import Callable, Mapping, Sequencefrom datetime import datetime-from collections.abc import Callable-from typing import List, Optional+from typing import Final, Iterator, List, Optionalfrom unittest.mock import MagicMock+import httpximport pytest+from pydantic import TypeAdapterimport litellm@@ -33,12 +35,13 @@ sys.path.insert(0, os.path.abspath("../../../../.."))from litellm.exceptions import MidStreamFallbackErrorfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapperfrom litellm.llms.anthropic.pass_through.adapters.streaming_iterator import (AnthropicStreamWrapper,_mid_stream_error_sse_event,)from litellm.llms.bedrock.common_utils import BedrockError-from litellm.types.utils import Delta, StreamingChoices+from litellm.types.utils import Delta, ModelResponseStream, StandardLoggingPayload, StreamingChoices, Usagedef _make_chunk(delta: Delta, finish_reason: Optional[str] = None) -> MagicMock:@@ -55,14 +58,14 @@ class _AsyncStreamThenRaise:"""Yields the given chunks, then raises ``exc`` (mimics a provider streamthat terminates mid-response)."""- def __init__(self, items: List[MagicMock], exc: BaseException):+ def __init__(self, items: Sequence[object], exc: BaseException) -> None:self._it = iter(items)self._exc = exc- def __aiter__(self):+ def __aiter__(self) -> "_AsyncStreamThenRaise":return self- async def __anext__(self):+ async def __anext__(self) -> object:try:return next(self._it)except StopIteration:@@ -182,9 +185,73 @@ class _AsyncFailureRecorder(CustomLogger):def __init__(self):super().__init__()self.exceptions: list[BaseException] = []-- async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):+ self.usages: tuple[tuple[int, int], ...] = ()++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: datetime,+ end_time: datetime,+ ) -> None:self.exceptions.append(kwargs["exception"])+ payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(kwargs["standard_logging_object"])+ self.usages = (*self.usages, (payload["prompt_tokens"], payload["completion_tokens"]))+++class _BoundaryAsyncFailureRecorder(_AsyncFailureRecorder):+ def __init__(self) -> None:+ super().__init__()+ self.started = 0+ self.completed = 0++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: datetime,+ end_time: datetime,+ ) -> None:+ self.started += 1+ await asyncio.sleep(0.05)+ await super().async_log_failure_event(kwargs, response_obj, start_time, end_time)+ self.completed += 1+++def test_anthropic_adapter_does_not_repeat_custom_stream_failure_dispatch() -> None:+ async_recorder: Final = _BoundaryAsyncFailureRecorder()+ sync_recorder: Final = _SyncFailureRecorder()+ logging_obj: Final = _make_logging_obj("wrapped-custom-stream", async_recorder, sync_recorder)+ chunk: Final = ModelResponseStream(+ id="chatcmpl-dropped",+ object="chat.completion.chunk",+ created=1,+ model="gpt-5.6",+ choices=[StreamingChoices(index=0, delta=Delta(content="partial"), finish_reason=None)],+ usage=Usage(prompt_tokens=30, completion_tokens=1, total_tokens=31),+ )+ inner_stream: Final = CustomStreamWrapper(+ completion_stream=_AsyncStreamThenRaise([chunk], httpx.ReadError("stream dropped")),+ model="gpt-5.6",+ logging_obj=logging_obj,+ custom_llm_provider="openai",+ )+ wrapper: Final = AnthropicStreamWrapper(+ completion_stream=inner_stream,+ model="openai/gpt-5.6",+ litellm_logging_obj=logging_obj,+ )++ events: Final = asyncio.run(_drain_sse(wrapper))++ assert async_recorder.started == 1+ assert async_recorder.completed == 1+ assert sync_recorder.called.wait(timeout=5), "sync failure callback never ran"+ assert _parse_sse(events[-1])[0] == "error"+ assert len(async_recorder.exceptions) == 1+ assert len(sync_recorder.exceptions) == 1+ assert async_recorder.usages == ((30, 1),)+ assert sync_recorder.exceptions[0] == async_recorder.exceptions[0]class _SyncFailureRecorder:diff --git a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.pyindex d2b5c8d5bd9..4c3ee9e7ca5 100644--- a/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py+++ b/tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py@@ -3278,6 +3278,14 @@ async def test_vertex_ai_streaming_bad_request_is_not_wrapped():async def dispatch_failure_handlers(self, *args, **kwargs):return None+ async def dispatch_attempt_failure_handlers(+ self, exception: Exception, traceback_exception: str+ ) -> None:+ return None++ def attempt_scoped_copy(self) -> "DummyLogging":+ return self+async def failing_make_call(client=None, **kwargs):raise VertexAIError(status_code=400, message="bad input", headers={})diff --git a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.pyindex 4770ecd5485..cc701e1ebd4 100644--- a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py+++ b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py@@ -2643,57 +2643,6 @@ class TestRecordPartialUsageForFailure:assert "response_cost" not in logging_obj.model_call_details-class _FailureRecorder(CustomLogger):- def __init__(self):- super().__init__()- self.failure_kwargs = []-- async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):- self.failure_kwargs.append(kwargs)---class TestLogErrorFrameAsFailure:- """A stream closed at the provider's `event: error` frame is one failed attempt: its failure log bills the- usage streamed before the frame on the attempt-scoped copy its caller hands it, and the request's shared- logging state stays as it was, so the attempt the router opens next logs with nothing left behind."""-- @pytest.mark.asyncio- async def test_logs_a_failure_with_the_usage_streamed_before_the_frame_and_leaves_the_request_state_alone(self):- recorder = _FailureRecorder()- logging_obj = LiteLLMLoggingObj(- model="claude-sonnet-5",- messages=[{"role": "user", "content": "hello"}],- stream=True,- call_type="anthropic_messages",- start_time=datetime.now(),- litellm_call_id="test-error-frame-failure",- function_id="test-error-frame-failure",- dynamic_async_failure_callbacks=[recorder],- )- chunks = [- *TestRecordPartialUsageForFailure()._interrupted_chunks()[:1],- TestRecordPartialUsageForFailure._sse(- "error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}- ),- ]-- await AnthropicPassthroughLoggingHandler.log_error_frame_as_failure(- attempt_logging_obj=logging_obj.attempt_scoped_copy(),- request_body={"model": "claude-sonnet-5", "stream": True},- all_chunks=chunks,- error_event=("overloaded_error", "Overloaded", 529),- )-- assert len(recorder.failure_kwargs) == 1- failure_payload = recorder.failure_kwargs[0]["standard_logging_object"]- assert failure_payload["status"] == "failure"- assert failure_payload["prompt_tokens"] == 52- assert failure_payload["response_cost"] > 0- assert isinstance(recorder.failure_kwargs[0]["exception"], litellm.InternalServerError)- assert "combined_usage_object" not in logging_obj.model_call_details- assert "response_cost" not in logging_obj.model_call_details- assert logging_obj.should_run_logging("async_failure")-@pytest.mark.parametrize(("all_chunks", "interrupted"),diff --git a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.pyindex da084146894..7d56487a844 100644--- a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py+++ b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler.py@@ -220,7 +220,11 @@ async def test_failed_anthropic_stream_records_partial_usage_off_the_event_loop(logging_obj.model_call_details = {"model": model, "stream": True}logging_obj.litellm_params = {}logging_obj.get_router_model_id.return_value = None+ logging_obj.attempt_scoped_copy.return_value = logging_objlogging_obj.dispatch_failure_handlers = AsyncMock()+ logging_obj.dispatch_attempt_failure_handlers = AsyncMock(+ side_effect=logging_obj.dispatch_failure_handlers+ )_, took, lags = await timed_with_loop_lags(lambda: PassThroughStreamingHandler.schedule_stream_failure_logging(diff --git a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler_interrupt.pyindex 8ce41129aec..4aa7e9cfbae 100644--- a/tests/unit/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py+++ b/tests/unit/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py@@ -2,7 +2,9 @@import asyncioimport json+from collections.abc import AsyncGenerator, AsyncIterator, Mapping, Sequencefrom datetime import datetime+from typing import Finalfrom unittest.mock import AsyncMock, MagicMock, patchimport httpx@@ -22,6 +24,8 @@ from litellm.llms.anthropic.pass_through.messages.streaming_iterator import aclofrom litellm.proxy.pass_through_endpoints.streaming_handler import (PassThroughStreamingHandler,)+from litellm.proxy.utils import _failure_fields_to_lift+from litellm.router_utils.fallback_event_handlers import carry_superseded_attempt_usagefrom litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType@@ -407,7 +411,7 @@ async def _collect_openai_passthrough_chunks(chunks, endpoint_type):request_body={"model": "gpt-4o-mini", "stream": True},litellm_logging_obj=_unarmed_logging_obj(),endpoint_type=endpoint_type,- start_time=datetime.now(),+ start_time=datetime(2026, 1, 1),passthrough_success_handler_obj=MagicMock(),url_route="/openai/v1/chat/completions",route_streaming_logging=AsyncMock(),@@ -705,7 +709,7 @@ async def test_chunk_processor_logs_failure_not_success_on_mid_stream_exception(messages=[{"role": "user", "content": "hi"}],stream=True,call_type="anthropic_messages",- start_time=datetime.now(),+ start_time=datetime(2026, 1, 1),litellm_call_id="test-mid-stream-timeout",function_id="test-mid-stream-timeout",dynamic_async_success_callbacks=[recorder],@@ -750,6 +754,109 @@ async def test_chunk_processor_logs_failure_not_success_on_mid_stream_exception(assert isinstance(recorder.failure_kwargs[0]["exception"], httpx.ReadTimeout)+def _anthropic_stream_dropping_after(frames: tuple[bytes, ...]) -> httpx.Response:+ mock: Final = MagicMock(spec=httpx.Response)+ mock.status_code = 200++ async def _aiter_bytes() -> AsyncIterator[bytes]:+ for frame in frames:+ yield frame+ raise httpx.ReadError("upstream closed the connection")++ mock.aiter_bytes = _aiter_bytes+ return mock+++def _anthropic_messages_attempt(+ logging_obj: LiteLLMLoggingObj, response: httpx.Response+) -> AsyncGenerator[bytes, None]:+ return PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body={"model": "claude-sonnet-5", "stream": True},+ litellm_logging_obj=logging_obj,+ endpoint_type=EndpointType.ANTHROPIC,+ start_time=datetime(2026, 1, 1),+ passthrough_success_handler_obj=MagicMock(),+ url_route="/v1/messages",+ )+++def _anthropic_messages_logging_obj(recorder: _EventRecorder, call_id: str) -> LiteLLMLoggingObj:+ return LiteLLMLoggingObj(+ model="claude-sonnet-5",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ call_type="anthropic_messages",+ start_time=datetime(2026, 1, 1),+ litellm_call_id=call_id,+ function_id=call_id,+ dynamic_async_success_callbacks=[recorder],+ dynamic_async_failure_callbacks=[recorder],+ )+++async def _drop_after_message_start(logging_obj: LiteLLMLoggingObj, message_id: str, input_tokens: int) -> None:+ dropped: Final = _anthropic_messages_attempt(+ logging_obj, _anthropic_stream_dropping_after((_anthropic_message_start_frame(message_id, input_tokens),))+ )+ with pytest.raises(httpx.ReadError):+ async for _ in dropped:+ pass+++async def test_dropped_attempt_logs_its_failure_without_claiming_the_shared_logging_object() -> None:+ """The router retries a /v1/messages stream the provider drops after message_start on the same logging+ object. The dropped attempt's failure log bills its own usage and leaves the shared object free: the+ retry's success log carries the retry's usage and no stale exception, while the stash stays for the+ failure row of a request that runs out of retries until the router opens the next attempt."""+ recorder: Final = _EventRecorder()+ logging_obj: Final = _anthropic_messages_logging_obj(recorder, "test-dropped-attempt")++ await _drop_after_message_start(logging_obj, "msg_a1", 52)+ await _settle(recorder.failure_kwargs)++ assert recorder.failure_kwargs[0]["standard_logging_object"]["prompt_tokens"] == 52+ assert isinstance(recorder.failure_kwargs[0]["exception"], httpx.ReadError)+ assert logging_obj.model_call_details.get("has_logged_async_failure") is not True+ assert "exception" not in logging_obj.model_call_details+ stashed: Final = logging_obj.model_call_details.get("combined_usage_object")+ assert isinstance(stashed, litellm.Usage) and stashed.prompt_tokens == 52++ logging_obj.carry_failed_attempt_usage()+ retry: Final = _anthropic_messages_attempt(+ logging_obj, _anthropic_stream_of((_anthropic_message_start_frame("msg_a2", 7), *_anthropic_completed_stream_tail()))+ )+ async for _ in retry:+ pass+ await _settle(recorder.success_kwargs)++ success_payload: Final = recorder.success_kwargs[0]["standard_logging_object"]+ assert success_payload["status"] == "success"+ assert (success_payload["prompt_tokens"], success_payload["completion_tokens"]) == (7, 3)+ assert recorder.success_kwargs[0].get("exception") is None+ assert len(recorder.failure_kwargs) == 1+++async def test_every_dropped_attempt_logs_its_own_failure() -> None:+ """Two attempts of one /v1/messages request dropped in a row each log a failure billing their own usage;+ the first attempt's log must not swallow the second's, and the shared object ends up holding the last+ attempt's usage for the request's failure row."""+ recorder: Final = _EventRecorder()+ logging_obj: Final = _anthropic_messages_logging_obj(recorder, "test-every-dropped-attempt")++ await _drop_after_message_start(logging_obj, "msg_a1", 52)+ await _settle(recorder.failure_kwargs)+ logging_obj.carry_failed_attempt_usage()+ await _drop_after_message_start(logging_obj, "msg_a2", 9)+ await _settle(recorder.failure_kwargs, count=2)++ assert [kwargs["standard_logging_object"]["prompt_tokens"] for kwargs in recorder.failure_kwargs] == [52, 9]+ assert all(isinstance(kwargs["exception"], httpx.ReadError) for kwargs in recorder.failure_kwargs)+ stashed: Final = logging_obj.model_call_details.get("combined_usage_object")+ assert isinstance(stashed, litellm.Usage) and stashed.prompt_tokens == 9+def _anthropic_message_start_frame(message_id: str = "msg_1", input_tokens: int = 52) -> bytes:return _anthropic_sse("message_start",@@ -788,9 +895,9 @@ def _anthropic_completed_stream_tail() -> tuple[bytes, ...]:)-async def _settle(recorded: list[dict[str, object]]) -> None:+async def _settle(recorded: Sequence[Mapping[str, object]], count: int = 1) -> None:for _ in range(300):- if recorded:+ if len(recorded) >= count:returnawait asyncio.sleep(0.01)@@ -857,8 +964,6 @@ async def test_chunk_processor_logs_a_provider_error_frame_as_a_failure_when_cloassert received == list(frames)assert recorder.success_kwargs == []assert logging_obj.model_call_details.get("has_dispatched_final_stream_success") is not True- assert "combined_usage_object" not in logging_obj.model_call_details- assert "response_cost" not in logging_obj.model_call_detailsassert logging_obj.should_run_logging("async_failure")assert len(recorder.failure_kwargs) == 1failure_payload = recorder.failure_kwargs[0]["standard_logging_object"]@@ -991,6 +1096,31 @@ async def test_superseded_attempt_failure_log_keeps_its_own_deployment_when_the_assert logging_obj.model_call_details["litellm_params"]["model_info"]["id"] == "deployment-2"+async def test_error_frame_then_exhausted_retry_bills_both_attempts() -> None:+ recorder: Final = _EventRecorder()+ logging_obj: Final = _anthropic_messages_logging_obj(recorder, "test-error-frame-terminal-billing")+ superseded: Final = _anthropic_messages_attempt(+ logging_obj, _anthropic_stream_of((_anthropic_message_start_frame("msg_a1", 52), _anthropic_overloaded_error_frame()))+ )+ async for chunk in superseded:+ if b"event: error" in chunk:+ break+ await aclose_superseded_attempt(superseded)+ carry_superseded_attempt_usage({"litellm_logging_obj": logging_obj})+ await _drop_after_message_start(logging_obj, "msg_a2", 9)+ await _settle(recorder.failure_kwargs, count=2)++ failures: Final = tuple(event["standard_logging_object"] for event in recorder.failure_kwargs)+ assert tuple(event["prompt_tokens"] for event in failures) == (52, 9)+ terminal: Final = _failure_fields_to_lift({"litellm_logging_obj": logging_obj})+ usage: Final = terminal["combined_usage_object"]+ assert isinstance(usage, litellm.Usage)+ assert usage.prompt_tokens == sum(event["prompt_tokens"] for event in failures)+ assert usage.completion_tokens == sum(event["completion_tokens"] for event in failures)+ assert terminal["response_cost"] == pytest.approx(sum(event["response_cost"] for event in failures))++@pytest.mark.asyncioasync def test_retry_success_log_carries_its_own_usage_after_a_provider_error_frame():"""Both attempts of a retried /v1/messages stream log through the request's one logging object. The@@ -1025,6 +1155,7 @@ async def test_retry_success_log_carries_its_own_usage_after_a_provider_error_frif b"event: error" in chunk:breakawait aclose_superseded_attempt(superseded)+ carry_superseded_attempt_usage({"litellm_logging_obj": logging_obj})await _settle(recorder.failure_kwargs)retry = attempt((_anthropic_message_start_frame("msg_a2", 7), *_anthropic_completed_stream_tail()))async for _ in retry:@@ -1036,8 +1167,6 @@ async def test_retry_success_log_carries_its_own_usage_after_a_provider_error_frsuccess_payload = recorder.success_kwargs[0]["standard_logging_object"]assert success_payload["status"] == "success"assert (success_payload["prompt_tokens"], success_payload["completion_tokens"]) == (7, 3)--def _google_sse(prompt_tokens: int, completion_tokens: int, text: str) -> bytes:payload = {"candidates": [{"content": {"parts": [{"text": text}], "role": "model"}, "index": 0}],diff --git a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.pyindex 7b18cb3350c..ab6a874a010 100644--- a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py+++ b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py@@ -1,5 +1,8 @@+import asyncioimport datetime as real_datetimeimport smtplib+import traceback+from collections.abc import Mappingfrom typing import Finalimport httpx@@ -11,8 +14,15 @@ from litellm.exceptions import InternalServerErrorfrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.bug_report import ISSUE_URL_BASE+from litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.proxy._types import ProxyErrorTypes, UserAPIKeyAuth-from litellm.proxy.utils import PrismaClient, ProxyLogging, handle_exception_on_proxy+from litellm.proxy.utils import (+ PrismaClient,+ ProxyLogging,+ _failure_fields_to_lift,+ handle_exception_on_proxy,+)+from litellm.router_utils.fallback_event_handlers import carry_superseded_attempt_usagefrom litellm.types.guardrails import GuardrailEventHooks@@ -2472,10 +2482,681 @@ def test_attempts_already_summed_into_the_final_row_are_not_lifted_again():lifted = _failure_fields_to_lift({"litellm_logging_obj": logging_obj}, provider_billed=True)- assert lifted["combined_usage_object"].prompt_tokens == 24+ current_only_logging_obj: Final = _dispatched_failure_logging_obj(+ FAILURE_USAGE_MODEL,+ get_litellm_params(+ metadata={+ "attempted_retries": 1,+ "model_info": {"id": "dep-lit145-final"},+ "previous_models": (+ {"deployment_id": "dep-lit145-final", "exception_type": "Timeout", "attempted_retries": 0},+ ),+ }+ ),+ )+ current_only: Final = _failure_fields_to_lift(+ {"litellm_logging_obj": current_only_logging_obj}, provider_billed=True+ )+ current_only_usage: Final = current_only["combined_usage_object"]++ assert current_only_usage.prompt_tokens > 0+ assert lifted["combined_usage_object"].prompt_tokens == 24 + current_only_usage.prompt_tokensassert "billed_failed_attempts" not in lifted+def test_carry_superseded_attempt_usage_without_stashed_usage_preserves_failure_estimate() -> None:+ request_start: Final = real_datetime.datetime(2026, 1, 1)+ logging_obj: Final = Logging(+ model=FAILURE_USAGE_MODEL,+ messages=ONE_USER_MESSAGE,+ stream=False,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-no-stashed-usage",+ function_id="fn-lit145-no-stashed-usage",+ )+ logging_obj.pre_call(input=ONE_USER_MESSAGE, api_key="sk-test", model=FAILURE_USAGE_MODEL)+ logging_obj.model_call_details["call_type"] = "acompletion"+ logging_obj.model_call_details["messages"] = ONE_USER_MESSAGE++ try:+ try:+ raise httpx.ReadTimeout("no bytes in time")+ except httpx.ReadTimeout as cause:+ raise litellm.Timeout("Request timed out.", model=FAILURE_USAGE_MODEL, llm_provider="openai") from cause+ except litellm.Timeout as timeout:+ logging_obj.failure_handler(+ timeout,+ traceback.format_exc(),+ request_start,+ request_start + real_datetime.timedelta(seconds=1),+ )++ assert "combined_usage_object" not in logging_obj.model_call_details+ request_data: Final = {"litellm_logging_obj": logging_obj}+ before: Final = _failure_fields_to_lift(request_data, provider_billed=True)++ carry_superseded_attempt_usage(request_data)++ after: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ before_usage: Final = before.get("combined_usage_object")+ after_usage: Final = after.get("combined_usage_object")+ assert before_usage is not None+ assert after_usage is not None+ assert after_usage == before_usage+ assert before["response_cost"] > 0+ assert after["response_cost"] == before["response_cost"]+++async def test_dropped_stream_failure_attribution_reaches_terminal_spend_row() -> None:+ from litellm.exceptions import MidStreamFallbackError+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices, Usage++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ model: Final = "deployment-model"+ logging_obj: Final = Logging(+ model=model,+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-attribution",+ function_id="fn-lit145-attribution",+ )+ logging_obj.update_environment_variables(+ model=model,+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-id"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": request_start,+ }+ wrapper: Final = CustomStreamWrapper(+ completion_stream=None,+ model=model,+ logging_obj=logging_obj,+ custom_llm_provider="openai",+ )+ wrapper.chunks = [+ ModelResponseStream(+ id="chatcmpl-attribution",+ created=1742056047,+ model=model,+ object="chat.completion.chunk",+ choices=[StreamingChoices(finish_reason=None, index=0, delta=Delta(content="The"))],+ usage=Usage(prompt_tokens=30, completion_tokens=1, total_tokens=31),+ )+ ]+ exception: Final = httpx.ReadError("connection dropped")++ with pytest.raises(MidStreamFallbackError):+ wrapper._log_stream_failure_and_raise(exception)+ await wrapper.wait_for_failure_logging(timeout=10)++ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=exception,+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ assert row["model_id"] == "deployment-id"+ assert row["custom_llm_provider"] == "openai"+ assert row["model"] == model+++class _ReplaceSharedFailurePayload(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logging_obj: Logging | None = None+ self.replaced: asyncio.Event = asyncio.Event()+ self.started: asyncio.Event = asyncio.Event()+ self.release: asyncio.Event = asyncio.Event()+ self.pause_until_released: bool = False+ self.replacement_payload: object | None = None++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: real_datetime.datetime,+ end_time: real_datetime.datetime,+ ) -> None:+ from pydantic import TypeAdapter++ from litellm.types.utils import StandardLoggingPayload++ payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(kwargs["standard_logging_object"])+ self.started.set()+ if self.pause_until_released:+ await self.release.wait()+ logging_obj: Final = self.logging_obj+ if logging_obj is None:+ return+ replacement: Final = self.replacement_payload or TypeAdapter(StandardLoggingPayload).validate_python(+ {+ **payload,+ "model_id": "newer-deployment-id",+ "custom_llm_provider": "newer-provider",+ "model": "newer-model",+ }+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "standard_logging_object": replacement,+ }+ self.replaced.set()+++class _OrderedAttemptFailureRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.attempt_a_started: asyncio.Event = asyncio.Event()+ self.attempt_b_started: asyncio.Event = asyncio.Event()+ self.release_attempt_a: asyncio.Event = asyncio.Event()+ self.release_attempt_b: asyncio.Event = asyncio.Event()++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: real_datetime.datetime,+ end_time: real_datetime.datetime,+ ) -> None:+ from pydantic import TypeAdapter++ from litellm.types.utils import StandardLoggingPayload++ payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(kwargs["standard_logging_object"])+ if payload["model_id"] == "deployment-a":+ self.attempt_a_started.set()+ await self.release_attempt_a.wait()+ return+ if payload["model_id"] == "deployment-b":+ self.attempt_b_started.set()+ await self.release_attempt_b.wait()+++class _PausedBaselineFailureRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.started: asyncio.Event = asyncio.Event()+ self.release: asyncio.Event = asyncio.Event()+ self.standard_logging_object: object | None = None++ async def async_log_failure_event(+ self,+ kwargs: Mapping[str, object],+ response_obj: object,+ start_time: real_datetime.datetime,+ end_time: real_datetime.datetime,+ ) -> None:+ self.standard_logging_object = kwargs.get("standard_logging_object")+ self.started.set()+ await self.release.wait()+++async def test_latest_dropped_attempt_publishes_its_payload_after_earlier_dispatch_finishes() -> None:+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.types.utils import Usage++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ marker_a: Final = request_start+ marker_b: Final = request_start + real_datetime.timedelta(seconds=1)+ recorder: Final = _OrderedAttemptFailureRecorder()+ logging_obj: Final = Logging(+ model="deployment-model-a",+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-attempt-order",+ function_id="fn-lit145-attempt-order",+ dynamic_async_failure_callbacks=[recorder],+ )+ logging_obj.update_environment_variables(+ model="deployment-model-a",+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-a"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": marker_a,+ "combined_usage_object": Usage(prompt_tokens=4, completion_tokens=1, total_tokens=5),+ "response_cost": 0.001,+ }++ attempt_a: Final = asyncio.create_task(+ logging_obj.dispatch_attempt_failure_handlers(httpx.ReadError("attempt A dropped"), "")+ )+ await asyncio.wait_for(recorder.attempt_a_started.wait(), timeout=10)++ logging_obj.carry_failed_attempt_usage()+ logging_obj.update_environment_variables(+ model="deployment-model-b",+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-b"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "model": "deployment-model-b",+ "custom_llm_provider": "anthropic",+ "current_attempt_api_call_start_time": marker_b,+ "combined_usage_object": Usage(prompt_tokens=7, completion_tokens=2, total_tokens=9),+ "response_cost": 0.002,+ }++ attempt_b: Final = asyncio.create_task(+ logging_obj.dispatch_attempt_failure_handlers(httpx.ReadError("attempt B dropped"), "")+ )+ await asyncio.wait_for(recorder.attempt_b_started.wait(), timeout=10)+ recorder.release_attempt_a.set()+ await attempt_a+ recorder.release_attempt_b.set()+ await attempt_b++ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=httpx.ReadError("attempt B dropped"),+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ assert row["model_id"] == "deployment-b"+ assert row["custom_llm_provider"] == "anthropic"+ assert row["model"] == "deployment-model-b"+++async def test_dropped_attempt_attribution_is_published_while_failure_callback_is_paused() -> None:+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.types.utils import Usage++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ marker_a: Final = request_start+ failure: Final = httpx.ReadError("attempt A dropped")+ recorder: Final = _OrderedAttemptFailureRecorder()+ logging_obj: Final = Logging(+ model="deployment-model-a",+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-attempt-paused",+ function_id="fn-lit145-attempt-paused",+ dynamic_async_failure_callbacks=[recorder],+ )+ logging_obj.update_environment_variables(+ model="deployment-model-a",+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-a"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": marker_a,+ "combined_usage_object": Usage(prompt_tokens=4, completion_tokens=1, total_tokens=5),+ "response_cost": 0.001,+ }++ attempt: Final = asyncio.create_task(logging_obj.dispatch_attempt_failure_handlers(failure, ""))+ await asyncio.wait_for(recorder.attempt_a_started.wait(), timeout=10)++ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=failure,+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ try:+ assert row["model_id"] == "deployment-a"+ assert row["custom_llm_provider"] == "openai"+ assert row["model"] == "deployment-model-a"+ assert row["prompt_tokens"] == 4+ assert row["completion_tokens"] == 1+ finally:+ recorder.release_attempt_a.set()+ await attempt+++async def test_failed_attempt_publishes_baseline_reason_after_invalidation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from pydantic import TypeAdapter++ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.proxy.hooks.autorouter_baseline_cache import AutoRouterBaselineCache, CapturedBaselineObservation+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.router import Router+ from litellm.types.utils import CallTypes, StandardLoggingPayload, Usage+ from tests.unit.proxy.hooks.test_autorouter_baseline_cache import _MODELS, _kwargs++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ marker: Final = request_start+ model: Final = "deployment-model-a"+ router: Final = Router(model_list=_MODELS, disable_cooldowns=True)+ baseline_cache: Final = AutoRouterBaselineCache(+ None,+ router=lambda: router,+ clock=lambda: request_start.timestamp() + 10,+ )+ recorder: Final = _PausedBaselineFailureRecorder()+ logging_obj: Final = Logging(+ model=model,+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type=CallTypes.anthropic_messages.value,+ start_time=request_start,+ litellm_call_id="call-lit145-baseline-failure",+ function_id="fn-lit145-baseline-failure",+ dynamic_async_failure_callbacks=[recorder],+ )+ logging_obj.update_environment_variables(+ model=model,+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-a"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": marker,+ "combined_usage_object": Usage(prompt_tokens=4, completion_tokens=1, total_tokens=5),+ "response_cost": 0.001,+ }+ await baseline_cache.async_pre_call_deployment_hook(_kwargs(logging_obj), CallTypes.anthropic_messages)+ assert logging_obj.baseline_cache_context is not None++ failure: Final = httpx.ReadError("attempt A dropped")+ attempt: Final = asyncio.create_task(logging_obj.dispatch_attempt_failure_handlers(failure, ""))+ try:+ await asyncio.wait_for(recorder.started.wait(), timeout=10)+ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=failure,+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ assert row["model_id"] == "deployment-a"+ assert row["custom_llm_provider"] == "openai"+ assert row["model"] == model+ assert row["prompt_tokens"] == 4+ assert row["completion_tokens"] == 1+ lifted_payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(lifted["standard_logging_object"])+ callback_payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(+ recorder.standard_logging_object+ )++ def baseline_reason(payload: StandardLoggingPayload) -> str:+ encoded: Final = payload["autorouter_baseline_observation"]+ assert isinstance(encoded, str)+ return CapturedBaselineObservation.model_validate_json(encoded).observation.reason or ""++ assert baseline_reason(lifted_payload) == "failed_request"+ assert baseline_reason(callback_payload) == "failed_request"+ finally:+ recorder.release.set()+ await attempt+++async def test_queued_stale_attempt_dispatch_does_not_publish_over_current_attempt() -> None:+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.types.utils import Usage++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ marker_a: Final = request_start+ marker_b: Final = request_start + real_datetime.timedelta(seconds=1)+ recorder: Final = _OrderedAttemptFailureRecorder()+ logging_obj: Final = Logging(+ model="deployment-model-a",+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-stale-attempt",+ function_id="fn-lit145-stale-attempt",+ dynamic_async_failure_callbacks=[recorder],+ )+ logging_obj.update_environment_variables(+ model="deployment-model-a",+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-a"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": marker_a,+ "combined_usage_object": Usage(prompt_tokens=4, completion_tokens=1, total_tokens=5),+ "response_cost": 0.001,+ }+ failure_a: Final = httpx.ReadError("attempt A dropped")+ coro_a: Final = logging_obj.dispatch_attempt_failure_handlers(failure_a, "")++ logging_obj.carry_failed_attempt_usage()+ logging_obj.update_environment_variables(+ model="deployment-model-b",+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-b"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "model": "deployment-model-b",+ "custom_llm_provider": "anthropic",+ "current_attempt_api_call_start_time": marker_b,+ "combined_usage_object": Usage(prompt_tokens=7, completion_tokens=2, total_tokens=9),+ "response_cost": 0.002,+ }+ failure_b: Final = httpx.ReadError("attempt B dropped")+ coro_b: Final = logging_obj.dispatch_attempt_failure_handlers(failure_b, "")++ task_a: Final = asyncio.create_task(coro_a)+ task_b: Final = asyncio.create_task(coro_b)+ try:+ await asyncio.wait_for(+ asyncio.gather(recorder.attempt_a_started.wait(), recorder.attempt_b_started.wait()),+ timeout=10,+ )+ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=failure_b,+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ assert row["model_id"] == "deployment-b"+ assert row["custom_llm_provider"] == "anthropic"+ assert row["model"] == "deployment-model-b"+ finally:+ recorder.release_attempt_a.set()+ recorder.release_attempt_b.set()+ await asyncio.gather(task_a, task_b)++[email protected]("queued_start", [False, True], ids=["running-start", "queued-start"])+async def test_dropped_stream_failure_does_not_overwrite_newer_terminal_payload(queued_start: bool) -> None:+ from litellm.exceptions import MidStreamFallbackError+ from litellm.litellm_core_utils.get_litellm_params import get_litellm_params+ from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload+ from litellm.types.utils import Delta, ModelResponseStream, StandardLoggingPayload, StreamingChoices, Usage+ from pydantic import TypeAdapter++ request_start: Final = real_datetime.datetime(2026, 1, 1)+ model: Final = "deployment-model"+ recorder: Final = _ReplaceSharedFailurePayload()+ logging_obj: Final = Logging(+ model=model,+ messages=ONE_USER_MESSAGE,+ stream=True,+ call_type="acompletion",+ start_time=request_start,+ litellm_call_id="call-lit145-identity",+ function_id="fn-lit145-identity",+ dynamic_async_failure_callbacks=[recorder],+ )+ recorder.logging_obj = logging_obj+ initial_payload: Final = {+ "model_id": "older-deployment-id",+ "custom_llm_provider": "older-provider",+ "model": "older-model",+ }+ logging_obj.update_environment_variables(+ model=model,+ user="",+ optional_params={},+ litellm_params=get_litellm_params(metadata={"model_info": {"id": "deployment-id"}}),+ )+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "custom_llm_provider": "openai",+ "first_api_call_start_time": request_start,+ "current_attempt_api_call_start_time": request_start,+ "standard_logging_object": initial_payload,+ }++ def assert_newer_payload_attribution() -> None:+ request_data: Final = {"litellm_logging_obj": logging_obj}+ lifted: Final = _failure_fields_to_lift(request_data, provider_billed=True)+ terminal_kwargs: Final = {+ key: value+ for key, value in {**request_data, **lifted}.items()+ if key != "litellm_logging_obj"+ }+ row: Final = get_logging_payload(+ kwargs=terminal_kwargs,+ response_obj=exception,+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )++ assert row["model_id"] == "newer-deployment-id"+ assert row["custom_llm_provider"] == "newer-provider"+ assert row["model"] == "newer-model"++ exception: Final = httpx.ReadError("connection dropped")+ if queued_start:+ dispatch: Final = logging_obj.dispatch_attempt_failure_handlers(exception, "")+ logging_obj._failure_handler_helper_fn(+ exception=httpx.ReadError("newer failure"),+ traceback_exception="",+ start_time=request_start,+ end_time=request_start + real_datetime.timedelta(seconds=1),+ )+ replacement_base: Final = logging_obj.model_call_details["standard_logging_object"]+ replacement_payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(+ {+ **replacement_base,+ "model_id": "newer-deployment-id",+ "custom_llm_provider": "newer-provider",+ "model": "newer-model",+ }+ )+ recorder.pause_until_released = True+ recorder.replacement_payload = replacement_payload+ logging_obj.model_call_details = {+ **logging_obj.model_call_details,+ "standard_logging_object": replacement_payload,+ }+ assert logging_obj.model_call_details["current_attempt_api_call_start_time"] == request_start++ task: Final = asyncio.create_task(dispatch)+ try:+ await asyncio.wait_for(recorder.started.wait(), timeout=10)+ assert_newer_payload_attribution()+ finally:+ recorder.release.set()+ await task++ await asyncio.wait_for(recorder.replaced.wait(), timeout=10)+ assert_newer_payload_attribution()+ return++ wrapper: Final = CustomStreamWrapper(+ completion_stream=None,+ model=model,+ logging_obj=logging_obj,+ custom_llm_provider="openai",+ )+ wrapper.chunks = [+ ModelResponseStream(+ id="chatcmpl-identity",+ created=1742056047,+ model=model,+ object="chat.completion.chunk",+ choices=[StreamingChoices(finish_reason=None, index=0, delta=Delta(content="The"))],+ usage=Usage(prompt_tokens=30, completion_tokens=1, total_tokens=31),+ )+ ]++ with pytest.raises(MidStreamFallbackError):+ wrapper._log_stream_failure_and_raise(exception)+ await wrapper.wait_for_failure_logging(timeout=10)+ await asyncio.wait_for(recorder.replaced.wait(), timeout=10)+ assert_newer_payload_attribution()++def test_a_timed_out_attempt_from_the_group_a_fallback_left_is_still_billed():"""After a fallback hop the router restarts ``attempted_retries`` at 0 for the new model group andre-logs the attempt that exhausted the previous group, so the final attempt (dep-b, retry 1) must be@@ -2655,6 +3336,47 @@ def test_a_request_that_timed_out_at_a_provider_bills_its_input_at_the_input_ratassert response_cost == pytest.approx(expected_input_cost)+ "current_attempt_api_call_start_time",+ [None, 1700000001.0],+ ids=["retry-not-dispatched", "retry-dispatched"],+)+def test_a_retry_failure_bills_input_only_for_dispatched_attempts(+ current_attempt_api_call_start_time: float | None,+) -> None:+ from litellm.proxy.utils import _estimate_dispatched_failure_usage, _failure_fields_to_lift+ from litellm.types.utils import Usage++ prior_usage: Final = Usage(prompt_tokens=4, completion_tokens=2, total_tokens=6)+ estimated_retry_usage: Final = _estimate_dispatched_failure_usage(FAILURE_USAGE_MODEL, ONE_USER_MESSAGE, None)+ assert estimated_retry_usage is not None++ lifted: Final = _failure_fields_to_lift(+ {+ "litellm_logging_obj": _LoggingObj(+ {+ "first_api_call_start_time": 1700000000.0,+ "current_attempt_api_call_start_time": current_attempt_api_call_start_time,+ "failed_attempts_usage": ((prior_usage, 0.25),),+ "call_type": "acompletion",+ "model": FAILURE_USAGE_MODEL,+ "messages": ONE_USER_MESSAGE,+ }+ )+ }+ )++ usage: Final = lifted["combined_usage_object"]+ assert isinstance(usage, Usage)+ expected_retry_tokens: Final = (+ estimated_retry_usage.prompt_tokens if current_attempt_api_call_start_time is not None else 0+ )+ assert usage.prompt_tokens == prior_usage.prompt_tokens + expected_retry_tokens+ assert usage.completion_tokens == prior_usage.completion_tokens+ assert usage.total_tokens == prior_usage.total_tokens + expected_retry_tokens+ assert lifted["response_cost"] == 0.25++@pytest.mark.parametrize("model_call_details, dispatched",[diff --git a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.pyindex f0f3fc37ddb..e88d951ff09 100644--- a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py+++ b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py@@ -27,7 +27,7 @@ from litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.llms.xai.common_utils import xai_reported_cost_in_usdfrom litellm.proxy._experimental.mcp_server import mcp_server_managerfrom litellm.proxy._experimental.mcp_server.faults.list_outcomes import ServerListOk-from litellm.proxy.utils import _failure_fields_to_lift+from litellm.proxy.utils import _estimate_dispatched_failure_usage, _failure_fields_to_liftfrom litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handlerfrom litellm.types.llms.openai import (ResponsesAPIResponse,@@ -1980,7 +1980,22 @@ async def test_non_stream_auto_execute_failing_every_retry_bills_each_paid_firstfailure_row_fields: Final = _failure_fields_to_lift(MappingProxyType({"litellm_logging_obj": logging_obj}))billed_usage: Final = failure_row_fields["combined_usage_object"]assert isinstance(billed_usage, Usage)- assert (billed_usage.prompt_tokens, billed_usage.completion_tokens) == billed_tokens+ estimated_failure_usage: Final = (+ _estimate_dispatched_failure_usage(+ model="gpt-5.6",+ request_input=logging_obj.model_call_details.get("messages"),+ system_input=None,+ )+ if not retried_first_rounds+ else None+ )+ expected_prompt_tokens: Final = billed_tokens[0] + (+ estimated_failure_usage.prompt_tokens if estimated_failure_usage is not None else 0+ )+ assert (billed_usage.prompt_tokens, billed_usage.completion_tokens) == (+ expected_prompt_tokens,+ billed_tokens[1],+ )assert failure_row_fields["response_cost"] == pytest.approx(_round_cost(_ROUND_ONE_BODY) + sum(_round_cost(body) for body in retried_first_rounds))diff --git a/tests/unit/router_utils/test_fallback_event_handlers.py b/tests/unit/router_utils/test_fallback_event_handlers.pyindex 09ce002353f..75b6ab04446 100644--- a/tests/unit/router_utils/test_fallback_event_handlers.py+++ b/tests/unit/router_utils/test_fallback_event_handlers.py@@ -2,7 +2,7 @@ import asyncioimport importlibimport jsonimport time-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom datetime import datetime, timedeltafrom types import MappingProxyTypefrom typing import Any, Final, Literal, NoReturn@@ -11,6 +11,7 @@ from unittest.mock import MagicMock, patchimport httpximport pytestimport respx+from pydantic import TypeAdapterimport litellmfrom litellm import Router@@ -19,7 +20,8 @@ from litellm.llms.anthropic.pass_through.messages.fake_stream_iterator import Fafrom litellm.litellm_core_utils import get_llm_provider_logicfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper-from litellm.router_utils.cooldown_handlers import mark_advisor_orchestration_failure+from litellm.router_utils.cooldown_handlers import async_get_cooldown_deployments, mark_advisor_orchestration_failure+from litellm.types.utils import Choices, Message, ModelResponse, StandardLoggingPayload, Usagefrom litellm.router_utils.fallback_event_handlers import (MID_STREAM_FALLBACK_CONTROLS_KEY,PRE_ROUTING_SELECTED_MODEL_KEY,@@ -147,6 +149,220 @@ class RecordingRouter:return StreamingWrapper()+def _request_logging_obj() -> Logging:+ return Logging(+ model="primary-model",+ messages=[{"role": "user", "content": "ping"}],+ stream=True,+ call_type="anthropic_messages",+ start_time=datetime(2026, 1, 1),+ litellm_call_id="fallback-hop",+ function_id="fallback-hop",+ )+++class _SuccessRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.logged: tuple[tuple[int, float], ...] = ()++ async def async_log_success_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: datetime, end_time: datetime+ ) -> None:+ payload: Final = TypeAdapter(StandardLoggingPayload).validate_python(kwargs["standard_logging_object"])+ self.logged = (*self.logged, (payload["completion_tokens"], payload["response_cost"]))+++class HopLoggingItsOwnSuccessRouter(FakeRouter):+ async def async_function_with_fallbacks(self, *args: object, **kwargs: object) -> StreamingWrapper:+ hop_response: Final = ModelResponse(+ id="chatcmpl-hop",+ model="gpt-5.6",+ choices=[Choices(index=0, message=Message(role="assistant", content="served by the hop"))],+ usage=Usage(prompt_tokens=52, completion_tokens=7, total_tokens=59),+ )+ now: Final = datetime(2026, 1, 1)+ logging_obj: Final = kwargs["litellm_logging_obj"]+ assert isinstance(logging_obj, Logging)+ await logging_obj.async_success_handler(result=hop_response, start_time=now, end_time=now)+ return StreamingWrapper()+++async def test_run_async_fallback_opens_the_hop_without_the_superseded_attempts_partial_usage() -> None:+ """A stream the failed attempt dropped stashed the usage it consumed on the request's logging object. The+ hop that replaces it logs its own usage, so the integrations see the hop's tokens and cost, not the stash."""+ recorder: Final = _SuccessRecorder()+ logging_obj: Final = Logging(+ model="gpt-5.6",+ messages=[{"role": "user", "content": "ping"}],+ stream=False,+ call_type="completion",+ start_time=datetime(2026, 1, 1),+ litellm_call_id="fallback-hop-success",+ function_id="fallback-hop-success",+ dynamic_async_success_callbacks=[recorder],+ )+ logging_obj.model_call_details["custom_llm_provider"] = "openai"+ logging_obj.model_call_details["litellm_params"] = {"acompletion": True}+ logging_obj.model_call_details["current_attempt_api_call_start_time"] = datetime(2026, 1, 1)+ logging_obj.litellm_params = logging_obj.model_call_details["litellm_params"]+ partial_usage: Final = Usage(prompt_tokens=52, completion_tokens=1, total_tokens=53)+ logging_obj.record_partial_usage_for_failure(partial_usage, 0.01)++ await run_async_fallback(+ litellm_router=HopLoggingItsOwnSuccessRouter(),+ fallback_model_group=["fallback-model"],+ original_model_group="primary-model",+ original_exception=RuntimeError("stream dropped before content"),+ max_fallbacks=3,+ fallback_depth=0,+ litellm_logging_obj=logging_obj,+ )++ assert tuple(tokens for tokens, _ in recorder.logged) == (7,)+ assert recorder.logged[0][1] != 0.01+ assert logging_obj.model_call_details["failed_attempts_usage"] == ((partial_usage, 0.01),)+ assert logging_obj.model_call_details["current_attempt_api_call_start_time"] is None+++async def test_run_async_fallback_preserves_superseded_usage_when_hop_fails_before_opening() -> None:+ logging_obj: Final = _request_logging_obj()+ partial_usage: Final = Usage(prompt_tokens=52, completion_tokens=1, total_tokens=53)+ logging_obj.record_partial_usage_for_failure(partial_usage, 0.01)++ with pytest.raises(RuntimeError, match="fallback model also failed"):+ await run_async_fallback(+ litellm_router=AlwaysFailRouter(),+ fallback_model_group=["fallback-model"],+ original_model_group="primary-model",+ original_exception=RuntimeError("stream dropped before content"),+ max_fallbacks=3,+ fallback_depth=0,+ litellm_logging_obj=logging_obj,+ )++ assert logging_obj.model_call_details["failed_attempts_usage"] == ((partial_usage, 0.01),)+++class _RateLimitedHop(Exception):+ def __init__(self, deployment_id: str = "fallback-dep-1") -> None:+ super().__init__("fallback deployment rate limited")+ self.status_code = 429+ self.failed_deployment_id = deployment_id+++_EARLIER_FAILURE_MARKER: Final = datetime(2026, 1, 1)+_FIRST_HOP_FAILURE_MARKER: Final = datetime(2026, 1, 2)+_FINAL_HOP_FAILURE_MARKER: Final = datetime(2026, 1, 3)+++class _TwoFailureFallbackRouter(Router):+ def __init__(self) -> None:+ super().__init__(+ model_list=[+ {+ "model_name": "fallback-model",+ "litellm_params": {"model": "openai/gpt-5.6", "api_key": "fake-key"},+ "model_info": {"id": f"fallback-dep-{index}"},+ }+ for index in (1, 2)+ ],+ allowed_fails=0,+ cooldown_time=60,+ num_retries=0,+ )++ async def async_function_with_fallbacks(self, *args: object, **kwargs: object) -> NoReturn:+ logging_obj: Final[object] = kwargs["litellm_logging_obj"]+ assert isinstance(logging_obj, Logging)+ assert logging_obj.model_call_details.get("has_logged_async_failure", False) is False++ logging_obj.model_call_details["current_attempt_api_call_start_time"] = _FIRST_HOP_FAILURE_MARKER+ try:+ raise _RateLimitedHop("fallback-dep-1")+ except _RateLimitedHop:+ logging_obj.mark_logging_complete("async_failure")++ logging_obj.model_call_details["current_attempt_api_call_start_time"] = _FINAL_HOP_FAILURE_MARKER+ raise _RateLimitedHop("fallback-dep-2")+++def _two_deployment_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "fallback-model",+ "litellm_params": {"model": "openai/gpt-5.6", "api_key": "fake-key"},+ "model_info": {"id": f"fallback-dep-{index}"},+ }+ for index in (1, 2)+ ],+ num_retries=0,+ )++[email protected]("failure_already_logged", [False, True])+async def test_run_async_fallback_cools_down_a_failed_hop_once(failure_already_logged: bool) -> None:+ """The manual cooldown stands in for the failure callbacks the logging object blocks once a failure has+ been logged. A hop whose own failure was the first one logged already ran them, so only a hop that failed+ with the flag already set gets the manual cooldown."""+ router: Final = _two_deployment_router()+ logging_obj: Final = _request_logging_obj()+ if failure_already_logged:+ logging_obj.model_call_details["current_attempt_api_call_start_time"] = _EARLIER_FAILURE_MARKER+ logging_obj.mark_logging_complete("async_failure")++ async def rate_limited_hop(*args: object, **kwargs: object) -> NoReturn:+ hop_logging_obj: Final = kwargs["litellm_logging_obj"]+ assert isinstance(hop_logging_obj, Logging)+ hop_logging_obj.model_call_details["current_attempt_api_call_start_time"] = _FINAL_HOP_FAILURE_MARKER+ if hop_logging_obj.model_call_details.get("has_logged_async_failure", False) is not True:+ hop_logging_obj.mark_logging_complete("async_failure")+ raise _RateLimitedHop()++ with pytest.raises(_RateLimitedHop):+ await run_async_fallback(+ litellm_router=router,+ fallback_model_group=["fallback-model"],+ original_model_group="primary-model",+ original_exception=RuntimeError("stream dropped before content"),+ max_fallbacks=3,+ fallback_depth=0,+ litellm_logging_obj=logging_obj,+ original_function=rate_limited_hop,+ metadata={},+ )++ cooled_down: Final = await async_get_cooldown_deployments(litellm_router_instance=router, parent_otel_span=None)+ assert cooled_down == (["fallback-dep-1"] if failure_already_logged else [])+++async def test_run_async_fallback_cools_down_the_final_deployment_after_retry_failure_logging() -> None:+ router: Final = _TwoFailureFallbackRouter()+ logging_obj: Final = _request_logging_obj()+ assert logging_obj.model_call_details.get("has_logged_async_failure", False) is False++ with pytest.raises(_RateLimitedHop):+ await run_async_fallback(+ litellm_router=router,+ fallback_model_group=["fallback-model"],+ original_model_group="primary-model",+ original_exception=RuntimeError("stream dropped before content"),+ max_fallbacks=3,+ fallback_depth=0,+ litellm_logging_obj=logging_obj,+ metadata={},+ )++ assert logging_obj.model_call_details.get("has_logged_async_failure", False) is True+ cooled_down: Final = await async_get_cooldown_deployments(litellm_router_instance=router, parent_otel_span=None)+ assert cooled_down == ["fallback-dep-2"]++@pytest.mark.asyncioasync def test_run_async_fallback_forwards_include_fallback_errors_to_nested_call():"""A nested fallback (multi-hop) must keep collecting errors, so the opt-in@@ -1163,11 +1379,18 @@ class TestRunAsyncFallbackTriggersCooldown:return Noneasync def async_function_with_fallbacks(self, *args, **kwargs):+ logging_obj: Final = kwargs.get("litellm_logging_obj")+ if isinstance(logging_obj, Logging):+ logging_obj.model_call_details["current_attempt_api_call_start_time"] = _FINAL_HOP_FAILURE_MARKER+ if logging_obj.model_call_details.get("has_logged_async_failure", False) is not True:+ logging_obj.mark_logging_complete("async_failure")raise RuntimeError("fallback model also failed")- def _logging_obj(self, has_logged_async_failure: bool) -> MagicMock:- logging_obj = MagicMock()- logging_obj.model_call_details = {"has_logged_async_failure": has_logged_async_failure}+ def _logging_obj(self, has_logged_async_failure: bool) -> Logging:+ logging_obj: Final = _request_logging_obj()+ if has_logged_async_failure:+ logging_obj.model_call_details["current_attempt_api_call_start_time"] = _EARLIER_FAILURE_MARKER+ logging_obj.mark_logging_complete("async_failure")return logging_obj@pytest.mark.asynciodiff --git a/tests/unit/test_router/test_router.py b/tests/unit/test_router/test_router.pyindex b119d216542..e1f748fcb58 100644--- a/tests/unit/test_router/test_router.py+++ b/tests/unit/test_router/test_router.py@@ -23,7 +23,7 @@ import pytestimport respxfrom fastapi import HTTPExceptionfrom opentelemetry import trace-from pydantic import BaseModel+from pydantic import BaseModel, TypeAdapterimport litellmfrom litellm import APIConnectionError, Router@@ -93,7 +93,7 @@ from litellm.llms.base_llm.vector_store.transformation import(LiteLLMVectorStoreEmbeddingExecutor,RouterVectorStoreEmbeddingExecutor,)-from litellm.types.utils import CallTypes, CredentialItem+from litellm.types.utils import CallTypes, CredentialItem, Usagefrom litellm.utils import _invalidate_model_cost_lowercase_mapfrom tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcomefrom tests.fake_openai_endpoint import FAKE_OPENAI_API_BASE@@ -16726,6 +16726,7 @@ class _AnthropicMessagesFakeByteStream:self._hidden_params = {"additional_headers": {"x-amzn-requestid": "req-1"}}self.closed = Falseself.closed_as_superseded = False+ self.close_contexts: tuple[bool, ...] = ()def __aiter__(self):return self@@ -16736,6 +16737,7 @@ class _AnthropicMessagesFakeByteStream:return self._chunks.pop(0)async def aclose(self) -> None:+ self.close_contexts = (*self.close_contexts, closing_superseded_attempt())self.closed_as_superseded = self.closed_as_superseded or closing_superseded_attempt()self.closed = True@@ -17979,6 +17981,51 @@ async def test_anthropic_messages_stream_dropped_before_content_is_retried_withiassert [(attempted, budget) for _, attempted, budget in provider.calls] == [(0, 2), (1, 2)]+class _AnthropicMessagesRetryStashRecorder:+ def __init__(self) -> None:+ self.observed: tuple[Usage | None, ...] = ()++ def record(self, usage: Usage | None) -> None:+ self.observed = (*self.observed, usage)+++async def test_anthropic_messages_retry_opens_without_the_superseded_attempts_partial_usage() -> None:+ """The dropped attempt's usage stays available for terminal billing without reaching the retry's success log."""+ router: Final = _anthropic_messages_retry_router(num_retries=1)+ logging_obj: Final = LiteLLMLogging(+ model="glm",+ messages=[{"role": "user", "content": "ping"}],+ stream=True,+ call_type="anthropic_messages",+ start_time=datetime(2026, 1, 1),+ litellm_call_id="retry-own-usage",+ function_id="retry-own-usage",+ )+ partial_usage: Final = Usage(prompt_tokens=52, completion_tokens=1, total_tokens=53)+ logging_obj.record_partial_usage_for_failure(partial_usage, 0.01)+ stash_recorder: Final = _AnthropicMessagesRetryStashRecorder()+ usage_adapter: Final = TypeAdapter(Usage | None)++ def retry_stream() -> _AnthropicMessagesFakeByteStream:+ stash_recorder.record(+ usage_adapter.validate_python(logging_obj.model_call_details.get("combined_usage_object"))+ )+ return _anthropic_messages_retried_stream()++ provider: Final = _AnthropicMessagesScriptedProvider(_anthropic_messages_dropped_before_content, retry_stream)++ stream: Final = await _anthropic_messages_stream_through_router(+ router, provider, litellm_logging_obj=logging_obj+ )+ body: Final = tuple([chunk async for chunk in stream])++ assert stash_recorder.observed == (None,)+ assert body == (_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("pong"))+ assert "response_cost" not in logging_obj.model_call_details+ assert logging_obj.model_call_details["failed_attempts_usage"] == ((partial_usage, 0.01),)++@pytest.mark.asyncioasync def test_anthropic_messages_superseded_stream_is_closed_before_the_retry_opens():"""Both attempts log through the request's one logging object, so the superseded attempt's end-of-stream@@ -18001,6 +18048,7 @@ async def test_anthropic_messages_superseded_stream_is_closed_before_the_retry_oassert body == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("pong")]assert superseded_closed_when_retry_opened == [True]+ assert superseded.close_contexts[0] is True@pytest.mark.asyncio