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
Merge remote-tracking branch 'origin/main' into litellm_lit7351_reservation_lease_renewal
yassin14cb7c65c2d2
diff --cc litellm/proxy/spend_tracking/budget_reservation.pyindex c0af6685600,4c4785339c8..f9e5c4ff1e4--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@@ -2,7 -2,7 +2,8 @@@ from __future__ import annotationimport asyncioimport json+ import math+import timefrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone@@@ -342,12 -324,8 +367,13 @@@ async def reserve_budget_for_request"entries": applied_entries,"finalized": False,"input_cost": min(float(input_cost or 0.0), reservation_cost),+ "input_tokens": max(input_token_counts.values(), default=None),}+ _start_reservation_lease_renewal(+ budget_reservation=budget_reservation,+ counter_keys=frozenset(get_reserved_counter_keys(budget_reservation=budget_reservation)),+ )+ return budget_reservationasync def reconcile_budget_reservation(diff --cc tests/test_litellm/proxy/test_budget_reservation.pyindex 626c82ea397,c834ac05f0a..6905585fd5e--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@@ -2238,94 -2368,27 +2387,114 @@@ class _ExpiringRedisCacheasync def async_delete_cache(self, key: str, *args: object, **kwargs: object) -> None:self.store.pop(key, None)+ self.expires_at.pop(key, None)++ async def async_refresh_ttl(self, key: str, ttl: int | None = None) -> bool:+ self.refresh_attempts += 1+ if self.fail_first_refresh and self.refresh_attempts == 1:+ raise ConnectionError("Redis circuit breaker is open")+ self._evict_expired(key)+ if key not in self.store:+ return False+ self.refresh_count += 1+ self.expires_at[key] = time.monotonic() + (ttl if ttl is not None else self.default_ttl)+ return True+++async def test_reservation_survives_redis_counter_ttl_while_request_in_flight(+ spend_counter_state,+):+ """A request that runs longer than the counter TTL must keep its reservation in Redis+ (so a concurrent request on any worker still sees it), and renewal must stop once the+ reservation is reconciled so an idle counter still expires on its own."""+ counter_cache, key_cache = spend_counter_state+ redis_cache = _ExpiringRedisCache(default_ttl=0.2)+ counter_cache.redis_cache = redis_cache+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-lease", spend=0.0, max_budget=1.0)+ counter_key = "spend:key:key-lease"++ reservation = await _reserve(valid_token, 0.6, key_cache, proxy_logging_obj)+ assert reservation is not None++ await asyncio.sleep(0.5)+ assert await redis_cache.async_get_cache(key=counter_key) == pytest.approx(0.6)+ concurrent = await _reserve(valid_token, 0.6, key_cache, proxy_logging_obj)+ assert concurrent is not None+ assert concurrent["reserved_cost"] == pytest.approx(0.4)++ await release_budget_reservation(reservation)+ await release_budget_reservation(concurrent)+ await asyncio.sleep(0.15)+ refreshes_after_release = redis_cache.refresh_count+ await asyncio.sleep(0.35)+ assert redis_cache.refresh_count == refreshes_after_release+ assert await redis_cache.async_get_cache(key=counter_key) is None+++async def test_reservation_lease_keeps_renewing_after_transient_redis_failure(+ spend_counter_state,+):+ """One failed EXPIRE (Redis blip, open circuit breaker) must not end renewal for the+ rest of the request."""+ counter_cache, key_cache = spend_counter_state+ redis_cache = _ExpiringRedisCache(default_ttl=0.2, fail_first_refresh=True)+ counter_cache.redis_cache = redis_cache+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-lease-blip", spend=0.0, max_budget=1.0)++ reservation = await _reserve(valid_token, 0.6, key_cache, proxy_logging_obj)+ assert reservation is not None++ await asyncio.sleep(0.5)+ assert redis_cache.refresh_attempts >= 3+ await release_budget_reservation(reservation)+++async def test_reservation_lease_stops_when_request_task_ends_without_reconciling(+ spend_counter_state,+):+ """A request whose task ends without reconciling (client disconnect path that skips the+ cost callbacks) must not keep renewing: the counter falls back to its plain TTL instead of+ pinning the reservation until the request timeout."""+ counter_cache, key_cache = spend_counter_state+ redis_cache = _ExpiringRedisCache(default_ttl=0.2)+ counter_cache.redis_cache = redis_cache+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)+ valid_token = UserAPIKeyAuth(token="key-lease-orphan", spend=0.0, max_budget=1.0)+ counter_key = "spend:key:key-lease-orphan"++ reservation = await asyncio.create_task(_reserve(valid_token, 0.6, key_cache, proxy_logging_obj))+ assert reservation is not None+ assert reservation["finalized"] is False++ await asyncio.sleep(0.5)+ assert redis_cache.refresh_count == 0+ assert await redis_cache.async_get_cache(key=counter_key) is None+ async def async_increment_pipeline(self, increment_list, **kwargs):+ results = []+ for op in increment_list:+ results.append(await self.async_increment(op["key"], op["increment_value"]))+ return results++ def get_ttl(self, **kwargs) -> None:+ return None+++ class _TeamMembershipFloorDb:+ """Stands in for `prisma_client.db`: only the team-membership row exists and its spend is the DB floor."""++ def __init__(self, spend: float) -> None:+ self.spend = spend++ def __getattr__(self, table_name: str) -> SimpleNamespace:+ row = SimpleNamespace(spend=self.spend) if table_name == "litellm_teammembership" else None+ return SimpleNamespace(find_unique=AsyncMock(return_value=row))+@pytest.mark.asyncioasync def test_reconcile_after_redis_counter_expiry_keeps_request_cost_enforced(