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
harden budget reservation edge cases
user0b1ea9eb8f21
diff --git a/litellm/proxy/db/spend_counter_reseed.py b/litellm/proxy/db/spend_counter_reseed.pyindex f4f193300b2..19ec6699390 100644--- a/litellm/proxy/db/spend_counter_reseed.py+++ b/litellm/proxy/db/spend_counter_reseed.py@@ -295,12 +295,28 @@ class SpendCounterReseed:return Nonetry:if spend_counter_cache.redis_cache is not None:- current_value = (- await spend_counter_cache.redis_cache.async_increment(- key=counter_key,- value=window_spend,- )+ seeded = await spend_counter_cache.redis_cache.async_set_cache(+ key=counter_key,+ value=window_spend,+ nx=True,)+ if seeded:+ current_value = window_spend+ else:+ current_cached_value = (+ await spend_counter_cache.redis_cache.async_get_cache(+ key=counter_key+ )+ )+ if current_cached_value is None:+ current_value = (+ await spend_counter_cache.redis_cache.async_increment(+ key=counter_key,+ value=window_spend,+ )+ )+ else:+ current_value = float(current_cached_value)spend_counter_cache.in_memory_cache.set_cache(key=counter_key,value=current_value,diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 675a7d471bb..e77561a5e59 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -2112,12 +2112,14 @@ async def _init_and_increment_window_spend_counter()return- await _ensure_window_spend_counter_initialized(+ initialized = await _ensure_window_spend_counter_initialized(counter_key=counter_key,entity_type=entity_type,entity_id=entity_id,window_start=window_start,)+ if initialized is False:+ returnawait _increment_spend_counter_cache(counter_key=counter_key, increment=increment)@@ -2166,22 +2168,26 @@ async def _ensure_window_spend_counter_initialized(entity_type: str,entity_id: str,window_start: datetime,-):+) -> bool:is_warm = await _is_spend_counter_cache_warm(counter_key=counter_key)- if is_warm is False:- window_spend = await SpendCounterReseed.coalesced_window(- prisma_client=prisma_client,- spend_counter_cache=spend_counter_cache,- counter_key=counter_key,- entity_type=entity_type,- entity_id=entity_id,- window_start=window_start,+ if is_warm is True:+ return True++ window_spend = await SpendCounterReseed.coalesced_window(+ prisma_client=prisma_client,+ spend_counter_cache=spend_counter_cache,+ counter_key=counter_key,+ entity_type=entity_type,+ entity_id=entity_id,+ window_start=window_start,+ )+ if window_spend is None:+ verbose_proxy_logger.warning(+ "Skipping cold spend counter seed for %s because window spend could not be loaded",+ counter_key,)- if window_spend is None:- verbose_proxy_logger.warning(- "Skipping cold spend counter seed for %s because window spend could not be loaded",- counter_key,- )+ return False+ return Trueasync def _is_spend_counter_cache_warm(counter_key: str) -> bool:diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.pyindex 77c6f9ae63e..3631f94a60a 100644--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@ -33,6 +33,10 @@ class _BudgetCounter:window_start: Optional[datetime] = None+class _CounterReservationUnavailable(Exception):+ pass++def get_reserved_counter_keys(budget_reservation: Optional[dict]) -> set:if not budget_reservation:return set()@@ -99,10 +103,13 @@ async def reserve_budget_for_request(counter=counter,reserved_cost=reservation_cost,)- reserved_value = await _reserve_counter(- counter=counter,- reservation_cost=reservation_cost,- )+ try:+ reserved_value = await _reserve_counter(+ counter=counter,+ reservation_cost=reservation_cost,+ )+ except _CounterReservationUnavailable:+ continueapplied_entries.append(entry)if reserved_value is not None:@@ -141,6 +148,9 @@ async def reserve_budget_for_request()raise+ if not applied_entries:+ return None+return {"reserved_cost": reservation_cost,"entries": applied_entries,@@ -572,12 +582,18 @@ async def _reserve_counter(source_cache_key=counter.source_cache_key,)elif counter.spend_log_entity_id is not None and counter.window_start is not None:- await _ensure_window_spend_counter_initialized(+ initialized = await _ensure_window_spend_counter_initialized(counter_key=counter.counter_key,entity_type=counter.entity_type,entity_id=counter.spend_log_entity_id,window_start=counter.window_start,)+ if initialized is False:+ verbose_proxy_logger.warning(+ "Skipping budget reservation for %s because window spend could not be loaded",+ counter.counter_key,+ )+ raise _CounterReservationUnavailablereserved_value = await _increment_spend_counter_cache(counter_key=counter.counter_key,@@ -707,6 +723,9 @@ async def _resize_applied_reservation(actual_cost=new_reserved_cost,default_reserved_cost=current_reserved_cost,)+ for entry in entries:+ entry["reserved_cost"] = new_reserved_cost+ entry["applied_adjustment"] = 0.0def _counter_to_reservation_entry(diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex d1684b7ef1f..c4f86655932 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -757,6 +757,14 @@ async def test_should_shrink_uncapped_reservation_multiple_times(assert reservation is not Noneassert reservation["reserved_cost"] == pytest.approx(0.6)+ assert [entry["reserved_cost"] for entry in reservation["entries"]] == [+ pytest.approx(0.6),+ pytest.approx(0.6),+ ]+ assert [entry["applied_adjustment"] for entry in reservation["entries"]] == [+ pytest.approx(0.0),+ pytest.approx(0.0),+ ]assert counter_cache.in_memory_cache.get_cache(key="spend:key:key-budget-double-resize") == pytest.approx(0.9)@@ -842,6 +850,47 @@ async def test_should_skip_budget_window_with_unparseable_duration() == pytest.approx(0.9)+async def test_should_skip_window_reservation_when_db_baseline_unavailable(+ 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-window-db-unavailable",+ budget_limits=[+ {+ "budget_duration": "1h",+ "max_budget": 1.0,+ }+ ],+ )++ with patch(+ "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",+ return_value=0.5,+ ):+ 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-window-db-unavailable:window:1h"+ )+ is None+ )++@pytest.mark.asyncioasync def test_should_not_re_read_uncapped_budget_after_reservation_fallback(spend_counter_state,diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 53690907712..2acb5493775 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -5261,8 +5261,15 @@ async def test_window_spend_counter_redis_clean_miss_skips_stale_in_memory():redis_store[key] = (redis_store.get(key) or 0.0) + valuereturn redis_store[key]+ async def redis_set_cache(key, value, **_):+ if key in redis_store:+ return False+ redis_store[key] = value+ return True+fake_redis = AsyncMock()fake_redis.async_get_cache = AsyncMock(return_value=None)+ fake_redis.async_set_cache = AsyncMock(side_effect=redis_set_cache)fake_redis.async_increment = AsyncMock(side_effect=redis_increment)counter_cache.redis_cache = fake_redis@@ -5302,6 +5309,69 @@ async def test_window_spend_counter_redis_clean_miss_skips_stale_in_memory():ps.prisma_client = orig_prisma+async def test_window_spend_counter_redis_concurrent_seed_does_not_double_seed():+ from litellm.caching.dual_cache import DualCache+ from litellm.proxy.proxy_server import _init_and_increment_window_spend_counter++ counter_cache = DualCache()+ counter_key = "spend:key:key-window-concurrent-seed:window:1h"+ window_start = datetime.now(timezone.utc) - timedelta(hours=1)+ redis_store = {counter_key: 2.75}+ redis_reads = 0++ async def redis_get_cache(key):+ nonlocal redis_reads+ redis_reads += 1+ if redis_reads <= 2:+ return None+ return redis_store.get(key)++ async def redis_increment(key, value, **_):+ redis_store[key] = (redis_store.get(key) or 0.0) + value+ return redis_store[key]++ fake_redis = AsyncMock()+ fake_redis.async_get_cache = AsyncMock(side_effect=redis_get_cache)+ fake_redis.async_set_cache = AsyncMock(return_value=False)+ fake_redis.async_increment = AsyncMock(side_effect=redis_increment)+ counter_cache.redis_cache = fake_redis++ fake_prisma = MagicMock()+ fake_prisma.db.litellm_spendlogs.group_by = AsyncMock(+ return_value=[+ {"api_key": "key-window-concurrent-seed", "_sum": {"spend": 2.25}}+ ]+ )++ import litellm.proxy.proxy_server as ps++ orig_counter, orig_prisma = ps.spend_counter_cache, ps.prisma_client+ ps.spend_counter_cache = counter_cache+ ps.prisma_client = fake_prisma+ try:+ await _init_and_increment_window_spend_counter(+ counter_key=counter_key,+ entity_type="Key",+ entity_id="key-window-concurrent-seed",+ window_start=window_start,+ increment=0.5,+ )++ fake_redis.async_set_cache.assert_awaited_once_with(+ key=counter_key,+ value=2.25,+ nx=True,+ )+ assert redis_store[counter_key] == pytest.approx(3.25)+ assert counter_cache.in_memory_cache.get_cache(+ key=counter_key+ ) == pytest.approx(3.25)+ finally:+ ps.spend_counter_cache = orig_counter+ ps.prisma_client = orig_prisma++@pytest.mark.asyncioasync def test_window_spend_counter_skips_invalid_window_start():from litellm.caching.dual_cache import DualCache@@ -5346,13 +5416,14 @@ async def test_window_spend_counter_does_not_seed_zero_when_db_unavailable():ps.spend_counter_cache = counter_cacheps.prisma_client = Nonetry:- await _ensure_window_spend_counter_initialized(+ initialized = await _ensure_window_spend_counter_initialized(counter_key=counter_key,entity_type="Key",entity_id="key-window-db-unavailable",window_start=datetime.now(timezone.utc) - timedelta(hours=1),)+ assert initialized is Falseassert counter_cache.in_memory_cache.get_cache(key=counter_key) is Nonefinally:ps.spend_counter_cache = orig_counter