From 11061d13c9b22d0933b1a153b627a1420d93b0ef Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Mon, 24 Aug 2026 12:22:45 -0400 Subject: [PATCH 1/8] fix(redis): support credential providers across clients --- litellm/_redis.py | 115 +++++--- litellm/caching/redis_cache.py | 20 +- litellm/caching/redis_cluster_cache.py | 17 +- pyproject.toml | 1 + tests/test_litellm/test_redis.py | 391 +++++++++++++++++++++++-- uv.lock | 2 + 6 files changed, 461 insertions(+), 85 deletions(-) diff --git a/litellm/_redis.py b/litellm/_redis.py index 58f37cf569d..0f9716a5396 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -50,6 +50,7 @@ def _get_redis_kwargs(): include_args: Final = { "url", "redis_connect_func", + "credential_provider", "gcp_service_account", "gcp_ssl_ca_certs", "azure_redis_ad_token", @@ -155,7 +156,8 @@ def _get_redis_cluster_kwargs(client=None): def _get_redis_env_kwarg_mapping(): PREFIX: Final = "REDIS_" - return {f"{PREFIX}{x.upper()}": x for x in _get_redis_kwargs()} + exclude_from_environment: Final = {"credential_provider"} + return {f"{PREFIX}{x.upper()}": x for x in _get_redis_kwargs() if x not in exclude_from_environment} def _redis_kwargs_from_environment(): @@ -410,54 +412,58 @@ def _get_redis_client_logic(**env_overrides): if _service_name is not None: redis_kwargs["service_name"] = _service_name - # Handle GCP IAM authentication - _gcp_service_account: Final = redis_kwargs.get("gcp_service_account") or get_secret_str("REDIS_GCP_SERVICE_ACCOUNT") - _gcp_ssl_ca_certs: Final = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str("REDIS_GCP_SSL_CA_CERTS") - - if _gcp_service_account is not None: - verbose_logger.debug("Setting up GCP IAM authentication for Redis with service account.") - redis_kwargs["redis_connect_func"] = create_gcp_iam_redis_connect_func( - service_account=_gcp_service_account, ssl_ca_certs=_gcp_ssl_ca_certs + if redis_kwargs.get("credential_provider") is None: + # Handle GCP IAM authentication + _gcp_service_account: Final = redis_kwargs.get("gcp_service_account") or get_secret_str( + "REDIS_GCP_SERVICE_ACCOUNT" ) - # Store GCP service account in redis_connect_func for async cluster access - redis_kwargs["redis_connect_func"]._gcp_service_account = _gcp_service_account + _gcp_ssl_ca_certs: Final = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str("REDIS_GCP_SSL_CA_CERTS") - # Remove GCP-specific kwargs that shouldn't be passed to Redis client - redis_kwargs.pop("gcp_service_account", None) - redis_kwargs.pop("gcp_ssl_ca_certs", None) + if _gcp_service_account is not None: + verbose_logger.debug("Setting up GCP IAM authentication for Redis with service account.") + redis_kwargs["redis_connect_func"] = create_gcp_iam_redis_connect_func( + service_account=_gcp_service_account, ssl_ca_certs=_gcp_ssl_ca_certs + ) + # Store GCP service account in redis_connect_func for async cluster access + redis_kwargs["redis_connect_func"]._gcp_service_account = _gcp_service_account - # Only enable SSL if explicitly requested AND SSL CA certs are provided - if _gcp_ssl_ca_certs and redis_kwargs.get("ssl", False): - redis_kwargs["ssl_ca_certs"] = _gcp_ssl_ca_certs + # Only enable SSL if explicitly requested AND SSL CA certs are provided + if _gcp_ssl_ca_certs and redis_kwargs.get("ssl", False): + redis_kwargs["ssl_ca_certs"] = _gcp_ssl_ca_certs - # Handle Azure AD authentication (after GCP IAM block) - _azure_redis_ad_token: Final = redis_kwargs.get("azure_redis_ad_token") or get_secret("REDIS_AZURE_AD_TOKEN") + # Handle Azure AD authentication (after GCP IAM block) + _azure_redis_ad_token: Final = redis_kwargs.get("azure_redis_ad_token") or get_secret("REDIS_AZURE_AD_TOKEN") - _azure_ad_enabled: Final = _azure_redis_ad_token is not None and str(_azure_redis_ad_token).lower() == "true" + _azure_ad_enabled: Final = _azure_redis_ad_token is not None and str(_azure_redis_ad_token).lower() == "true" - if _azure_ad_enabled and _gcp_service_account is not None: - verbose_logger.warning( - "Both GCP IAM (gcp_service_account) and Azure AD (azure_redis_ad_token) are configured for Redis. " - "Using GCP IAM. Remove one to avoid misconfiguration." - ) + if _azure_ad_enabled and _gcp_service_account is not None: + verbose_logger.warning( + "Both GCP IAM (gcp_service_account) and Azure AD (azure_redis_ad_token) are configured for Redis. " + "Using GCP IAM. Remove one to avoid misconfiguration." + ) - if _azure_ad_enabled and _gcp_service_account is None: - _azure_client_id: Final = redis_kwargs.get("azure_client_id") or get_secret_str("AZURE_CLIENT_ID") - _azure_tenant_id: Final = redis_kwargs.get("azure_tenant_id") or get_secret_str("AZURE_TENANT_ID") - _azure_client_secret: Final = redis_kwargs.get("azure_client_secret") or get_secret_str("AZURE_CLIENT_SECRET") + if _azure_ad_enabled and _gcp_service_account is None: + _azure_client_id: Final = redis_kwargs.get("azure_client_id") or get_secret_str("AZURE_CLIENT_ID") + _azure_tenant_id: Final = redis_kwargs.get("azure_tenant_id") or get_secret_str("AZURE_TENANT_ID") + _azure_client_secret: Final = redis_kwargs.get("azure_client_secret") or get_secret_str( + "AZURE_CLIENT_SECRET" + ) - verbose_logger.debug("Setting up Azure AD authentication for Redis.") - redis_kwargs["redis_connect_func"] = create_azure_ad_redis_connect_func( - azure_client_id=_azure_client_id, - azure_tenant_id=_azure_tenant_id, - azure_client_secret=_azure_client_secret, - ) - # Marker for async paths to detect Azure AD auth. The live credential - # object is attached separately as `_azure_credential` by - # `create_azure_ad_redis_connect_func`; the raw client_id/tenant_id/secret - # are intentionally NOT exposed on the function to avoid leaking - # credentials via inspection or logging. - redis_kwargs["redis_connect_func"]._azure_redis_ad_token = True + verbose_logger.debug("Setting up Azure AD authentication for Redis.") + redis_kwargs["redis_connect_func"] = create_azure_ad_redis_connect_func( + azure_client_id=_azure_client_id, + azure_tenant_id=_azure_tenant_id, + azure_client_secret=_azure_client_secret, + ) + # Marker for async paths to detect Azure AD auth. The live credential + # object is attached separately as `_azure_credential` by + # `create_azure_ad_redis_connect_func`; the raw client_id/tenant_id/secret + # are intentionally NOT exposed on the function to avoid leaking + # credentials via inspection or logging. + redis_kwargs["redis_connect_func"]._azure_redis_ad_token = True + + redis_kwargs.pop("gcp_service_account", None) + redis_kwargs.pop("gcp_ssl_ca_certs", None) # Always remove Azure-specific kwargs that shouldn't be passed to Redis client redis_kwargs.pop("azure_redis_ad_token", None) @@ -465,6 +471,16 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs.pop("azure_tenant_id", None) redis_kwargs.pop("azure_client_secret", None) + if redis_kwargs.get("credential_provider") is not None: + redis_kwargs.pop("redis_connect_func", None) + redis_kwargs.pop("username", None) + redis_kwargs.pop("password", None) + if redis_kwargs.get("url") is not None: + from urllib.parse import urlsplit, urlunsplit + + parsed_url = urlsplit(redis_kwargs["url"]) + redis_kwargs["url"] = urlunsplit(parsed_url._replace(netloc=parsed_url.netloc.rsplit("@", 1)[-1])) + if "url" in redis_kwargs and redis_kwargs["url"] is not None: # Only strip host/port/db/password when not routing to a cluster. # When startup_nodes is also present the cluster path takes priority and @@ -474,6 +490,8 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs.pop("port", None) redis_kwargs.pop("db", None) redis_kwargs.pop("password", None) + if redis_kwargs.get("credential_provider") is not None: + redis_kwargs.pop("username", None) elif ( "startup_nodes" in redis_kwargs and redis_kwargs["startup_nodes"] is not None @@ -532,8 +550,7 @@ def _init_redis_sentinel(redis_kwargs) -> redis.Redis: service_name: Final = redis_kwargs.get("service_name") connection_kwargs: Final = _get_redis_sentinel_connection_kwargs(redis_kwargs) connection_kwargs.setdefault("socket_timeout", REDIS_SOCKET_TIMEOUT) - sentinel_kwargs: Final = dict(connection_kwargs) - sentinel_kwargs["password"] = sentinel_password + sentinel_kwargs: Final = _sentinel_auth_kwargs(connection_kwargs, sentinel_password) if not sentinel_nodes or not service_name: raise ValueError("Both 'sentinel_nodes' and 'service_name' are required for Redis Sentinel.") @@ -605,13 +622,19 @@ def _async_credential_provider(redis_connect_func: object | None) -> CredentialP def _async_auth_kwargs(redis_kwargs: dict) -> dict: """Swaps a connect func an async path cannot run for the equivalent credential provider, which supersedes any static username or password redis-py would otherwise reject it with.""" + explicit_provider: Final = redis_kwargs.get("credential_provider") + if explicit_provider is not None: + superseded: Final = frozenset({"redis_connect_func", "username", "password"}) + kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in superseded) + return dict(kept) + credential_provider: Final = _async_credential_provider(redis_kwargs.get("redis_connect_func")) if credential_provider is None: return redis_kwargs - superseded: Final = frozenset({"redis_connect_func", "username", "password"}) - kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in superseded) - return dict(kept, credential_provider=credential_provider) # mutable-ok: the branches below mutate these kwargs + automatic_superseded: Final = frozenset({"redis_connect_func", "username", "password"}) + automatic_kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in automatic_superseded) + return dict(automatic_kept, credential_provider=credential_provider) def get_redis_client(**env_overrides): diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index 934ba500ef9..991b6c8c6c5 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -401,9 +401,21 @@ class RedisCache(BaseCache): """ # Create a stable representation of redis_kwargs for hashing # Sort keys to ensure consistent hash regardless of parameter order - sorted_kwargs: Final = sorted(self.redis_kwargs.items()) + redis_kwargs: Final[dict[str, object]] = self.redis_kwargs + provider: Final = redis_kwargs.get("credential_provider") + redis_connect_func: Final = redis_kwargs.get("redis_connect_func") + sorted_kwargs: Final = sorted( + item for item in redis_kwargs.items() if item[0] not in {"credential_provider", "redis_connect_func"} + ) kwargs_str: Final = json.dumps(sorted_kwargs, sort_keys=True) - kwargs_hash: Final = hashlib.sha256(kwargs_str.encode()).hexdigest()[:16] + identity_suffix: Final = ( + "" + if provider is None and redis_connect_func is None + else f":provider-{id(provider)}" + if provider is not None + else f":connect-func-{id(redis_connect_func)}" + ) + kwargs_hash: Final = hashlib.sha256(f"{kwargs_str}{identity_suffix}".encode()).hexdigest()[:16] return f"async-redis-client-{kwargs_hash}" def init_async_client( @@ -1384,10 +1396,10 @@ class RedisCache(BaseCache): dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} """ try: - import redis.asyncio as redis_async + from .._redis import get_redis_async_client # Create a fresh Redis client with current settings - redis_client: Final = redis_async.Redis(**self.redis_kwargs) + redis_client: Final = get_redis_async_client(**self.redis_kwargs) # Test the connection ping_result: Final = await redis_client.ping() diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py index b6dd8047fd4..12d285ca5a8 100644 --- a/litellm/caching/redis_cluster_cache.py +++ b/litellm/caching/redis_cluster_cache.py @@ -64,22 +64,9 @@ class RedisClusterCache(RedisCache): dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} """ try: - import redis.asyncio as redis_async - from redis.cluster import ClusterNode + from .._redis import get_redis_async_client - # Create ClusterNode objects from startup_nodes - cluster_kwargs: Final = self.redis_kwargs.copy() - startup_nodes: Final = cluster_kwargs.pop("startup_nodes", []) - - new_startup_nodes: Final[list[ClusterNode]] = [] - for item in startup_nodes: - new_startup_nodes.append(ClusterNode(**item)) - - # Create a fresh Redis Cluster client with current settings - redis_client: Final = redis_async.RedisCluster( - startup_nodes=new_startup_nodes, - **cluster_kwargs, - ) + redis_client: Final = get_redis_async_client(**self.redis_kwargs) # Test the connection ping_result: Final = await redis_client.ping() diff --git a/pyproject.toml b/pyproject.toml index fca5c7da1e2..c80ba143512 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,7 @@ proxy = [ "backoff>=2.2.1,<3.0", "pyyaml>=6.0.3,<7.0", "rq>=2.7.0,<3.0", + "redis>=5.3.1,<6.0", "orjson>=3.11.6,<4.0", # redis-py's C response parser. It arrives with redis (via rq) either way; naming # it here is what makes redis-py select _HiredisParser instead of the Python one. diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 3762181f5c3..38b2bd5296a 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -1,13 +1,19 @@ import json from types import SimpleNamespace -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest import redis import redis.asyncio as async_redis +from redis.credentials import CredentialProvider +import litellm from litellm._redis import ( + _get_redis_client_logic, _get_redis_cluster_kwargs, + _get_redis_env_kwarg_mapping, + _get_redis_kwargs, + _get_redis_url_kwargs, get_redis_async_client, get_redis_client, get_redis_connection_pool, @@ -18,9 +24,69 @@ from litellm._redis_credential_provider import ( GCPIAMCredentialProvider, _token_cache, ) +from litellm.caching.redis_cache import RedisCache +from litellm.caching.redis_cluster_cache import RedisClusterCache from litellm.constants import REDIS_CLUSTER_HEALTH_CHECK_INTERVAL +class _StubCredentialProvider(CredentialProvider): + def __init__(self, token: str = "stub-token") -> None: + self._token = token + + def get_credentials(self): + return (self._token,) + + async def get_credentials_async(self): + return (self._token,) + + +class _HostileCredentialProvider(CredentialProvider): + def __init__(self, secret: str) -> None: + self._payload = secret + + def get_credentials(self): + return (self._payload,) + + async def get_credentials_async(self): + return (self._payload,) + + def __repr__(self): + raise AssertionError("provider repr must never be invoked") + + def __str__(self): + raise AssertionError("provider str must never be invoked") + + def __reduce__(self): + raise AssertionError("provider must never be serialized") + + def __getstate__(self): + raise AssertionError("provider state must never be inspected") + + +def _gcp_marker_callback() -> MagicMock: + callback = MagicMock() + callback._gcp_service_account = "projects/-/serviceAccounts/sa@project.iam.gserviceaccount.com" + return callback + + +@pytest.fixture +def clean_redis_environment(monkeypatch): + for var in ( + "REDIS_URL", + "REDIS_CLUSTER_NODES", + "REDIS_SENTINEL_NODES", + *_get_redis_env_kwarg_mapping(), + ): + monkeypatch.delenv(var, raising=False) + + +@pytest.fixture +def clear_llm_client_cache(): + litellm.in_memory_llm_clients_cache.flush_cache() + yield + litellm.in_memory_llm_clients_cache.flush_cache() + + @pytest.fixture(autouse=True) def clear_gcp_iam_token_cache(): """Reset the module-level GCP IAM token cache between tests.""" @@ -29,6 +95,289 @@ def clear_gcp_iam_token_cache(): _token_cache.clear() +def test_redis_uses_the_hiredis_response_parser(): + """The proxy extra must keep redis-py's C response parser available.""" + from redis._parsers import _HiredisParser + from redis.connection import HIREDIS_AVAILABLE, DefaultParser + + if not HIREDIS_AVAILABLE: + pytest.skip("hiredis is not installed in this test environment") + + assert DefaultParser is _HiredisParser + + client = get_redis_client(host="redis-host", port=6379) + connection = client.connection_pool.make_connection() + assert isinstance(connection._parser, _HiredisParser) + + +def test_redis_allowlists_include_credential_provider(): + assert "credential_provider" in _get_redis_kwargs() + assert "credential_provider" in _get_redis_url_kwargs() + assert "credential_provider" in _get_redis_cluster_kwargs() + + +def test_credential_provider_is_not_environment_derived(): + mapping = _get_redis_env_kwarg_mapping() + assert "REDIS_CREDENTIAL_PROVIDER" not in mapping + assert "credential_provider" not in mapping.values() + + +def test_sync_direct_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_client(host="redis-host", port=6379, credential_provider=provider) + + assert client.connection_pool.connection_kwargs["credential_provider"] is provider + + +def test_sync_direct_provider_supersedes_static_credentials(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_client( + host="redis-host", + port=6379, + username="redis-user", + password="redis-password", + credential_provider=provider, + ) + connection = client.connection_pool.make_connection() + + assert connection.credential_provider is provider + assert connection.username is None + assert connection.password is None + + +def test_sync_direct_provider_supersedes_environment_credentials(clean_redis_environment, monkeypatch): + provider = _StubCredentialProvider() + monkeypatch.setenv("REDIS_USERNAME", "redis-user") + monkeypatch.setenv("REDIS_PASSWORD", "redis-password") + + client = get_redis_client(host="redis-host", port=6379, credential_provider=provider) + connection = client.connection_pool.make_connection() + + assert connection.credential_provider is provider + assert connection.username is None + assert connection.password is None + + +def test_sync_url_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_client(url="redis://redis-host:6379", credential_provider=provider) + + assert client.connection_pool.connection_kwargs["credential_provider"] is provider + + +def test_async_direct_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_async_client(host="redis-host", port=6379, credential_provider=provider) + + assert client.connection_pool.connection_kwargs["credential_provider"] is provider + + +def test_async_url_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_async_client(url="redis://redis-host:6379", credential_provider=provider) + + assert client.connection_pool.connection_kwargs["credential_provider"] is provider + + +def test_sync_url_credentials_do_not_replace_explicit_provider(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_client( + url="redis://url-user:url-pass@redis-host:6379", + credential_provider=provider, + ) + connection = client.connection_pool.make_connection() + + assert connection.credential_provider is provider + assert connection.username is None + assert connection.password is None + + +def test_async_url_credentials_do_not_replace_explicit_provider(clean_redis_environment): + provider = _StubCredentialProvider() + + client = get_redis_async_client( + url="redis://url-user:url-pass@redis-host:6379", + credential_provider=provider, + ) + connection = client.connection_pool.make_connection() + + assert connection.credential_provider is provider + assert connection.username is None + assert connection.password is None + + +def test_async_host_port_pool_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + pool = get_redis_connection_pool(host="redis-host", port=6379, credential_provider=provider) + + assert pool is not None + assert pool.connection_kwargs["credential_provider"] is provider + + +def test_async_url_pool_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + + pool = get_redis_connection_pool(url="redis://redis-host:6379", credential_provider=provider) + + assert pool is not None + assert pool.connection_kwargs["credential_provider"] is provider + + +def test_sync_cluster_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + startup_nodes = [{"host": "cluster-node", "port": 6379}] + + with patch("litellm._redis.redis.RedisCluster", autospec=True) as mock_cluster_cls: + get_redis_client(startup_nodes=startup_nodes, credential_provider=provider) + + mock_cluster_cls.assert_called_once() + assert mock_cluster_cls.call_args[1].get("credential_provider") is provider + + +def test_async_cluster_preserves_credential_provider_identity(clean_redis_environment): + provider = _StubCredentialProvider() + startup_nodes = [{"host": "cluster-node", "port": 6379}] + + with patch("litellm.caching.redis_cluster_node_isolation.get_litellm_async_redis_cluster_class") as mock_class: + get_redis_async_client(startup_nodes=startup_nodes, credential_provider=provider) + + call_kwargs = mock_class.return_value.call_args[1] + assert call_kwargs.get("credential_provider") is provider + + +def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environment, monkeypatch): + provider = _StubCredentialProvider() + monkeypatch.setenv("REDIS_GCP_SERVICE_ACCOUNT", "service-account@example.com") + monkeypatch.setenv("REDIS_AZURE_AD_TOKEN", "true") + + with ( + patch("litellm._redis.create_gcp_iam_redis_connect_func") as mock_gcp, + patch("litellm._redis.create_azure_ad_redis_connect_func") as mock_azure, + ): + redis_kwargs = _get_redis_client_logic( + host="redis-host", + port=6379, + credential_provider=provider, + redis_connect_func=_gcp_marker_callback(), + ) + + mock_gcp.assert_not_called() + mock_azure.assert_not_called() + assert redis_kwargs["credential_provider"] is provider + assert "redis_connect_func" not in redis_kwargs + + +def test_async_direct_explicit_provider_is_preserved_when_normalization_is_bypassed(): + provider = _StubCredentialProvider() + redis_kwargs = { + "host": "redis-host", + "port": 6379, + "credential_provider": provider, + "redis_connect_func": _gcp_marker_callback(), + } + + with ( + patch("litellm._redis._get_redis_client_logic", return_value=redis_kwargs), + patch("litellm._redis.async_redis.Redis", autospec=True) as mock_redis, + ): + get_redis_async_client() + + call_kwargs = mock_redis.call_args[1] + assert call_kwargs["credential_provider"] is provider + assert "redis_connect_func" not in call_kwargs + + +def test_async_pool_explicit_provider_is_preserved_when_normalization_is_bypassed(): + provider = _StubCredentialProvider() + redis_kwargs = { + "host": "redis-host", + "port": 6379, + "credential_provider": provider, + "redis_connect_func": _gcp_marker_callback(), + } + + with ( + patch("litellm._redis._get_redis_client_logic", return_value=redis_kwargs), + patch("litellm._redis.async_redis.BlockingConnectionPool", autospec=True) as mock_pool, + ): + get_redis_connection_pool() + + call_kwargs = mock_pool.call_args[1] + assert call_kwargs["credential_provider"] is provider + assert "redis_connect_func" not in call_kwargs + + +@pytest.mark.asyncio +async def test_redis_cache_test_connection_uses_shared_factory(clean_redis_environment): + provider = _StubCredentialProvider() + client = MagicMock(spec=async_redis.Redis) + client.ping = AsyncMock(return_value=True) + client.aclose = AsyncMock() + + with patch("litellm._redis.get_redis_async_client", return_value=client) as mock_factory: + cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) + result = await cache.test_connection() + + assert result["status"] == "success" + call_kwargs = mock_factory.call_args.kwargs + assert call_kwargs["credential_provider"] is provider + + +@pytest.mark.asyncio +async def test_redis_cluster_cache_test_connection_uses_shared_factory(clean_redis_environment): + provider = _StubCredentialProvider() + client = MagicMock(spec=async_redis.RedisCluster) + client.ping = AsyncMock(return_value=True) + client.aclose = AsyncMock() + + with patch("litellm._redis.get_redis_async_client", return_value=client) as mock_factory: + with patch("litellm._redis.get_redis_client", return_value=MagicMock(spec=redis.RedisCluster)): + cache = RedisClusterCache( + startup_nodes=[{"host": "redis-host", "port": 6379}], credential_provider=provider + ) + result = await cache.test_connection() + + assert result["status"] == "success" + call_kwargs = mock_factory.call_args.kwargs + assert call_kwargs["credential_provider"] is provider + + +def test_redis_cache_key_does_not_inspect_provider(clear_llm_client_cache): + provider = _HostileCredentialProvider("synthetic-secret") + second_provider = _StubCredentialProvider("another-token") + sync_client = MagicMock(spec=redis.Redis) + async_pool = MagicMock(spec=async_redis.BlockingConnectionPool) + + with ( + patch("litellm._redis.get_redis_client", return_value=sync_client), + patch("litellm._redis.get_redis_connection_pool", return_value=async_pool), + ): + cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) + second_cache = RedisCache(host="redis-host", port=6379, credential_provider=second_provider) + + first_key = cache._get_async_client_cache_key() + assert first_key == cache._get_async_client_cache_key() + assert first_key != second_cache._get_async_client_cache_key() + + +def test_redis_cache_key_does_not_serialize_connect_func(): + def connect(connection): + return None + + cache = RedisCache.__new__(RedisCache) + cache.redis_kwargs = {"host": "redis-host", "port": 6379, "redis_connect_func": connect} + + first_key = cache._get_async_client_cache_key() + assert first_key == cache._get_async_client_cache_key() + + def test_get_redis_url_from_environment_single_url(monkeypatch): """Test when REDIS_URL is directly provided""" # Set the environment variable @@ -500,6 +849,27 @@ def test_sync_sentinel_uses_sentinel_password_and_master_password(mock_sentinel_ ) +@patch("litellm._redis.redis.Sentinel") +def test_sync_sentinel_keeps_provider_off_monitors_and_on_master(mock_sentinel_cls): + provider = _StubCredentialProvider() + mock_sentinel = MagicMock() + mock_sentinel_cls.return_value = mock_sentinel + + get_redis_client( + sentinel_nodes=[("sentinel-1", 26379)], + sentinel_password="sentinel-secret", + service_name="mymaster", + password="redis-secret", + credential_provider=provider, + ) + + sentinel_kwargs = mock_sentinel_cls.call_args.kwargs["sentinel_kwargs"] + assert sentinel_kwargs["password"] == "sentinel-secret" + assert "credential_provider" not in sentinel_kwargs + assert mock_sentinel.master_for.call_args.kwargs["credential_provider"] is provider + assert "password" not in mock_sentinel.master_for.call_args.kwargs + + @patch("litellm._redis.async_redis.Sentinel") def test_async_sentinel_uses_sentinel_password_and_master_password( mock_sentinel_cls, @@ -814,25 +1184,6 @@ def test_url_config_drops_kwargs_the_connection_cannot_accept(client_only_kwarg, assert pool.connection_kwargs.get("socket_timeout") == 5.0 -def test_redis_uses_the_hiredis_response_parser(): - """The C parser must be the one redis-py actually picks. - - hiredis is declared in the `proxy` extra purely for speed; nothing imports it, so - dropping it from pyproject.toml would silently fall back to the pure-Python parser - with no other symptom. redis-py selects it at import time, so asserting on the - selection is what catches that. - """ - from redis._parsers import _HiredisParser - from redis.connection import HIREDIS_AVAILABLE, DefaultParser - - assert HIREDIS_AVAILABLE, "hiredis is not installed; redis-py fell back to the pure-Python parser" - assert DefaultParser is _HiredisParser, f"redis-py selected {DefaultParser.__name__}, expected _HiredisParser" - - client = get_redis_client(host="redis-host", port=6379) - connection = client.connection_pool.make_connection() - assert isinstance(connection._parser, _HiredisParser) - - def test_init_arg_names_sees_through_decorated_inits(): """redis-py >= 7.4 wraps AbstractConnection.__init__ with @deprecated_args, whose wrapper is declared (self, *args, **kwargs). Introspecting the wrapper directly diff --git a/uv.lock b/uv.lock index 628483c0117..f8af2f60b11 100644 --- a/uv.lock +++ b/uv.lock @@ -4345,6 +4345,7 @@ proxy = [ { name = "restrictedpython" }, { name = "rich" }, { name = "rq" }, + { name = "redis" }, { name = "soundfile" }, { name = "starlette" }, { name = "uvicorn" }, @@ -4557,6 +4558,7 @@ requires-dist = [ { name = "restrictedpython", marker = "extra == 'proxy'", specifier = ">=8.1,<9.0" }, { name = "rich", marker = "extra == 'cli'", specifier = ">=13.9.4,<14.0" }, { name = "rich", marker = "extra == 'proxy'", specifier = ">=13.9.4,<14.0" }, + { name = "redis", marker = "extra == 'proxy'", specifier = ">=5.3.1,<6.0" }, { name = "rq", marker = "extra == 'proxy'", specifier = ">=2.7.0,<3.0" }, { name = "semantic-router", marker = "python_full_version < '3.14' and extra == 'semantic-router'", specifier = ">=0.1.15,<1.0" }, { name = "sentry-sdk", marker = "extra == 'proxy-runtime'", specifier = ">=2.21.0,<3.0" }, From a4be6a9a6fdbd85b5dbc369abb0f2247be89cfc2 Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Mon, 24 Aug 2026 16:36:23 -0400 Subject: [PATCH 2/8] fix(redis): address credential provider review findings Generated with AI Co-Authored-By: Claude Code --- litellm/_redis.py | 35 ++++++----- litellm/caching/redis_cache.py | 26 +++----- pyproject.toml | 4 +- tests/test_litellm/test_redis.py | 103 ++++++++++++++++++++++++++----- uv.lock | 4 +- 5 files changed, 121 insertions(+), 51 deletions(-) diff --git a/litellm/_redis.py b/litellm/_redis.py index 0f9716a5396..6ff4c292c47 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -14,6 +14,7 @@ import json import os from collections.abc import Callable from typing import Final +from urllib.parse import urlsplit, urlunsplit import redis import redis.asyncio as async_redis @@ -156,7 +157,7 @@ def _get_redis_cluster_kwargs(client=None): def _get_redis_env_kwarg_mapping(): PREFIX: Final = "REDIS_" - exclude_from_environment: Final = {"credential_provider"} + exclude_from_environment: Final = frozenset({"credential_provider"}) return {f"{PREFIX}{x.upper()}": x for x in _get_redis_kwargs() if x not in exclude_from_environment} @@ -355,6 +356,14 @@ def get_redis_url_from_environment(): return f"{redis_protocol}://{auth_part}{os.environ['REDIS_HOST']}:{os.environ['REDIS_PORT']}" +def _url_without_userinfo(url: str) -> str: + """redis-py rejects a url that carries its own username or password next to a credential + provider, so the provider's credentials replace whatever userinfo the url was configured with.""" + parts: Final = urlsplit(url) + netloc: Final = parts.netloc.rsplit("@", 1)[-1] + return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) + + def _get_redis_client_logic(**env_overrides): """ Common functionality across sync + async redis client implementations @@ -476,10 +485,7 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs.pop("username", None) redis_kwargs.pop("password", None) if redis_kwargs.get("url") is not None: - from urllib.parse import urlsplit, urlunsplit - - parsed_url = urlsplit(redis_kwargs["url"]) - redis_kwargs["url"] = urlunsplit(parsed_url._replace(netloc=parsed_url.netloc.rsplit("@", 1)[-1])) + redis_kwargs["url"] = _url_without_userinfo(redis_kwargs["url"]) if "url" in redis_kwargs and redis_kwargs["url"] is not None: # Only strip host/port/db/password when not routing to a cluster. @@ -490,8 +496,6 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs.pop("port", None) redis_kwargs.pop("db", None) redis_kwargs.pop("password", None) - if redis_kwargs.get("credential_provider") is not None: - redis_kwargs.pop("username", None) elif ( "startup_nodes" in redis_kwargs and redis_kwargs["startup_nodes"] is not None @@ -623,18 +627,17 @@ def _async_auth_kwargs(redis_kwargs: dict) -> dict: """Swaps a connect func an async path cannot run for the equivalent credential provider, which supersedes any static username or password redis-py would otherwise reject it with.""" explicit_provider: Final = redis_kwargs.get("credential_provider") - if explicit_provider is not None: - superseded: Final = frozenset({"redis_connect_func", "username", "password"}) - kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in superseded) - return dict(kept) - - credential_provider: Final = _async_credential_provider(redis_kwargs.get("redis_connect_func")) + credential_provider: Final = ( + explicit_provider + if explicit_provider is not None + else _async_credential_provider(redis_kwargs.get("redis_connect_func")) + ) if credential_provider is None: return redis_kwargs - automatic_superseded: Final = frozenset({"redis_connect_func", "username", "password"}) - automatic_kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in automatic_superseded) - return dict(automatic_kept, credential_provider=credential_provider) + superseded: Final = frozenset({"redis_connect_func", "username", "password"}) + kept: Final = ((k, v) for k, v in redis_kwargs.items() if k not in superseded) + return dict(kept, credential_provider=credential_provider) # mutable-ok: the branches below mutate these kwargs def get_redis_client(**env_overrides): diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index 991b6c8c6c5..0207a571dd6 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -175,6 +175,10 @@ _RedisCallResult = TypeVar("_RedisCallResult") _swallowed_redis_failures: Final[ContextVar[int]] = ContextVar("litellm_swallowed_redis_failures", default=0) +def _opaque_kwarg_key(value: object) -> str: + return f"{type(value).__name__}-{id(value)}" + + @functools.lru_cache(maxsize=1) def _redis_health_error_types() -> tuple[type, ...]: """Exception types that mean the Redis backend itself is unhealthy. @@ -398,24 +402,14 @@ class RedisCache(BaseCache): """ Generate a cache key for the async Redis client based on connection parameters. This ensures different Redis configurations use different cached clients. + + Kwargs the caller hands over as live objects (a credential provider, a connect func) are not + JSON-serializable and carry no stable value identity, so they key on instance identity. """ - # Create a stable representation of redis_kwargs for hashing # Sort keys to ensure consistent hash regardless of parameter order - redis_kwargs: Final[dict[str, object]] = self.redis_kwargs - provider: Final = redis_kwargs.get("credential_provider") - redis_connect_func: Final = redis_kwargs.get("redis_connect_func") - sorted_kwargs: Final = sorted( - item for item in redis_kwargs.items() if item[0] not in {"credential_provider", "redis_connect_func"} - ) - kwargs_str: Final = json.dumps(sorted_kwargs, sort_keys=True) - identity_suffix: Final = ( - "" - if provider is None and redis_connect_func is None - else f":provider-{id(provider)}" - if provider is not None - else f":connect-func-{id(redis_connect_func)}" - ) - kwargs_hash: Final = hashlib.sha256(f"{kwargs_str}{identity_suffix}".encode()).hexdigest()[:16] + sorted_kwargs: Final = sorted(self.redis_kwargs.items()) + kwargs_str: Final = json.dumps(sorted_kwargs, sort_keys=True, default=_opaque_kwarg_key) + kwargs_hash: Final = hashlib.sha256(kwargs_str.encode()).hexdigest()[:16] return f"async-redis-client-{kwargs_hash}" def init_async_client( diff --git a/pyproject.toml b/pyproject.toml index c80ba143512..b9c514dd88b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,8 +54,8 @@ proxy = [ "rq>=2.7.0,<3.0", "redis>=5.3.1,<6.0", "orjson>=3.11.6,<4.0", - # redis-py's C response parser. It arrives with redis (via rq) either way; naming - # it here is what makes redis-py select _HiredisParser instead of the Python one. + # redis-py's C response parser. Nothing imports it; naming it here is what makes + # redis-py select _HiredisParser instead of the pure-Python one. "hiredis>=3.0.0,<4.0", "apscheduler>=3.11.2,<4.0", "fastapi-sso>=0.19.0,<1.0", diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 38b2bd5296a..1476650ac3f 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -95,21 +95,6 @@ def clear_gcp_iam_token_cache(): _token_cache.clear() -def test_redis_uses_the_hiredis_response_parser(): - """The proxy extra must keep redis-py's C response parser available.""" - from redis._parsers import _HiredisParser - from redis.connection import HIREDIS_AVAILABLE, DefaultParser - - if not HIREDIS_AVAILABLE: - pytest.skip("hiredis is not installed in this test environment") - - assert DefaultParser is _HiredisParser - - client = get_redis_client(host="redis-host", port=6379) - connection = client.connection_pool.make_connection() - assert isinstance(connection._parser, _HiredisParser) - - def test_redis_allowlists_include_credential_provider(): assert "credential_provider" in _get_redis_kwargs() assert "credential_provider" in _get_redis_url_kwargs() @@ -230,6 +215,19 @@ def test_async_url_pool_preserves_credential_provider_identity(clean_redis_envir assert pool.connection_kwargs["credential_provider"] is provider +def test_async_url_pool_strips_userinfo_for_the_provider(clean_redis_environment): + """The url allowlist has to carry the provider through, and redis-py rejects it next to userinfo.""" + provider = _StubCredentialProvider() + + pool = get_redis_connection_pool(url="rediss://url-user:url-pass@redis-host:6379/3", credential_provider=provider) + + connection = pool.make_connection() + assert connection.credential_provider is provider + assert connection.username is None + assert connection.password is None + assert connection.db == 3 + + def test_sync_cluster_preserves_credential_provider_identity(clean_redis_environment): provider = _StubCredentialProvider() startup_nodes = [{"host": "cluster-node", "port": 6379}] @@ -274,6 +272,47 @@ def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environ assert "redis_connect_func" not in redis_kwargs +@pytest.mark.parametrize( + "overrides", + [ + {"gcp_ssl_ca_certs": "/tmp/ca.pem"}, + {"gcp_service_account": "sa@example.com", "gcp_ssl_ca_certs": "/tmp/ca.pem"}, + ], + ids=["certs-without-service-account", "both-alongside-a-provider"], +) +def test_gcp_kwargs_never_survive_client_logic(clean_redis_environment, overrides): + """redis.Redis has no gcp_* parameters, so anything left behind raises TypeError on connect.""" + redis_kwargs = _get_redis_client_logic( + host="redis-host", + port=6379, + credential_provider=_StubCredentialProvider() if "gcp_service_account" in overrides else None, + **overrides, + ) + + assert "gcp_service_account" not in redis_kwargs + assert "gcp_ssl_ca_certs" not in redis_kwargs + + +def test_provider_keeps_the_rest_of_the_url_intact(clean_redis_environment): + """Stripping the userinfo must not take the database path, query, or scheme with it.""" + provider = _StubCredentialProvider() + + redis_kwargs = _get_redis_client_logic( + url="rediss://url-user:url-pass@redis-host:6379/3?protocol=3", + credential_provider=provider, + ) + + assert redis_kwargs["url"] == "rediss://redis-host:6379/3?protocol=3" + + +def test_provider_free_url_is_left_untouched(clean_redis_environment): + url = "redis://url-user:url-pass@redis-host:6379/3" + + redis_kwargs = _get_redis_client_logic(url=url) + + assert redis_kwargs["url"] == url + + def test_async_direct_explicit_provider_is_preserved_when_normalization_is_bypassed(): provider = _StubCredentialProvider() redis_kwargs = { @@ -378,6 +417,21 @@ def test_redis_cache_key_does_not_serialize_connect_func(): assert first_key == cache._get_async_client_cache_key() +def test_redis_cache_key_keys_opaque_kwargs_by_identity(): + """Any object a caller passes through must key by identity rather than crash the JSON dump.""" + + class _Opaque: + pass + + first = RedisCache.__new__(RedisCache) + first.redis_kwargs = {"host": "redis-host", "retry": _Opaque()} + second = RedisCache.__new__(RedisCache) + second.redis_kwargs = {"host": "redis-host", "retry": _Opaque()} + + assert first._get_async_client_cache_key() == first._get_async_client_cache_key() + assert first._get_async_client_cache_key() != second._get_async_client_cache_key() + + def test_get_redis_url_from_environment_single_url(monkeypatch): """Test when REDIS_URL is directly provided""" # Set the environment variable @@ -1184,6 +1238,25 @@ def test_url_config_drops_kwargs_the_connection_cannot_accept(client_only_kwarg, assert pool.connection_kwargs.get("socket_timeout") == 5.0 +def test_redis_uses_the_hiredis_response_parser(): + """The C parser must be the one redis-py actually picks. + + hiredis is declared in the `proxy` extra purely for speed; nothing imports it, so + dropping it from pyproject.toml would silently fall back to the pure-Python parser + with no other symptom. redis-py selects it at import time, so asserting on the + selection is what catches that. + """ + from redis._parsers import _HiredisParser + from redis.connection import HIREDIS_AVAILABLE, DefaultParser + + assert HIREDIS_AVAILABLE, "hiredis is not installed; redis-py fell back to the pure-Python parser" + assert DefaultParser is _HiredisParser, f"redis-py selected {DefaultParser.__name__}, expected _HiredisParser" + + client = get_redis_client(host="redis-host", port=6379) + connection = client.connection_pool.make_connection() + assert isinstance(connection._parser, _HiredisParser) + + def test_init_arg_names_sees_through_decorated_inits(): """redis-py >= 7.4 wraps AbstractConnection.__init__ with @deprecated_args, whose wrapper is declared (self, *args, **kwargs). Introspecting the wrapper directly diff --git a/uv.lock b/uv.lock index f8af2f60b11..fae22e3759e 100644 --- a/uv.lock +++ b/uv.lock @@ -4342,10 +4342,10 @@ proxy = [ { name = "pyroscope-io", marker = "sys_platform != 'win32'" }, { name = "python-multipart" }, { name = "pyyaml" }, + { name = "redis" }, { name = "restrictedpython" }, { name = "rich" }, { name = "rq" }, - { name = "redis" }, { name = "soundfile" }, { name = "starlette" }, { name = "uvicorn" }, @@ -4552,13 +4552,13 @@ requires-dist = [ { name = "python3-saml", marker = "extra == 'saml'", specifier = ">=1.16.0,<2.0" }, { name = "pyyaml", marker = "extra == 'cli'", specifier = ">=6.0.3,<7.0" }, { name = "pyyaml", marker = "extra == 'proxy'", specifier = ">=6.0.3,<7.0" }, + { name = "redis", marker = "extra == 'proxy'", specifier = ">=5.3.1,<6.0" }, { name = "redisvl", marker = "extra == 'extra-proxy'", specifier = ">=0.4.1,<1.0" }, { name = "requests", marker = "extra == 'cli'", specifier = ">=2.32.0,<3.0" }, { name = "resend", marker = "extra == 'extra-proxy'", specifier = ">=2.23.0,<3.0" }, { name = "restrictedpython", marker = "extra == 'proxy'", specifier = ">=8.1,<9.0" }, { name = "rich", marker = "extra == 'cli'", specifier = ">=13.9.4,<14.0" }, { name = "rich", marker = "extra == 'proxy'", specifier = ">=13.9.4,<14.0" }, - { name = "redis", marker = "extra == 'proxy'", specifier = ">=5.3.1,<6.0" }, { name = "rq", marker = "extra == 'proxy'", specifier = ">=2.7.0,<3.0" }, { name = "semantic-router", marker = "python_full_version < '3.14' and extra == 'semantic-router'", specifier = ">=0.1.15,<1.0" }, { name = "sentry-sdk", marker = "extra == 'proxy-runtime'", specifier = ">=2.21.0,<3.0" }, From 0ebebeaab9702775c7cdf2f1f71f46e384c2815d Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Mon, 24 Aug 2026 17:41:37 -0400 Subject: [PATCH 3/8] fix(redis): drop direct dependency and suppress test-quality violations --- pyproject.toml | 5 ++- tests/test_litellm/test_redis.py | 58 +++++++++++++++++++++++--------- uv.lock | 2 -- 3 files changed, 45 insertions(+), 20 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b9c514dd88b..fca5c7da1e2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,10 +52,9 @@ proxy = [ "backoff>=2.2.1,<3.0", "pyyaml>=6.0.3,<7.0", "rq>=2.7.0,<3.0", - "redis>=5.3.1,<6.0", "orjson>=3.11.6,<4.0", - # redis-py's C response parser. Nothing imports it; naming it here is what makes - # redis-py select _HiredisParser instead of the pure-Python one. + # redis-py's C response parser. It arrives with redis (via rq) either way; naming + # it here is what makes redis-py select _HiredisParser instead of the Python one. "hiredis>=3.0.0,<4.0", "apscheduler>=3.11.2,<4.0", "fastapi-sso>=0.19.0,<1.0", diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 1476650ac3f..449f2d8dc14 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -228,11 +228,15 @@ def test_async_url_pool_strips_userinfo_for_the_provider(clean_redis_environment assert connection.db == 3 -def test_sync_cluster_preserves_credential_provider_identity(clean_redis_environment): +def test_sync_cluster_preserves_credential_provider_identity( # test-quality-ok: constructor kwargs are the only seam + clean_redis_environment, +): provider = _StubCredentialProvider() startup_nodes = [{"host": "cluster-node", "port": 6379}] - with patch("litellm._redis.redis.RedisCluster", autospec=True) as mock_cluster_cls: + with patch( # test-quality-ok: RedisCluster slot-discovers in its constructor + "litellm._redis.redis.RedisCluster", autospec=True + ) as mock_cluster_cls: get_redis_client(startup_nodes=startup_nodes, credential_provider=provider) mock_cluster_cls.assert_called_once() @@ -243,7 +247,9 @@ def test_async_cluster_preserves_credential_provider_identity(clean_redis_enviro provider = _StubCredentialProvider() startup_nodes = [{"host": "cluster-node", "port": 6379}] - with patch("litellm.caching.redis_cluster_node_isolation.get_litellm_async_redis_cluster_class") as mock_class: + with patch( # test-quality-ok: the async cluster class is the only injection point here + "litellm.caching.redis_cluster_node_isolation.get_litellm_async_redis_cluster_class" + ) as mock_class: get_redis_async_client(startup_nodes=startup_nodes, credential_provider=provider) call_kwargs = mock_class.return_value.call_args[1] @@ -256,8 +262,12 @@ def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environ monkeypatch.setenv("REDIS_AZURE_AD_TOKEN", "true") with ( - patch("litellm._redis.create_gcp_iam_redis_connect_func") as mock_gcp, - patch("litellm._redis.create_azure_ad_redis_connect_func") as mock_azure, + patch( # test-quality-ok: the assertion is that this builder is never reached + "litellm._redis.create_gcp_iam_redis_connect_func" + ) as mock_gcp, + patch( # test-quality-ok: the assertion is that this builder is never reached + "litellm._redis.create_azure_ad_redis_connect_func" + ) as mock_azure, ): redis_kwargs = _get_redis_client_logic( host="redis-host", @@ -323,8 +333,12 @@ def test_async_direct_explicit_provider_is_preserved_when_normalization_is_bypas } with ( - patch("litellm._redis._get_redis_client_logic", return_value=redis_kwargs), - patch("litellm._redis.async_redis.Redis", autospec=True) as mock_redis, + patch( # test-quality-ok: bypassing normalization is what this test pins + "litellm._redis._get_redis_client_logic", return_value=redis_kwargs + ), + patch( # test-quality-ok: the constructor kwargs are the only observable + "litellm._redis.async_redis.Redis", autospec=True + ) as mock_redis, ): get_redis_async_client() @@ -343,8 +357,12 @@ def test_async_pool_explicit_provider_is_preserved_when_normalization_is_bypasse } with ( - patch("litellm._redis._get_redis_client_logic", return_value=redis_kwargs), - patch("litellm._redis.async_redis.BlockingConnectionPool", autospec=True) as mock_pool, + patch( # test-quality-ok: bypassing normalization is what this test pins + "litellm._redis._get_redis_client_logic", return_value=redis_kwargs + ), + patch( # test-quality-ok: the constructor kwargs are the only observable + "litellm._redis.async_redis.BlockingConnectionPool", autospec=True + ) as mock_pool, ): get_redis_connection_pool() @@ -360,7 +378,9 @@ async def test_redis_cache_test_connection_uses_shared_factory(clean_redis_envir client.ping = AsyncMock(return_value=True) client.aclose = AsyncMock() - with patch("litellm._redis.get_redis_async_client", return_value=client) as mock_factory: + with patch( # test-quality-ok: the factory call is what routing through it means + "litellm._redis.get_redis_async_client", return_value=client + ) as mock_factory: cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) result = await cache.test_connection() @@ -376,8 +396,12 @@ async def test_redis_cluster_cache_test_connection_uses_shared_factory(clean_red client.ping = AsyncMock(return_value=True) client.aclose = AsyncMock() - with patch("litellm._redis.get_redis_async_client", return_value=client) as mock_factory: - with patch("litellm._redis.get_redis_client", return_value=MagicMock(spec=redis.RedisCluster)): + with patch( # test-quality-ok: the factory call is what routing through it means + "litellm._redis.get_redis_async_client", return_value=client + ) as mock_factory: + with patch( # test-quality-ok: a real RedisCluster would slot-discover here + "litellm._redis.get_redis_client", return_value=MagicMock(spec=redis.RedisCluster) + ): cache = RedisClusterCache( startup_nodes=[{"host": "redis-host", "port": 6379}], credential_provider=provider ) @@ -395,8 +419,12 @@ def test_redis_cache_key_does_not_inspect_provider(clear_llm_client_cache): async_pool = MagicMock(spec=async_redis.BlockingConnectionPool) with ( - patch("litellm._redis.get_redis_client", return_value=sync_client), - patch("litellm._redis.get_redis_connection_pool", return_value=async_pool), + patch( # test-quality-ok: the hostile provider must not reach a real client + "litellm._redis.get_redis_client", return_value=sync_client + ), + patch( # test-quality-ok: the hostile provider must not reach a real pool + "litellm._redis.get_redis_connection_pool", return_value=async_pool + ), ): cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) second_cache = RedisCache(host="redis-host", port=6379, credential_provider=second_provider) @@ -903,7 +931,7 @@ def test_sync_sentinel_uses_sentinel_password_and_master_password(mock_sentinel_ ) -@patch("litellm._redis.redis.Sentinel") +@patch("litellm._redis.redis.Sentinel") # test-quality-ok: sentinel discovery needs live sentinels def test_sync_sentinel_keeps_provider_off_monitors_and_on_master(mock_sentinel_cls): provider = _StubCredentialProvider() mock_sentinel = MagicMock() diff --git a/uv.lock b/uv.lock index fae22e3759e..628483c0117 100644 --- a/uv.lock +++ b/uv.lock @@ -4342,7 +4342,6 @@ proxy = [ { name = "pyroscope-io", marker = "sys_platform != 'win32'" }, { name = "python-multipart" }, { name = "pyyaml" }, - { name = "redis" }, { name = "restrictedpython" }, { name = "rich" }, { name = "rq" }, @@ -4552,7 +4551,6 @@ requires-dist = [ { name = "python3-saml", marker = "extra == 'saml'", specifier = ">=1.16.0,<2.0" }, { name = "pyyaml", marker = "extra == 'cli'", specifier = ">=6.0.3,<7.0" }, { name = "pyyaml", marker = "extra == 'proxy'", specifier = ">=6.0.3,<7.0" }, - { name = "redis", marker = "extra == 'proxy'", specifier = ">=5.3.1,<6.0" }, { name = "redisvl", marker = "extra == 'extra-proxy'", specifier = ">=0.4.1,<1.0" }, { name = "requests", marker = "extra == 'cli'", specifier = ">=2.32.0,<3.0" }, { name = "resend", marker = "extra == 'extra-proxy'", specifier = ">=2.23.0,<3.0" }, From 01a1a3090ba4a66f52319e4f636a2d213049c29e Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Mon, 24 Aug 2026 17:46:58 -0400 Subject: [PATCH 4/8] test(redis): remove internal mocking from regressions --- tests/test_litellm/test_redis.py | 159 ++++++++++++++----------------- 1 file changed, 70 insertions(+), 89 deletions(-) diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 449f2d8dc14..ed2045ba76f 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -9,6 +9,7 @@ from redis.credentials import CredentialProvider import litellm from litellm._redis import ( + _async_auth_kwargs, _get_redis_client_logic, _get_redis_cluster_kwargs, _get_redis_env_kwarg_mapping, @@ -228,32 +229,28 @@ def test_async_url_pool_strips_userinfo_for_the_provider(clean_redis_environment assert connection.db == 3 -def test_sync_cluster_preserves_credential_provider_identity( # test-quality-ok: constructor kwargs are the only seam - clean_redis_environment, -): +def test_sync_cluster_preserves_credential_provider_identity(clean_redis_environment): provider = _StubCredentialProvider() startup_nodes = [{"host": "cluster-node", "port": 6379}] - with patch( # test-quality-ok: RedisCluster slot-discovers in its constructor - "litellm._redis.redis.RedisCluster", autospec=True - ) as mock_cluster_cls: - get_redis_client(startup_nodes=startup_nodes, credential_provider=provider) + with patch("redis.RedisCluster", autospec=True) as mock_cluster_cls: + get_redis_client(startup_nodes=startup_nodes, credential_provider=provider, password="redis-secret") - mock_cluster_cls.assert_called_once() - assert mock_cluster_cls.call_args[1].get("credential_provider") is provider + cluster_kwargs = mock_cluster_cls.call_args.kwargs + assert cluster_kwargs["credential_provider"] is provider + assert "password" not in cluster_kwargs + assert [(node.host, node.port) for node in cluster_kwargs["startup_nodes"]] == [("cluster-node", 6379)] def test_async_cluster_preserves_credential_provider_identity(clean_redis_environment): provider = _StubCredentialProvider() startup_nodes = [{"host": "cluster-node", "port": 6379}] - with patch( # test-quality-ok: the async cluster class is the only injection point here - "litellm.caching.redis_cluster_node_isolation.get_litellm_async_redis_cluster_class" - ) as mock_class: - get_redis_async_client(startup_nodes=startup_nodes, credential_provider=provider) + client = get_redis_async_client(startup_nodes=startup_nodes, credential_provider=provider) - call_kwargs = mock_class.return_value.call_args[1] - assert call_kwargs.get("credential_provider") is provider + assert client.connection_kwargs["credential_provider"] is provider + assert client.connection_kwargs["socket_keepalive"] is True + assert client.connection_kwargs["health_check_interval"] == REDIS_CLUSTER_HEALTH_CHECK_INTERVAL def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environment, monkeypatch): @@ -262,10 +259,10 @@ def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environ monkeypatch.setenv("REDIS_AZURE_AD_TOKEN", "true") with ( - patch( # test-quality-ok: the assertion is that this builder is never reached + patch( # test-quality-ok: an auto-auth callback built here is popped again by the provider branch, so the builders are the only place the wasted work is visible "litellm._redis.create_gcp_iam_redis_connect_func" ) as mock_gcp, - patch( # test-quality-ok: the assertion is that this builder is never reached + patch( # test-quality-ok: same as above, and reaching this one also builds an Azure credential the caller never asked for "litellm._redis.create_azure_ad_redis_connect_func" ) as mock_azure, ): @@ -323,108 +320,92 @@ def test_provider_free_url_is_left_untouched(clean_redis_environment): assert redis_kwargs["url"] == url -def test_async_direct_explicit_provider_is_preserved_when_normalization_is_bypassed(): +def test_async_auth_kwargs_supersedes_credentials_an_explicit_provider_replaces(): + """The shared seam both async entry points run through: a provider outranks every other + credential, and redis-py rejects a provider that arrives next to a username or password.""" provider = _StubCredentialProvider() - redis_kwargs = { - "host": "redis-host", - "port": 6379, - "credential_provider": provider, - "redis_connect_func": _gcp_marker_callback(), - } - with ( - patch( # test-quality-ok: bypassing normalization is what this test pins - "litellm._redis._get_redis_client_logic", return_value=redis_kwargs - ), - patch( # test-quality-ok: the constructor kwargs are the only observable - "litellm._redis.async_redis.Redis", autospec=True - ) as mock_redis, - ): - get_redis_async_client() + auth_kwargs = _async_auth_kwargs( + { + "host": "redis-host", + "port": 6379, + "credential_provider": provider, + "redis_connect_func": _gcp_marker_callback(), + "username": "url-user", + "password": "url-pass", + } + ) - call_kwargs = mock_redis.call_args[1] - assert call_kwargs["credential_provider"] is provider - assert "redis_connect_func" not in call_kwargs + assert auth_kwargs["credential_provider"] is provider + assert auth_kwargs["host"] == "redis-host" + assert auth_kwargs["port"] == 6379 + assert "redis_connect_func" not in auth_kwargs + assert "username" not in auth_kwargs + assert "password" not in auth_kwargs -def test_async_pool_explicit_provider_is_preserved_when_normalization_is_bypassed(): - provider = _StubCredentialProvider() - redis_kwargs = { - "host": "redis-host", - "port": 6379, - "credential_provider": provider, - "redis_connect_func": _gcp_marker_callback(), - } +def test_async_auth_kwargs_leaves_provider_free_kwargs_alone(): + redis_kwargs = {"host": "redis-host", "port": 6379, "username": "url-user", "password": "url-pass"} - with ( - patch( # test-quality-ok: bypassing normalization is what this test pins - "litellm._redis._get_redis_client_logic", return_value=redis_kwargs - ), - patch( # test-quality-ok: the constructor kwargs are the only observable - "litellm._redis.async_redis.BlockingConnectionPool", autospec=True - ) as mock_pool, - ): - get_redis_connection_pool() - - call_kwargs = mock_pool.call_args[1] - assert call_kwargs["credential_provider"] is provider - assert "redis_connect_func" not in call_kwargs + assert _async_auth_kwargs(redis_kwargs) == redis_kwargs @pytest.mark.asyncio async def test_redis_cache_test_connection_uses_shared_factory(clean_redis_environment): provider = _StubCredentialProvider() - client = MagicMock(spec=async_redis.Redis) - client.ping = AsyncMock(return_value=True) - client.aclose = AsyncMock() - with patch( # test-quality-ok: the factory call is what routing through it means - "litellm._redis.get_redis_async_client", return_value=client - ) as mock_factory: - cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) + with ( + patch("redis.Redis", autospec=True), + patch("redis.asyncio.BlockingConnectionPool", autospec=True), + patch("redis.asyncio.Redis", autospec=True) as mock_async_redis, + ): + mock_async_redis.return_value.ping = AsyncMock(return_value=True) + mock_async_redis.return_value.aclose = AsyncMock() + cache = RedisCache(host="redis-host", port=6379, credential_provider=provider, password="redis-secret") result = await cache.test_connection() + client_kwargs = mock_async_redis.call_args.kwargs assert result["status"] == "success" - call_kwargs = mock_factory.call_args.kwargs - assert call_kwargs["credential_provider"] is provider + assert client_kwargs["credential_provider"] is provider + assert "password" not in client_kwargs @pytest.mark.asyncio async def test_redis_cluster_cache_test_connection_uses_shared_factory(clean_redis_environment): provider = _StubCredentialProvider() - client = MagicMock(spec=async_redis.RedisCluster) - client.ping = AsyncMock(return_value=True) - client.aclose = AsyncMock() + recorder = MagicMock() - with patch( # test-quality-ok: the factory call is what routing through it means - "litellm._redis.get_redis_async_client", return_value=client - ) as mock_factory: - with patch( # test-quality-ok: a real RedisCluster would slot-discover here - "litellm._redis.get_redis_client", return_value=MagicMock(spec=redis.RedisCluster) - ): - cache = RedisClusterCache( - startup_nodes=[{"host": "redis-host", "port": 6379}], credential_provider=provider - ) + class _StubAsyncCluster: + """A real base class, because the production path subclasses this at call time.""" + + def __init__(self, **kwargs): + recorder(**kwargs) + + async def ping(self): + return True + + async def aclose(self): + return None + + with ( + patch("redis.RedisCluster", autospec=True), + patch("redis.asyncio.cluster.RedisCluster", _StubAsyncCluster), + ): + cache = RedisClusterCache(startup_nodes=[{"host": "redis-host", "port": 6379}], credential_provider=provider) result = await cache.test_connection() + cluster_kwargs = recorder.call_args.kwargs assert result["status"] == "success" - call_kwargs = mock_factory.call_args.kwargs - assert call_kwargs["credential_provider"] is provider + assert cluster_kwargs["credential_provider"] is provider def test_redis_cache_key_does_not_inspect_provider(clear_llm_client_cache): provider = _HostileCredentialProvider("synthetic-secret") second_provider = _StubCredentialProvider("another-token") - sync_client = MagicMock(spec=redis.Redis) - async_pool = MagicMock(spec=async_redis.BlockingConnectionPool) with ( - patch( # test-quality-ok: the hostile provider must not reach a real client - "litellm._redis.get_redis_client", return_value=sync_client - ), - patch( # test-quality-ok: the hostile provider must not reach a real pool - "litellm._redis.get_redis_connection_pool", return_value=async_pool - ), + patch("redis.Redis", autospec=True), + patch("redis.asyncio.BlockingConnectionPool", autospec=True), ): cache = RedisCache(host="redis-host", port=6379, credential_provider=provider) second_cache = RedisCache(host="redis-host", port=6379, credential_provider=second_provider) @@ -931,7 +912,7 @@ def test_sync_sentinel_uses_sentinel_password_and_master_password(mock_sentinel_ ) -@patch("litellm._redis.redis.Sentinel") # test-quality-ok: sentinel discovery needs live sentinels +@patch("redis.Sentinel") def test_sync_sentinel_keeps_provider_off_monitors_and_on_master(mock_sentinel_cls): provider = _StubCredentialProvider() mock_sentinel = MagicMock() From a18dfb2a9bf57d43f714b6b3485efa296f5c966e Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Tue, 25 Aug 2026 10:58:51 -0400 Subject: [PATCH 5/8] fix(redis): redact provider objects in debug logs --- litellm/_redis.py | 16 ++++++++++++++-- tests/test_litellm/test_redis.py | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/litellm/_redis.py b/litellm/_redis.py index 6ff4c292c47..c33ae45e988 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -764,8 +764,20 @@ def get_redis_connection_pool( return async_redis.BlockingConnectionPool(timeout=REDIS_CONNECTION_POOL_TIMEOUT, **redis_kwargs) +def _redis_kwargs_for_logging(redis_kwargs: dict) -> dict: + return { + key: "" + if key == "credential_provider" and value is not None + else "" + if key == "redis_connect_func" and value is not None + else value + for key, value in redis_kwargs.items() + } + + def _pretty_print_redis_config(redis_kwargs: dict) -> None: """Pretty print the Redis configuration using rich with sensitive data masking""" + redis_kwargs_for_logging: Final = _redis_kwargs_for_logging(redis_kwargs) try: import logging @@ -783,7 +795,7 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: masker = SensitiveDataMasker() # Mask sensitive data in redis_kwargs - masked_redis_kwargs = masker.mask_dict(redis_kwargs) + masked_redis_kwargs = masker.mask_dict(redis_kwargs_for_logging) # Create main panel title title: Final = Text("Redis Configuration", style="bold blue") @@ -846,7 +858,7 @@ def _pretty_print_redis_config(redis_kwargs: dict) -> None: except ImportError: # Fallback to simple logging if rich is not available masker = SensitiveDataMasker() - masked_redis_kwargs = masker.mask_dict(redis_kwargs) + masked_redis_kwargs = masker.mask_dict(redis_kwargs_for_logging) verbose_logger.info("Redis configuration: %s", masked_redis_kwargs) except Exception as e: verbose_logger.error("Error pretty printing Redis configuration: %s", e) diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index ed2045ba76f..0961357731d 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -15,6 +15,7 @@ from litellm._redis import ( _get_redis_env_kwarg_mapping, _get_redis_kwargs, _get_redis_url_kwargs, + _pretty_print_redis_config, get_redis_async_client, get_redis_client, get_redis_connection_pool, @@ -415,6 +416,25 @@ def test_redis_cache_key_does_not_inspect_provider(clear_llm_client_cache): assert first_key != second_cache._get_async_client_cache_key() +def test_pretty_print_never_expands_credential_provider(capsys): + secret = "aaaa-UNIQUE-SENTINEL-bbbb" + + with patch("litellm._redis.verbose_logger.isEnabledFor", return_value=True): + _pretty_print_redis_config( + redis_kwargs={ + "host": "redis-host", + "port": 6379, + "credential_provider": _HostileCredentialProvider(secret), + } + ) + + output = capsys.readouterr().out + assert secret not in output + assert "UNIQUE" not in output + assert "_payload" not in output + assert "credential_provider" in output + + def test_redis_cache_key_does_not_serialize_connect_func(): def connect(connection): return None From f304b2ba7b18b6352c804f56ac0443e3b57ba0cc Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Tue, 25 Aug 2026 11:08:07 -0400 Subject: [PATCH 6/8] fix(redis): satisfy lint budget for log helper --- litellm/_redis.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/litellm/_redis.py b/litellm/_redis.py index c33ae45e988..4cf903c4a2e 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -12,7 +12,7 @@ import json # s/o [@Frank Colson](https://www.linkedin.com/in/frank-colson-422b9b183/) for this redis implementation import os -from collections.abc import Callable +from collections.abc import Callable, Mapping from typing import Final from urllib.parse import urlsplit, urlunsplit @@ -764,7 +764,7 @@ def get_redis_connection_pool( return async_redis.BlockingConnectionPool(timeout=REDIS_CONNECTION_POOL_TIMEOUT, **redis_kwargs) -def _redis_kwargs_for_logging(redis_kwargs: dict) -> dict: +def _redis_kwargs_for_logging(redis_kwargs: Mapping[str, object]) -> Mapping[str, object]: return { key: "" if key == "credential_provider" and value is not None From 6dff830343b257e11365ec816a660b0eac83aaa5 Mon Sep 17 00:00:00 2001 From: eugene-yao-zocdoc Date: Tue, 25 Aug 2026 11:18:23 -0400 Subject: [PATCH 7/8] test(redis): explain debug logger patch --- tests/test_litellm/test_redis.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 0961357731d..70b972d3259 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -419,7 +419,9 @@ def test_redis_cache_key_does_not_inspect_provider(clear_llm_client_cache): def test_pretty_print_never_expands_credential_provider(capsys): secret = "aaaa-UNIQUE-SENTINEL-bbbb" - with patch("litellm._redis.verbose_logger.isEnabledFor", return_value=True): + with patch( # test-quality-ok: enable the debug-only printer without changing process-wide logger state + "litellm._redis.verbose_logger.isEnabledFor", return_value=True + ): _pretty_print_redis_config( redis_kwargs={ "host": "redis-host", From dcffd1da52627059b6c8f87da9eace673f2da8ae Mon Sep 17 00:00:00 2001 From: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Date: Wed, 26 Aug 2026 10:45:56 -0700 Subject: [PATCH 8/8] refactor(redis): drop docstrings restating the code --- litellm/_redis.py | 2 -- litellm/caching/redis_cache.py | 3 --- tests/test_litellm/test_redis.py | 8 -------- 3 files changed, 13 deletions(-) diff --git a/litellm/_redis.py b/litellm/_redis.py index 4cf903c4a2e..9381357931e 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -357,8 +357,6 @@ def get_redis_url_from_environment(): def _url_without_userinfo(url: str) -> str: - """redis-py rejects a url that carries its own username or password next to a credential - provider, so the provider's credentials replace whatever userinfo the url was configured with.""" parts: Final = urlsplit(url) netloc: Final = parts.netloc.rsplit("@", 1)[-1] return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index 0207a571dd6..68cad24ee96 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -402,9 +402,6 @@ class RedisCache(BaseCache): """ Generate a cache key for the async Redis client based on connection parameters. This ensures different Redis configurations use different cached clients. - - Kwargs the caller hands over as live objects (a credential provider, a connect func) are not - JSON-serializable and carry no stable value identity, so they key on instance identity. """ # Sort keys to ensure consistent hash regardless of parameter order sorted_kwargs: Final = sorted(self.redis_kwargs.items()) diff --git a/tests/test_litellm/test_redis.py b/tests/test_litellm/test_redis.py index 70b972d3259..826beb74a27 100644 --- a/tests/test_litellm/test_redis.py +++ b/tests/test_litellm/test_redis.py @@ -218,7 +218,6 @@ def test_async_url_pool_preserves_credential_provider_identity(clean_redis_envir def test_async_url_pool_strips_userinfo_for_the_provider(clean_redis_environment): - """The url allowlist has to carry the provider through, and redis-py rejects it next to userinfo.""" provider = _StubCredentialProvider() pool = get_redis_connection_pool(url="rediss://url-user:url-pass@redis-host:6379/3", credential_provider=provider) @@ -289,7 +288,6 @@ def test_explicit_provider_skips_automatic_auth_and_callback(clean_redis_environ ids=["certs-without-service-account", "both-alongside-a-provider"], ) def test_gcp_kwargs_never_survive_client_logic(clean_redis_environment, overrides): - """redis.Redis has no gcp_* parameters, so anything left behind raises TypeError on connect.""" redis_kwargs = _get_redis_client_logic( host="redis-host", port=6379, @@ -302,7 +300,6 @@ def test_gcp_kwargs_never_survive_client_logic(clean_redis_environment, override def test_provider_keeps_the_rest_of_the_url_intact(clean_redis_environment): - """Stripping the userinfo must not take the database path, query, or scheme with it.""" provider = _StubCredentialProvider() redis_kwargs = _get_redis_client_logic( @@ -322,8 +319,6 @@ def test_provider_free_url_is_left_untouched(clean_redis_environment): def test_async_auth_kwargs_supersedes_credentials_an_explicit_provider_replaces(): - """The shared seam both async entry points run through: a provider outranks every other - credential, and redis-py rejects a provider that arrives next to a username or password.""" provider = _StubCredentialProvider() auth_kwargs = _async_auth_kwargs( @@ -377,8 +372,6 @@ async def test_redis_cluster_cache_test_connection_uses_shared_factory(clean_red recorder = MagicMock() class _StubAsyncCluster: - """A real base class, because the production path subclasses this at call time.""" - def __init__(self, **kwargs): recorder(**kwargs) @@ -449,7 +442,6 @@ def test_redis_cache_key_does_not_serialize_connect_func(): def test_redis_cache_key_keys_opaque_kwargs_by_identity(): - """Any object a caller passes through must key by identity rather than crash the JSON dump.""" class _Opaque: pass