mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-30 01:08:33 +00:00
* fix(proxy): charge budget windows when the cached key or team expired before the request ended The post-call spend update reads a key's or team's budget_limits from user_api_key_cache and returned early on a miss, skipping both the window counter increment and the LiteLLM_BudgetWindowSpend row. The cached object expires after user_api_key_cache_ttl (60s by default), so any request that ran longer than that without another request refreshing the entry was counted in the key's lifetime spend but never in its budget windows. With budget reservation disabled nothing else charges the windows, so keys kept running past their window caps On a miss the update now reads budget_limits straight from the key or team row. It does not re-cache the object, since a write from the spend path could race a /key/delete and put a just-deleted key back into the auth cache * test(proxy): assert the budget window fallback never re-caches the key or team * fix(proxy): read a missing key or team row once per cache TTL in the budget window fallback The master key and UI session tokens are logged under names no key row carries, so every one of their requests missed the auth cache and read the database. A missing row is now remembered for the cache TTL in this process only. A failed read is not remembered, and a row that exists is read fresh on every miss so a key update is never served stale. * fix(proxy): skip the budget window row read for a key or team with no windows The fallback remembered only a missing row, so a key or team that exists but holds no budget_limits was read from the database on every request that outlived the key cache. It now remembers both cases under one cache key built in user_api_key_cache.py, for the same TTL as the auth cache * fix(proxy): keep no-window markers in their own cache and clear them when an update adds windows Markers for keys and teams with no budget windows lived in the shared 200-entry auth cache, so a burst of late costs could evict cached teams and users. They now live in a dedicated in-memory cache on UserApiKeyCache, reached by local and broadcast evictions. /key/update and /team/update now evict the marker on every worker, so a late cost after an update charges the windows the update added. * test(proxy): give the spend counter tests the proxy's real key cache and type the window spend helper * fix(proxy): keep a row read that an update outran from restoring the no-window marker * fix(proxy): clear finished no-window reads and evict a marker-shaped user id from both caches * fix(proxy): apply other spend counters before a window row read and let no-window notes follow the key cache settings --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
713 lines
30 KiB
Python
713 lines
30 KiB
Python
"""
|
|
Dual Cache implementation - Class to update both Redis and an in-memory cache simultaneously.
|
|
|
|
Has 4 primary methods:
|
|
- set_cache
|
|
- get_cache
|
|
- async_set_cache
|
|
- async_get_cache
|
|
"""
|
|
|
|
import asyncio
|
|
import itertools
|
|
import logging
|
|
import time
|
|
from collections.abc import Mapping, Sequence
|
|
from dataclasses import dataclass
|
|
from threading import Lock
|
|
from typing import TYPE_CHECKING, Any, Final
|
|
|
|
import litellm
|
|
from litellm._logging import print_verbose, verbose_logger
|
|
from litellm.constants import DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE
|
|
from litellm.types.caching import RedisPipelineIncrementOperation
|
|
|
|
from .base_cache import BaseCache
|
|
from .in_memory_cache import DEFAULT_MAX_SIZE_IN_MEMORY, InMemoryCache
|
|
from .redis_batch import BatchResult, RedisBatch, active_post_call_redis_batch, active_request_redis_batch
|
|
from .redis_cache import RedisCache, RedisCircuitBreakerOpenError, log_redis_failure
|
|
|
|
if TYPE_CHECKING:
|
|
from opentelemetry.trace import Span as _Span
|
|
|
|
Span = _Span | Any
|
|
else:
|
|
Span = Any
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
|
class LimitedSizeOrderedDict(OrderedDict):
|
|
def __init__(self, *args, max_size=100, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.max_size = max_size
|
|
|
|
def __setitem__(self, key, value):
|
|
# If inserting a new key exceeds max size, remove the oldest item
|
|
if len(self) >= self.max_size:
|
|
self.popitem(last=False)
|
|
super().__setitem__(key, value)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PendingBatchRead:
|
|
"""A batch read that has consulted the in-memory tier and reserved its Redis keys, but not hit Redis yet."""
|
|
|
|
keys: list[str]
|
|
result: list[object | None]
|
|
redis_keys: list[str]
|
|
previous_access_times: dict[str, float | None]
|
|
|
|
|
|
def _log_deferred_increment_failure(future: asyncio.Future[float]) -> None:
|
|
if future.cancelled():
|
|
return
|
|
failure: Final = future.exception()
|
|
if failure is not None:
|
|
log_redis_failure(verbose_logger, logging.WARNING, "post-call Redis increment failed", failure)
|
|
|
|
|
|
class DualCache(BaseCache):
|
|
"""
|
|
DualCache is a cache implementation that updates both Redis and an in-memory cache simultaneously.
|
|
When data is updated or inserted, it is written to both the in-memory cache + Redis.
|
|
This ensures that even if Redis hasn't been updated yet, the in-memory cache reflects the most recent data.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
in_memory_cache: InMemoryCache | None = None,
|
|
redis_cache: RedisCache | None = None,
|
|
default_in_memory_ttl: float | None = None,
|
|
default_redis_ttl: float | None = None,
|
|
default_redis_batch_cache_expiry: float | None = None,
|
|
default_max_redis_batch_cache_size: int = DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE,
|
|
) -> None:
|
|
super().__init__()
|
|
# If in_memory_cache is not provided, use the default InMemoryCache
|
|
self.in_memory_cache = in_memory_cache or InMemoryCache()
|
|
# If redis_cache is not provided, use the default RedisCache
|
|
self.redis_cache = redis_cache
|
|
self.last_redis_batch_access_time = LimitedSizeOrderedDict(max_size=default_max_redis_batch_cache_size)
|
|
self._last_redis_batch_access_time_lock = Lock()
|
|
self.redis_batch_cache_expiry = (
|
|
default_redis_batch_cache_expiry or litellm.default_redis_batch_cache_expiry or 10
|
|
)
|
|
self.default_in_memory_ttl = default_in_memory_ttl or litellm.default_in_memory_ttl
|
|
self.default_redis_ttl = default_redis_ttl or litellm.default_redis_ttl
|
|
|
|
def update_cache_ttl(self, default_in_memory_ttl: float | None, default_redis_ttl: float | None):
|
|
if default_in_memory_ttl is not None:
|
|
self.default_in_memory_ttl = default_in_memory_ttl
|
|
|
|
if default_redis_ttl is not None:
|
|
self.default_redis_ttl = default_redis_ttl
|
|
|
|
def update_in_memory_max_size(self, max_size: int | None) -> None:
|
|
self.in_memory_cache.max_size_in_memory = DEFAULT_MAX_SIZE_IN_MEMORY if max_size is None else max_size
|
|
|
|
def attach_redis_cache(
|
|
self,
|
|
redis_cache: RedisCache | None = None,
|
|
*,
|
|
default_redis_ttl: float | None = None,
|
|
) -> None:
|
|
"""
|
|
Attach a Redis backend if this DualCache does not already have one.
|
|
|
|
No-op when ``redis_cache`` is None or when Redis was already set (constructor
|
|
or a prior attach). Use this for lazy wiring after a shared Redis client exists.
|
|
Does not backfill in-memory-only keys to Redis.
|
|
"""
|
|
if redis_cache is None or self.redis_cache is not None:
|
|
return
|
|
self.redis_cache = redis_cache
|
|
if default_redis_ttl is not None:
|
|
self.default_redis_ttl = default_redis_ttl
|
|
|
|
def _backfill_kwargs(self, kwargs: "dict[str, object]") -> "dict[str, object]":
|
|
"""
|
|
Kwargs for writing a Redis read result into the in-memory tier.
|
|
|
|
Applies ``default_in_memory_ttl`` exactly like the write paths do;
|
|
without it, backfilled entries fall to ``InMemoryCache``'s own default
|
|
TTL and can outlive the TTL this cache was configured with.
|
|
"""
|
|
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
|
|
return {**kwargs, "ttl": self.default_in_memory_ttl}
|
|
return kwargs
|
|
|
|
def set_cache(self, key, value, local_only: bool = False, **kwargs):
|
|
# Update both Redis and in-memory cache
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
|
|
kwargs["ttl"] = self.default_in_memory_ttl
|
|
|
|
self.in_memory_cache.set_cache(key, value, **kwargs)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
self.redis_cache.set_cache(key, value, **kwargs)
|
|
except Exception as e:
|
|
print_verbose(e)
|
|
|
|
def increment_cache(self, key, value: int, local_only: bool = False, **kwargs) -> int:
|
|
"""
|
|
Key - the key in cache
|
|
|
|
Value - int - the value you want to increment by
|
|
|
|
Returns - int - the incremented value
|
|
"""
|
|
try:
|
|
result: int = value
|
|
if self.in_memory_cache is not None:
|
|
result = self.in_memory_cache.increment_cache(key, value, **kwargs)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
result = self.redis_cache.increment_cache(key, value, **kwargs)
|
|
|
|
return result
|
|
except Exception as e:
|
|
verbose_logger.error("LiteLLM Cache: Excepton async add_cache: %s", e)
|
|
raise e
|
|
|
|
def get_cache(
|
|
self,
|
|
key,
|
|
parent_otel_span: Span | None = None,
|
|
local_only: bool = False,
|
|
**kwargs,
|
|
):
|
|
# Try to fetch from in-memory cache first
|
|
try:
|
|
result = None
|
|
if self.in_memory_cache is not None:
|
|
in_memory_result: Final = self.in_memory_cache.get_cache(key, **kwargs)
|
|
|
|
if in_memory_result is not None:
|
|
result = in_memory_result
|
|
|
|
if result is None and self.redis_cache is not None and local_only is False:
|
|
# If not found in in-memory cache, try fetching from Redis
|
|
redis_result: Final = self.redis_cache.get_cache(key, parent_otel_span=parent_otel_span)
|
|
|
|
if redis_result is not None:
|
|
# Update in-memory cache with the value from Redis
|
|
self.in_memory_cache.set_cache(key, redis_result, **self._backfill_kwargs(kwargs))
|
|
|
|
result = redis_result
|
|
|
|
print_verbose(f"get cache: cache result: {result}")
|
|
return result
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger, logging.ERROR, "LiteLLM Cache: exception in get_cache", e, with_traceback=True
|
|
)
|
|
|
|
def batch_get_cache(
|
|
self,
|
|
keys: list,
|
|
parent_otel_span: Span | None = None,
|
|
local_only: bool = False,
|
|
**kwargs,
|
|
):
|
|
try:
|
|
in_memory_result: Final = (
|
|
self.in_memory_cache.batch_get_cache(keys, **kwargs) if self.in_memory_cache is not None else None
|
|
)
|
|
result: Final = in_memory_result if in_memory_result is not None else tuple(None for _ in keys)
|
|
|
|
if None not in result or self.redis_cache is None or local_only:
|
|
return result
|
|
|
|
sublist_keys, previous_access_times = self._reserve_redis_batch_keys(time.time(), keys, result)
|
|
if len(sublist_keys) == 0:
|
|
return result
|
|
|
|
try:
|
|
redis_result: Final = self.redis_cache.batch_get_cache(
|
|
key_list=sublist_keys, parent_otel_span=parent_otel_span
|
|
)
|
|
except Exception as e:
|
|
# Do not throttle subsequent callers if the Redis read fails.
|
|
self._rollback_redis_batch_key_reservations(previous_access_times)
|
|
if isinstance(e, RedisCircuitBreakerOpenError):
|
|
verbose_logger.debug("LiteLLM Cache: batch_get_cache served from memory only: %s", e)
|
|
return result
|
|
raise
|
|
|
|
if self.in_memory_cache is not None:
|
|
for key, value in redis_result.items():
|
|
if value is not None:
|
|
self.in_memory_cache.set_cache(key, value, **self._backfill_kwargs(kwargs))
|
|
|
|
return list(redis_result.get(key) if value is None else value for key, value in zip(keys, result))
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger, logging.ERROR, "LiteLLM Cache: exception in batch_get_cache", e, with_traceback=True
|
|
)
|
|
|
|
async def async_get_cache(
|
|
self,
|
|
key,
|
|
parent_otel_span: Span | None = None,
|
|
local_only: bool = False,
|
|
**kwargs,
|
|
):
|
|
# Try to fetch from in-memory cache first
|
|
try:
|
|
print_verbose(f"async get cache: cache key: {key}; local_only: {local_only}")
|
|
result = None
|
|
if self.in_memory_cache is not None:
|
|
in_memory_result: Final = await self.in_memory_cache.async_get_cache(key, **kwargs)
|
|
|
|
print_verbose(f"in_memory_result: {in_memory_result}")
|
|
if in_memory_result is not None:
|
|
result = in_memory_result
|
|
|
|
if result is None and self.redis_cache is not None and local_only is False:
|
|
request_batch: Final = active_request_redis_batch(self.redis_cache)
|
|
if request_batch is not None and request_batch.read_as_missing(key):
|
|
return None
|
|
# If not found in in-memory cache, try fetching from Redis
|
|
redis_result: Final = await self.redis_cache.async_get_cache(key, parent_otel_span=parent_otel_span)
|
|
|
|
if redis_result is not None:
|
|
# Update in-memory cache with the value from Redis
|
|
await self.in_memory_cache.async_set_cache(key, redis_result, **self._backfill_kwargs(kwargs))
|
|
|
|
result = redis_result
|
|
|
|
print_verbose(f"get cache: cache result: {result}")
|
|
return result
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger, logging.ERROR, "LiteLLM Cache: exception in async_get_cache", e, with_traceback=True
|
|
)
|
|
|
|
def _reserve_redis_batch_keys(
|
|
self,
|
|
current_time: float,
|
|
keys: list[str],
|
|
result: Sequence[object],
|
|
) -> tuple[list[str], dict[str, float | None]]:
|
|
"""
|
|
Atomically choose keys to fetch from Redis and reserve their access time.
|
|
This prevents check-then-act races under concurrent async callers.
|
|
"""
|
|
sublist_keys: Final[list[str]] = []
|
|
previous_access_times: Final[dict[str, float | None]] = {}
|
|
|
|
with self._last_redis_batch_access_time_lock:
|
|
for key, value in zip(keys, result):
|
|
if value is not None:
|
|
continue
|
|
|
|
if (
|
|
key not in self.last_redis_batch_access_time
|
|
or current_time - self.last_redis_batch_access_time[key] >= self.redis_batch_cache_expiry
|
|
):
|
|
sublist_keys.append(key)
|
|
previous_access_times[key] = self.last_redis_batch_access_time.get(key)
|
|
self.last_redis_batch_access_time[key] = current_time
|
|
|
|
return sublist_keys, previous_access_times
|
|
|
|
def reserve_redis_batch_reads(self, keys: Sequence[str]) -> tuple[list[str], dict[str, float | None]]:
|
|
"""Reserve the memory-missed keys whose throttled Redis reads are due, as a batch read would."""
|
|
if self.redis_cache is None:
|
|
return [], {}
|
|
key_list: Final = list(keys)
|
|
memory: Final = self.in_memory_cache
|
|
in_memory_result: Final = (
|
|
None
|
|
if memory is None # pyright: ignore[reportUnnecessaryComparison] # handle an absent in-memory tier
|
|
else memory.batch_get_cache(key_list)
|
|
)
|
|
result: Final = in_memory_result if in_memory_result is not None else tuple(None for _ in key_list)
|
|
return self._reserve_redis_batch_keys(time.time(), key_list, result)
|
|
|
|
def _rollback_redis_batch_key_reservations(self, previous_access_times: dict[str, float | None]) -> None:
|
|
with self._last_redis_batch_access_time_lock:
|
|
for key, previous_time in previous_access_times.items():
|
|
if previous_time is None:
|
|
self.last_redis_batch_access_time.pop(key, None)
|
|
else:
|
|
self.last_redis_batch_access_time[key] = previous_time
|
|
|
|
async def _prepare_batch_get(
|
|
self, keys: list[str], local_only: bool, throttle_redis: bool = True, **kwargs: object
|
|
) -> PendingBatchRead:
|
|
result: list[object | None] = [None] * len(keys)
|
|
if self.in_memory_cache is not None:
|
|
in_memory_result: Final = await self.in_memory_cache.async_batch_get_cache(keys, **kwargs)
|
|
|
|
if in_memory_result is not None:
|
|
result = in_memory_result
|
|
|
|
redis_keys: list[str] = []
|
|
previous_access_times: dict[str, float | None] = {}
|
|
if None in result and self.redis_cache is not None and local_only is False:
|
|
if throttle_redis:
|
|
redis_keys, previous_access_times = self._reserve_redis_batch_keys(time.time(), keys, result)
|
|
else:
|
|
redis_keys = [key for key, value in zip(keys, result) if value is None]
|
|
return PendingBatchRead(
|
|
keys=keys, result=result, redis_keys=redis_keys, previous_access_times=previous_access_times
|
|
)
|
|
|
|
async def _apply_batch_get(
|
|
self, pending: PendingBatchRead, redis_result: Mapping[str, object] | None, **kwargs: object
|
|
) -> list[object | None]:
|
|
if redis_result is None or all(v is None for v in redis_result.values()):
|
|
return pending.result
|
|
|
|
merged: Final[list[object | None]] = [
|
|
redis_result.get(key, value) for key, value in zip(pending.keys, pending.result)
|
|
]
|
|
if self.in_memory_cache is not None:
|
|
for key, value in redis_result.items():
|
|
if value is not None:
|
|
await self.in_memory_cache.async_set_cache(key, value, **self._backfill_kwargs(kwargs))
|
|
return merged
|
|
|
|
async def async_batch_get_cache(
|
|
self,
|
|
keys: list,
|
|
parent_otel_span: Span | None = None,
|
|
local_only: bool = False,
|
|
throttle_redis: bool = True,
|
|
**kwargs,
|
|
):
|
|
"""With ``throttle_redis`` False every key memory cannot serve is read from Redis, exactly as a per-key
|
|
``async_get_cache`` would read it, instead of skipping keys that missed within ``redis_batch_cache_expiry``."""
|
|
try:
|
|
pending: Final = await self._prepare_batch_get(keys, local_only, throttle_redis, **kwargs)
|
|
# Only hit Redis for keys memory could not serve and enough time has passed since last access.
|
|
if not pending.redis_keys or self.redis_cache is None:
|
|
return pending.result
|
|
try:
|
|
redis_result: Final = await self.redis_cache.async_batch_get_cache(
|
|
pending.redis_keys, parent_otel_span=parent_otel_span
|
|
)
|
|
except Exception as e:
|
|
# Do not throttle subsequent callers if the Redis read fails.
|
|
self._rollback_redis_batch_key_reservations(pending.previous_access_times)
|
|
if isinstance(e, RedisCircuitBreakerOpenError):
|
|
verbose_logger.debug("LiteLLM Cache: async_batch_get_cache served from memory only: %s", e)
|
|
return pending.result
|
|
raise
|
|
return await self._apply_batch_get(pending, redis_result, **kwargs)
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger,
|
|
logging.ERROR,
|
|
"LiteLLM Cache: exception in async_batch_get_cache",
|
|
e,
|
|
with_traceback=True,
|
|
)
|
|
|
|
@staticmethod
|
|
async def async_batch_get_cache_shared(
|
|
reads: Sequence[tuple["DualCache", list[str]]],
|
|
parent_otel_span: Span | None = None,
|
|
) -> list[list[object | None] | None]:
|
|
"""
|
|
`async_batch_get_cache` for several caches in one Redis round trip.
|
|
|
|
Each cache still serves what it can from its own in-memory tier, applies its own Redis read
|
|
throttle and backfills its own memory; only the Redis MGET is shared. A failed MGET is reported
|
|
to every cache that took part in it exactly as its own failed `async_batch_get_cache` would be:
|
|
None when the read raised, the in-memory result when the circuit breaker is open. A cache whose
|
|
Redis client is not the one the first cache uses falls back to its own read.
|
|
"""
|
|
results: Final[list[list[object | None] | None]] = [None] * len(reads)
|
|
shared_redis: Final = reads[0][0].redis_cache if reads else None
|
|
pendings: Final[list[tuple[int, DualCache, PendingBatchRead]]] = []
|
|
for index, (cache, keys) in enumerate(reads):
|
|
if shared_redis is None or cache.redis_cache is not shared_redis:
|
|
results[index] = await cache.async_batch_get_cache(keys=keys, parent_otel_span=parent_otel_span)
|
|
continue
|
|
try:
|
|
pending = await cache._prepare_batch_get(keys, local_only=False)
|
|
except Exception as e:
|
|
DualCache._log_shared_batch_get_failure(e)
|
|
continue
|
|
pendings.append((index, cache, pending))
|
|
results[index] = pending.result
|
|
|
|
redis_keys: Final = list(
|
|
dict.fromkeys(itertools.chain.from_iterable(pending.redis_keys for _, _, pending in pendings))
|
|
)
|
|
if shared_redis is None or not redis_keys:
|
|
return results
|
|
try:
|
|
redis_result: Final = await shared_redis.async_batch_get_cache(
|
|
redis_keys, parent_otel_span=parent_otel_span
|
|
)
|
|
except Exception as e:
|
|
for index, cache, pending in pendings:
|
|
cache._rollback_redis_batch_key_reservations(pending.previous_access_times)
|
|
if pending.redis_keys and not isinstance(e, RedisCircuitBreakerOpenError):
|
|
results[index] = None
|
|
if isinstance(e, RedisCircuitBreakerOpenError):
|
|
verbose_logger.debug("LiteLLM Cache: async_batch_get_cache_shared served from memory only: %s", e)
|
|
else:
|
|
DualCache._log_shared_batch_get_failure(e)
|
|
return results
|
|
|
|
for index, cache, pending in pendings:
|
|
own_result = {key: redis_result[key] for key in pending.redis_keys if key in redis_result}
|
|
try:
|
|
results[index] = await cache._apply_batch_get(pending, own_result)
|
|
except Exception as e:
|
|
results[index] = None
|
|
DualCache._log_shared_batch_get_failure(e)
|
|
return results
|
|
|
|
@staticmethod
|
|
def _log_shared_batch_get_failure(e: Exception) -> None:
|
|
log_redis_failure(
|
|
verbose_logger,
|
|
logging.ERROR,
|
|
"LiteLLM Cache: exception in async_batch_get_cache_shared",
|
|
e,
|
|
with_traceback=True,
|
|
)
|
|
|
|
async def async_set_cache(self, key, value, local_only: bool = False, **kwargs):
|
|
print_verbose(f"async set cache: cache key: {key}; local_only: {local_only}; value: {value}")
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
|
|
kwargs["ttl"] = self.default_in_memory_ttl
|
|
await self.in_memory_cache.async_set_cache(key, value, **kwargs)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
await self.redis_cache.async_set_cache(key, value, **kwargs)
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger, logging.ERROR, "LiteLLM Cache: exception in async add_cache", e, with_traceback=True
|
|
)
|
|
|
|
async def async_set_cache_pre_call(self, key: str, value: object, ttl: float | None) -> BatchResult[None] | None:
|
|
"""Memory now, the Redis SET on the request's pipeline, sent with the next read any caller awaits; None
|
|
when no pipeline is open, so the caller takes its direct path."""
|
|
batch: Final = None if self.redis_cache is None else active_request_redis_batch(self.redis_cache)
|
|
return None if batch is None else await self._set_on_batch(batch, key, value, ttl)
|
|
|
|
async def async_delete_cache_pre_call(self, key: str) -> BatchResult[None] | None:
|
|
"""Memory now, the Redis DEL on the request's pipeline; None when no pipeline is open, so the caller
|
|
takes its direct path."""
|
|
batch: Final = None if self.redis_cache is None else active_request_redis_batch(self.redis_cache)
|
|
if batch is None:
|
|
return None
|
|
if self.in_memory_cache is not None:
|
|
self.in_memory_cache.delete_cache(key)
|
|
return batch.delete(key)
|
|
|
|
async def _set_on_batch(self, batch: RedisBatch, key: str, value: object, ttl: float | None) -> BatchResult[None]:
|
|
effective_ttl: Final = self.default_in_memory_ttl if ttl is None else ttl
|
|
if self.in_memory_cache is not None:
|
|
await self.in_memory_cache.async_set_cache(key, value, ttl=effective_ttl)
|
|
return batch.set(key, value, effective_ttl)
|
|
|
|
# async_batch_set_cache
|
|
async def async_set_cache_pipeline(
|
|
self, cache_list: Sequence[tuple[str, object]], local_only: bool = False, **kwargs
|
|
):
|
|
"""
|
|
Batch write values to the cache
|
|
"""
|
|
print_verbose(f"async batch set cache: cache keys: {cache_list}; local_only: {local_only}")
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
|
|
kwargs["ttl"] = self.default_in_memory_ttl
|
|
await self.in_memory_cache.async_set_cache_pipeline(cache_list=cache_list, **kwargs)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
await self.redis_cache.async_set_cache_pipeline(
|
|
cache_list=cache_list, ttl=kwargs.pop("ttl", None), **kwargs
|
|
)
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger, logging.ERROR, "LiteLLM Cache: exception in async add_cache", e, with_traceback=True
|
|
)
|
|
|
|
async def async_increment_cache(
|
|
self,
|
|
key,
|
|
value: float,
|
|
parent_otel_span: Span | None = None,
|
|
local_only: bool = False,
|
|
refresh_ttl: bool = False,
|
|
**kwargs,
|
|
) -> float | None:
|
|
"""
|
|
Key - the key in cache
|
|
|
|
Value - float - the value you want to increment by
|
|
|
|
Refresh_ttl - bool - if True, resets the Redis TTL on every write.
|
|
Default False preserves window-style semantics.
|
|
|
|
Returns - the incremented value, or None if no cache backend is
|
|
available (in_memory_cache is None and Redis failed/is absent).
|
|
"""
|
|
result: float | None = None
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
result = await self.in_memory_cache.async_increment(key, value, **kwargs)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
result = await self.redis_cache.async_increment(
|
|
key,
|
|
value,
|
|
parent_otel_span=parent_otel_span,
|
|
ttl=kwargs.get("ttl", None),
|
|
refresh_ttl=refresh_ttl,
|
|
)
|
|
|
|
return result
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger,
|
|
logging.WARNING,
|
|
"Redis async_increment_cache failed, falling back to in-memory result",
|
|
e,
|
|
)
|
|
return result
|
|
|
|
async def async_increment_cache_post_call(
|
|
self,
|
|
key: str,
|
|
value: float,
|
|
ttl: int | None,
|
|
parent_otel_span: Span | None = None,
|
|
) -> None:
|
|
"""Memory is incremented now; the Redis increment rides the request's post-call pipeline when one is
|
|
open, and runs on its own as ``async_increment_cache`` otherwise."""
|
|
await self.async_increment_cache_pipeline_post_call(
|
|
(RedisPipelineIncrementOperation(key=key, increment_value=value, ttl=ttl),), parent_otel_span
|
|
)
|
|
|
|
async def async_increment_cache_pipeline_post_call(
|
|
self,
|
|
increment_list: Sequence["RedisPipelineIncrementOperation"],
|
|
parent_otel_span: Span | None = None,
|
|
) -> None:
|
|
batch: Final = None if self.redis_cache is None else active_post_call_redis_batch(self.redis_cache)
|
|
operations: Final = list(increment_list)
|
|
if batch is None:
|
|
await self.async_increment_cache_pipeline(operations, parent_otel_span=parent_otel_span)
|
|
return
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
await self.in_memory_cache.async_increment_pipeline(
|
|
increment_list=operations, parent_otel_span=parent_otel_span
|
|
)
|
|
except Exception as e: # noqa: BLE001 # same tolerance as async_increment_cache_pipeline
|
|
log_redis_failure(verbose_logger, logging.WARNING, "in-memory increment failed", e)
|
|
for operation in increment_list:
|
|
batch.increment(operation["key"], operation["increment_value"], operation["ttl"]).on_settled(
|
|
_log_deferred_increment_failure
|
|
)
|
|
|
|
async def async_increment_cache_pipeline(
|
|
self,
|
|
increment_list: list["RedisPipelineIncrementOperation"],
|
|
local_only: bool = False,
|
|
parent_otel_span: Span | None = None,
|
|
**kwargs,
|
|
) -> list[float] | None:
|
|
result: list[float] | None = None
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
result = await self.in_memory_cache.async_increment_pipeline(
|
|
increment_list=increment_list,
|
|
parent_otel_span=parent_otel_span,
|
|
)
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
result = await self.redis_cache.async_increment_pipeline(
|
|
increment_list=increment_list,
|
|
parent_otel_span=parent_otel_span,
|
|
)
|
|
|
|
return result
|
|
except Exception as e:
|
|
log_redis_failure(
|
|
verbose_logger,
|
|
logging.WARNING,
|
|
"Redis async_increment_cache_pipeline failed, falling back to in-memory result",
|
|
e,
|
|
)
|
|
return result
|
|
|
|
async def async_set_cache_sadd(self, key, value: list, local_only: bool = False, **kwargs) -> None:
|
|
"""
|
|
Add value to a set
|
|
|
|
Key - the key in cache
|
|
|
|
Value - str - the value you want to add to the set
|
|
|
|
Returns - None
|
|
"""
|
|
try:
|
|
if self.in_memory_cache is not None:
|
|
_ = await self.in_memory_cache.async_set_cache_sadd(key, value, ttl=kwargs.get("ttl", None))
|
|
|
|
if self.redis_cache is not None and local_only is False:
|
|
_ = await self.redis_cache.async_set_cache_sadd(key, value, ttl=kwargs.get("ttl", None))
|
|
|
|
return
|
|
except Exception as e:
|
|
raise e # don't log, if exception is raised
|
|
|
|
def flush_cache(self):
|
|
if self.in_memory_cache is not None:
|
|
self.in_memory_cache.flush_cache()
|
|
if self.redis_cache is not None:
|
|
self.redis_cache.flush_cache()
|
|
|
|
def delete_cache(self, key: str) -> None:
|
|
"""
|
|
Delete a key from the cache
|
|
"""
|
|
if self.in_memory_cache is not None:
|
|
self.in_memory_cache.delete_cache(key)
|
|
if self.redis_cache is not None:
|
|
self.redis_cache.delete_cache(key)
|
|
|
|
async def async_delete_cache(self, key: str):
|
|
"""
|
|
Delete a key from the cache
|
|
"""
|
|
if self.in_memory_cache is not None:
|
|
self.in_memory_cache.delete_cache(key)
|
|
if self.redis_cache is not None:
|
|
await self.redis_cache.async_delete_cache(key)
|
|
|
|
async def async_delete_cache_keys(self, keys: Sequence[str]) -> None:
|
|
"""Batch twin of ``async_delete_cache``, chunked because Redis takes the
|
|
whole list as one DELETE command."""
|
|
if not keys:
|
|
return
|
|
for key in keys:
|
|
self.in_memory_cache.delete_cache(key)
|
|
if self.redis_cache is None:
|
|
return
|
|
for start in range(0, len(keys), DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE):
|
|
await self.redis_cache.delete_cache_keys(keys[start : start + DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE])
|
|
|
|
async def async_get_ttl(self, key: str) -> int | None:
|
|
"""
|
|
Get the remaining TTL of a key in in-memory cache or redis
|
|
"""
|
|
ttl = await self.in_memory_cache.async_get_ttl(key)
|
|
if ttl is None and self.redis_cache is not None:
|
|
ttl = await self.redis_cache.async_get_ttl(key)
|
|
return ttl
|