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(batch_enqueued_tokens): roll back partial reserves, route refunds by backend, lowercase terminal statuses

mateo-berri50896f21b346
diff --git a/litellm/proxy/hooks/batch_enqueued_tokens.py b/litellm/proxy/hooks/batch_enqueued_tokens.py
index e484b6a59fe..570291aa452 100644
--- a/litellm/proxy/hooks/batch_enqueued_tokens.py
+++ b/litellm/proxy/hooks/batch_enqueued_tokens.py
@@ -77,10 +77,14 @@ class BatchEnqueuedTokenScope:
limit: int
+ReservationBackend: TypeAlias = Literal["redis", "memory"]
+
+
@dataclass(frozen=True, slots=True)
class BatchEnqueuedTokenReservation:
tokens: int
scopes: tuple[BatchEnqueuedTokenScope, ...]
+ backend: ReservationBackend = "redis"
@dataclass(frozen=True, slots=True)
@@ -170,9 +174,10 @@ class BatchEnqueuedTokenStore:
Counters and records live in Redis when Redis is configured, through
single-key Lua scripts issued one scope at a time (Redis Cluster safe: no
- cross-slot commands), with an over-limit scope rolling back the scopes
- reserved before it; otherwise a single-process in-memory fallback guarded
- by one asyncio lock is used. Everything expires after
+ cross-slot commands), with an over-limit or failing scope rolling back the
+ scopes reserved before it; otherwise a single-process in-memory fallback
+ guarded by one asyncio lock is used. Reservations remember which backend
+ granted them so a refund never debits counters the grant did not charge. Everything expires after
``BATCH_ENQUEUED_TOKEN_TTL_SECONDS`` so a crash between submission and the
terminal-state refund can never leak tokens forever.
"""
@@ -229,15 +234,49 @@ class BatchEnqueuedTokenStore:
scopes: tuple[BatchEnqueuedTokenScope, ...],
) -> BatchEnqueuedTokenOutcome:
for index, scope in enumerate(scopes):
- raw_result = await reserve_script(
- (self._counter_key(scope),),
- (tokens, BATCH_ENQUEUED_TOKEN_TTL_SECONDS, scope.limit),
+ result = await self._run_reserve_script(
+ reserve_script,
+ refund_script,
+ tokens=tokens,
+ scope=scope,
+ already_reserved=scopes[:index],
)
- result = _RESERVE_RESULT_ADAPTER.validate_python(raw_result)
if result[0] != 1:
await self._refund_via_redis(refund_script, tokens=tokens, scopes=scopes[:index])
return BatchEnqueuedTokenOverLimit(scope=scope, enqueued=result[1])
- return BatchEnqueuedTokenReservation(tokens=tokens, scopes=scopes)
+ return BatchEnqueuedTokenReservation(tokens=tokens, scopes=scopes, backend="redis")
+
+ async def _run_reserve_script(
+ self,
+ reserve_script: _ScriptRunner,
+ refund_script: _ScriptRunner,
+ tokens: int,
+ scope: BatchEnqueuedTokenScope,
+ already_reserved: tuple[BatchEnqueuedTokenScope, ...],
+ ) -> tuple[int, int]:
+ try:
+ raw_result: Final = await reserve_script(
+ (self._counter_key(scope),),
+ (tokens, BATCH_ENQUEUED_TOKEN_TTL_SECONDS, scope.limit),
+ )
+ return _RESERVE_RESULT_ADAPTER.validate_python(raw_result)
+ except Exception:
+ await self._rollback_partial_reserve(refund_script, tokens=tokens, scopes=already_reserved)
+ raise
+
+ async def _rollback_partial_reserve(
+ self,
+ refund_script: _ScriptRunner,
+ tokens: int,
+ scopes: tuple[BatchEnqueuedTokenScope, ...],
+ ) -> None:
+ try:
+ await self._refund_via_redis(refund_script, tokens=tokens, scopes=scopes)
+ except Exception as e: # noqa: BLE001 # best-effort rollback: the leak is TTL-bounded and only tightens the allowance
+ verbose_proxy_logger.warning(
+ "Rollback of partially reserved enqueued tokens failed; leaked increments expire with the TTL: %s",
+ str(e),
+ )
async def _refund_via_redis(
self,
@@ -261,7 +300,7 @@ class BatchEnqueuedTokenStore:
return BatchEnqueuedTokenOverLimit(scope=scope, enqueued=current)
for scope, current in zip(scopes, currents):
await self._set_local_counter(scope, current + tokens, span)
- return BatchEnqueuedTokenReservation(tokens=tokens, scopes=scopes)
+ return BatchEnqueuedTokenReservation(tokens=tokens, scopes=scopes, backend="memory")
async def refund(
self,
@@ -271,7 +310,7 @@ class BatchEnqueuedTokenStore:
if reservation.tokens <= 0 or not reservation.scopes:
return
refund_script: Final = self._refund_script
- if refund_script is not None:
+ if reservation.backend == "redis" and refund_script is not None:
try:
await self._refund_via_redis(refund_script, tokens=reservation.tokens, scopes=reservation.scopes)
except Exception as e: # noqa: BLE001 # any Redis failure must fall back to the in-memory counters
diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.py
index b295da69255..1e65da5b867 100644
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@ -4700,7 +4700,7 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):
litellm_parent_otel_span=span,
)
stash.batch_enqueued_reservation = None
- if view.status in BATCH_ENQUEUED_REFUND_STATUSES:
+ if view.status.lower() in BATCH_ENQUEUED_REFUND_STATUSES:
popped: Final = await self.batch_enqueued_token_store.pop_reservation(
batch_id=canonical_provider_batch_id(view.id),
litellm_parent_otel_span=span,
diff --git a/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py b/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
index 1bb4798eaa0..bc924c32ba3 100644
--- a/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
+++ b/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
@@ -128,9 +128,10 @@ async def test_zero_token_reserve_charges_nothing():
class _SingleKeyRedisFake:
"""Emulates the Redis script path one single-key call at a time, recording every call."""
- def __init__(self) -> None:
+ def __init__(self, fail_reserve_keys: frozenset[str] = frozenset()) -> None:
self.script_calls: tuple[tuple[str, tuple[str, ...]], ...] = ()
self.counters: Mapping[str, int] = MappingProxyType({})
+ self.fail_reserve_keys = fail_reserve_keys
def async_register_script(self, script: str):
kind: Final = "reserve" if "INCRBY" in script else "refund" if "DECRBY" in script else "record"
@@ -143,6 +144,8 @@ class _SingleKeyRedisFake:
def _run(self, kind: str, keys: tuple[str, ...], args: tuple[str | bytes | int | float, ...]) -> object:
if kind == "reserve":
+ if keys[0] in self.fail_reserve_keys:
+ raise ConnectionError(f"simulated redis failure for {keys[0]}")
amount, limit = int(args[0]), int(args[2])
current: Final = self.counters.get(keys[0], 0)
if current + amount > limit:
@@ -181,6 +184,42 @@ async def test_redis_reserve_issues_single_key_calls_and_rolls_back_on_over_limi
assert all(len(keys) == 1 for _, keys in fake.script_calls)
+async def test_partial_redis_reserve_failure_rolls_back_and_grants_in_memory():
+ key_scope = _scope(limit=100, key="api_key")
+ team_scope = _scope(limit=50, key="team")
+ fake = _SingleKeyRedisFake(fail_reserve_keys=frozenset({f"batch_enqueued_tokens:team:{team_scope.value}"}))
+ store = BatchEnqueuedTokenStore(
+ internal_usage_cache=InternalUsageCache(DualCache(redis_cache=fake, default_in_memory_ttl=60))
+ )
+
+ outcome = await store.reserve(tokens=10, scopes=(key_scope, team_scope))
+ assert isinstance(outcome, BatchEnqueuedTokenReservation)
+ assert outcome.backend == "memory"
+ assert tuple(kind for kind, _ in fake.script_calls) == ("reserve", "reserve", "refund")
+ assert not fake.counters
+
+ await store.refund(outcome)
+ assert tuple(kind for kind, _ in fake.script_calls) == ("reserve", "reserve", "refund")
+
+ refilled = await store.reserve(tokens=50, scopes=(team_scope,))
+ assert isinstance(refilled, BatchEnqueuedTokenReservation)
+ assert refilled.backend == "memory"
+
+
+async def test_pop_reservation_defaults_legacy_records_to_redis_backend():
+ store = _in_memory_store()
+ legacy = '{"tokens": 5, "scopes": [{"key": "api_key", "value": "k", "limit": 10}]}'
+ store.internal_usage_cache.dual_cache.in_memory_cache.set_cache(
+ key="batch_enqueued_token_reservation:batch_legacy", value=legacy
+ )
+ popped = await store.pop_reservation("batch_legacy")
+ assert popped == BatchEnqueuedTokenReservation(
+ tokens=5, scopes=(BatchEnqueuedTokenScope(key="api_key", value="k", limit=10),), backend="redis"
+ )
+
+
def test_canonical_provider_batch_id_passes_raw_ids_through():
assert canonical_provider_batch_id("batch_abc123") == "batch_abc123"
diff --git a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
index 68c219fd72d..fee892ad342 100644
--- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
+++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
@@ -5935,6 +5935,33 @@ async def test_success_hook_refunds_batch_enqueued_reservation_on_cancellation()
assert isinstance(await store.reserve(tokens=100, scopes=(scope,)), BatchEnqueuedTokenReservation)
+async def test_success_hook_refunds_on_provider_cased_terminal_status():
+ from litellm.proxy.hooks.batch_enqueued_tokens import (
+ BatchEnqueuedTokenOverLimit,
+ BatchEnqueuedTokenReservation,
+ BatchEnqueuedTokenScope,
+ )
+
+ handler = _enqueued_test_handler()
+ store = handler.batch_enqueued_token_store
+ scope = BatchEnqueuedTokenScope(key="api_key", value="hashed-enqueued-key", limit=100)
+ user = UserAPIKeyAuth(api_key="hashed-enqueued-key")
+
+ reservation = await store.reserve(tokens=90, scopes=(scope,))
+ assert isinstance(reservation, BatchEnqueuedTokenReservation)
+ get_or_create_request_stash().batch_enqueued_reservation = reservation
+ await handler.async_post_call_success_hook(
+ data={}, user_api_key_dict=user, response=_batch_response("batch_enq_cased", "InProgress")
+ )
+ assert isinstance(await store.reserve(tokens=100, scopes=(scope,)), BatchEnqueuedTokenOverLimit)
+
+ await handler.async_post_call_success_hook(
+ data={}, user_api_key_dict=user, response=_batch_response("batch_enq_cased", "Completed")
+ )
+ assert isinstance(await store.reserve(tokens=100, scopes=(scope,)), BatchEnqueuedTokenReservation)
+
+
@pytest.mark.asyncio
async def test_failure_hook_refunds_stashed_batch_enqueued_reservation():
from litellm.proxy.hooks.batch_enqueued_tokens import (