mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* fix(proxy): seed a cold end-user spend counter once from the end-user row A cold spend:end_user counter was seeded by adding the cached end-user spend, so requests that overlapped on the cold counter added it once each and a customer under budget was refused. The write path now seeds it with SET NX under the per-counter lock, from LiteLLM_EndUserTable and never below the cached spend, the way key, team, user, org and project counters seed. Reads of a cold counter are unchanged. Fixes #47062 * fix(proxy): write a cold counter's cached spend with SET NX, drop the row read The cold seed goes back to the cached spend main already used, written with SET NX in place of INCRBYFLOAT, so requests and proxies that overlap on a cold counter write it once. This drops the LiteLLM_EndUserTable read from the first commit: the row could already hold the request's own charge, and the post-call increment would then add it a second time. * fix(proxy): raise a cold counter to the cached spend, never past it The cold seed now uses the store's set_max, the write the stale-counter repair already uses. A charge that creates the counter just before the seed no longer makes the seed skip the cached spend, and two proxies with different cached spends leave the larger one. The new tests read the cached spend through a real UserApiKeyCache. * fix(proxy): seed a cold counter with an increment when Redis refuses the script * test: keep main's import block in the spend counter tests * fix(budgets): raise a cold counter to the cached spend in the rust post-call step The post-call step that main now runs in Rust added the auth cache's spend to a cold counter with INCRBYFLOAT, so requests that overlap on a cold counter with budget reservation off still multiplied it. Raise it with set_max as the Python seed does, and drop this process's copy when a seed fails. * fix(budgets): drop a cold counter everywhere when its seed may have applied A seed whose reply is lost may have written the cached spend to Redis. A failed increment already drops the counter from Redis and memory, and the set_max seed now does the same in the Python and Rust paths. * test(budgets): key the cold seed tests by AuthObject after the main merge * fix(budgets): end the cold seed with the charge's own increment On Redis Cluster a slot mid-migration answers the set_max script through an ASK redirect but refuses the pipelined INCRBYFLOAT that charges the counter. The seed then succeeded, the charge pipeline failed, and every counter in that step was dropped. The seed now ends with INCRBYFLOAT 0, so a counter the charge cannot reach fails in the seed and is dropped on its own, as it was when the seed was that increment. * test(budgets): mark the new charge tests with rstest --------- Co-authored-by: kenneth <kenneth@berri.ai>
273 lines
11 KiB
Python
273 lines
11 KiB
Python
"""A stand-in for ``NativeSpendCounters`` with the native store's semantics: Redis first, this worker's memory
|
|
behind it, every Redis round trip logged in ``commands``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections.abc import Awaitable, Callable, Sequence
|
|
from dataclasses import dataclass, field
|
|
from typing import Final, Literal, TypeVar
|
|
|
|
from litellm.redis.stores.spend_counters import SpendCounterStore, SpendIncrement
|
|
from litellm.rust_bridge._native import NativeRedisClient, NativeRedisStoreError, SpendRead
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
def _done(value: T) -> asyncio.Future[T]:
|
|
future: Final[asyncio.Future[T]] = asyncio.get_running_loop().create_future()
|
|
future.set_result(value)
|
|
return future
|
|
|
|
|
|
def _failed(error: BaseException) -> asyncio.Future[T]:
|
|
future: Final[asyncio.Future[T]] = asyncio.get_running_loop().create_future()
|
|
future.set_exception(error)
|
|
return future
|
|
|
|
|
|
def unavailable(kind: str = "transport") -> NativeRedisStoreError:
|
|
return NativeRedisStoreError(kind, "Redis did not answer")
|
|
|
|
|
|
def _is_number(value: object) -> bool:
|
|
"""What the native codec decodes; anything else reads as a failed Redis read."""
|
|
return value is None or (isinstance(value, (int, float)) and not isinstance(value, bool))
|
|
|
|
|
|
_TWIN_SCOPES: Final = frozenset({"key", "team", "user", "org", "end_user"})
|
|
_WINDOWED_SCOPES: Final = frozenset({"key", "team"})
|
|
|
|
|
|
def _native_store_takes_twin(twin: str) -> bool:
|
|
scope, _, counter_id = twin.partition(":")
|
|
_, separator, window = counter_id.rpartition(":window:")
|
|
return scope in _TWIN_SCOPES and not (scope in _WINDOWED_SCOPES and separator and window)
|
|
|
|
|
|
def _check(counter: str) -> None:
|
|
if not counter.startswith("spend:"):
|
|
raise ValueError(f"{counter!r} is not a spend counter")
|
|
twin: Final = counter.removeprefix("spend:committed:")
|
|
if twin != counter and not _native_store_takes_twin(twin):
|
|
raise ValueError(f"{counter!r} is not a spend counter")
|
|
|
|
|
|
@dataclass
|
|
class DeclaredRead:
|
|
counters: tuple[str, ...]
|
|
owner: FakeSpendCounters
|
|
request: object
|
|
|
|
async def resolve(self) -> Sequence[float | None] | None:
|
|
events: Final = getattr(self.request, "events", None)
|
|
if events is not None and "flush_pre" not in events:
|
|
raise ConnectionError("resolved before its batch was flushed")
|
|
return self.owner.mget(self.counters)
|
|
|
|
|
|
@dataclass
|
|
class FakeSpendCounters:
|
|
"""``redis`` is None for a worker without Redis, and ``redis_default`` answers reads of a key it lacks. ``fail``
|
|
makes every Redis call fail with ``failure``, ``fail_pipelines`` only the increment pipelines and ``failing`` only
|
|
the named writes ("set", "set_max", "delete")."""
|
|
|
|
redis: dict[str, object] | None = field(default_factory=dict)
|
|
memory: dict[str, float] = field(default_factory=dict)
|
|
commands: list[str] = field(default_factory=list)
|
|
fail: bool = False
|
|
fail_pipelines: bool = False
|
|
failing: frozenset[str] = frozenset()
|
|
failure: str = "transport"
|
|
redis_default: float | None = None
|
|
redis_ttl: float = 60
|
|
committed_ttl: float | None = None
|
|
batch_reads: bool = True
|
|
read_hook: Callable[[str], Awaitable[None]] | None = None
|
|
on_delete: Callable[[tuple[str, ...]], None] | None = None
|
|
deletes: list[tuple[str, ...]] = field(default_factory=list)
|
|
post_call: list[tuple[object, tuple[SpendIncrement, ...]]] = field(default_factory=list)
|
|
declared: list[DeclaredRead] = field(default_factory=list)
|
|
|
|
def store(self) -> SpendCounterStore:
|
|
return SpendCounterStore(self)
|
|
|
|
@property
|
|
def has_redis(self) -> bool:
|
|
return self.redis is not None
|
|
|
|
@property
|
|
def redis_ttl_seconds(self) -> float | None:
|
|
return None if self.redis is None else self.redis_ttl
|
|
|
|
def set_committed_ttl(self, ttl_seconds: float, /) -> None:
|
|
self.committed_ttl = ttl_seconds
|
|
|
|
def attach(self, client: NativeRedisClient, /) -> bool:
|
|
if self.redis is not None:
|
|
return False
|
|
self.redis = {}
|
|
self.redis_ttl = client.default_ttl_seconds
|
|
return True
|
|
|
|
def mget(self, counters: Sequence[str]) -> list[float | None] | None:
|
|
if self.redis is None or self.fail or not self.batch_reads:
|
|
return None
|
|
self.commands.append(f"MGET {' '.join(counters)}")
|
|
values: Final = [self.redis.get(counter, self.redis_default) for counter in counters]
|
|
return values if all(_is_number(value) for value in values) else None
|
|
|
|
async def read(self, counter: str) -> SpendRead:
|
|
_check(counter)
|
|
if self.read_hook is not None:
|
|
await self.read_hook(counter)
|
|
if self.redis is not None and not self.fail:
|
|
self.commands.append(f"GET {counter}")
|
|
value: Final = self.redis.get(counter, self.redis_default)
|
|
if _is_number(value):
|
|
return SpendRead(value, from_redis=True)
|
|
return SpendRead(self.memory.get(counter), from_redis=False)
|
|
|
|
def read_many(self, counters: Sequence[str], send: object) -> DeclaredRead | None:
|
|
if self.redis is None:
|
|
return None
|
|
declared: Final = DeclaredRead(tuple(counters), self, send)
|
|
events: Final = getattr(send, "events", None)
|
|
if isinstance(events, list):
|
|
self.declared.append(declared)
|
|
events.append("declare spend_counters")
|
|
return declared
|
|
|
|
def increment(self, counter: str, amount: float) -> asyncio.Future[float]:
|
|
_check(counter)
|
|
if self.redis is None:
|
|
return _done(self.increment_local(counter, amount))
|
|
if self.fail:
|
|
self.memory.pop(counter, None)
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"INCRBYFLOAT {counter} {amount}")
|
|
return _done(self._incr(counter, amount))
|
|
|
|
def increment_many(self, increments: Sequence[SpendIncrement]) -> asyncio.Future[Sequence[float]]:
|
|
if self.redis is None:
|
|
return _done([self.increment_local(counter, amount) for counter, amount in increments])
|
|
if self.fail or self.fail_pipelines:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"PIPELINE {' '.join(counter for counter, _ in increments)}")
|
|
return _done([self._incr(counter, amount) for counter, amount in increments])
|
|
|
|
def increment_many_post_call(self, request: object, increments: Sequence[SpendIncrement]) -> bool:
|
|
if self.redis is None:
|
|
return False
|
|
self.post_call.append((request, tuple(increments)))
|
|
return True
|
|
|
|
def settle_post_call(self) -> None:
|
|
"""What the native task does once the post-call batch goes out."""
|
|
pending: Final = tuple(self.post_call)
|
|
self.post_call.clear()
|
|
for _, increments in pending:
|
|
if self.fail:
|
|
for counter, _ in increments:
|
|
self.memory.pop(counter, None)
|
|
continue
|
|
self.commands.append(f"POST PIPELINE {' '.join(counter for counter, _ in increments)}")
|
|
for counter, amount in increments:
|
|
self._incr(counter, amount)
|
|
|
|
def set_max(self, counter: str, spend: float) -> asyncio.Future[float | None]:
|
|
_check(counter)
|
|
if self.memory.get(counter) is None or self.memory[counter] < spend:
|
|
self.memory[counter] = spend
|
|
if self.redis is None:
|
|
return _done(None)
|
|
if self.fail or "set_max" in self.failing:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"SETMAX {counter} {spend}")
|
|
current: Final = self.redis.get(counter)
|
|
if current is None or current < spend:
|
|
self.redis[counter] = spend
|
|
return _done(float(self.redis[counter]))
|
|
|
|
def seed(self, counter: str, spend: float, *, increment_if_lost: bool) -> asyncio.Future[float]:
|
|
_check(counter)
|
|
if self.redis is None:
|
|
cached: Final = self.memory.get(counter)
|
|
seeded: Final = spend if cached is None or cached <= spend else float(cached)
|
|
self.memory[counter] = seeded
|
|
return _done(seeded)
|
|
if self.fail:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"SETNX {counter} {spend}")
|
|
current: Final = self.redis.setdefault(counter, spend)
|
|
self.memory[counter] = float(current)
|
|
return _done(float(current))
|
|
|
|
def set(self, counter: str, spend: float, ttl_seconds: float | None = None) -> asyncio.Future[None]:
|
|
_check(counter)
|
|
self.memory[counter] = spend
|
|
if self.redis is None:
|
|
return _done(None)
|
|
if self.fail or "set" in self.failing:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"SET {counter} {spend} {ttl_seconds}")
|
|
self.redis[counter] = spend
|
|
return _done(None)
|
|
|
|
def deleted(self) -> frozenset[str]:
|
|
"""Every counter a delete reached, memory and Redis alike."""
|
|
return frozenset(counter for batch in self.deletes for counter in batch)
|
|
|
|
def delete(self, counters: Sequence[str]) -> asyncio.Future[None]:
|
|
for counter in counters:
|
|
_check(counter)
|
|
self.memory.pop(counter, None)
|
|
self.deletes.append(tuple(counters))
|
|
if self.on_delete is not None:
|
|
self.on_delete(tuple(counters))
|
|
if self.redis is None:
|
|
return _done(None)
|
|
if self.fail or "delete" in self.failing:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"DEL {' '.join(counters)}")
|
|
for counter in counters:
|
|
self.redis.pop(counter, None)
|
|
return _done(None)
|
|
|
|
def refresh_ttl(self, counter: str) -> asyncio.Future[bool]:
|
|
_check(counter)
|
|
if self.redis is None:
|
|
return _done(False)
|
|
if self.fail:
|
|
return _failed(unavailable(self.failure))
|
|
self.commands.append(f"EXPIRE {counter}")
|
|
return _done(counter in self.redis)
|
|
|
|
def get_local(self, counter: str) -> float | None:
|
|
_check(counter)
|
|
return self.memory.get(counter)
|
|
|
|
def set_local(self, counter: str, spend: float, ttl_seconds: float | None = None) -> None:
|
|
_check(counter)
|
|
self.memory[counter] = spend
|
|
|
|
def delete_local(self, counter: str) -> None:
|
|
_check(counter)
|
|
self.memory.pop(counter, None)
|
|
|
|
def increment_local(self, counter: str, amount: float) -> float:
|
|
_check(counter)
|
|
self.memory[counter] = self.memory.get(counter, 0) + amount
|
|
return self.memory[counter]
|
|
|
|
def flush_local(self) -> None:
|
|
self.memory.clear()
|
|
|
|
def snapshot(self) -> dict[str, float]:
|
|
return dict(self.memory)
|
|
|
|
def _incr(self, counter: str, amount: float) -> float:
|
|
assert self.redis is not None
|
|
self.redis[counter] = float(self.redis.get(counter, 0.0)) + amount
|
|
self.memory[counter] = self.redis[counter]
|
|
return self.redis[counter]
|