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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_redis_pool_timeout_counts_as_timeout
mateo-berrifea4970159f4
diff --cc tests/test_litellm/caching/test_redis_cache.pyindex 2e1dfb77fd2,bcae33b976e..d3b7f8a63ad--- a/tests/test_litellm/caching/test_redis_cache.py+++ b/tests/test_litellm/caching/test_redis_cache.py@@@ -1032,61 -1068,137 +1068,197 @@@ def test_sync_guard_counts_a_timeout_asassert breaker.is_open() is False+ def test_success_admitted_before_the_breaker_opened_cannot_close_it():+ """A stale in-flight success must not close a breaker that opened while it ran.++ Calls admitted while the breaker was still closed finish after later failures opened it.+ Recording their success unconditionally closed the breaker again, skipping the recovery+ timeout and the single half-open probe, so the breaker flapped between open and closed+ on every straggler while Redis was still down.+ """+ from litellm.caching.redis_cache import RedisCircuitBreaker++ breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)+ for _ in range(3):+ breaker.record_failure()+ assert breaker._state == breaker.OPEN++ breaker.record_success()++ assert breaker._state == breaker.OPEN+ assert breaker.is_open() is True+++ def test_recovery_probe_still_closes_the_breaker():+ from litellm.caching.redis_cache import RedisCircuitBreaker++ breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)+ for _ in range(3):+ breaker.record_failure()+ breaker._opened_at = time.time() - 9999+ assert breaker.is_open() is False+ assert breaker._state == breaker.HALF_OPEN++ breaker.record_success()++ assert breaker._state == breaker.CLOSED+ assert breaker.is_open() is False+++ @pytest.mark.asyncio+ async def test_stale_success_during_the_recovery_probe_leaves_the_breaker_to_the_probe():+ """A call admitted before the trip that finishes while HALF_OPEN must not close the breaker.++ Only the one call designated as the recovery probe has actually reached Redis after the+ outage, so closing on the straggler's success resumed full Redis traffic before the probe+ had proven anything.+ """+ from litellm.caching.redis_cache import RedisCircuitBreaker, _run_under_circuit_breaker++ breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)+ stale_admitted = asyncio.Event()+ stale_release = asyncio.Event()+ probe_admitted = asyncio.Event()+ probe_release = asyncio.Event()++ async def stale_call() -> str:+ stale_admitted.set()+ await stale_release.wait()+ return "stale"++ async def probe_call() -> str:+ probe_admitted.set()+ await probe_release.wait()+ return "probe"++ stale = asyncio.ensure_future(_run_under_circuit_breaker(breaker, "op", stale_call))+ await stale_admitted.wait()+ for _ in range(3):+ breaker.record_failure()+ assert breaker._state == breaker.OPEN+ breaker._opened_at = time.time() - 9999+ probe = asyncio.ensure_future(_run_under_circuit_breaker(breaker, "op", probe_call))+ await probe_admitted.wait()+ assert breaker._state == breaker.HALF_OPEN++ stale_release.set()+ assert await stale == "stale"++ assert breaker._state == breaker.HALF_OPEN, "the straggler must not close the breaker for the probe"+ assert breaker.is_open() is True++ probe_release.set()+ assert await probe == "probe"++ assert breaker._state == breaker.CLOSED+ assert breaker.is_open() is False+++ @pytest.mark.asyncio+ async def test_a_probe_overtaken_by_a_later_outage_leaves_the_breaker_to_the_new_probe():+ """A probe still in flight when a late failure reopens the breaker must not close it for the next probe.++ Once the breaker has reopened, only the probe admitted after that outage has reached+ Redis, so the older probe's success no longer says anything about whether Redis recovered.+ """+ from litellm.caching.redis_cache import RedisCircuitBreaker, _run_under_circuit_breaker++ breaker = RedisCircuitBreaker(failure_threshold=3, recovery_timeout=60)+ old_probe_admitted = asyncio.Event()+ old_probe_release = asyncio.Event()+ new_probe_admitted = asyncio.Event()+ new_probe_release = asyncio.Event()++ async def old_probe_call() -> str:+ old_probe_admitted.set()+ await old_probe_release.wait()+ return "old probe"++ async def new_probe_call() -> str:+ new_probe_admitted.set()+ await new_probe_release.wait()+ return "new probe"++ for _ in range(3):+ breaker.record_failure()+ breaker._opened_at = time.time() - 9999+ old_probe = asyncio.ensure_future(_run_under_circuit_breaker(breaker, "op", old_probe_call))+ await old_probe_admitted.wait()+ assert breaker._state == breaker.HALF_OPEN++ breaker.record_failure()+ assert breaker._state == breaker.OPEN+ breaker._opened_at = time.time() - 9999+ new_probe = asyncio.ensure_future(_run_under_circuit_breaker(breaker, "op", new_probe_call))+ await new_probe_admitted.wait()+ assert breaker._state == breaker.HALF_OPEN++ old_probe_release.set()+ assert await old_probe == "old probe"++ assert breaker._state == breaker.HALF_OPEN, "the overtaken probe must not close the breaker for the new probe"+ assert breaker.is_open() is True++ new_probe_release.set()+ assert await new_probe == "new probe"+ assert breaker._state == breaker.CLOSED+++++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++ 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