mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-02 01:28:38 +00:00
* fix(proxy): report live key and team spend to budget gauges within the key cache TTL * fix(prometheus): carry live spend for the user, org and customer budget gauges too The remaining budget gauges for users, orgs and customers read the same cached rows as the key and team gauges, so they read high for about a minute after a charge. Auth now carries the live counter for each budgeted entity in one snapshot that only the gauges read, floored at the spend auth loaded. The x-litellm-key-spend header and logging spend fields keep their current values. * fix(prometheus): show committed spend in the remaining budget gauges Reads twin counters that take only charged cost, so a worst-case budget hold never shows as spent and a request that finishes last cannot set a gauge back. The twins exist only while the Prometheus logger is registered, and every path that resets a spend counter drops them. Failed requests now set the org gauge from the carried org row and committed spend, not the cached org row. * fix(prometheus): count a charge the cached customer row already holds once * fix(prometheus): keep committed spend only for budgeted entities and drop it on spend resets Auth now reads committed spend through the admission MGET and names the counters a charge may move, so the master key and unbudgeted entities get no twin. Organization spend edits and the global spend reset drop their twins, and a long request no longer reads as charged. * fix(prometheus): read the committed org spend on failed requests without the auth object * test(prometheus): cover a failed request with no carried org * fix(prometheus): move the committed counters for charges with no auth on the row A billed background response is charged from its creator's stored attribution, after the request's auth is gone. Its charge moved the live counters but not the committed ones, so every gauge read one charge behind. It now moves the committed counters that already exist, and its own gauge adds its cost to them. * fix(prometheus): keep the gauges right for pass-through rows, overlapping charges and slow DB spend writes Pass-through rows carry the auth object, so a cold committed counter gets seeded there too. The gauges read a charge still waiting in the post-call pipeline as not counted, whatever other charges reached the counter. Committed counters outlive two DB spend writes. Cold seeds read the DB once per worker, and the global spend reset reads keys and teams in bounded pages. * fix(prometheus): count a charged failure's own cost in the org gauge A stream cut mid-response still charges for what it delivered, and that charge is usually still queued when the failure logs. The failure path passed a cost of 0, so the org gauge left that charge out until the worker's next request * fix(prometheus): skip twins for window-named ids, drop twins on delete, keep auth out of PostHog * fix(prometheus): keep the auth object off pass-through rows and drop user twins on every user delete Pass-through rows now carry only the committed spend in litellm_params, so loggers that dump the row's metadata never get the auth object. Every user delete path, SCIM and bulk delete included, drops the deleted users' committed spend twins * fix(prometheus): keep committed spend values out of logger dumps of pass-through rows CommittedBudgetSpend fields are repr=False, so Athina's payload, Sentry breadcrumbs and debug logs that str() a pass-through row's litellm_params show no spend values * fix(prometheus): keep the gauge fallback on a slow committed read and refresh committed twin TTLs on cluster The success-path committed read now gets half the per-request budget, so a slow Redis falls back to stored spend before the outer timeout cancels the gauges. Post-call charges refresh a committed twin's TTL on Redis Cluster too, so a twin never expires while its charges are still on their way to the DB. Also applies cargo fmt to the PR's Rust files * fix(proxy): key the global reset's committed-spend page queries so the Prisma span check reads them --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
280 lines
11 KiB
Python
280 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 FakeSettlement:
|
|
settled: bool = False
|
|
|
|
|
|
@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", "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, ...], FakeSettlement]] = 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]) -> FakeSettlement | None:
|
|
if self.redis is None:
|
|
return None
|
|
settlement: Final = FakeSettlement()
|
|
self.post_call.append((request, tuple(increments), settlement))
|
|
return settlement
|
|
|
|
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, settlement in pending:
|
|
settlement.settled = True
|
|
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:
|
|
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]
|