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(proxy): enforce budgets against authoritative DB spend when the cross-pod counter is unreliable (#30684)
Yassin Kortama8b94b9a87c2
diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.pyindex 263e1df2ee7..ba07511448a 100644--- a/litellm/caching/redis_cache.py+++ b/litellm/caching/redis_cache.py@@ -903,6 +903,43 @@ class RedisCache(BaseCache):)raise e+ @_redis_circuit_breaker_guard+ async def async_set_max(+ self,+ key: str,+ value: float,+ ttl: int | None = None,+ ) -> float | None:+ """Atomically set ``key`` to ``value`` only when ``value`` is greater+ than the stored value (or the key is unset), refreshing the TTL.++ Monotonic by construction: it never lowers the stored value, so a repair+ that writes an authoritative-but-slightly-stale total cannot clobber a+ concurrent increment that has already pushed the counter higher. The+ GET/compare/SET runs in a single Lua call, so it is also atomic across+ racing callers and pods. Returns the resulting value.+ """+ _redis_client = self.init_async_client()+ _used_ttl = self.get_ttl(ttl=ttl)+ key = self.check_and_fix_namespace(key=key)+ lua = (+ "local cur = redis.call('GET', KEYS[1]) "+ "if cur == false or tonumber(cur) < tonumber(ARGV[1]) then "+ "redis.call('SET', KEYS[1], ARGV[1]) "+ "if tonumber(ARGV[2]) > 0 then redis.call('EXPIRE', KEYS[1], ARGV[2]) end "+ "return ARGV[1] end "+ "return cur"+ )+ result = cast(+ "str | bytes | int | float | None",+ await _redis_client.eval(lua, 1, key, str(value), str(int(_used_ttl or 0))),+ )+ if result is None:+ return None+ if isinstance(result, bytes):+ result = result.decode()+ return float(result)+async def flush_cache_buffer(self):print_verbose(f"flushing to redis....reached size of buffer {len(self.redis_batch_writing_buffer)}"diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 814346eddf8..6ddf2cfeb20 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -61,6 +61,7 @@ from litellm.proxy._types import (UserAPIKeyAuth,)from litellm.proxy.auth.route_checks import RouteChecks+from litellm.proxy.spend_tracking.budget_reservation import get_budget_window_startfrom litellm.proxy.common_utils.cache_pydantic_utils import CacheCodecfrom litellm.proxy.common_utils.http_parsing_utils import (_safe_get_request_headers,@@ -725,6 +726,7 @@ async def common_checks(user_spend = await get_current_spend(counter_key=f"spend:user:{user_object.user_id}",fallback_spend=user_object.spend or 0.0,+ max_budget=user_budget,)if math.isfinite(user_budget) and user_spend >= user_budget:raise litellm.BudgetExceededError(@@ -1127,6 +1129,8 @@ async def _check_end_user_budget(end_user_spend = await get_current_spend(counter_key=f"spend:end_user:{end_user_obj.user_id}",fallback_spend=end_user_obj.spend or 0.0,+ max_budget=end_user_budget,+ fallback_authoritative=True,)if end_user_spend > end_user_budget:raise litellm.BudgetExceededError(@@ -3615,6 +3619,7 @@ async def _virtual_key_max_budget_check(spend = await get_current_spend(counter_key=counter_key,fallback_spend=fallback_spend,+ max_budget=valid_token.max_budget,)####################################@@ -3684,6 +3689,10 @@ async def _virtual_key_multi_budget_check(window_spend = await get_current_spend(counter_key=counter_key,fallback_spend=0.0,+ max_budget=w["max_budget"],+ window_entity_type="Key",+ window_entity_id=valid_token.token,+ window_start=get_budget_window_start(w),)if math.isfinite(w["max_budget"]) and window_spend >= w["max_budget"]:raise litellm.BudgetExceededError(@@ -3938,6 +3947,7 @@ async def _check_team_member_budget(team_member_spend = await get_current_spend(counter_key=f"spend:team_member:{valid_token.user_id}:{team_object.team_id}",fallback_spend=team_member_spend,+ max_budget=team_member_budget,)if (@@ -4023,6 +4033,7 @@ async def _team_max_budget_check(spend = await get_current_spend(counter_key=f"spend:team:{team_object.team_id}",fallback_spend=team_object.spend or 0.0,+ max_budget=team_object.max_budget,)if math.isfinite(team_object.max_budget) and spend > team_object.max_budget:@@ -4072,6 +4083,10 @@ async def _team_multi_budget_check(window_spend = await get_current_spend(counter_key=counter_key,fallback_spend=0.0,+ max_budget=w["max_budget"],+ window_entity_type="Team",+ window_entity_id=team_object.team_id,+ window_start=get_budget_window_start(w),)if math.isfinite(w["max_budget"]) and window_spend >= w["max_budget"]:raise litellm.BudgetExceededError(@@ -4377,6 +4392,7 @@ async def _organization_max_budget_check(org_spend = await get_current_spend(counter_key=f"spend:org:{org_id}",fallback_spend=org_table.spend or 0.0,+ max_budget=org_max_budget,)# Check if organization spend exceeds max budget@@ -4454,6 +4470,8 @@ async def _tag_max_budget_check(tag_spend = await get_current_spend(counter_key=f"spend:tag:{tag_name}",fallback_spend=tag_object.spend or 0.0,+ max_budget=tag_object.litellm_budget_table.max_budget,+ fallback_authoritative=True,)if tag_spend <= tag_object.litellm_budget_table.max_budget:continuediff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.pyindex 6f359e52eeb..00d98a04a78 100644--- a/litellm/proxy/auth/user_api_key_auth.py+++ b/litellm/proxy/auth/user_api_key_auth.py@@ -1837,6 +1837,7 @@ async def _user_api_key_auth_builder(team_member_spend = await get_current_spend(counter_key=f"spend:team_member:{valid_token.user_id}:{valid_token.team_id}",fallback_spend=team_member_spend,+ max_budget=team_member_budget,)if team_member_spend > team_member_budget:raise litellm.BudgetExceededError(diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex e6ce92344ff..921da73bb51 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -2026,7 +2026,43 @@ def cost_tracking():)-async def get_current_spend(counter_key: str, fallback_spend: float) -> float:+# Bounds authoritative DB re-reads when enforcing a budget against a+# stale-low spend counter: at most one DB read per counter per window.+SPEND_DB_FLOOR_CACHE_TTL_SECONDS = 5+++def _fail_closed_budget_enforcement() -> bool:+ return general_settings.get("fail_closed_budget_enforcement") is True+++def _raise_budget_unverifiable(counter_key: str) -> None:+ verbose_proxy_logger.warning(+ "fail_closed_budget_enforcement: rejecting request — spend for %s could "+ "not be verified against Redis or the database",+ counter_key,+ )+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "error": (+ "Budget enforcement unavailable: current spend could not be "+ "verified against Redis or the database, and "+ "fail_closed_budget_enforcement is enabled, so the request was "+ "rejected to avoid exceeding the configured budget. Retry shortly."+ )+ },+ )+++async def get_current_spend(+ counter_key: str,+ fallback_spend: float,+ max_budget: float | None = None,+ window_entity_type: str | None = None,+ window_entity_id: str | None = None,+ window_start: datetime | None = None,+ fallback_authoritative: bool = False,+) -> float:"""Read current spend from the cross-pod spend counter.@@ -2040,7 +2076,168 @@ async def get_current_spend(counter_key: str, fallback_spend: float) -> float:2. In-memory counter (single-instance or Redis failure)3. Reseed from authoritative DB spend (counter expired, cross-pod stale)4. Caller-supplied fallback (DB unavailable, cold start)++ When ``max_budget`` is supplied, the counter is re-checked against the+ authoritative recorded spend before a request is admitted. A Redis counter+ that survived a Redis restart can return a stale-low value loaded from an+ older RDB snapshot; that read is a hit (not a clean miss), so step 3 never+ runs and a key can leak spend past ``max_budget`` indefinitely. The+ authoritative source depends on the counter: primary key/team/user/org+ counters read the DB row; per-window counters (``window_start`` supplied)+ aggregate spend logs; end-user/tag counters have no DB row, so the caller's+ ``fallback_spend`` (loaded fresh in auth) is authoritative. The DB read is+ skipped for healthy primary counters (counter at or above recorded spend)+ and cached in-process for a few seconds, so a persistently stale counter+ drives at most one read per counter per window rather than one per request.+ """+ current, verified = await _read_spend_counter_estimate(+ counter_key=counter_key, fallback_spend=fallback_spend+ )+ if fallback_authoritative:+ verified = True++ if max_budget is None or current >= max_budget:+ return current++ # Cheap staleness signal for primary counters: the counter reads below the+ # spend this caller already knows about. Window counters have no such signal+ # (fallback is 0), so they always re-check, bounded by the cache. Strict mode+ # (fail_closed_budget_enforcement) always re-checks against the authoritative+ # source too, so a counter that is stale-low at the same time as the caller's+ # cached spend cannot slip through; the 5s cache keeps that bounded.+ is_window = window_start is not None+ if fallback_spend > current or is_window or _fail_closed_budget_enforcement():+ authoritative = await _authoritative_floor_spend(+ counter_key=counter_key,+ window_entity_type=window_entity_type,+ window_entity_id=window_entity_id,+ window_start=window_start,+ )+ if authoritative is not None:+ verified = True+ if authoritative > current:+ await _repair_stale_spend_counter(+ counter_key=counter_key, db_spend=authoritative+ )+ return authoritative+ elif fallback_spend > current:+ # end-user / tag counters have no DB row; fallback_spend is the+ # authoritative recorded value loaded in auth.+ return fallback_spend++ # Opt-in hard guarantee: when the spend backing this admit decision came+ # only from a per-pod cache (Redis and DB both unreadable), reject rather+ # than admit on an unverifiable budget. No-op unless the flag is set, so+ # default behavior is unchanged.+ if not verified and _fail_closed_budget_enforcement():+ _raise_budget_unverifiable(counter_key)++ return current+++async def _repair_stale_spend_counter(counter_key: str, db_spend: float) -> None:+ """Raise a counter that has fallen below the authoritative DB spend (e.g.+ Redis restarted and reloaded an older snapshot) so every worker reads the+ corrected value directly instead of re-deriving it per request, and so a+ worker whose own cached spend is also stale still sees the true total.++ The write is monotonic: it only ever raises the counter, so a repair that+ carries a slightly-stale DB total cannot clobber a concurrent increment that+ already pushed the counter higher (which would let racing requests+ under-count). Redis enforces this atomically via async_set_max; the+ in-memory copy is guarded by a read-compare-write with no await in between,+ so it is atomic within the worker.+ """+ cached = spend_counter_cache.in_memory_cache.get_cache(key=counter_key)+ needs_update = True+ if cached is not None:+ try:+ needs_update = float(cached) < db_spend+ except (TypeError, ValueError):+ needs_update = True+ if needs_update:+ spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=db_spend)+ if spend_counter_cache.redis_cache is not None:+ try:+ await spend_counter_cache.redis_cache.async_set_max(+ key=counter_key, value=db_spend+ )+ except Exception:+ verbose_proxy_logger.debug(+ "Unable to repair stale spend counter %s in Redis",+ counter_key,+ exc_info=True,+ )+++async def reseed_spend_counter_from_db(counter_key: str) -> None:+ """Recover a counter that the reservation reconcile found in an inconsistent+ state (missing, or where applying the reconcile delta would drive it+ negative) by reseeding it from the DB instead of deleting it.++ The DB row is a LAGGING authoritative floor, not post-request truth: the+ entity .spend column is flushed in batches (every PROXY_BATCH_WRITE_AT), so+ it can exclude this request's just-recorded cost and other buffered spend.+ That is fine here: the monotonic set-max can only RAISE a stale-low counter+ toward that floor (never lowers it or clobbers a concurrent increment), and+ the read-time floor (_authoritative_floor_spend) converges to the true total+ as the buffer flushes. The point is to restore enforcement to a real floor+ rather than leave the counter deleted and unenforced (the prior fail-open).+ Counters with no DB row (window/end-user/tag) are left untouched rather than+ deleted, so enforcement keeps reading whatever value they hold."""+ db_spend = await SpendCounterReseed.from_db(+ prisma_client=prisma_client, counter_key=counter_key+ )+ if db_spend is None:+ return+ await _repair_stale_spend_counter(counter_key=counter_key, db_spend=db_spend)+++async def _authoritative_floor_spend(+ counter_key: str,+ window_entity_type: str | None = None,+ window_entity_id: str | None = None,+ window_start: datetime | None = None,+) -> float | None:+ marker_key = f"spend_db_floor:{counter_key}"+ cached = spend_counter_cache.in_memory_cache.get_cache(key=marker_key)+ if cached is not None:+ return float(cached)++ db_spend = await SpendCounterReseed.from_db(+ prisma_client=prisma_client, counter_key=counter_key+ )+ if (+ db_spend is None+ and window_entity_type is not None+ and window_entity_id is not None+ and window_start is not None+ ):+ db_spend = await SpendCounterReseed.window_from_spend_logs(+ prisma_client=prisma_client,+ entity_type=window_entity_type,+ entity_id=window_entity_id,+ window_start=window_start,+ )+ if db_spend is None:+ return None++ spend_counter_cache.in_memory_cache.set_cache(+ key=marker_key,+ value=db_spend,+ ttl=SPEND_DB_FLOOR_CACHE_TTL_SECONDS,+ )+ return db_spend+++async def _read_spend_counter_estimate(+ counter_key: str, fallback_spend: float+) -> tuple[float, bool]:+ """Return (spend, authoritative). ``authoritative`` is True when the value+ came from Redis or a fresh DB read (cross-pod truth), False when it came+ from the per-pod in-memory copy or the caller's fallback. Only the+ fail-closed path reads the flag; normal callers ignore it."""# 1. Redis first (cross-pod authoritative). On clean miss, skip# in-memory: per-pod in-memory only has this pod's writes, so it# would mask cross-pod increments.@@ -2049,7 +2246,7 @@ async def get_current_spend(counter_key: str, fallback_spend: float) -> float:try:val = await spend_counter_cache.redis_cache.async_get_cache(key=counter_key)if val is not None:- return float(val)+ return float(val), Trueredis_clean_miss = Trueexcept Exception as e:verbose_proxy_logger.debug(@@ -2062,7 +2259,7 @@ async def get_current_spend(counter_key: str, fallback_spend: float) -> float:if not redis_clean_miss:val = spend_counter_cache.in_memory_cache.get_cache(key=counter_key)if val is not None:- return float(val)+ return float(val), False# 3. Reseed from DB - fallback_spend lags cross-pod, would allow bypass.db_spend = await SpendCounterReseed.coalesced(@@ -2071,10 +2268,10 @@ async def get_current_spend(counter_key: str, fallback_spend: float) -> float:counter_key=counter_key,)if db_spend is not None:- return db_spend+ return db_spend, True# 4. Caller-supplied fallback (DB unavailable).- return fallback_spend+ return fallback_spend, Falseasync def increment_spend_counters(diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.pyindex eb8af3b073e..0bd6d75d5f4 100644--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@ -628,12 +628,14 @@ async def _set_reserved_entries_actual_cost(entries: List[dict],actual_cost: float,default_reserved_cost: float,+ reseed_on_inconsistent: bool = True,) -> None:for entry in entries:await _set_reserved_entry_actual_cost(entry=entry,actual_cost=actual_cost,default_reserved_cost=default_reserved_cost,+ reseed_on_inconsistent=reseed_on_inconsistent,)@@ -641,8 +643,12 @@ async def _set_reserved_entry_actual_cost(entry: dict,actual_cost: float,default_reserved_cost: float,+ reseed_on_inconsistent: bool = True,) -> None:- from litellm.proxy.proxy_server import _increment_spend_counter_cache+ from litellm.proxy.proxy_server import (+ _increment_spend_counter_cache,+ reseed_spend_counter_from_db,+ )counter_key = entry.get("counter_key")if counter_key is None:@@ -656,46 +662,49 @@ async def _set_reserved_entry_actual_cost(adjustment = target_adjustment - applied_adjustmentif adjustment == 0:return- await _ensure_counter_can_apply_adjustment(+ if await _counter_can_apply_adjustment(counter_key=counter_key,adjustment=adjustment,- )- await _increment_spend_counter_cache(- counter_key=counter_key,- increment=adjustment,- )+ ):+ await _increment_spend_counter_cache(+ counter_key=counter_key,+ increment=adjustment,+ )+ elif reseed_on_inconsistent:+ # Post-call reconcile / release: the counter was flushed or reseeded+ # between reservation and reconcile (Redis restart / cross-pod reset),+ # so the optimistic delta no longer applies. Recover by reseeding from+ # the DB's lagging authoritative floor rather than deleting the counter+ # and failing open — deleting it is what left budgets unenforced after a+ # Redis reload.+ await reseed_spend_counter_from_db(counter_key=counter_key)+ else:+ # Pre-call admission resize: the in-flight reservation cost is not yet+ # persisted, so the DB floor would discard it. Keep the original+ # fail-closed behavior (raise -> reserve_budget_for_request releases and+ # denies) rather than admitting against an inconsistent counter.+ raise RuntimeError(+ f"Cannot resize budget reservation against inconsistent counter {counter_key}"+ )entry["applied_adjustment"] = target_adjustment-async def _ensure_counter_can_apply_adjustment(+async def _counter_can_apply_adjustment(counter_key: str,adjustment: float,-) -> None:- from litellm.proxy.proxy_server import (- _invalidate_spend_counter,- spend_counter_cache,- )+) -> bool:+ from litellm.proxy.proxy_server import spend_counter_cachecurrent_value = await spend_counter_cache.async_get_cache(key=counter_key)if current_value is None:- await _invalidate_spend_counter(counter_key=counter_key)- raise RuntimeError(- f"Cannot apply budget reservation adjustment to missing counter {counter_key}"- )+ return Falsetry:current_float = float(current_value)except (TypeError, ValueError):- await _invalidate_spend_counter(counter_key=counter_key)- raise RuntimeError(- f"Cannot apply budget reservation adjustment to non-numeric counter {counter_key}"- )+ return False- if adjustment < 0 and current_float + adjustment < -1e-12:- await _invalidate_spend_counter(counter_key=counter_key)- raise RuntimeError(- f"Budget reservation adjustment would make counter negative {counter_key}"- )+ return not (adjustment < 0 and current_float + adjustment < -1e-12)async def _release_applied_entries_best_effort(@@ -735,6 +744,7 @@ async def _resize_applied_reservation(entries=entries,actual_cost=new_reserved_cost,default_reserved_cost=current_reserved_cost,+ reseed_on_inconsistent=False,)for entry in entries:entry["reserved_cost"] = new_reserved_costdiff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.pyindex e14ef05bd43..5ec5d12784f 100644--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@ -2365,7 +2365,7 @@ async def test_virtual_key_budget_check_reads_from_spend_counter():proxy_logging_obj = ProxyLogging(user_api_key_cache=None)proxy_logging_obj.budget_alerts = AsyncMock()- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:key:test-hashed-token":return 1.5return fallback_spend@@ -2397,7 +2397,7 @@ async def test_virtual_key_budget_check_fallback_no_counter():proxy_logging_obj.budget_alerts = AsyncMock()# get_current_spend returns fallback_spend when no counter exists- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):return fallback_spendwith patch("litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend):@@ -2409,8 +2409,6 @@ async def test_virtual_key_budget_check_fallback_no_counter():assert exc_info.value.current_cost == 15.0--@pytest.mark.asyncioasync def test_team_budget_check_reads_from_spend_counter():"""Team budget check should use get_current_spend when counter exists."""@@ -2426,7 +2424,7 @@ async def test_team_budget_check_reads_from_spend_counter():proxy_logging_obj = ProxyLogging(user_api_key_cache=None)proxy_logging_obj.budget_alerts = AsyncMock()- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team:test-team":return 1.5return fallback_spend@@ -2451,7 +2449,7 @@ async def test_end_user_budget_check_reads_from_spend_counter():litellm_budget_table=LiteLLM_BudgetTable(max_budget=1.0),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:end_user:customer-1":return 1.5return fallback_spend@@ -2477,7 +2475,7 @@ async def test_tag_budget_check_reads_from_spend_counter():litellm_budget_table=LiteLLM_BudgetTable(max_budget=1.0),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:tag:paid-tag":return 1.5return fallback_spend@@ -2525,7 +2523,7 @@ async def test_team_member_budget_check_reads_from_spend_counter():proxy_logging_obj = ProxyLogging(user_api_key_cache=None)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 1.5return fallback_spend@@ -2758,7 +2756,7 @@ async def test_team_member_budget_check_falls_back_to_team_default_budget_id():return_value=fake_budget_row)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 70.0return fallback_spend@@ -2855,7 +2853,7 @@ async def test_team_member_budget_check_per_member_override_wins_over_team_defaumocked_spend = 70.0- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return mocked_spendreturn fallback_spend@@ -2945,7 +2943,7 @@ async def test_team_member_budget_check_null_clone_falls_back_to_team_default():return_value=fake_default_row)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 500.0return fallback_spend@@ -3012,7 +3010,7 @@ async def test_team_member_budget_check_null_clone_with_null_default_skips_enforreturn_value=fake_default_row)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 1000.0return fallback_spend@@ -3079,7 +3077,7 @@ async def test_team_member_budget_check_zero_team_default_treated_as_no_cap():return_value=fake_default_row)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 0.0return fallback_spend@@ -3137,7 +3135,7 @@ async def test_team_member_budget_check_zero_per_member_row_still_blocks():prisma_client = MagicMock()prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=None)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:team_member:test-user:test-team":return 0.0return fallback_spenddiff --git a/tests/test_litellm/proxy/auth/test_custom_auth_end_user_budget.py b/tests/test_litellm/proxy/auth/test_custom_auth_end_user_budget.pyindex 68907de6f2d..e49f025df2e 100644--- a/tests/test_litellm/proxy/auth/test_custom_auth_end_user_budget.py+++ b/tests/test_litellm/proxy/auth/test_custom_auth_end_user_budget.py@@ -106,7 +106,7 @@ async def test_custom_auth_enforces_end_user_budget_when_common_checks_skipped()litellm_budget_table=LiteLLM_BudgetTable(max_budget=1.0),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:end_user:customer-1":return 5.0return fallback_spenddiff --git a/tests/test_litellm/proxy/auth/test_multi_budget_windows.py b/tests/test_litellm/proxy/auth/test_multi_budget_windows.pyindex ed94fca837b..0f01391b2f5 100644--- a/tests/test_litellm/proxy/auth/test_multi_budget_windows.py+++ b/tests/test_litellm/proxy/auth/test_multi_budget_windows.py@@ -62,7 +62,7 @@ async def test_over_first_window_raises():call_count = 0- async def fake_get_spend(counter_key, fallback_spend):+ async def fake_get_spend(counter_key, fallback_spend, max_budget=None, **kwargs):nonlocal call_countval = spend_by_window[call_count]call_count += 1@@ -94,7 +94,7 @@ async def test_over_second_window_raises():call_count = 0- async def fake_get_spend(counter_key, fallback_spend):+ async def fake_get_spend(counter_key, fallback_spend, max_budget=None, **kwargs):nonlocal call_countval = spend_by_window[call_count]call_count += 1diff --git a/tests/test_litellm/proxy/proxy_server/test_spend_counters.py b/tests/test_litellm/proxy/proxy_server/test_spend_counters.pyindex 4e5f13fdf88..a839d82984c 100644--- a/tests/test_litellm/proxy/proxy_server/test_spend_counters.py+++ b/tests/test_litellm/proxy/proxy_server/test_spend_counters.py@@ -54,6 +54,8 @@ def _make_spend_counter_cache(side_effect=redis_increment_side_effect,)cache.redis_cache.async_delete_cache = AsyncMock()+ cache.redis_cache.async_set_cache = AsyncMock()+ cache.redis_cache.async_set_max = AsyncMock()else:cache.redis_cache = Nonecache.async_increment_cache = AsyncMock(return_value=redis_increment_value)@@ -111,6 +113,272 @@ async def test_get_current_spend_redis_error_falls_back_to_in_memory(monkeypatchassert result == 17.0+async def test_get_current_spend_floors_stale_low_counter_against_db(monkeypatch):+ """A Redis counter left stale-low by a Redis restart must not admit a key+ whose authoritative DB spend is already over budget. With max_budget set,+ get_current_spend re-checks the DB and returns the higher recorded spend."""+ fake_cache = _make_spend_counter_cache(redis_get_value=2.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ from_db = AsyncMock(return_value=12.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ result = await ps.get_current_spend(+ counter_key="spend:key:abc",+ fallback_spend=12.0,+ max_budget=10.0,+ )++ assert result == 12.0+ assert from_db.await_count == 1+ # the stale counter is repaired up to the authoritative DB value via a+ # monotonic set-max so other workers read the corrected total, and a+ # concurrent increment cannot be clobbered+ fake_cache.redis_cache.async_set_max.assert_awaited_once_with(+ key="spend:key:abc", value=12.0+ )+++async def test_get_current_spend_no_db_recheck_when_counter_healthy(monkeypatch):+ """A healthy counter (at or above the caller's recorded spend) is trusted+ without a DB read, so under-budget traffic stays off the DB path."""+ fake_cache = _make_spend_counter_cache(redis_get_value=5.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ from_db = AsyncMock(return_value=99.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ result = await ps.get_current_spend(+ counter_key="spend:key:abc",+ fallback_spend=3.0,+ max_budget=10.0,+ )++ assert result == 5.0+ assert from_db.await_count == 0+++async def test_get_current_spend_no_floor_without_max_budget(monkeypatch):+ """Without max_budget the read-time DB floor is skipped: callers that only+ read spend (alerts, soft budgets) keep the cheap counter-only behavior."""+ fake_cache = _make_spend_counter_cache(redis_get_value=2.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ from_db = AsyncMock(return_value=12.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ result = await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=12.0+ )++ assert result == 2.0+ assert from_db.await_count == 0+++async def test_get_current_spend_floor_admits_after_reset(monkeypatch):+ """Right after a weekly reset the counter is 0 while the per-worker cached+ spend can still be last week's value. The DB floor reads the reset spend (0)+ and admits, so reset keys are not over-blocked."""+ fake_cache = _make_spend_counter_cache(redis_get_value=0.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ from_db = AsyncMock(return_value=0.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ result = await ps.get_current_spend(+ counter_key="spend:key:abc",+ fallback_spend=12.0,+ max_budget=10.0,+ )++ assert result == 0.0+ assert from_db.await_count == 1+ # counter already matches the DB (reset to 0); nothing to repair, so no write+ fake_cache.redis_cache.async_set_max.assert_not_called()+++async def test_get_current_spend_floor_caches_db_read(monkeypatch):+ """A persistently stale-low counter must not drive a DB read per request:+ the authoritative spend is cached in-process and reused within the window."""+ cache = ps.DualCache()+ cache.redis_cache = MagicMock()+ cache.redis_cache.async_get_cache = AsyncMock(return_value=2.0)+ monkeypatch.setattr(ps, "spend_counter_cache", cache)+ from_db = AsyncMock(return_value=12.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ first = await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=12.0, max_budget=10.0+ )+ second = await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=12.0, max_budget=10.0+ )++ assert first == 12.0+ assert second == 12.0+ assert from_db.await_count == 1+++async def test_get_current_spend_floors_end_user_tag_against_fallback(monkeypatch):+ """End-user and tag counters have no DB row (from_db returns None). When the+ counter is stale-low, enforcement falls back to the caller's recorded spend+ (loaded fresh in auth) instead of trusting the stale counter."""+ fake_cache = _make_spend_counter_cache(redis_get_value=2.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", AsyncMock(return_value=None))++ result = await ps.get_current_spend(+ counter_key="spend:end_user:e1",+ fallback_spend=20.0,+ max_budget=10.0,+ )++ assert result == 20.0+ # no DB row to repair against, so the shared counter is left untouched+ fake_cache.redis_cache.async_set_max.assert_not_called()+++async def test_get_current_spend_floors_window_against_spend_logs(monkeypatch):+ """Per-window counters have no DB row but aggregate from spend logs. A+ stale-low window counter is floored to (and repaired up to) the logged+ window spend, even though the caller's fallback is 0."""+ from datetime import datetime, timezone++ fake_cache = _make_spend_counter_cache(redis_get_value=2.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", AsyncMock(return_value=None))+ wfsl = AsyncMock(return_value=15.0)+ monkeypatch.setattr(ps.SpendCounterReseed, "window_from_spend_logs", wfsl)++ counter_key = "spend:key:tok:window:7d"+ result = await ps.get_current_spend(+ counter_key=counter_key,+ fallback_spend=0.0,+ max_budget=10.0,+ window_entity_type="Key",+ window_entity_id="tok",+ window_start=datetime(2026, 1, 1, tzinfo=timezone.utc),+ )++ assert result == 15.0+ assert wfsl.await_count == 1+ fake_cache.redis_cache.async_set_max.assert_awaited_once_with(+ key=counter_key, value=15.0+ )+++async def test_get_current_spend_fail_closed_rejects_when_unverifiable(monkeypatch):+ """With fail_closed_budget_enforcement on, an admit decision backed only by a+ per-pod fallback (Redis unreachable and DB unreadable) is rejected with 503+ rather than admitted on an unverifiable budget."""+ from fastapi import HTTPException++ fake_cache = _make_spend_counter_cache(+ redis_get_side_effect=RuntimeError("redis down")+ )+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(+ ps, "general_settings", {"fail_closed_budget_enforcement": True}+ )+ monkeypatch.setattr(+ ps.SpendCounterReseed, "coalesced", AsyncMock(return_value=None)+ )++ with pytest.raises(HTTPException) as exc:+ await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=1.0, max_budget=10.0+ )+ assert exc.value.status_code == 503+++async def test_get_current_spend_fail_closed_off_admits_when_unverifiable(monkeypatch):+ """Default (flag off): an unverifiable read keeps the existing behavior and+ admits using the cached fallback — no new rejection."""+ fake_cache = _make_spend_counter_cache(+ redis_get_side_effect=RuntimeError("redis down")+ )+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(ps, "general_settings", {})+ monkeypatch.setattr(+ ps.SpendCounterReseed, "coalesced", AsyncMock(return_value=None)+ )++ result = await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=1.0, max_budget=10.0+ )+ assert result == 1.0+++async def test_get_current_spend_fail_closed_admits_when_redis_verified(monkeypatch):+ """Fail-closed only rejects unverifiable reads: a value served by Redis is+ authoritative, so an under-budget request is admitted normally."""+ fake_cache = _make_spend_counter_cache(redis_get_value=1.0)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(+ ps, "general_settings", {"fail_closed_budget_enforcement": True}+ )++ result = await ps.get_current_spend(+ counter_key="spend:key:abc", fallback_spend=1.0, max_budget=10.0+ )+ assert result == 1.0+++async def test_get_current_spend_fail_closed_allows_authoritative_fallback(monkeypatch):+ """End-user/tag callers pass fallback_authoritative=True (their spend is+ loaded fresh from the DB in auth), so fail-closed does not reject them even+ when the counter path is unreadable."""+ fake_cache = _make_spend_counter_cache(+ redis_get_side_effect=RuntimeError("redis down")+ )+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(+ ps, "general_settings", {"fail_closed_budget_enforcement": True}+ )+ monkeypatch.setattr(+ ps.SpendCounterReseed, "coalesced", AsyncMock(return_value=None)+ )++ result = await ps.get_current_spend(+ counter_key="spend:end_user:e1",+ fallback_spend=1.0,+ max_budget=10.0,+ fallback_authoritative=True,+ )+ assert result == 1.0+++async def test_get_current_spend_strict_floors_when_fallback_also_stale(monkeypatch):+ """Strict mode closes the both-stale gap: when the counter AND the caller's+ cached spend are both stale-low (cheap guard would skip), strict mode still+ re-checks the authoritative DB and enforces against it."""+ fake_cache = _make_spend_counter_cache(redis_get_value=0.00001)+ monkeypatch.setattr(ps, "spend_counter_cache", fake_cache)+ monkeypatch.setattr(+ ps, "general_settings", {"fail_closed_budget_enforcement": True}+ )+ from_db = AsyncMock(return_value=0.5)+ monkeypatch.setattr(ps.SpendCounterReseed, "from_db", from_db)++ # fallback == current, so the default cheap guard would NOT re-check+ result = await ps.get_current_spend(+ counter_key="spend:team:t1",+ fallback_spend=0.00001,+ max_budget=0.0002,+ )++ assert result == 0.5+ assert from_db.await_count == 1++# ---------------------------------------------------------------------------# increment_spend_counters# ---------------------------------------------------------------------------diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex aa0f8d63274..e3cdb33e2ed 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -1438,9 +1438,13 @@ async def test_should_preserve_budget_error_and_continue_partial_cleanup(@pytest.mark.asyncio-async def test_should_not_create_negative_counter_when_release_counter_is_missing(+async def test_release_missing_counter_reseeds_from_db_instead_of_failing(spend_counter_state,):+ """A reconcile/release that finds the counter missing must NOT delete it and+ raise (the old fail-open that left budgets unenforced after a Redis reload).+ It reseeds from the authoritative DB; with no DB it leaves the counter+ untouched and finalizes."""counter_cache, _ = spend_counter_statereservation = {"reserved_cost": 0.4,@@ -1454,22 +1458,26 @@ async def test_should_not_create_negative_counter_when_release_counter_is_missin"finalized": False,}- with pytest.raises(RuntimeError, match="missing counter"):- await release_budget_reservation(reservation)+ # must not raise+ await release_budget_reservation(reservation)+ # counter not driven negative / not corrupted; left absent (no DB to reseed)assert (counter_cache.in_memory_cache.get_cache(key="spend:key:key-budget-missing-release")is None)- assert reservation["finalized"] is False+ assert reservation["finalized"] is True@pytest.mark.asyncio-async def test_should_invalidate_counter_when_release_would_underflow(- spend_counter_state,-):+async def test_release_underflow_counter_reseeds_from_db(spend_counter_state):+ """When the release delta would drive the counter negative (counter was+ reset/reseeded mid-flight), reseed from the authoritative DB rather than+ deleting and failing open."""+ import litellm.proxy.proxy_server as ps+counter_cache, _ = spend_counter_stateawait counter_cache.async_increment_cache(key="spend:key:key-budget-underflow-release",@@ -1487,22 +1495,22 @@ async def test_should_invalidate_counter_when_release_would_underflow("finalized": False,}- with pytest.raises(RuntimeError, match="negative"):+ with patch.object(ps.SpendCounterReseed, "from_db", AsyncMock(return_value=0.25)):await release_budget_reservation(reservation)- assert (- counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-underflow-release"- )- is None- )- assert reservation["finalized"] is False+ # counter reseeded up to the authoritative DB value, not deleted or negated+ assert counter_cache.in_memory_cache.get_cache(+ key="spend:key:key-budget-underflow-release"+ ) == pytest.approx(0.25)+ assert reservation["finalized"] is True@pytest.mark.asyncio-async def test_should_invalidate_non_numeric_counter_during_release(- spend_counter_state,-):+async def test_release_non_numeric_counter_reseeds_from_db(spend_counter_state):+ """A non-numeric counter value (corrupt/stale) during release is recovered by+ reseeding from the DB, not by deleting the counter and raising."""+ import litellm.proxy.proxy_server as ps+counter_cache, _ = spend_counter_statecounter_cache.in_memory_cache.set_cache(key="spend:key:key-budget-nonnumeric-release",@@ -1520,16 +1528,13 @@ async def test_should_invalidate_non_numeric_counter_during_release("finalized": False,}- with pytest.raises(RuntimeError, match="non-numeric"):+ with patch.object(ps.SpendCounterReseed, "from_db", AsyncMock(return_value=0.5)):await release_budget_reservation(reservation)- assert (- counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-nonnumeric-release"- )- is None- )- assert reservation["finalized"] is False+ assert counter_cache.in_memory_cache.get_cache(+ key="spend:key:key-budget-nonnumeric-release"+ ) == pytest.approx(0.5)+ assert reservation["finalized"] is True@pytest.mark.asynciodiff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.pyindex 09cc7a51caf..6b692180559 100644--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py@@ -4150,7 +4150,7 @@ class TestApplyClientTagPolicyPreAuth:litellm_budget_table=LiteLLM_BudgetTable(max_budget=0.10),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:tag:paid":return 0.50return fallback_spend@@ -4207,7 +4207,7 @@ class TestApplyClientTagPolicyPreAuth:litellm_budget_table=LiteLLM_BudgetTable(max_budget=0.10),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:tag:tenant:acme":return 0.50return fallback_spend@@ -4362,7 +4362,7 @@ class TestApplyKeyTagsPreAuth:litellm_budget_table=LiteLLM_BudgetTable(max_budget=0.10),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:tag:engineering":return 0.50return fallback_spend@@ -4413,7 +4413,7 @@ class TestApplyKeyTagsPreAuth:litellm_budget_table=LiteLLM_BudgetTable(max_budget=0.10),)- async def mock_get_current_spend(counter_key, fallback_spend):+ async def mock_get_current_spend(counter_key, fallback_spend, max_budget=None, **kwargs):if counter_key == "spend:tag:engineering":return 0.05return fallback_spenddiff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 7cc08534d14..6017b9555e9 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -6896,14 +6896,15 @@ async def test_increment_spend_counters_finalizes_none_cost_reservation():@pytest.mark.asyncio-async def test_increment_spend_counters_falls_back_to_direct_increment_on_bad_reserved_counter():- """When the reservation reconcile fails, the reserved counters are- invalidated and the actual response cost must still be written via the- direct increment fallback. Leaving the counter at ``None`` lets the next- request reseed a stale value from the DB and silently stops budget gating,- which is the bug this fix addresses."""+async def test_increment_spend_counters_reseeds_from_db_on_bad_reserved_counter():+ """When the reservation reconcile finds the counter in an inconsistent state+ (here: missing), it must NOT delete the counter and fail open (the old+ behavior, which left the counter unenforced after a Redis reload). It reseeds+ from the authoritative DB so the counter reflects the recorded total and+ budget gating continues."""from litellm.caching.dual_cache import DualCachefrom litellm.proxy.proxy_server import increment_spend_counters+ from litellm.proxy.db.spend_counter_reseed import SpendCounterReseedcounter_cache = DualCache()budget_reservation = {@@ -6923,11 +6924,11 @@ async def test_increment_spend_counters_falls_back_to_direct_increment_on_bad_reimport litellm.proxy.proxy_server as psorig_counter = ps.spend_counter_cache+ orig_prisma = ps.prisma_clientps.spend_counter_cache = counter_cache+ ps.prisma_client = MagicMock() # truthy so reseed reaches from_dbtry:- with patch(- "litellm.proxy.proxy_server.verbose_proxy_logger.warning"- ) as mock_warning:+ with patch.object(SpendCounterReseed, "from_db", AsyncMock(return_value=0.6)):await increment_spend_counters(token="key-bad-reserved-counter",team_id=None,@@ -6936,16 +6937,15 @@ async def test_increment_spend_counters_falls_back_to_direct_increment_on_bad_rebudget_reservation=budget_reservation,)- mock_warning.assert_called_once()assert budget_reservation["finalized"] is True- assert (- counter_cache.in_memory_cache.get_cache(- key="spend:key:key-bad-reserved-counter"- )- == 0.25- )+ # counter reseeded to the authoritative DB value, not deleted/left None+ # and not double-counted via a direct increment+ assert counter_cache.in_memory_cache.get_cache(+ key="spend:key:key-bad-reserved-counter"+ ) == pytest.approx(0.6)finally:ps.spend_counter_cache = orig_counter+ ps.prisma_client = orig_prisma@pytest.mark.asyncio