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): stop two settlement paths from pinning the budget reservation
mateo-berri8b566a7f0aa3
diff --git a/litellm/interactions/background_cost_polling.py b/litellm/interactions/background_cost_polling.pyindex f2957d08840..5d7dca80b73 100644--- a/litellm/interactions/background_cost_polling.py+++ b/litellm/interactions/background_cost_polling.py@@ -10,6 +10,14 @@ billing: it schedules a poll task that fetches the interaction until itreaches a terminal status and logs the final usage as a single success eventattributed to the original request.+``requires_action`` is terminal for the interaction it names. The API has no+operation that resumes one: a caller answers a tool request by creating a new+interaction whose ``previous_interaction_id`` points at it, and that new+interaction bills itself. The paused interaction keeps the tokens it already+spent producing the tool request, so it is billed and settled where it stops+rather than polled until the timeout, which would both lose that usage and+hold its budget reservation open for the whole timeout window.+Deleting an interaction makes every subsequent poll fail, which would let acaller retrieve the completed output themselves and then delete it before thepoll task settles, leaving the work unbilled and the budget reservation@@ -39,7 +47,7 @@ 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"})+_TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled", "incomplete", "budget_exceeded", "requires_action"})@dataclass(frozen=True, slots=True)@@ -125,7 +133,7 @@ async def poll_and_log_background_interaction_cost(if not _claim_settlement(context.logging_obj):returnif response.usage is not None:- await context.logging_obj.async_log_background_interaction_completion(result=response)+ await _bill_settled_interaction(logging_obj=context.logging_obj, response=response)else:await _release_open_budget_reservation(logging_obj=context.logging_obj)return@@ -162,6 +170,20 @@ async def _release_open_budget_reservation(logging_obj: "LiteLLMLoggingObj") ->verbose_logger.exception("Failed to release budget reservation for an unbilled background interaction")+async def _bill_settled_interaction(logging_obj: "LiteLLMLoggingObj", response: InteractionsAPIResponse) -> None:+ """+ Claiming the settlement makes the claimer solely responsible for the+ reservation, and no one retries a claim that is already set. A billing+ failure here must therefore release the reservation on its way out, or it+ stays pinned at the estimated cost until the whole poll times out.+ """+ try:+ await logging_obj.async_log_background_interaction_completion(result=response)+ except Exception:+ await _release_open_budget_reservation(logging_obj=logging_obj)+ raise++def is_pollable_background_interaction(response: InteractionsAPIResponse) -> bool:"""The single gate deciding whether a create's response gets a poll task.@@ -247,6 +269,6 @@ async def maybe_settle_background_interaction_before_delete(if not _claim_settlement(context.logging_obj):returnif response.status in _TERMINAL_STATUSES and response.usage is not None:- await context.logging_obj.async_log_background_interaction_completion(result=response)+ await _bill_settled_interaction(logging_obj=context.logging_obj, response=response)returnawait _release_open_budget_reservation(logging_obj=context.logging_obj)diff --git a/tests/test_litellm/interactions/test_background_cost_polling.py b/tests/test_litellm/interactions/test_background_cost_polling.pyindex 7908e0e8f17..759bdc71dfc 100644--- a/tests/test_litellm/interactions/test_background_cost_polling.py+++ b/tests/test_litellm/interactions/test_background_cost_polling.py@@ -59,6 +59,10 @@ def _logging_obj_with_reservation(reservation: dict) -> LitellmLogging:return _logging_obj(litellm_params={"metadata": {"user_api_key_budget_reservation": reservation}})+async def _raise_on_billing(result: InteractionsAPIResponse) -> None:+ raise RuntimeError("cost calculation failed for a settled background interaction")++def _context(logging_obj: LitellmLogging, timeout_seconds: float = 1.0) -> BackgroundInteractionPollContext:return BackgroundInteractionPollContext(interaction_id="interactions/bg-abc",@@ -120,6 +124,33 @@ async def test_poller_bills_once_when_interaction_completes():assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175+async def test_poller_bills_an_interaction_paused_for_a_tool_result():+ logging_obj = _logging_obj()+ fetch, calls = _fetch_sequence(+ _response("in_progress", with_usage=False),+ _response("requires_action", with_usage=True),+ )++ await poll_and_log_background_interaction_cost(_context(logging_obj), fetch_interaction=fetch)++ assert len(calls) == 2+ assert logging_obj.model_call_details["response_cost"] > 0+ assert logging_obj.model_call_details["standard_logging_object"]["total_tokens"] == 175+++async def test_poller_does_not_pin_the_budget_for_an_interaction_paused_for_a_tool_result():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ fetch, _ = _fetch_sequence(_response("requires_action", 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_stops_without_billing_on_terminal_status_without_usage():logging_obj = _logging_obj()@@ -170,6 +201,19 @@ async def test_poller_releases_budget_reservation_on_timeout_give_up():assert reservation["finalized"] is True+async def test_poller_releases_budget_reservation_when_billing_raises():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ fetch, _ = _fetch_sequence(_response("completed", with_usage=True))+ logging_obj.async_log_background_interaction_completion = _raise_on_billing++ with pytest.raises(RuntimeError):+ await poll_and_log_background_interaction_cost(_context(logging_obj), fetch_interaction=fetch)++ assert reservation["finalized"] is True++@pytest.mark.asyncioasync def test_poller_leaves_reservation_reconciliation_to_the_completion_event():reservation = _reservation()@@ -248,6 +292,22 @@ def _register_poll(logging_obj: LitellmLogging, poll_fetch=None) -> asyncio.Taskreturn task+async def test_delete_settlement_bills_an_interaction_paused_for_a_tool_result():+ logging_obj = _logging_obj()+ task = _register_poll(logging_obj)+ fetch, calls = _fetch_sequence(_response("requires_action", with_usage=True))++ await maybe_settle_background_interaction_before_delete(+ interaction_id="interactions/bg-abc",+ fetch_interaction=fetch,+ )++ assert len(calls) == 1+ assert logging_obj.model_call_details["response_cost"] > 0+ await asyncio.wait_for(task, timeout=5)++@pytest.mark.asyncioasync def test_delete_settlement_bills_pending_background_interaction():logging_obj = _logging_obj()@@ -299,6 +359,24 @@ async def test_delete_settlement_releases_reservation_when_prefetch_fails():await asyncio.wait_for(task, timeout=5)+async def test_delete_settlement_releases_reservation_when_billing_raises():+ reservation = _reservation()+ logging_obj = _logging_obj_with_reservation(reservation)+ task = _register_poll(logging_obj)+ fetch, _ = _fetch_sequence(_response("completed", with_usage=True))+ logging_obj.async_log_background_interaction_completion = _raise_on_billing++ with pytest.raises(RuntimeError):+ await maybe_settle_background_interaction_before_delete(+ interaction_id="interactions/bg-abc",+ fetch_interaction=fetch,+ )++ assert reservation["finalized"] is True+ await asyncio.wait_for(task, timeout=5)++@pytest.mark.asyncioasync def test_delete_settlement_ignores_interactions_without_pending_poll():fetch, calls = _fetch_sequence(_response("completed", with_usage=True))