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): keep the over-limit verdict on rollback failure, find locally saved records on pop

mateo-berri504112d5ca0f
diff --git a/litellm/proxy/hooks/batch_enqueued_tokens.py b/litellm/proxy/hooks/batch_enqueued_tokens.py
index bbc007bb00d..9d6a599af4a 100644
--- a/litellm/proxy/hooks/batch_enqueued_tokens.py
+++ b/litellm/proxy/hooks/batch_enqueued_tokens.py
@@ -246,7 +246,7 @@ class BatchEnqueuedTokenStore:
already_reserved=scopes[:index],
)
if result[0] != 1:
- await self._refund_via_redis(refund_script, tokens=tokens, scopes=scopes[:index])
+ await self._rollback_partial_reserve(refund_script, tokens=tokens, scopes=scopes[:index])
return BatchEnqueuedTokenOverLimit(scope=scope, enqueued=result[1])
return BatchEnqueuedTokenReservation(tokens=tokens, scopes=scopes, backend="redis")
@@ -376,17 +376,10 @@ class BatchEnqueuedTokenStore:
batch_id: str,
litellm_parent_otel_span: "Span | None" = None,
) -> BatchEnqueuedTokenReservation | None:
- raw: object = None
- if self._pop_script is not None:
- try:
- raw = _POPPED_VALUE_ADAPTER.validate_python(await self._pop_script((self._record_key(batch_id),), ()))
- except Exception as e: # noqa: BLE001 # any Redis failure must fall back to the in-memory record
- verbose_proxy_logger.warning(
- "Redis enqueued-token reservation pop failed, falling back to in-memory: %s", str(e)
- )
- raw = await self._pop_local_record(batch_id, litellm_parent_otel_span)
- else:
- raw = await self._pop_local_record(batch_id, litellm_parent_otel_span)
+ redis_raw: Final = await self._pop_redis_record(batch_id)
+ raw: Final = (
+ redis_raw if redis_raw is not None else await self._pop_local_record(batch_id, litellm_parent_otel_span)
+ )
if raw is None:
return None
try:
@@ -397,6 +390,18 @@ class BatchEnqueuedTokenStore:
verbose_proxy_logger.warning("Discarding malformed enqueued-token reservation record for %s", batch_id)
return None
+ async def _pop_redis_record(self, batch_id: str) -> str | bytes | None:
+ pop_script: Final = self._pop_script
+ if pop_script is None:
+ return None
+ try:
+ return _POPPED_VALUE_ADAPTER.validate_python(await pop_script((self._record_key(batch_id),), ()))
+ except Exception as e: # noqa: BLE001 # any Redis failure must fall back to the in-memory record
+ verbose_proxy_logger.warning(
+ "Redis enqueued-token reservation pop failed, falling back to in-memory: %s", str(e)
+ )
+ return None
+
async def _pop_local_record(self, batch_id: str, span: "Span | None") -> object:
async with self._lock:
stored = await self.internal_usage_cache.async_get_cache(
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 d6ae200dfaf..5167856359d 100644
--- a/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
+++ b/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
@@ -132,14 +132,21 @@ class _SingleKeyRedisFake:
self,
fail_reserve_keys: frozenset[str] = frozenset(),
fail_refund_keys: frozenset[str] = frozenset(),
+ fail_save_keys: frozenset[str] = frozenset(),
) -> None:
self.script_calls: tuple[tuple[str, tuple[str, ...]], ...] = ()
self.counters: Mapping[str, int] = MappingProxyType({})
+ self.records: Mapping[str, str] = MappingProxyType({})
self.fail_reserve_keys = fail_reserve_keys
self.fail_refund_keys = fail_refund_keys
+ self.fail_save_keys = fail_save_keys
def async_register_script(self, script: str):
- kind: Final = "reserve" if "INCRBY" in script else "refund" if "DECRBY" in script else "record"
+ kind: Final = (
+ "reserve"
+ if "INCRBY" in script
+ else "refund" if "DECRBY" in script else "save" if "SET" in script else "pop"
+ )
async def run(keys: Sequence[str], args: Sequence[str | bytes | int | float]) -> object:
self.script_calls = (*self.script_calls, (kind, tuple(keys)))
@@ -167,6 +174,15 @@ class _SingleKeyRedisFake:
else {**self.counters, keys[0]: remaining}
)
return 1
+ if kind == "save":
+ if keys[0] in self.fail_save_keys:
+ raise ConnectionError(f"simulated redis failure for {keys[0]}")
+ self.records = MappingProxyType({**self.records, keys[0]: str(args[0])})
+ return 1
+ if kind == "pop":
+ popped: Final = self.records.get(keys[0])
+ self.records = MappingProxyType({key: value for key, value in self.records.items() if key != keys[0]})
+ return popped
raise AssertionError(f"unexpected {kind} script call for keys {keys}")
@@ -214,6 +230,42 @@ async def test_partial_redis_reserve_failure_rolls_back_and_grants_in_memory():
assert refilled.backend == "memory"
+async def test_over_limit_verdict_survives_a_failing_rollback():
+ key_scope = _scope(limit=100, key="api_key")
+ team_scope = _scope(limit=5, key="team")
+ key_counter: Final = f"batch_enqueued_tokens:api_key:{key_scope.value}"
+ fake = _SingleKeyRedisFake(fail_refund_keys=frozenset({key_counter}))
+ 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 outcome == BatchEnqueuedTokenOverLimit(scope=team_scope, enqueued=0)
+ assert fake.counters == {key_counter: 10}
+
+
+async def test_pop_falls_back_to_local_record_when_redis_pop_finds_nothing():
+ scope = _scope(limit=100)
+ record_key: Final = "batch_enqueued_token_reservation:batch_local_record"
+ fake = _SingleKeyRedisFake(fail_save_keys=frozenset({record_key}))
+ store = BatchEnqueuedTokenStore(
+ internal_usage_cache=InternalUsageCache(DualCache(redis_cache=fake, default_in_memory_ttl=60))
+ )
+
+ reservation = await store.reserve(tokens=60, scopes=(scope,))
+ assert isinstance(reservation, BatchEnqueuedTokenReservation)
+ await store.save_reservation("batch_local_record", reservation)
+ assert not fake.records
+
+ popped = await store.pop_reservation("batch_local_record")
+ assert popped == reservation
+ await store.refund(popped)
+ assert not fake.counters
+ assert await store.pop_reservation("batch_local_record") is None
+
+
@pytest.mark.asyncio
async def test_memory_refund_skips_reservations_granted_by_another_worker():
store = _in_memory_store()