Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1879,6 +1879,7 @@
SPEND_LOG_KEY_METADATA_CACHE_TTL: Final = 600
SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL: Final = 30
SPEND_LOG_KEY_METADATA_CACHE_MAX_ITEMS: Final = 10000
SPEND_COUNTER_CACHE_MAX_SIZE: Final = 10000
SPEND_LOG_KEY_METADATA_QUERY_TIMEOUT_MS: Final = 5000
# Short TTL for negative MCP access-group existence lookups. Keeps unauthenticated
# callers from forcing a DB query per request for unknown names, while bounding
Expand Down
8 changes: 6 additions & 2 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def generate_feedback_box():
import litellm._redis
from litellm import Router
from litellm._logging import _redact_string, verbose_proxy_logger, verbose_router_logger
from litellm.caching.caching import DualCache, RedisCache
from litellm.caching.caching import DualCache, InMemoryCache, RedisCache
from litellm.caching.redis_cache import RedisCircuitBreakerOpenError, is_redis_timeout_failure
from litellm.caching.redis_cluster_cache import RedisClusterCache
from litellm.constants import (
Expand Down Expand Up @@ -285,6 +285,7 @@ def generate_feedback_box():
REALTIME_SESSION_FAILURE_LOGGED_KEY,
REALTIME_SESSION_SUCCESS_LOGGED_KEY,
ROUTER_SETTINGS_MANAGED_OUTSIDE_CONFIG,
SPEND_COUNTER_CACHE_MAX_SIZE,
USER_SPEND_ALERTS_JOB_ID,
WEEKLY_SPEND_REPORT_JOB_ID,
)
Expand Down Expand Up @@ -2506,7 +2507,10 @@ def general_settings_view() -> Mapping[str, object]:
user_api_key_cache: UserApiKeyCache = UserApiKeyCache(
default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value
)
spend_counter_cache: Final = DualCache(default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value)
spend_counter_cache: Final = DualCache(
in_memory_cache=InMemoryCache(max_size_in_memory=SPEND_COUNTER_CACHE_MAX_SIZE),
default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value,
)
cli_sso_session_cache: Final = DualCache(default_in_memory_ttl=CLI_SSO_SESSION_TTL_SECONDS)
model_max_budget_limiter: Final = _PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=spend_counter_cache)
litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/coverage_registry/quota_management.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
- {id: quota_management.budget.team_multi_window.blocks_then_resets, module: quota_management, tier: P1, behavior: budget, variant: team_multi_window, assertions: [blocks_then_resets], exercised_on: [chat_completions], source: "proxy/common_utils/reset_budget_job.py", rationale: "Team budget_limits enforce and reset per window"}
- {id: quota_management.budget.fallback.routes_to_fallback, module: quota_management, tier: P1, behavior: budget, variant: fallback, assertions: [routes_to_fallback], exercised_on: [messages], source: "proxy/hooks/model_max_budget_limiter.py", rationale: "budget_fallbacks reroute to the fallback model once the primary's budget is exhausted"}
- {id: quota_management.budget.spend_counter.reseed_matches_db, module: quota_management, tier: P2, behavior: budget, variant: spend_counter, assertions: [reseed_matches_db], exercised_on: [chat_completions], source: "proxy/spend_tracking/budget_reservation.py", rationale: "Concurrent cold-counter reseeds keep the enforcement counter equal to DB spend (#26829)"}
- {id: quota_management.budget.spend_counter.survives_scope_churn, module: quota_management, tier: P1, behavior: budget, variant: spend_counter, assertions: [survives_scope_churn], exercised_on: [chat_completions], source: "proxy/proxy_server.py:spend_counter_cache", rationale: "A key's in-memory spend counter is not evicted by traffic on hundreds of other budget scopes, so an over-budget key stays blocked instead of being re-admitted off lagging DB spend (#40221)"}
- {id: quota_management.spend_tracking.chat_completions.logs_cost, module: quota_management, tier: P0, behavior: spend_tracking, variant: chat_completions, assertions: [logs_cost], exercised_on: [chat_completions], source: "proxy/spend_tracking/spend_tracking_utils.py", rationale: "A paid chat call writes a nonzero spend row"}
- {id: quota_management.spend_tracking.stream.logs_cost, module: quota_management, tier: P1, behavior: spend_tracking, variant: stream, assertions: [logs_cost], exercised_on: [chat_completions], source: "proxy/spend_tracking/spend_tracking_utils.py", rationale: "Streaming responses aggregate token counts into a spend row"}
- {id: quota_management.spend_tracking.messages_bridge.logs_cost, module: quota_management, tier: P1, behavior: spend_tracking, variant: messages_bridge, assertions: [logs_cost], exercised_on: [messages], source: "llms/anthropic/experimental_pass_through/responses_adapters/handler.py", rationale: "A streaming /v1/messages request served by an openai-provider model is bridged through the anthropic-messages -> Responses adapter and must aggregate the consumed SSE stream into one spend row with nonzero cost and token counts, attributed to custom_llm_provider openai under call_type anthropic_messages"}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Live e2e: an over-budget key stays blocked while hundreds of other budget scopes take traffic (#40221).

The proxy keeps one in-memory spend counter per budget scope (key, team, end user, tag, ...)
in ``spend_counter_cache``. Every request that names a new ``user`` creates a new end-user
counter. When that cache is sized like the generic in-memory cache (200 entries), the 201st
active scope evicts a still-valid counter, and the next request on the evicted key reseeds it
from the DB. The DB row lags the counter until ``proxy_batch_write_at`` flushes, so a key the
proxy had just rejected for being over budget is admitted again.

The test blocks a tiny-budget key with a real call, then drives more than 200 distinct end users
on a second key, then re-probes the blocked key. The invariant (blocked stays blocked) must hold
on every stack. The eviction itself is only reachable on a proxy without Redis whose DB row still
lags (``proxy_batch_write_at`` above the churn time); with Redis the cross-pod counter answers
first, and a flushed row reseeds correctly, so those stacks re-prove the plain budget block.
The probe key's DB spend at re-probe time is reported in the failure message so a reader can
tell which path was exercised.
"""

from concurrent.futures import ThreadPoolExecutor

import pytest

from budget_client import BudgetClient, is_budget_block
from e2e_config import unique_marker
from e2e_http import StreamingResponse
from lifecycle import ResourceManager

pytestmark = pytest.mark.e2e

MODEL = "claude-haiku-4-5"
TINY_BUDGET = 0.000001
GENERIC_CACHE_SIZE = 200
CHURN_SCOPES = 250
CHURN_WORKERS = 24


def _chat(client: BudgetClient, key: str, user: str) -> StreamingResponse:
return client.chat(key, MODEL, f"scope churn {unique_marker()}", max_tokens=1, user=user)


@pytest.mark.covers("quota_management.budget.spend_counter.survives_scope_churn")
def test_over_budget_key_stays_blocked_after_hundreds_of_other_scopes(
client: BudgetClient, resources: ResourceManager
) -> None:
run = unique_marker()
probe_key = client.generate_key(max_budget=TINY_BUDGET, models=[MODEL])
resources.defer(lambda: client.delete_key(probe_key))
churn_key = client.generate_key(models=[MODEL])
resources.defer(lambda: client.delete_key(churn_key))
churn_users = [f"churn-{run}-{index}" for index in range(CHURN_SCOPES)]
resources.defer(lambda: client.delete_customers(churn_users))

first = _chat(client, probe_key, user=f"probe-{run}")
assert first.ok, f"first call on a fresh key must be admitted: {first.status_code} {first.body[:300]}"
blocked = _chat(client, probe_key, user=f"probe-{run}")
assert is_budget_block(blocked), (
f"precondition: the key must be over budget before the churn: {blocked.status_code} {blocked.body[:300]}"
)

def churn_call(user: str) -> StreamingResponse:
return _chat(client, churn_key, user=user)

with ThreadPoolExecutor(max_workers=CHURN_WORKERS) as pool:
churn = list(pool.map(churn_call, churn_users))
admitted = sum(1 for r in churn if r.ok)
assert admitted > GENERIC_CACHE_SIZE, (
f"only {admitted}/{CHURN_SCOPES} churn calls succeeded; cannot exceed {GENERIC_CACHE_SIZE} live scopes"
)

db_spend = client.proxy.key_info(probe_key).spend or 0.0
after = _chat(client, probe_key, user=f"probe-{run}")
assert is_budget_block(after), (
f"over-budget key was admitted after {admitted} other scopes took traffic (DB spend {db_spend}): "
f"{after.status_code} {after.body[:300]}; its spend counter was evicted and reseeded from lagging "
"DB spend (#40221)"
)
25 changes: 25 additions & 0 deletions tests/test_litellm/proxy/test_proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8553,6 +8553,31 @@ async def test_get_current_spend_fallback_to_in_memory():
ps.spend_counter_cache = original


@pytest.mark.asyncio
async def test_over_budget_key_spend_survives_hundreds_of_other_scopes_incrementing():
from litellm.caching.in_memory_cache import DEFAULT_MAX_SIZE_IN_MEMORY
from litellm.proxy.proxy_server import get_current_spend, increment_spend_counters, spend_counter_cache

token = "unit-40221-probe"
other_scopes = DEFAULT_MAX_SIZE_IN_MEMORY + 100
end_users = [f"unit-40221-{index}" for index in range(other_scopes)]
try:
await increment_spend_counters(token=token, team_id=None, user_id=None, response_cost=0.25)
for end_user in end_users:
await increment_spend_counters(
token=None, team_id=None, user_id=None, response_cost=0.01, end_user_id=end_user
)
spend = await get_current_spend(counter_key=f"spend:key:{token}", fallback_spend=0.0)
finally:
for counter_key in [f"spend:key:{token}", *(f"spend:end_user:{end_user}" for end_user in end_users)]:
spend_counter_cache.in_memory_cache.delete_cache(key=counter_key)

assert spend == 0.25, (
f"key spend read back as {spend} after {other_scopes} other scopes were charged; "
"the counter was evicted and the budget check fell back to the stale value (#40221)"
)


@pytest.mark.asyncio
async def test_increment_spend_counters_initializes_and_increments():
"""Counter should initialize from cached object spend, then increment.
Expand Down
Loading