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
skip invalid budget window reservations
user46068be6f65e
diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.pyindex b5bafb1cc35..956d2e80818 100644--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@ -31,7 +31,6 @@ class _BudgetCounter:source_cache_key: Optional[str] = Nonespend_log_entity_id: Optional[str] = Nonewindow_start: Optional[datetime] = None- parent_counter_key: Optional[str] = Nonedef get_reserved_counter_keys(budget_reservation: Optional[dict]) -> set:@@ -495,16 +494,23 @@ def _get_budget_limit_counters(if not budget_duration or max_budget is None or max_budget <= 0:continuewindow_start = get_budget_window_start(window_dict)+ if window_start is None:+ verbose_proxy_logger.warning(+ "Skipping budget window with invalid duration for %s=%s: %s",+ entity_type,+ entity_id,+ budget_duration,+ )+ continuecounters.append(_BudgetCounter(counter_key=f"{entity_prefix}:window:{budget_duration}",max_budget=float(max_budget),- fallback_spend=fallback_spend if window_start is None else 0.0,+ fallback_spend=0.0,entity_type=entity_type,entity_id=f"{entity_id}:{budget_duration}",spend_log_entity_id=entity_id,window_start=window_start,- parent_counter_key=entity_prefix if window_start is None else None,))return counters@@ -572,8 +578,6 @@ async def _reserve_counter(entity_id=counter.spend_log_entity_id,window_start=counter.window_start,)- elif counter.parent_counter_key is not None:- await _ensure_malformed_window_counter_initialized(counter=counter)reserved_value = await _increment_spend_counter_cache(counter_key=counter.counter_key,@@ -585,48 +589,12 @@ async def _reserve_counter(async def _get_current_counter_value(counter: _BudgetCounter) -> float:from litellm.proxy.proxy_server import get_current_spend- if counter.parent_counter_key is not None:- await _ensure_malformed_window_counter_initialized(counter=counter)-return await get_current_spend(counter_key=counter.counter_key,fallback_spend=counter.fallback_spend,)-async def _ensure_malformed_window_counter_initialized(- counter: _BudgetCounter,-) -> None:- if counter.parent_counter_key is None:- return-- from litellm.proxy.db.spend_counter_reseed import SpendCounterReseed- from litellm.proxy.proxy_server import (- _increment_spend_counter_cache,- get_current_spend,- spend_counter_cache,- )-- current = await spend_counter_cache.async_get_cache(key=counter.counter_key)- if current is not None:- return-- lock = await SpendCounterReseed._get_lock(counter.counter_key)- async with lock:- current = await spend_counter_cache.async_get_cache(key=counter.counter_key)- if current is not None:- return-- parent_spend = await get_current_spend(- counter_key=counter.parent_counter_key,- fallback_spend=counter.fallback_spend,- )- await _increment_spend_counter_cache(- counter_key=counter.counter_key,- increment=parent_spend,- )--async def _set_reserved_entries_actual_cost(entries: List[dict],actual_cost: float,diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex 3b9454d5d80..dde1056e416 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -644,70 +644,15 @@ def test_should_start_window_without_reset_at_at_duration_boundary():@pytest.mark.asyncio-async def test_should_seed_malformed_window_counter_from_parent_authoritative_spend(+async def test_should_skip_budget_window_with_unparseable_duration(spend_counter_state,):counter_cache, key_cache = spend_counter_stateproxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)valid_token = UserAPIKeyAuth(token="key-budget-malformed-window",- spend=0.0,- budget_limits=[- {- "budget_duration": "not-a-duration",- "max_budget": 1.0,- }- ],- )-- import litellm.proxy.proxy_server as ps-- db_row = MagicMock()- db_row.spend = 0.9- prisma_client = MagicMock()- prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(- return_value=db_row- )- ps.prisma_client = prisma_client-- with patch(- "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",- return_value=0.2,- ):- with pytest.raises(litellm.BudgetExceededError):- 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=prisma_client,- user_api_key_cache=key_cache,- proxy_logging_obj=proxy_logging_obj,- )-- prisma_client.db.litellm_verificationtoken.find_unique.assert_awaited_once_with(- where={"token": "key-budget-malformed-window"}- )- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-malformed-window:window:not-a-duration"- ) == pytest.approx(0.9)---async def test_should_coalesce_malformed_window_counter_initialization(- spend_counter_state,-):- import asyncio as _asyncio-- counter_cache, key_cache = spend_counter_state- proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)- token = "key-budget-malformed-window-concurrent"- malformed_window_counter_key = f"spend:key:{token}:window:not-a-duration"- valid_token = UserAPIKeyAuth(- token=token,- spend=0.0,+ spend=0.9,+ max_budget=10.0,budget_limits=[{"budget_duration": "not-a-duration",@@ -715,60 +660,45 @@ async def test_should_coalesce_malformed_window_counter_initialization(}],)-- import litellm.proxy.proxy_server as ps-- db_call_count = 0-- async def slow_find_unique(**kwargs):- nonlocal db_call_count- db_call_count += 1- await _asyncio.sleep(0.05)- db_row = MagicMock()- db_row.spend = 0.35- return db_row-- prisma_client = MagicMock()- prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(- side_effect=slow_find_unique+ counter_cache.in_memory_cache.set_cache(+ key="spend:key:key-budget-malformed-window",+ value=0.9,)- ps.prisma_client = prisma_clientwith patch("litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",return_value=0.2,):- results = await _asyncio.gather(- *[- 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=prisma_client,- user_api_key_cache=key_cache,- proxy_logging_obj=proxy_logging_obj,- )- for _ in range(2)- ],- return_exceptions=True,+ 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 not any(isinstance(result, Exception) for result in results), results- assert all(result is not None for result in results)- assert db_call_count == 1+ assert reservation is not None+ assert [entry["counter_key"] for entry in reservation["entries"]] == [+ "spend:key:key-budget-malformed-window"+ ]assert counter_cache.in_memory_cache.get_cache(- key=malformed_window_counter_key- ) == pytest.approx(0.75)-- for reservation in results:- await release_budget_reservation(reservation)+ key="spend:key:key-budget-malformed-window"+ ) == pytest.approx(1.1)+ assert (+ counter_cache.in_memory_cache.get_cache(+ key="spend:key:key-budget-malformed-window:window:not-a-duration"+ )+ is None+ )+ await release_budget_reservation(reservation)assert counter_cache.in_memory_cache.get_cache(- key=malformed_window_counter_key- ) == pytest.approx(0.35)+ key="spend:key:key-budget-malformed-window"+ ) == pytest.approx(0.9)@pytest.mark.asyncio