Skip to content

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]

track reservation entry before counter write

user83ed317c50c8
diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.py
index 47bd1a35a3e..1d296611bfc 100644
--- a/litellm/proxy/spend_tracking/budget_reservation.py
+++ b/litellm/proxy/spend_tracking/budget_reservation.py
@@ -34,7 +34,14 @@ class _BudgetCounter:
class _CounterReservationUnavailable(Exception):
- pass
+ def __init__(
+ self,
+ touched_counter: bool = False,
+ counter_invalidated: bool = False,
+ ) -> None:
+ self.touched_counter = touched_counter
+ self.counter_invalidated = counter_invalidated
+ super().__init__("Counter reservation unavailable")
def get_reserved_counter_keys(budget_reservation: Optional[dict]) -> set:
@@ -103,14 +110,20 @@ async def reserve_budget_for_request(
counter=counter,
reserved_cost=reservation_cost,
)
+ applied_entries.append(entry)
try:
reserved_value = await _reserve_counter(
counter=counter,
reservation_cost=reservation_cost,
)
- except _CounterReservationUnavailable:
+ except _CounterReservationUnavailable as exc:
+ if exc.touched_counter and not exc.counter_invalidated:
+ await _release_applied_entries_best_effort(
+ entries=[entry],
+ default_reserved_cost=reservation_cost,
+ )
+ applied_entries.remove(entry)
continue
- applied_entries.append(entry)
if reserved_value is not None:
current_spend = reserved_value
@@ -577,6 +590,7 @@ async def _reserve_counter(
_increment_spend_counter_cache,
)
+ attempted_increment = False
try:
if counter.source_cache_key is not None:
await _ensure_spend_counter_initialized(
@@ -599,6 +613,7 @@ async def _reserve_counter(
)
raise _CounterReservationUnavailable
+ attempted_increment = True
reserved_value = await _increment_spend_counter_cache(
counter_key=counter.counter_key,
increment=reservation_cost,
@@ -612,15 +627,20 @@ async def _reserve_counter(
counter.counter_key,
exc_info=True,
)
+ counter_invalidated = False
try:
await _invalidate_spend_counter(counter_key=counter.counter_key)
+ counter_invalidated = True
except Exception:
verbose_proxy_logger.warning(
"Failed to invalidate spend counter after budget reservation failure for %s",
counter.counter_key,
exc_info=True,
)
- raise _CounterReservationUnavailable
+ raise _CounterReservationUnavailable(
+ touched_counter=attempted_increment,
+ counter_invalidated=counter_invalidated,
+ )
async def _get_current_counter_value(counter: _BudgetCounter) -> float:
diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.py
index 350eb952e2a..070b232066a 100644
--- a/tests/test_litellm/proxy/test_budget_reservation.py
+++ b/tests/test_litellm/proxy/test_budget_reservation.py
@@ -987,6 +987,66 @@ async def test_should_skip_reservation_when_counter_initialization_fails(
)
+async def test_should_release_tracked_entry_when_reservation_fails_after_increment(
+ spend_counter_state,
+):
+ counter_cache, key_cache = spend_counter_state
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)
+ valid_token = UserAPIKeyAuth(
+ token="key-budget-reserve-after-increment-failure",
+ spend=0.0,
+ max_budget=1.0,
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ original_increment_counter = ps._increment_spend_counter_cache
+ first_increment = True
+
+ async def fail_after_increment(counter_key: str, increment: float):
+ nonlocal first_increment
+ if first_increment:
+ first_increment = False
+ await counter_cache.async_increment_cache(key=counter_key, value=increment)
+ raise RuntimeError("lost increment response")
+ return await original_increment_counter(
+ counter_key=counter_key,
+ increment=increment,
+ )
+
+ with (
+ patch(
+ "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",
+ return_value=0.5,
+ ),
+ patch(
+ "litellm.proxy.proxy_server._increment_spend_counter_cache",
+ side_effect=fail_after_increment,
+ ),
+ patch(
+ "litellm.proxy.proxy_server._invalidate_spend_counter",
+ side_effect=RuntimeError("invalidate unavailable"),
+ ),
+ ):
+ reservation = await reserve_budget_for_request(
+ request_body=_request_body(),
+ route="/chat/completions",
+ llm_router=None,
+ valid_token=valid_token,
+ team_object=None,
+ user_object=None,
+ prisma_client=None,
+ user_api_key_cache=key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ assert reservation is None
+ assert counter_cache.in_memory_cache.get_cache(
+ key="spend:key:key-budget-reserve-after-increment-failure"
+ ) == pytest.approx(0.0)
+
+
@pytest.mark.asyncio
async def test_should_not_re_read_uncapped_budget_after_reservation_fallback(
spend_counter_state,