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(interactions): poll queued background creates and drop the poll's deployment identity
mateo-berria41ac5c13921
diff --git a/litellm/interactions/background_cost_polling.py b/litellm/interactions/background_cost_polling.pyindex 279d2d6b32e..51325354e7d 100644--- a/litellm/interactions/background_cost_polling.py+++ b/litellm/interactions/background_cost_polling.py@@ -32,7 +32,7 @@ the interaction is billed exactly once no matter who settles first.import asynciofrom collections.abc import Awaitable, Callable, Iterator, Mappingfrom dataclasses import dataclass-from typing import TYPE_CHECKING, TypeAlias+from typing import TYPE_CHECKING, Final, TypeAliasfrom litellm._logging import verbose_loggerfrom litellm.constants import (@@ -47,9 +47,13 @@ from litellm.types.interactions import InteractionsAPIResponseif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj-_TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled", "incomplete", "budget_exceeded", "requires_action"})+_TERMINAL_STATUSES: Final = frozenset(+ {"completed", "failed", "cancelled", "incomplete", "budget_exceeded", "requires_action"}+)++_POLLABLE_STATUSES: Final = frozenset({"in_progress", "queued"})-_STATUSES_THAT_PRODUCED_OUTPUT = frozenset({"completed", "requires_action"})+_STATUSES_THAT_PRODUCED_OUTPUT: Final = frozenset({"completed", "requires_action"})@dataclass(frozen=True, slots=True)@@ -113,6 +117,7 @@ async def poll_and_log_background_interaction_cost(context: BackgroundInteractionPollContext,fetch_interaction: FetchInteraction = _fetch_interaction,) -> None:+ last_seen_status: str | None = Nonefor interval in _poll_intervals(initial=context.initial_interval_seconds,maximum=context.max_interval_seconds,@@ -130,6 +135,7 @@ async def poll_and_log_background_interaction_cost(e,)continue+ last_seen_status = response.statusif response.status not in _TERMINAL_STATUSES:continueif not _claim_settlement(context.logging_obj):@@ -141,11 +147,21 @@ async def poll_and_log_background_interaction_cost(returnif not _claim_settlement(context.logging_obj):return- verbose_logger.warning(- "Gave up cost polling for background interaction %s after %ss; its usage will not be tracked",- context.interaction_id,- context.timeout_seconds,- )+ if last_seen_status is not None and last_seen_status not in _POLLABLE_STATUSES:+ verbose_logger.error(+ "Gave up cost polling for background interaction %s after %ss: its last status %r is in neither "+ "the pollable nor the terminal set, so this proxy never learned how to settle it and its usage "+ "will not be tracked",+ context.interaction_id,+ context.timeout_seconds,+ last_seen_status,+ )+ else:+ verbose_logger.warning(+ "Gave up cost polling for background interaction %s after %ss; its usage will not be tracked",+ context.interaction_id,+ context.timeout_seconds,+ )await _release_open_budget_reservation(logging_obj=context.logging_obj)@@ -193,8 +209,14 @@ def is_pollable_background_interaction(response: InteractionsAPIResponse) -> booexactly these responses, on the promise that a poll task will settle them,so a response one site accepts and the other refuses strands itsreservation on the spend counters with nothing left to reconcile it.++ ``queued`` belongs here alongside ``in_progress``. It is the API's+ not-started-yet state, so it reaches a terminal status the same way and+ needs polling for the same reason: nothing else in the proxy ever bills a+ create that came back without usage, so a status missing from both this+ set and ``_TERMINAL_STATUSES`` is billed nowhere and alerts nobody."""- return response.status == "in_progress" and bool(response.id)+ return response.status in _POLLABLE_STATUSES and bool(response.id)def missing_usage_is_expected(response: InteractionsAPIResponse) -> bool:diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 853df91cb89..cdc12896678 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -2212,10 +2212,16 @@ class Logging(LiteLLMLoggingBaseClass):cost breakdown at the zeros the usage-less create stamped and writingthose zeros to the spend log. Dropping it makes this event price thesettled body itself, against the deployment that served the create.++ The same throwaway call stamped the deployment identity that travels+ with the price, so ``model_id`` and ``litellm_model_name`` go with it.+ Left in place they overwrite the create's real deployment with the+ poll's empty one in the payload every logging integration reads."""settled_hidden_params: Final = getattr(result, "_hidden_params", None)if isinstance(settled_hidden_params, dict):- settled_hidden_params.pop("response_cost", None)+ for poll_scoped_key in ("response_cost", "model_id", "litellm_model_name"):+ settled_hidden_params.pop(poll_scoped_key, None)self._reset_success_emission_dedupe()await self.async_success_handler(result=result)diff --git a/tests/test_litellm/interactions/test_background_cost_polling.py b/tests/test_litellm/interactions/test_background_cost_polling.pyindex 759bdc71dfc..97f09de1b52 100644--- a/tests/test_litellm/interactions/test_background_cost_polling.py+++ b/tests/test_litellm/interactions/test_background_cost_polling.py@@ -448,3 +448,98 @@ async def test_schedule_respects_kill_switch(monkeypatch):)assert task is None+++def test_every_status_the_api_can_return_is_either_pollable_or_terminal():+ """+ The proxy bills a usage-less create in exactly two ways: it polls the+ interaction until it settles, or it recognises the status as terminal and+ settles immediately. A status in neither set is billed by nobody, alerts+ nobody, and releases its budget reservation, which is the zero-spend bug+ this whole module exists to fix.++ Pinned against the generated spec enum rather than a hand-written list, so+ a status Google adds later breaks this test instead of silently shipping+ another unbilled path.+ """+ from litellm.interactions.background_cost_polling import _POLLABLE_STATUSES, _TERMINAL_STATUSES+ from litellm.types.interactions.generated import Status1++ spec_statuses = {member.value for member in Status1}+ handled = _POLLABLE_STATUSES | _TERMINAL_STATUSES++ assert spec_statuses - handled == set()+ assert handled - spec_statuses == set()+++async def test_schedule_creates_poll_task_for_queued_create():+ """+ ``queued`` is the API's not-started-yet state. It carries no usage, so the+ create cannot bill it, and it is not terminal, so nothing settles it:+ without a poll task it is never charged at all.+ """+ logging_obj = _logging_obj()+ task = maybe_schedule_background_interaction_cost_polling(+ response=_response("queued", with_usage=False),+ create_kwargs={"litellm_logging_obj": logging_obj},+ custom_llm_provider="gemini",+ )++ assert isinstance(task, asyncio.Task)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+++async def test_poller_bills_an_interaction_that_started_out_queued():+ logging_obj = _logging_obj()+ fetch, calls = _fetch_sequence(+ _response("queued", with_usage=False),+ _response("in_progress", with_usage=False),+ _response("completed", with_usage=True),+ )++ await poll_and_log_background_interaction_cost(_context(logging_obj), fetch_interaction=fetch)++ assert len(calls) == 3+ assert logging_obj.model_call_details["response_cost"] > 0+ assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175+++def test_poll_intervals_double_up_to_the_cap_and_stay_inside_the_timeout():+ """+ The degenerate cases are covered above; this pins the shape the proxy+ actually ships, so an off-by-one in the doubling or in the remaining-budget+ check cannot pass green.+ """+ intervals = list(_poll_intervals(initial=5.0, maximum=60.0, timeout=3600.0))++ assert intervals[:6] == [5.0, 10.0, 20.0, 40.0, 60.0, 60.0]+ assert max(intervals) == 60.0+ assert sum(intervals) <= 3600.0+ assert sum(intervals) + 60.0 > 3600.0+++async def test_giving_up_on_an_unrecognized_status_says_which_status_it_was(monkeypatch):+ """+ A status outside both sets polls for the full timeout and then gives up.+ The give-up line is the only trace it leaves, so it has to name the status+ rather than reporting it as an interaction that was merely still running.+ """+ import litellm.interactions.background_cost_polling as bg++ errors = []+ monkeypatch.setattr(bg.verbose_logger, "error", lambda *args, **kwargs: errors.append(args))++ logging_obj = _logging_obj()+ fetch, _ = _fetch_sequence(_response("halted_for_review", with_usage=False))++ await poll_and_log_background_interaction_cost(+ _context(logging_obj, timeout_seconds=0.01), fetch_interaction=fetch+ )++ assert len(errors) == 1+ assert "halted_for_review" in errors[0]diff --git a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.pyindex d840611fc7b..ca517474a5c 100644--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py@@ -785,11 +785,17 @@ def _in_progress_interaction_kwargs(reservation: dict) -> dict:@pytest.mark.asyncio-async def test_track_cost_callback_keeps_reservation_open_for_in_progress_background_interaction():[email protected]("status", ["in_progress", "queued"])+async def test_track_cost_callback_keeps_reservation_open_for_in_progress_background_interaction(status):"""The pre-call budget reservation must stay open while a backgroundinteraction is in flight, so concurrent creates cannot stack past thebudget; the poll task's completion event reconciles it to the actual cost.++ ``queued`` is in flight for the same reason ``in_progress`` is: it has not+ reached a terminal status, so releasing its reservation here would drop the+ estimate off the spend counters while the interaction is still going to run+ and still going to cost money."""from litellm.types.interactions import InteractionsAPIResponse@@ -798,7 +804,7 @@ async def test_track_cost_callback_keeps_reservation_open_for_in_progress_backgrin_progress_response = InteractionsAPIResponse(id="interactions/bg-abc",model="gemini-3-flash-preview",- status="in_progress",+ status=status,)with patch(@@ -982,29 +988,59 @@ async def test_track_cost_callback_releases_reservation_for_interaction_without_mock_proxy_logging.failed_tracking_alert.assert_not_called()- "status",- ["in_progress", "completed", "failed", "cancelled", "incomplete", "requires_action"],-)[email protected]("interaction_id", ["interactions/bg-abc", ""])-def test_callback_defers_exactly_the_interactions_the_scheduler_polls(status, interaction_id):+async def test_callback_handles_every_status_the_interactions_api_can_return():"""- Pins the invariant the two modules share: the callback may only hold a- budget reservation open for a response the scheduler will actually poll.- Any drift between the two gates leaks reservations onto live spend- counters, so assert they agree rather than restating either condition.+ Whatever status a usage-less create comes back with, exactly one of two+ things has to happen to its budget reservation: the callback holds it open+ for a poll task that will settle it, or it releases it on the spot. A+ status that falls through both leaves the pre-call estimate pinned to the+ key, user, team and org spend counters forever, refusing traffic against+ budget nobody spent.++ Driven off the generated spec enum so a status Google adds later fails here+ instead of quietly leaking reservations in production."""- from litellm.interactions.background_cost_polling import is_pollable_background_interaction- from litellm.proxy.hooks.proxy_track_cost_callback import _is_unbilled_in_progress_interactionfrom litellm.types.interactions import InteractionsAPIResponse+ from litellm.types.interactions.generated import Status1++ deferred = set()+ released = set()++ for status in sorted(member.value for member in Status1):+ logger = _ProxyDBLogger()+ reservation = {"reserved_cost": 0.05, "entries": [], "finalized": False}+ response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status=status,+ )- response = InteractionsAPIResponse(- id=interaction_id,- model="gemini-3-flash-preview",- status=status,- )+ with patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ ) as mock_proxy_logging:+ mock_proxy_logging.failed_tracking_alert = AsyncMock()+ mock_proxy_logging.db_spend_update_writer = MagicMock()+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()++ await logger._PROXY_track_cost_callback(+ kwargs=_in_progress_interaction_kwargs(reservation),+ completion_response=response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )- assert _is_unbilled_in_progress_interaction(response) is is_pollable_background_interaction(response)+ (deferred if reservation["finalized"] is False else released).add(status)++ assert deferred == {"in_progress", "queued"}+ assert released == {+ "completed",+ "requires_action",+ "failed",+ "cancelled",+ "incomplete",+ "budget_exceeded",+ }@pytest.mark.asyncio