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): hold budget reservation open until background interaction completes
mateo-berribbb156577245
diff --git a/litellm/interactions/background_cost_polling.py b/litellm/interactions/background_cost_polling.pyindex fefbf8715cb..846b26f28b9 100644--- a/litellm/interactions/background_cost_polling.py+++ b/litellm/interactions/background_cost_polling.py@@ -22,6 +22,7 @@ from litellm.constants import (BACKGROUND_INTERACTION_COST_POLL_TIMEOUT_SECONDS,BACKGROUND_INTERACTION_COST_POLLING_ENABLED,)+from litellm.litellm_core_utils.core_helpers import get_litellm_metadata_from_kwargsfrom litellm.types.interactions import InteractionsAPIResponseif TYPE_CHECKING:@@ -87,12 +88,37 @@ async def poll_and_log_background_interaction_cost(continueif response.usage is not None:await context.logging_obj.async_log_background_interaction_completion(result=response)+ else:+ await _release_open_budget_reservation(logging_obj=context.logging_obj)returnverbose_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)+++async def _release_open_budget_reservation(logging_obj: "LiteLLMLoggingObj") -> None:+ """+ The proxy keeps the pre-call budget reservation open for an in-progress+ background interaction so concurrent creates cannot stack past the budget.+ The completion success event reconciles it to the actual cost; when the+ interaction terminates without billable usage (or polling gives up), no+ such event fires, so the poller must release the reservation here or the+ spend counters stay pinned at the estimated cost.+ """+ metadata = get_litellm_metadata_from_kwargs(kwargs=logging_obj.model_call_details)+ budget_reservation = metadata.get("user_api_key_budget_reservation")+ if not isinstance(budget_reservation, dict):+ return++ from litellm.proxy.spend_tracking.budget_reservation import release_budget_reservation++ try:+ await release_budget_reservation(budget_reservation=budget_reservation)+ except Exception: # noqa: BLE001 # a failed release must not crash the poll task; counters expire via TTL+ verbose_logger.exception("Failed to release budget reservation for an unbilled background interaction")_ACTIVE_POLL_TASKS: set["asyncio.Task[None]"] = set() # mutable-ok: asyncio requires strong refs to running tasksdiff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex 6359eae0fa4..a645bb9929f 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -5,6 +5,7 @@ from typing import Any, List, Optional, Union, castimport litellmfrom litellm._logging import verbose_proxy_logger+from litellm.constants import BACKGROUND_INTERACTION_COST_POLLING_ENABLEDfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.core_helpers import (_get_parent_otel_span_from_kwargs,@@ -278,13 +279,20 @@ class _ProxyDBLogger(CustomLogger):elif budget_reservation is not None:await _release_budget_reservation(budget_reservation=budget_reservation)else:- await _release_budget_reservation(budget_reservation=budget_reservation)if _is_unbilled_in_progress_interaction(completion_response):+ if BACKGROUND_INTERACTION_COST_POLLING_ENABLED:+ verbose_proxy_logger.debug(+ "Cost tracking deferred for in-progress background interaction; "+ "the budget reservation stays open until the poll task logs the final usage"+ )+ return+ await _release_budget_reservation(budget_reservation=budget_reservation)verbose_proxy_logger.debug(- "Cost tracking deferred for in-progress background interaction; "- "a poll task logs the final usage once it completes"+ "Background interaction cost polling is disabled; released the budget "+ "reservation for an in-progress interaction that will not be billed")return+ await _release_budget_reservation(budget_reservation=budget_reservation)# Non-model call types (health checks, afile_delete) have no model or standard_logging_object.# Use .get() for "stream" to avoid KeyError on health checks.# WS session wrappers (_aresponses_websocket, _arealtime) also reach here withdiff --git a/tests/test_litellm/interactions/test_background_cost_polling.py b/tests/test_litellm/interactions/test_background_cost_polling.pyindex aac97826b02..24abeec1053 100644--- a/tests/test_litellm/interactions/test_background_cost_polling.py+++ b/tests/test_litellm/interactions/test_background_cost_polling.py@@ -1,5 +1,6 @@import asyncioimport time+from typing import Optionalimport pytest@@ -23,7 +24,10 @@ USAGE_BLOCK = {}-def _logging_obj(call_type: str = "acreate_interaction") -> LitellmLogging:+def _logging_obj(+ call_type: str = "acreate_interaction",+ litellm_params: Optional[dict] = None,+) -> LitellmLogging:logging_obj = LitellmLogging(model="gemini-2.5-flash",messages=[],@@ -34,7 +38,7 @@ def _logging_obj(call_type: str = "acreate_interaction") -> LitellmLogging:function_id="bg-interactions-fn-id",)logging_obj.update_environment_variables(- litellm_params={},+ litellm_params=litellm_params or {},optional_params={},model="gemini-2.5-flash",custom_llm_provider="gemini",@@ -43,6 +47,14 @@ def _logging_obj(call_type: str = "acreate_interaction") -> LitellmLogging:return logging_obj+def _reservation() -> dict:+ return {"reserved_cost": 0.05, "entries": [], "finalized": False, "input_cost": 0.001}+++def _logging_obj_with_reservation(reservation: dict) -> LitellmLogging:+ return _logging_obj(litellm_params={"metadata": {"user_api_key_budget_reservation": reservation}})++def _context(logging_obj: LitellmLogging, timeout_seconds: float = 1.0) -> BackgroundInteractionPollContext:return BackgroundInteractionPollContext(interaction_id="interactions/bg-abc",@@ -118,6 +130,46 @@ async def test_poller_gives_up_after_timeout_without_billing():assert logging_obj.model_call_details.get("response_cost") is None+async def test_poller_releases_budget_reservation_when_interaction_ends_without_usage():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ fetch, _ = _fetch_sequence(_response("failed", with_usage=False))++ await poll_and_log_background_interaction_cost(_context(logging_obj), fetch_interaction=fetch)++ assert reservation["finalized"] is True+++async def test_poller_releases_budget_reservation_on_timeout_give_up():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ fetch, _ = _fetch_sequence(_response("in_progress", with_usage=False))++ await poll_and_log_background_interaction_cost(+ _context(logging_obj, timeout_seconds=0.01),+ fetch_interaction=fetch,+ )++ assert reservation["finalized"] is True+++async def test_poller_leaves_reservation_reconciliation_to_the_completion_event():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ fetch, _ = _fetch_sequence(+ _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 logging_obj.model_call_details["response_cost"] > 0+ assert reservation["finalized"] is False++@pytest.mark.asyncioasync def test_poller_retries_after_fetch_error_and_still_bills():logging_obj = _logging_obj()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 02a586a3dcc..725e7f22f7d 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@@ -647,6 +647,91 @@ async def test_track_cost_callback_defers_in_progress_background_interaction():mock_proxy_logging.failed_tracking_alert.assert_not_called()+def _in_progress_interaction_kwargs(reservation: dict) -> dict:+ return {+ "call_type": "acreate_interaction",+ "model": "gemini/gemini-3-flash-preview",+ "litellm_call_id": "test-call-id",+ "litellm_params": {"metadata": {"user_api_key_budget_reservation": reservation}},+ "stream": False,+ }+++async def test_track_cost_callback_keeps_reservation_open_for_in_progress_background_interaction():+ """+ The pre-call budget reservation must stay open while a background+ interaction is in flight, so concurrent creates cannot stack past the+ budget; the poll task's completion event reconciles it to the actual cost.+ """+ from litellm.types.interactions import InteractionsAPIResponse++ logger = _ProxyDBLogger()+ reservation = {"reserved_cost": 0.05, "entries": [], "finalized": False}+ in_progress_response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status="in_progress",+ )++ 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=in_progress_response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ assert reservation["finalized"] is False+ mock_proxy_logging.failed_tracking_alert.assert_not_called()+++async def test_track_cost_callback_releases_reservation_for_in_progress_interaction_when_polling_disabled(+ monkeypatch,+):+ """+ With the poll task kill switch off nothing will ever reconcile the+ reservation, so the callback must release it or the spend counters stay+ pinned at the estimated cost forever.+ """+ import litellm.proxy.hooks.proxy_track_cost_callback as callback_module+ from litellm.types.interactions import InteractionsAPIResponse++ monkeypatch.setattr(callback_module, "BACKGROUND_INTERACTION_COST_POLLING_ENABLED", False)++ logger = _ProxyDBLogger()+ reservation = {"reserved_cost": 0.05, "entries": [], "finalized": False}+ in_progress_response = InteractionsAPIResponse(+ id="interactions/bg-abc",+ model="gemini-3-flash-preview",+ status="in_progress",+ )++ 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=in_progress_response,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ assert reservation["finalized"] is True+ mock_proxy_logging.failed_tracking_alert.assert_not_called()++@pytest.mark.asyncioasync def test_async_post_call_failure_hook_propagates_trace_id_from_logging_obj():"""