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): tombstone popped Redis reservation records so local ghosts cannot double-refund

mateo-berri5ab20c367875
diff --git a/litellm/proxy/hooks/batch_enqueued_tokens.py b/litellm/proxy/hooks/batch_enqueued_tokens.py
index 54b0111682d..82d4e7c66fc 100644
--- a/litellm/proxy/hooks/batch_enqueued_tokens.py
+++ b/litellm/proxy/hooks/batch_enqueued_tokens.py
@@ -62,8 +62,8 @@ return 1
POP_RESERVATION_SCRIPT: Final = """
local value = redis.call('GET', KEYS[1])
-if value then
- redis.call('DEL', KEYS[1])
+if value and value ~= '' then
+ redis.call('SET', KEYS[1], '', 'EX', tonumber(ARGV[1]))
end
return value
"""
@@ -375,6 +375,12 @@ class BatchEnqueuedTokenStore:
litellm_parent_otel_span: "Span | None" = None,
) -> BatchEnqueuedTokenReservation | None:
redis_raw: Final = await self._pop_redis_record(batch_id)
+ if redis_raw is not None and not redis_raw:
+ # The Redis pop tombstones popped records in place, so a hit on the empty
+ # tombstone means the batch was already refunded elsewhere; a local copy
+ # left behind by a save that raised after landing must not refund again.
+ await self._pop_local_record(batch_id, litellm_parent_otel_span)
+ return None
raw: Final = (
redis_raw if redis_raw is not None else await self._pop_local_record(batch_id, litellm_parent_otel_span)
)
@@ -393,7 +399,9 @@ class BatchEnqueuedTokenStore:
if pop_script is None:
return None
try:
- return _POPPED_VALUE_ADAPTER.validate_python(await pop_script((self._record_key(batch_id),), ()))
+ return _POPPED_VALUE_ADAPTER.validate_python(
+ await pop_script((self._record_key(batch_id),), (BATCH_ENQUEUED_TOKEN_TTL_SECONDS,))
+ )
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)
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 5167856359d..440b3050a39 100644
--- a/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
+++ b/tests/test_litellm/proxy/hooks/test_batch_enqueued_tokens.py
@@ -133,6 +133,7 @@ class _SingleKeyRedisFake:
fail_reserve_keys: frozenset[str] = frozenset(),
fail_refund_keys: frozenset[str] = frozenset(),
fail_save_keys: frozenset[str] = frozenset(),
+ raise_after_landing_save_keys: frozenset[str] = frozenset(),
) -> None:
self.script_calls: tuple[tuple[str, tuple[str, ...]], ...] = ()
self.counters: Mapping[str, int] = MappingProxyType({})
@@ -140,12 +141,13 @@ class _SingleKeyRedisFake:
self.fail_reserve_keys = fail_reserve_keys
self.fail_refund_keys = fail_refund_keys
self.fail_save_keys = fail_save_keys
+ self.raise_after_landing_save_keys = raise_after_landing_save_keys
def async_register_script(self, script: str):
kind: Final = (
"reserve"
if "INCRBY" in script
- else "refund" if "DECRBY" in script else "save" if "SET" in script else "pop"
+ else "refund" if "DECRBY" in script else "pop" if "GET" in script else "save"
)
async def run(keys: Sequence[str], args: Sequence[str | bytes | int | float]) -> object:
@@ -178,10 +180,13 @@ class _SingleKeyRedisFake:
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])})
+ if keys[0] in self.raise_after_landing_save_keys:
+ raise TimeoutError(f"simulated redis timeout after landing for {keys[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]})
+ if popped:
+ self.records = MappingProxyType({**self.records, keys[0]: ""})
return popped
raise AssertionError(f"unexpected {kind} script call for keys {keys}")
@@ -266,6 +271,38 @@ async def test_pop_falls_back_to_local_record_when_redis_pop_finds_nothing():
assert await store.pop_reservation("batch_local_record") is None
+async def test_local_ghost_left_by_landed_save_never_refunds_twice():
+ scope = _scope(limit=100)
+ record_key: Final = "batch_enqueued_token_reservation:batch_ghost"
+ fake = _SingleKeyRedisFake(raise_after_landing_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_ghost", reservation)
+ assert fake.records[record_key]
+
+ first = await store.pop_reservation("batch_ghost")
+ assert first == reservation
+ await store.refund(first)
+ assert not fake.counters
+ assert fake.records[record_key] == ""
+
+ assert await store.pop_reservation("batch_ghost") is None
+ assert (
+ await store.internal_usage_cache.async_get_cache(
+ key=record_key, litellm_parent_otel_span=None, local_only=True
+ )
+ is None
+ )
+ assert await store.pop_reservation("batch_ghost") is None
+ assert isinstance(await store.reserve(tokens=100, scopes=(scope,)), BatchEnqueuedTokenReservation)
+ assert fake.counters[f"batch_enqueued_tokens:{scope.key}:{scope.value}"] == 100
+
+
@pytest.mark.asyncio
async def test_memory_refund_skips_reservations_granted_by_another_worker():
store = _in_memory_store()