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
fix(caching): keep upstream RedisCluster on redis-py with per-connection recovery (#38171)
devin-ai-integration[bot]896e2598dadc
diff --git a/litellm/caching/redis_cluster_node_isolation.py b/litellm/caching/redis_cluster_node_isolation.pyindex 8b0c120e80c..ae8c78709d9 100644--- a/litellm/caching/redis_cluster_node_isolation.py+++ b/litellm/caching/redis_cluster_node_isolation.py@@ -18,6 +18,14 @@ already does when one of its pooled connections errors), leaving every other nodconnections untouched. Every other branch (MOVED, ASK, CLUSTERDOWN, slot-not-covered,retry-exhaustion) is unchanged from upstream, since those already carry real evidence thetopology changed.++redis-py 8.x fixed this upstream with gentler machinery than this override's+``node.disconnect()`` (which also kills connections other coroutines are mid-operation+on, so one timeout cascades into a reconnect storm and, with TLS, a fresh handshake per+killed connection): it marks in-use connections for reconnect only after their current+operation completes, disconnects only the idle pooled ones, and defers reinitialization+to the outer retry loop. When the installed ``ClusterNode`` has that per-connection+recovery API, the factory returns the base ``RedisCluster`` unmodified."""import asyncio@@ -72,8 +80,16 @@ class _ClusterAttrs(Protocol):_VERIFIED_REDIS_VERSIONS: Final = frozenset({"5.3.1"})-def get_litellm_async_redis_cluster_class() -> type["_AsyncRedisClusterType"]:- """Builds the ``RedisCluster`` subclass with the per-node isolation fix.+def get_litellm_async_redis_cluster_class(+ cluster_node_class: type | None = None,+) -> type["_AsyncRedisClusterType"]:+ """Returns the base ``RedisCluster`` when the installed redis-py already recovers a+ node-level connection error per-connection (8.x+), else builds the ``RedisCluster``+ subclass with the per-node isolation fix for older versions whose upstream branch+ tears down the whole cluster client.++ ``cluster_node_class`` exists for dependency injection in tests; production callers+ leave it unset and the installed ``ClusterNode`` is used.Imported lazily because this module is reachable from a base ``import litellm`` whileredis is not a base dependency. Cheap to call repeatedly: the underlying redis@@ -81,7 +97,10 @@ def get_litellm_async_redis_cluster_class() -> type["_AsyncRedisClusterType"]:"""import redisfrom redis.asyncio.cluster import (- RedisCluster as _BaseAsyncRedisCluster, # pyright: ignore[reportUnknownVariableType] # redis-py ships no resolvable stub for this class under the repo's current (stale) types-redis pin+ ClusterNode as _AsyncClusterNode, # pyright: ignore[reportUnknownVariableType] # redis-py ships no resolvable stub for this class under the repo's current (stale) types-redis pin+ )+ from redis.asyncio.cluster import (+ RedisCluster as _BaseAsyncRedisCluster, # pyright: ignore[reportUnknownVariableType] # same stale-stub gap as the import above)from redis.cluster import get_node_namefrom redis.commands import READ_COMMANDS@@ -98,6 +117,15 @@ def get_litellm_async_redis_cluster_class() -> type["_AsyncRedisClusterType"]:from redis.exceptions import ConnectionError as _RedisConnectionErrorfrom redis.exceptions import TimeoutError as _RedisTimeoutError+ node_class: Final = cluster_node_class if cluster_node_class is not None else _AsyncClusterNode+ if hasattr(node_class, "update_active_connections_for_reconnect"):+ verbose_logger.debug(+ "redis-py %s recovers a node-level connection error per-connection upstream; "+ "using the base RedisCluster without litellm's node-isolation override.",+ redis.__version__,+ )+ return _BaseAsyncRedisCluster+if redis.__version__ not in _VERIFIED_REDIS_VERSIONS:verbose_logger.warning("redis-py %s is not in the set this cluster-teardown-storm fix was verified "diff --git a/tests/test_litellm/caching/test_redis_cluster_node_isolation.py b/tests/test_litellm/caching/test_redis_cluster_node_isolation.pyindex f4cd3ab20ef..c16ceec8c31 100644--- a/tests/test_litellm/caching/test_redis_cluster_node_isolation.py+++ b/tests/test_litellm/caching/test_redis_cluster_node_isolation.py@@ -28,6 +28,14 @@ if TYPE_CHECKING:from redis.asyncio.cluster import RedisCluster as _AsyncRedisClusterType+class _NodeClassWithPerConnectionRecovery:+ def update_active_connections_for_reconnect(self) -> None: ...+++class _NodeClassWithoutPerConnectionRecovery:+ pass++class _FakeClusterNode:def __init__(self, name: str, raises: Exception | None = None, response: object = None) -> None:self.name = name@@ -47,7 +55,9 @@ class _FakeNodesManager:def _build_cluster_instance() -> "_AsyncRedisClusterType":- cluster_cls = get_litellm_async_redis_cluster_class()+ cluster_cls = get_litellm_async_redis_cluster_class(+ cluster_node_class=_NodeClassWithoutPerConnectionRecovery+ )instance = cluster_cls.__new__(cluster_cls)instance.RedisClusterRequestTTL = 1instance.reinitialize_counter = 0@@ -58,6 +68,33 @@ def _build_cluster_instance() -> "_AsyncRedisClusterType":return instance+def test_per_connection_recovery_redis_py_gets_the_unmodified_upstream_class() -> None:+ """Regression (redis-py 8.x): when upstream ClusterNode already recovers a node-level+ connection error per-connection, the factory must NOT install the copied override,+ whose node.disconnect() also kills connections other coroutines are mid-operation on."""+ from redis.asyncio.cluster import RedisCluster++ cluster_cls = get_litellm_async_redis_cluster_class(+ cluster_node_class=_NodeClassWithPerConnectionRecovery+ )++ assert cluster_cls is RedisCluster+++def test_pre_recovery_redis_py_still_gets_the_node_isolation_override() -> None:+ """Old redis-py (5.x) responds to a node-level error with a full-cluster aclose(),+ so those versions must keep litellm's per-node isolation override."""+ from redis.asyncio.cluster import RedisCluster++ cluster_cls = get_litellm_async_redis_cluster_class(+ cluster_node_class=_NodeClassWithoutPerConnectionRecovery+ )++ assert cluster_cls is not RedisCluster+ assert issubclass(cluster_cls, RedisCluster)+ assert "_execute_command" in cluster_cls.__dict__++@pytest.mark.asyncio@pytest.mark.parametrize("error_cls", [RedisConnectionError, RedisTimeoutError])async def test_node_level_error_resets_only_that_node_not_the_whole_client(error_cls: type[Exception]) -> None: