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]

Merge remote-tracking branch 'origin/main' into pr-40817

yassin53c8a82a31fb
diff --cc litellm/caching/redis_cache.py
index e5e27d1e02b,d0cefcb6086..3c3539eb8a9
--- a/litellm/caching/redis_cache.py
+++ b/litellm/caching/redis_cache.py
@@@ -15,9 -15,8 +15,9 @@@ import hashli
import inspect
import json
import logging
+import threading
import time
- from collections.abc import Awaitable, Callable, Sequence
+ from collections.abc import Awaitable, Callable, Iterator, Sequence
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import timedelta
@@@ -326,12 -324,30 +326,30 @@@ def _redis_timeout_error_types() -> tup
try:
from redis.exceptions import TimeoutError as RedisTimeoutError
except ImportError:
- return (TimeoutError,)
- return (RedisTimeoutError, TimeoutError)
+ return (TimeoutError, asyncio.TimeoutError)
+ return (RedisTimeoutError, TimeoutError, asyncio.TimeoutError)
+
+
+ _MAX_EXCEPTION_CAUSE_DEPTH: Final = 20
+
+
+ def _explicit_causes(exc: BaseException) -> Iterator[BaseException]:
+ current = exc # rebind-ok: advances one link per iteration of the bounded walk
+ for _ in range(_MAX_EXCEPTION_CAUSE_DEPTH):
+ yield current
+ if current.__cause__ is None:
+ return
+ current = current.__cause__
-def _is_redis_timeout_failure(exc: BaseException) -> bool:
+def is_redis_timeout_failure(exc: BaseException) -> bool:
- return isinstance(exc, _redis_timeout_error_types())
+ """True when ``exc`` or any exception it was explicitly raised ``from`` is a timeout.
+
+ redis-py's blocking pool reports a pool wait timeout as ``ConnectionError`` chained from
+ ``asyncio.TimeoutError``, which is a busy pool rather than an unreachable Redis.
+ """
+ timeout_types: Final = _redis_timeout_error_types()
+ return any(isinstance(link, timeout_types) for link in _explicit_causes(exc))
class _BreakerMetrics:
diff --cc litellm/proxy/proxy_server.py
index 318ea96dbcb,d9f8e04ebda..3cc2ea0d548
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@@ -3390,7 -3447,16 +3447,18 @@@ async def _invalidate_spend_counter(cou
)
- async def _apply_spend_counter_increments(pending: Sequence[_PendingSpendIncrement]) -> None:
+ async def _apply_spend_counter_increments(pending: Sequence[PendingSpendIncrement]) -> None:
+ try:
+ await increment_spend_counters_pipeline(pending=pending)
- except RedisCircuitBreakerOpenError:
- return
++ except Exception as e:
++ if isinstance(e, RedisCircuitBreakerOpenError) or is_redis_timeout_failure(e):
++ return
++ raise
+
+
+ async def increment_spend_counters_pipeline(pending: Sequence[PendingSpendIncrement]) -> None:
+ """One INCRBYFLOAT+EXPIRE pipeline for every pending counter; on failure every counter is invalidated
+ before the error propagates, so no caller can read a half-applied batch."""
if not pending:
return
redis_cache: Final = spend_counter_cache.redis_cache
diff --cc tests/test_litellm/caching/test_redis_cache.py
index 5ea21dae539,c1e3240adb7..9fdddd3c085
--- a/tests/test_litellm/caching/test_redis_cache.py
+++ b/tests/test_litellm/caching/test_redis_cache.py
@@@ -1204,108 -1205,189 +1205,296 @@@ async def test_a_probe_overtaken_by_a_l
assert breaker._state == breaker.CLOSED
+def test_timeouts_during_a_blip_log_once_per_interval_not_once_per_call(sync_batch_redis_cache, caplog, monkeypatch):
+ """A timeout streak logs its first failure plus one summary per interval; other failures log per call."""
+ import logging
+
+ from redis.exceptions import TimeoutError as RedisTimeoutError
+
+ from litellm.caching import redis_cache as redis_cache_module
+ from litellm.caching.redis_cache import _RedisTimeoutLogThrottle
+
+ clock = MagicMock(return_value=1_000.0)
+ monkeypatch.setattr(
+ redis_cache_module, "_redis_timeout_log_throttle", _RedisTimeoutLogThrottle(interval=5.0, clock=clock)
+ )
+ sync_batch_redis_cache.redis_client.get.side_effect = RedisTimeoutError("Timeout reading from 127.0.0.1:6379")
+ sync_batch_redis_cache.redis_client.mget.side_effect = RedisTimeoutError("Timeout reading from 127.0.0.1:6379")
+
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
+ for _ in range(200):
+ assert sync_batch_redis_cache.get_cache("lit7520") is None
+ assert sync_batch_redis_cache.batch_get_cache(key_list=["lit7520"]) == {}
+
+ timeout_records = [r for r in caplog.records if "Timeout reading from" in r.getMessage()]
+ assert len(timeout_records) == 201, "every timeout must stay visible at DEBUG"
+ assert [r.getMessage() for r in timeout_records if r.levelno >= logging.WARNING] == [
+ "litellm.caching.caching: get() - Got exception from REDIS: Timeout reading from 127.0.0.1:6379"
+ ]
+ assert timeout_records[0].levelno == logging.ERROR
+ assert timeout_records[0].filename == "redis_cache.py"
+ assert timeout_records[0].lineno != timeout_records[-1].lineno, "the record must point at the cache operation"
+
+ caplog.clear()
+ clock.return_value += 5.0
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
+ assert sync_batch_redis_cache.batch_get_cache(key_list=["lit7520"]) == {}
+ assert [(r.levelno, r.getMessage()) for r in caplog.records] == [
+ (
+ logging.ERROR,
+ "Error occurred in batch get cache: Timeout reading from 127.0.0.1:6379"
+ " (200 more Redis timeouts since the previous Redis timeout line were logged at DEBUG)",
+ )
+ ]
+
+ caplog.clear()
+ sync_batch_redis_cache.redis_client.get.side_effect = OSError("redis unavailable")
+ with caplog.at_level(logging.DEBUG, logger="LiteLLM"):
+ for _ in range(3):
+ assert sync_batch_redis_cache.get_cache("lit7520") is None
+ assert [r.levelno for r in caplog.records if "redis unavailable" in r.getMessage()] == [logging.ERROR] * 3
+
+
+ "call_method",
+ [
+ pytest.param(lambda c: c.async_set_cache_pipeline([("lit7520", "v")]), id="async_set_cache_pipeline"),
+ pytest.param(lambda c: c.async_set_cache_sadd("lit7520", ["v"], ttl=None), id="async_set_cache_sadd"),
+ pytest.param(lambda c: c.async_increment("lit7520", 1.0), id="async_increment"),
+ pytest.param(
+ lambda c: c.async_increment_pipeline([{"key": "lit7520", "increment_value": 1.0, "ttl": 60}]),
+ id="async_increment_pipeline",
+ ),
+ pytest.param(lambda c: c.async_rpush("lit7520", ["v"]), id="async_rpush"),
+ pytest.param(
+ lambda c: c.async_rpush_pipeline([{"key": "lit7520", "values": ["v"]}]), id="async_rpush_pipeline"
+ ),
+ pytest.param(lambda c: c.async_lpop("lit7520"), id="async_lpop"),
+ pytest.param(lambda c: c.async_lpop_pipeline([{"key": "lit7520", "count": 1}]), id="async_lpop_pipeline"),
+ ],
+)
+async def test_write_path_timeouts_inside_the_interval_stay_at_debug(call_method, caplog, monkeypatch, redis_no_ping):
+ """A write or list operation timing out mid-streak is counted by the throttle instead of logging its own ERROR."""
+ import contextlib
+ import logging
+
+ from redis.exceptions import TimeoutError as RedisTimeoutError
+
+ from litellm.caching import redis_cache as redis_cache_module
+ from litellm.caching.redis_cache import _RedisTimeoutLogThrottle
+
+ clock = MagicMock(return_value=1_000.0)
+ throttle = _RedisTimeoutLogThrottle(interval=5.0, clock=clock)
+ assert throttle.admit() == 0
+ monkeypatch.setattr(redis_cache_module, "_redis_timeout_log_throttle", throttle)
+
+ timeout = RedisTimeoutError("Timeout reading from 127.0.0.1:6379")
+ client = MagicMock()
+ client.pipeline.return_value.__aenter__.side_effect = timeout
+ client.sadd = AsyncMock(side_effect=timeout)
+ client.incrbyfloat = AsyncMock(side_effect=timeout)
+ client.rpush = AsyncMock(side_effect=timeout)
+ client.lpop = AsyncMock(side_effect=timeout)
+ monkeypatch.setenv("REDIS_HOST", "https://my-test-host")
+ cache = RedisCache()
+
+ with (
+ patch.object(cache, "init_async_client", return_value=client),
+ caplog.at_level(logging.DEBUG, logger="LiteLLM"),
+ ):
+ with contextlib.suppress(RedisTimeoutError):
+ await call_method(cache)
+
+ timeout_records = [r for r in caplog.records if "Timeout reading from" in r.getMessage()]
+ assert [(r.levelno, r.filename) for r in timeout_records] == [(logging.DEBUG, "redis_cache.py")]
+ clock.return_value += 5.0
+ assert throttle.admit() == 1
++
++
+ @pytest.mark.asyncio
+ async def test_pool_wait_timeout_is_a_timeout_failure_not_hard_connectivity():
+ """A saturated blocking pool must not open the breaker before the timeout minimum duration.
+
+ redis-py's async BlockingConnectionPool gives up waiting for a free connection by raising
+ ConnectionError("No connection available.") chained from asyncio.TimeoutError. Redis itself
+ is healthy in that case, so the failure has to be classed as a timeout and stay behind the
+ duration gate instead of being counted as a hard connectivity failure.
+ """
+ from fakeredis import FakeServer
+ from fakeredis.aioredis import FakeConnection
+ from redis.asyncio import BlockingConnectionPool, Redis
+ from redis.exceptions import ConnectionError as RedisConnectionError
+
+ from litellm.caching.redis_cache import RedisCircuitBreaker, _run_under_circuit_breaker
+
+ pool = BlockingConnectionPool(connection_class=FakeConnection, server=FakeServer(), max_connections=1, timeout=0.01)
+ client = Redis(connection_pool=pool)
+ breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60, timeout_min_duration=5.0)
+
+ busy_connection = await pool.get_connection()
+ try:
+ for _ in range(breaker.failure_threshold * 2):
+ with pytest.raises(RedisConnectionError, match="No connection available"):
+ await _run_under_circuit_breaker(breaker, "op", lambda: client.get("k"))
+ finally:
+ await pool.release(busy_connection)
+
+ assert breaker.is_open() is False, "a busy pool is a timeout gated on duration, not a dead Redis"
+ assert await _run_under_circuit_breaker(breaker, "op", lambda: client.get("k")) is None
+ await client.aclose()
+
+
+ def test_timeout_classification_follows_the_explicit_cause_chain_only():
+ from redis.exceptions import ConnectionError as RedisConnectionError
+
- from litellm.caching.redis_cache import _is_redis_timeout_failure
++ from litellm.caching.redis_cache import is_redis_timeout_failure
+
+ def raise_chained_from_timeout() -> None:
+ try:
+ raise asyncio.TimeoutError()
+ except asyncio.TimeoutError as err:
+ raise RedisConnectionError("No connection available.") from err
+
+ def raise_while_handling_timeout() -> None:
+ try:
+ raise asyncio.TimeoutError()
+ except asyncio.TimeoutError:
+ raise RedisConnectionError("refused")
+
+ with pytest.raises(RedisConnectionError) as chained:
+ raise_chained_from_timeout()
+ with pytest.raises(RedisConnectionError) as contextual:
+ raise_while_handling_timeout()
+
- assert _is_redis_timeout_failure(chained.value) is True
- assert _is_redis_timeout_failure(contextual.value) is False
- assert _is_redis_timeout_failure(RedisConnectionError("refused")) is False
++ assert is_redis_timeout_failure(chained.value) is True
++ assert is_redis_timeout_failure(contextual.value) is False
++ assert is_redis_timeout_failure(RedisConnectionError("refused")) is False
+
+
+ class _RoundTripCountingRedis:
+ """Fake redis.asyncio client: one round trip per awaited command or pipeline execute."""
+
+ def __init__(self, ttl: int) -> None:
+ self.values: dict[str, float] = {}
+ self.ttls: dict[str, int] = {}
+ self.round_trips = 0
+ self._initial_ttl = ttl
+
+ async def incrbyfloat(self, name: str, amount: float) -> float:
+ self.round_trips += 1
+ return self._incr(name, amount)
+
+ async def expire(self, name: str, time: int) -> bool:
+ self.round_trips += 1
+ self.ttls[name] = time
+ return True
+
+ def _incr(self, name: str, amount: float) -> float:
+ self.values[name] = self.values.get(name, 0.0) + amount
+ self.ttls.setdefault(name, self._initial_ttl)
+ return self.values[name]
+
+ def pipeline(self, transaction: bool) -> "_RoundTripCountingRedis._Pipeline":
+ return _RoundTripCountingRedis._Pipeline(self)
+
+ class _Pipeline:
+ def __init__(self, client: "_RoundTripCountingRedis") -> None:
+ self._client = client
+ self._commands: list[tuple[str, tuple[object, ...]]] = []
+
+ async def __aenter__(self) -> "_RoundTripCountingRedis._Pipeline":
+ return self
+
+ async def __aexit__(self, *exc_info: object) -> None:
+ return None
+
+ def incrbyfloat(self, name: str, amount: float) -> None:
+ self._commands.append(("incrbyfloat", (name, amount)))
+
+ def expire(self, name: str, time: int) -> None:
+ self._commands.append(("expire", (name, time)))
+
+ def ttl(self, name: str) -> None:
+ self._commands.append(("ttl", (name,)))
+
+ async def execute(self) -> list[object]:
+ self._client.round_trips += 1
+ results: list[object] = []
+ for command, args in self._commands:
+ if command == "incrbyfloat":
+ results.append(self._client._incr(str(args[0]), float(args[1]))) # pyright: ignore[reportArgumentType] # fake stores str/float
+ elif command == "expire":
+ self._client.ttls[str(args[0])] = int(args[1]) # pyright: ignore[reportArgumentType] # fake stores int
+ results.append(True)
+ else:
+ results.append(self._client.ttls.get(str(args[0]), -2))
+ return results
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("refresh_ttl", "existing_ttl", "expected_round_trips", "expected_ttl"),
+ [
+ pytest.param(True, 100, 2, 60, id="refresh_ttl: INCRBYFLOAT+EXPIRE in one round trip each"),
+ pytest.param(False, 100, 2, 100, id="keep ttl: INCRBYFLOAT+TTL in one round trip each, no EXPIRE"),
+ pytest.param(False, -1, 3, 60, id="unexpiring key: INCRBYFLOAT+TTL then EXPIRE once, 1 trip after"),
+ ],
+ )
+ async def test_async_increment_pipelines_the_ttl_command(
+ monkeypatch, redis_no_ping, refresh_ttl, existing_ttl, expected_round_trips, expected_ttl
+ ):
+ monkeypatch.setenv("REDIS_HOST", "https://my-test-host")
+ redis_cache = RedisCache(namespace="ns")
+ client = _RoundTripCountingRedis(ttl=existing_ttl)
+
+ with patch.object(redis_cache, "init_async_client", return_value=client):
+ first = await redis_cache.async_increment(key="spend:key:k", value=1.5, ttl=60, refresh_ttl=refresh_ttl)
+ second = await redis_cache.async_increment(key="spend:key:k", value=2.0, ttl=60, refresh_ttl=refresh_ttl)
+
+ assert (first, second) == (1.5, 3.5)
+ assert client.values == {"ns:spend:key:k": 3.5}
+ assert client.ttls == {"ns:spend:key:k": expected_ttl}
+ assert client.round_trips == expected_round_trips
+
+
+ class _SetRecordingPipeline:
+ def __init__(self) -> None:
+ self.sets: list[tuple[str, str, timedelta | None]] = []
+ self.executes = 0
+
+ async def __aenter__(self) -> "_SetRecordingPipeline":
+ return self
+
+ async def __aexit__(self, *exc_info: object) -> None:
+ return None
+
+ def set(self, name: str, value: str, ex: timedelta | None) -> None:
+ self.sets.append((name, value, ex))
+
+ async def execute(self) -> list[bool]:
+ self.executes += 1
+ return [True] * len(self.sets)
+
+
+ @pytest.mark.asyncio
+ async def test_async_set_cache_pipeline_with_ttls_keeps_each_entry_ttl(monkeypatch, redis_no_ping):
+ monkeypatch.setenv("REDIS_HOST", "https://my-test-host")
+ monkeypatch.setattr(litellm, "default_redis_ttl", 300)
+ redis_cache = RedisCache(namespace="ns")
+ pipe = _SetRecordingPipeline()
+ client = MagicMock()
+ client.pipeline = MagicMock(return_value=pipe)
+
+ with patch.object(redis_cache, "init_async_client", return_value=client):
+ await redis_cache.async_set_cache_pipeline_with_ttls(
+ (("team_id:t1", {"team_id": "t1"}, 60), ("u1", {"user_id": "u1"}, 7), ("org_id:o1", {"a": 1}, None))
+ )
+
+ client.pipeline.assert_called_once_with(transaction=False)
+ assert pipe.executes == 1
+ assert pipe.sets == [
+ ("ns:team_id:t1", '{"team_id": "t1"}', timedelta(seconds=60)),
+ ("ns:u1", '{"user_id": "u1"}', timedelta(seconds=7)),
+ ("ns:org_id:o1", '{"a": 1}', timedelta(seconds=300)),
+ ]