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
tests(vcr): make redis persister resilient to transient outages
mateo-berria7e8189b173d
diff --git a/tests/_vcr_redis_persister.py b/tests/_vcr_redis_persister.pyindex 4903a16068a..537f314bfb7 100644--- a/tests/_vcr_redis_persister.py+++ b/tests/_vcr_redis_persister.py@@ -1,5 +1,6 @@from __future__ import annotations+import loggingimport osfrom typing import Any, Optional@@ -9,6 +10,8 @@ from vcr.serialize import deserialize, serializeCASSETTE_TTL_SECONDS = 24 * 60 * 60REDIS_KEY_PREFIX = "litellm:vcr:cassette:"+_log = logging.getLogger(__name__)+def redis_key_for(cassette_path: str) -> str:rel = os.path.relpath(str(cassette_path))@@ -31,6 +34,10 @@ def _redis_url_from_env() -> Optional[str]:def _build_default_client():import redis+ from redis.backoff import ExponentialBackoff+ from redis.exceptions import ConnectionError as RedisConnectionError+ from redis.exceptions import TimeoutError as RedisTimeoutError+ from redis.retry import Retryurl = _redis_url_from_env()if not url:@@ -39,11 +46,15 @@ def _build_default_client():"Cassette Redis is intentionally separate from the application ""Redis (REDIS_URL/REDIS_HOST) to avoid being flushed by tests.")+ # Managed Redis providers (e.g. Upstash) drop idle TLS connections; retry on+ # connection/timeout errors so a single dropped socket doesn't fail teardown.return redis.Redis.from_url(url,socket_timeout=5,socket_connect_timeout=5,decode_responses=False,+ retry=Retry(ExponentialBackoff(cap=2, base=0.1), retries=2),+ retry_on_error=[RedisConnectionError, RedisTimeoutError],)@@ -53,10 +64,30 @@ def make_redis_persister():redis_client = client if client is not None else _build_default_client()+ # Lazily resolve the redis exception classes so callers can pass any+ # client (incl. fakeredis) without importing the real `redis` package.+ try:+ from redis.exceptions import ConnectionError as RedisConnectionError+ from redis.exceptions import TimeoutError as RedisTimeoutError++ _transient_errors: tuple = (RedisConnectionError, RedisTimeoutError)+ except ImportError: # pragma: no cover - redis is a hard test dep+ _transient_errors = ()+class _RedisPersister:@staticmethoddef load_cassette(cassette_path, serializer):- data = redis_client.get(redis_key_for(cassette_path))+ try:+ data = redis_client.get(redis_key_for(cassette_path))+ except _transient_errors as exc:+ # Treat a Redis outage on read as a cassette miss so tests fall+ # through to a live call instead of erroring in setup.+ _log.warning(+ "VCR redis load failed for %s; treating as cache miss: %s",+ cassette_path,+ exc,+ )+ raise CassetteNotFoundError() from excif data is None:raise CassetteNotFoundError()if isinstance(data, bytes):@@ -67,7 +98,17 @@ def make_redis_persister(def save_cassette(cassette_path, cassette_dict, serializer):data = serialize(cassette_dict, serializer)payload = data.encode("utf-8") if isinstance(data, str) else data- redis_client.set(redis_key_for(cassette_path), payload, ex=ttl_seconds)+ try:+ redis_client.set(redis_key_for(cassette_path), payload, ex=ttl_seconds)+ except _transient_errors as exc:+ # Cassette persistence is a cache, not test correctness. A Redis+ # outage on save should not fail an otherwise-passing test —+ # the next run will simply re-record.+ _log.warning(+ "VCR redis save failed for %s; cassette not persisted: %s",+ cassette_path,+ exc,+ )return _RedisPersisterdiff --git a/tests/llm_translation/test_vcr_redis_persister.py b/tests/llm_translation/test_vcr_redis_persister.pyindex d10aa388c4b..b4dcd4ded80 100644--- a/tests/llm_translation/test_vcr_redis_persister.py+++ b/tests/llm_translation/test_vcr_redis_persister.py@@ -5,6 +5,7 @@ import sysimport fakeredisimport pytest+from redis.exceptions import ConnectionError as RedisConnectionErrorfrom vcr.persisters.filesystem import CassetteNotFoundErrorfrom vcr.request import Requestfrom vcr.serializers import yamlserializer@@ -82,6 +83,48 @@ def test_redis_key_normalizes_path_passed_by_pytest_recording():)+class _FlakyRedis:+ """Wraps a fake redis but raises ConnectionError on the chosen op."""++ def __init__(self, inner, fail_on: str):+ self._inner = inner+ self._fail_on = fail_on++ def get(self, *args, **kwargs):+ if self._fail_on == "get":+ raise RedisConnectionError("simulated outage")+ return self._inner.get(*args, **kwargs)++ def set(self, *args, **kwargs):+ if self._fail_on == "set":+ raise RedisConnectionError("simulated outage")+ return self._inner.set(*args, **kwargs)+++def test_save_swallows_connection_errors_so_teardown_does_not_fail():+ # Persistence is a cache; an outage shouldn't fail an otherwise-passing test.+ flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="set")+ persister = make_redis_persister(client=flaky)++ persister.save_cassette(+ "tests/llm_translation/test_x/test_save_outage",+ _sample_cassette_dict(),+ yamlserializer,+ )+++def test_load_treats_connection_errors_as_cassette_miss():+ # An outage on read should fall through to a live call (CassetteNotFound),+ # not surface a redis exception in the test setup.+ flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="get")+ persister = make_redis_persister(client=flaky)++ with pytest.raises(CassetteNotFoundError):+ persister.load_cassette(+ "tests/llm_translation/test_x/test_load_outage", yamlserializer+ )++@pytest.mark.parametrize(("status_code", "expect_dropped"),[