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]

fix budget reservation review findings

user694fadd17548
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index d9d9da5c93d..06b28142a7d 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -1592,9 +1592,12 @@ async def _cache_key_object(
## CACHE REFRESH TIME
user_api_key_obj.last_refreshed_at = time.time()
+ cached_key_obj = _copy_user_api_key_auth_for_cache(
+ user_api_key_obj=user_api_key_obj
+ )
await _cache_management_object(
key=key,
- value=user_api_key_obj,
+ value=cached_key_obj,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
@@ -2318,9 +2321,11 @@ async def get_key_object(
if cached_key_obj is not None:
if isinstance(cached_key_obj, dict):
- return UserAPIKeyAuth(**cached_key_obj)
+ return _copy_user_api_key_auth_for_cache(
+ user_api_key_obj=UserAPIKeyAuth(**cached_key_obj)
+ )
elif isinstance(cached_key_obj, UserAPIKeyAuth):
- return cached_key_obj
+ return _copy_user_api_key_auth_for_cache(user_api_key_obj=cached_key_obj)
if check_cache_only:
raise Exception(
@@ -2373,6 +2378,16 @@ async def get_key_object(
return _response
+def _copy_user_api_key_auth_for_cache(
+ user_api_key_obj: UserAPIKeyAuth,
+) -> UserAPIKeyAuth:
+ copied_key_obj = user_api_key_obj.model_copy()
+ copied_key_obj.budget_reservation = None
+ copied_key_obj.parent_otel_span = None
+ copied_key_obj.request_route = None
+ return copied_key_obj
+
+
@log_db_metrics
async def get_object_permission(
object_permission_id: str,
diff --git a/litellm/proxy/db/spend_counter_reseed.py b/litellm/proxy/db/spend_counter_reseed.py
index 1a2f64d988d..0137acf5ed9 100644
--- a/litellm/proxy/db/spend_counter_reseed.py
+++ b/litellm/proxy/db/spend_counter_reseed.py
@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, ClassVar, Optional
from litellm._logging import verbose_proxy_logger
from litellm.constants import SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE
+from litellm.litellm_core_utils.duration_parser import duration_in_seconds
if TYPE_CHECKING:
from litellm.caching.dual_cache import DualCache
@@ -72,9 +73,10 @@ class SpendCounterReseed:
"""
if prisma_client is None:
return None
- # Per-window counters share prefixes with primary counters but
- # don't correspond to a DB row.
- if ":window:" in counter_key:
+ # Per-window key/team counters share prefixes with primary counters
+ # but don't correspond to a DB row. Do not reject arbitrary entity IDs
+ # or tag names that merely contain ":window:".
+ if SpendCounterReseed._is_key_or_team_window_counter(counter_key):
return None
try:
if counter_key.startswith("spend:key:"):
@@ -126,6 +128,21 @@ class SpendCounterReseed:
return None
return float(getattr(row, "spend", 0.0) or 0.0)
+ @staticmethod
+ def _is_key_or_team_window_counter(counter_key: str) -> bool:
+ for prefix in ("spend:key:", "spend:team:"):
+ if not counter_key.startswith(prefix):
+ continue
+ _, separator, duration = counter_key.rpartition(":window:")
+ if not separator or not duration:
+ return False
+ try:
+ duration_in_seconds(duration)
+ except Exception:
+ return False
+ return True
+ return False
+
@staticmethod
async def coalesced(
prisma_client: Optional["PrismaClient"],
diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.py
index 56b471c290b..82f5a554ca3 100644
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@ -45,6 +45,16 @@ class _ProxyDBLogger(CustomLogger):
verbose_proxy_logger.exception(
"Failed to release budget reservation during failure handling"
)
+ try:
+ await _invalidate_budget_reservation_counters(
+ budget_reservation=user_api_key_dict.budget_reservation
+ )
+ if user_api_key_dict.budget_reservation is not None:
+ user_api_key_dict.budget_reservation["finalized"] = True
+ except Exception:
+ verbose_proxy_logger.exception(
+ "Failed to invalidate budget reservation counters after failure release failed"
+ )
request_route = user_api_key_dict.request_route
if _ProxyDBLogger._should_track_errors_in_db() is False:
diff --git a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py
index 8fa7dc67a6c..83e4788fa16 100644
--- a/tests/test_litellm/proxy/auth/test_user_api_key_auth.py
+++ b/tests/test_litellm/proxy/auth/test_user_api_key_auth.py
@@ -23,6 +23,7 @@ from litellm.proxy._types import (
JWTRoutingOverride,
)
from litellm.proxy.auth.handle_jwt import JWTHandler
+from litellm.proxy.auth.auth_checks import get_key_object, _cache_key_object
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.auth.user_api_key_auth import (
_reserve_budget_after_common_checks,
@@ -76,6 +77,48 @@ async def test_should_clear_stale_budget_reservation_when_budget_checks_skip():
assert user_api_key_auth_obj.budget_reservation is None
+async def test_should_not_reuse_cached_key_object_for_request_state():
+ key_cache = DualCache()
+ cached_key = UserAPIKeyAuth(
+ token="cached-token",
+ request_route="/old-route",
+ budget_reservation={
+ "reserved_cost": 0.5,
+ "entries": [{"counter_key": "spend:key:cached-token"}],
+ },
+ )
+
+ await _cache_key_object(
+ hashed_token="cached-token",
+ user_api_key_obj=cached_key,
+ user_api_key_cache=key_cache,
+ proxy_logging_obj=None,
+ )
+
+ first_request_key = await get_key_object(
+ hashed_token="cached-token",
+ prisma_client=MagicMock(),
+ user_api_key_cache=key_cache,
+ )
+ first_request_key.budget_reservation = {
+ "reserved_cost": 0.9,
+ "entries": [{"counter_key": "spend:key:cached-token"}],
+ }
+ first_request_key.request_route = "/chat/completions"
+
+ second_request_key = await get_key_object(
+ hashed_token="cached-token",
+ prisma_client=MagicMock(),
+ user_api_key_cache=key_cache,
+ )
+
+ assert first_request_key is not cached_key
+ assert second_request_key is not first_request_key
+ assert second_request_key.budget_reservation is None
+ assert second_request_key.request_route is None
+
+
@pytest.mark.asyncio
async def test_custom_auth_does_not_enforce_key_model_access_by_default():
valid_token = UserAPIKeyAuth(token="test_token", models=["gpt-4o-mini"])
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.py
index 01cfd1708aa..482ddf74757 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
@@ -153,8 +153,10 @@ async def test_async_post_call_failure_hook_releases_budget_reservation_before_r
user_api_key_dict=user_api_key_dict,
)
- mock_release_budget_reservation.assert_awaited_once_with(
- budget_reservation=budget_reservation,
+ assert mock_release_budget_reservation.await_count == 1
+ assert (
+ mock_release_budget_reservation.await_args.kwargs["budget_reservation"]
+ is user_api_key_dict.budget_reservation
)
mock_update_database.assert_not_called()
@@ -177,6 +179,10 @@ async def test_should_continue_failure_tracking_when_budget_release_fails():
new_callable=AsyncMock,
side_effect=RuntimeError("redis unavailable"),
) as mock_release_budget_reservation,
+ patch(
+ "litellm.proxy.hooks.proxy_track_cost_callback._invalidate_budget_reservation_counters",
+ new_callable=AsyncMock,
+ ) as mock_invalidate_budget_reservation_counters,
patch(
"litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter.update_database",
new_callable=AsyncMock,
@@ -194,9 +200,19 @@ async def test_should_continue_failure_tracking_when_budget_release_fails():
user_api_key_dict=user_api_key_dict,
)
- mock_release_budget_reservation.assert_awaited_once_with(
- budget_reservation=budget_reservation,
+ assert mock_release_budget_reservation.await_count == 1
+ assert (
+ mock_release_budget_reservation.await_args.kwargs["budget_reservation"]
+ is user_api_key_dict.budget_reservation
+ )
+ assert mock_invalidate_budget_reservation_counters.await_count == 1
+ assert (
+ mock_invalidate_budget_reservation_counters.await_args.kwargs[
+ "budget_reservation"
+ ]
+ is user_api_key_dict.budget_reservation
)
+ assert user_api_key_dict.budget_reservation["finalized"] is True
mock_log_exception.assert_called_once()
mock_update_database.assert_called_once()
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 9748963f90d..3dfd68a5fff 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -5088,11 +5088,30 @@ async def test_reseed_spend_from_db_user_and_org_prefixes():
where={"user_id": "customer-1"}
)
+ fake_prisma.db.litellm_endusertable.find_unique.reset_mock()
+ assert (
+ await SpendCounterReseed.from_db(
+ fake_prisma, "spend:end_user:customer:window:1h"
+ )
+ == 21.0
+ )
+ fake_prisma.db.litellm_endusertable.find_unique.assert_awaited_once_with(
+ where={"user_id": "customer:window:1h"}
+ )
+
assert await SpendCounterReseed.from_db(fake_prisma, "spend:tag:paid-tag") == 8.0
fake_prisma.db.litellm_tagtable.find_unique.assert_awaited_once_with(
where={"tag_name": "paid-tag"}
)
+ fake_prisma.db.litellm_tagtable.find_unique.reset_mock()
+ assert (
+ await SpendCounterReseed.from_db(fake_prisma, "spend:tag:paid:window:1h") == 8.0
+ )
+ fake_prisma.db.litellm_tagtable.find_unique.assert_awaited_once_with(
+ where={"tag_name": "paid:window:1h"}
+ )
+
assert await SpendCounterReseed.from_db(fake_prisma, "spend:org:acme") == 305.0
fake_prisma.db.litellm_organizationtable.find_unique.assert_awaited_once_with(
where={"organization_id": "acme"}