litellm/tests/unit/redis/stores/test_cache_invalidation.py
yujonglee 6245f94734
Some checks failed
smoke / all-extras-py (push) Blocked by required conditions
unit / key-generation (push) Blocked by required conditions
unit / lint-runtime (push) Blocked by required conditions
smoke / smoke-rust-bridge (push) Waiting to run
smoke / dashboard-build (push) Waiting to run
smoke / py (push) Blocked by required conditions
unit / logging-misc (push) Blocked by required conditions
smoke / windows-sdk (push) Waiting to run
smoke / proxy-build-from-pip (push) Waiting to run
unit / mcp-oauth (push) Blocked by required conditions
smoke / smoke passed (push) Blocked by required conditions
LiteLLM Rust DB / db-queries (push) Waiting to run
unit / llms-vertex-ai (push) Blocked by required conditions
CodSpeed Benchmarks / benchmarks (push) Waiting to run
unit / mcp-elicitation (push) Blocked by required conditions
Cost map pins recheck / rerun-cost-map-guard (push) Waiting to run
unit / mcp-server (push) Blocked by required conditions
Publish lint base counts / publish (basedpyright, litellm/scripts/type_check_gate.py) (push) Waiting to run
unit / proxy-auth (push) Blocked by required conditions
unit / proxy-runtime (push) Blocked by required conditions
unit / caching-local (push) Blocked by required conditions
unit / enterprise-repositories-secrets (push) Blocked by required conditions
Publish lint base counts / publish (openapi-docs, litellm/scripts/openapi_docs_gate.py) (push) Waiting to run
unit / proxy-extras (push) Blocked by required conditions
Publish lint base counts / publish (ruff-strict, litellm/scripts/ruff_strict_gate.py) (push) Waiting to run
unit / proxy-hooks-client (push) Blocked by required conditions
Publish lint base counts / publish (test-quality, litellm/scripts/test_quality_gate.py) (push) Waiting to run
unit / proxy-infra-db-spend (push) Blocked by required conditions
Publish lint base counts / publish (type-discipline, litellm/scripts/type_discipline_gate.py) (push) Waiting to run
unit / proxy-infra-root-a-p (push) Blocked by required conditions
unit / proxy-server-core (push) Blocked by required conditions
unit / core-utils (push) Blocked by required conditions
unit / proxy-server (push) Blocked by required conditions
unit / OpenAI 2.20.0 compatibility (push) Blocked by required conditions
unit / redis-py 6.4.0 compatibility (push) Blocked by required conditions
unit / redis-py 8.0.1 compatibility (push) Blocked by required conditions
Root entry limit / root-entry-limit (push) Waiting to run
unit / proxy-infra-root-q-z (push) Blocked by required conditions
unit / root (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
unit / proxy-infra-routing (push) Blocked by required conditions
unit / custom-logging (push) Blocked by required conditions
unit / proxy-utils (push) Blocked by required conditions
unit / endpoints (push) Blocked by required conditions
unit / lens-python-310 (push) Blocked by required conditions
unit / OpenAI 3.0.0 compatibility (push) Blocked by required conditions
unit / redis-py 7.4.1 compatibility (push) Blocked by required conditions
GitHub Actions Security Analysis / zizmor (push) Waiting to run
lint / lint plan (push) Waiting to run
unit / proxy-subprocess (push) Blocked by required conditions
unit / router (push) Blocked by required conditions
unit / core-auth-request (push) Blocked by required conditions
unit / enterprise-package (push) Blocked by required conditions
unit / ui-unit (push) Waiting to run
unit / OpenAI 3.25.0 compatibility (push) Blocked by required conditions
unit / unit passed (push) Blocked by required conditions
lint / python (push) Blocked by required conditions
lint / typecheck (push) Blocked by required conditions
unit / responses-caching-types (push) Blocked by required conditions
unit / db-and-spend (push) Blocked by required conditions
unit / core-auth-spend (push) Blocked by required conditions
unit / integrations (push) Blocked by required conditions
lint / e2e-harness (push) Blocked by required conditions
unit / rust-bridge-harness (push) Blocked by required conditions
unit / core-logging-request-path (push) Blocked by required conditions
unit / llms-anthropic (push) Blocked by required conditions
lint / secret-scan (push) Waiting to run
unit / llms-providers (push) Blocked by required conditions
unit / endpoints-and-responses (push) Blocked by required conditions
unit / core-management-cost (push) Blocked by required conditions
unit / llms-bedrock (push) Blocked by required conditions
lint / ui (push) Blocked by required conditions
unit / proxy-endpoints (push) Blocked by required conditions
lint / ui-api-types (push) Blocked by required conditions
unit / proxy-feature-endpoints (push) Blocked by required conditions
unit / core-utils-route (push) Blocked by required conditions
unit / llms-openai-meta (push) Blocked by required conditions
unit / docs (push) Blocked by required conditions
unit / redis-py 5.3.1 compatibility (push) Blocked by required conditions
unit / rust-bridge (push) Waiting to run
unit / plan (push) Waiting to run
lint / code-quality (push) Blocked by required conditions
unit / auth-checks (push) Blocked by required conditions
unit / enterprise-routing (push) Blocked by required conditions
lint / ci-coverage (push) Blocked by required conditions
unit / budgets (push) Blocked by required conditions
unit / core-router (push) Blocked by required conditions
unit / changed-tests (push) Blocked by required conditions
lint / semgrep (push) Blocked by required conditions
unit / guardrails-hooks (push) Blocked by required conditions
unit / core-router-core (push) Blocked by required conditions
unit / enterprise-managed-files (push) Blocked by required conditions
unit / helm (push) Blocked by required conditions
lint / lint passed (push) Blocked by required conditions
unit / jwt-and-keys (push) Blocked by required conditions
unit / core-router-retries (push) Blocked by required conditions
Terraform Provider / gofmt, vet, build, test (push) Has been cancelled
Terraform Provider / Provider endpoints vs proxy OpenAPI schema (push) Has been cancelled
refactor(auth_cache_invalidation): move the invalidation channel to the native client (#51135)
* refactor(auth_cache_invalidation): move the invalidation channel to the native client

The litellm_proxy.auth_cache_invalidation channel is now a redis-store family on the redis-client publish and subscribe. It keeps the channel name, the message codec main writes and reads, the bounded background publish, the pipelined bulk eviction and the resubscribing stream

Each message is applied natively to the auth cache and the spend counters, then handed to a host callback for the caches still in Python. An eviction from another worker also voids the lease this worker holds on that key. The redis-py publisher and AuthCacheInvalidationSubscriber are deleted

The channel is prefixed with RedisCache.namespace, handed over when the channel starts, because the native client's own namespace misses one that Cache assigns after building the RedisCache. Publishes go through RedisClient::publish, outside the circuit breaker like the redis-py pub/sub client main published through, so an invalidation is sent the moment Redis is back and not after the breaker's recovery timeout

* refactor: rename native cache invalidation modules

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-21 18:58:27 +09:00

182 lines
6.9 KiB
Python

import json
from collections.abc import Sequence
from typing import Final
import pytest
from pydantic import TypeAdapter, ValidationError
from litellm._internal_context import current_service_target
from litellm.caching.in_memory_cache import InMemoryCache
from litellm.caching.redis_cache import RedisCache
from litellm.constants import AUTH_OBJECTS_TARGET
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.redis.stores.auth_cache import AuthCacheStore, AuthObject
from litellm.redis.stores.cache_invalidation import CacheInvalidation, PythonCaches, connect_invalidation
from litellm.redis.stores.connection import connect
from litellm.redis.stores.spend_counters import SpendCounterStore
from tests.unit.redis.stores.auth_cache_double import shared_cache
from tests.unit.redis.stores.cache_invalidation_double import FakeChannel, Message
from tests.unit.redis.stores.spend_counters_double import FakeSpendCounters
_PAYLOAD: Final = TypeAdapter(dict[str, object])
def _mains_json(message: Message) -> str:
return json.dumps(
{field: value for field, value in zip(("cache_key", "new_value", "ttl"), message) if value is not None}
)
def _number(value: object) -> float | None:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
return float(value)
def _as_mains_subscriber_applies(payload: bytes) -> Message | None:
try:
decoded: Final = _PAYLOAD.validate_json(payload.decode("utf-8", errors="replace"))
except ValidationError:
return None
cache_key: Final = decoded.get("cache_key")
if not isinstance(cache_key, str):
return None
new_value: Final = _number(decoded.get("new_value"))
return (cache_key, new_value, None if new_value is None else _number(decoded.get("ttl")))
@pytest.mark.parametrize(
("message", "payload"),
[
(("team_id:t1", None, None), r'{"cache_key": "team_id:t1"}'),
(("t\u00e9", None, None), r'{"cache_key": "t\u00e9"}'),
(("spend:key:abc", 1.5, 60), r'{"cache_key": "spend:key:abc", "new_value": 1.5, "ttl": 60}'),
(
("spend_db_floor:spend:team:t", 0.1 + 0.2, 5),
r'{"cache_key": "spend_db_floor:spend:team:t", "new_value": 0.30000000000000004, "ttl": 5}',
),
(("spend:user:u", 0.0, None), r'{"cache_key": "spend:user:u", "new_value": 0.0}'),
],
)
def test_a_message_is_mains_json(message: Message, payload: str) -> None:
assert _mains_json(message) == payload
@pytest.mark.parametrize(
("payload", "expected"),
[
(rb'{"cache_key": "team_id:t1"}', ("team_id:t1", None, None)),
(rb'{"cache_key": "k", "ttl": 60}', ("k", None, None)),
(rb'{"cache_key": "k", "new_value": 2, "ttl": 60}', ("k", 2.0, 60.0)),
(rb'{"cache_key": "k", "new_value": true}', ("k", None, None)),
(rb'{"cache_key": "k", "new_value": "1.5"}', ("k", None, None)),
(rb'{"cache_key": "k", "new_value": 1.5, "ttl": "60"}', ("k", 1.5, None)),
(b'{"cache_key": "k\xff"}', ("k\ufffd", None, None)),
(rb'{"cache_key": 7}', None),
(rb'["team_id:t1"]', None),
(b"not json", None),
],
)
def test_a_message_reads_as_mains_subscriber_reads_it(payload: bytes, expected: Message | None) -> None:
applied: Final = _as_mains_subscriber_applies(payload)
assert applied == expected
assert applied is None or all(value is None or type(value) is float for value in applied[1:])
def test_a_value_is_written_into_the_copies_and_leaves_the_evicted_caches_alone() -> None:
copy: Final = InMemoryCache()
copy.set_cache("spend:key:k-1", 9.0)
evicted: Final = InMemoryCache()
evicted.set_cache("spend:key:k-1", "hook state")
PythonCaches(copies=(copy,), evicted=(evicted,)).apply("spend:key:k-1", 0.0, 60.0)
assert copy.get_cache("spend:key:k-1") == 0.0
assert evicted.get_cache("spend:key:k-1") == "hook state"
def test_an_eviction_drops_the_key_from_the_copies_and_the_evicted_caches() -> None:
copy: Final = InMemoryCache()
evicted: Final = InMemoryCache()
for cache in (copy, evicted):
cache.set_cache("team_id:t-1", "stale")
cache.set_cache("team_id:t-2", "kept")
PythonCaches(copies=(copy,), evicted=(evicted,)).apply("team_id:t-1", None, 60.0)
assert [cache.get_cache("team_id:t-1") for cache in (copy, evicted)] == [None, None]
assert [cache.get_cache("team_id:t-2") for cache in (copy, evicted)] == ["kept", "kept"]
@pytest.mark.asyncio
async def test_an_eviction_from_another_worker_voids_a_lease_this_worker_holds() -> None:
cache: Final = UserApiKeyCache()
team: Final = AuthObject.team("t-1")
lease: Final = await cache.lease(team)
PythonCaches(on_eviction=(cache.void_lease,)).apply(team.key, None, None)
assert await cache.async_set_leased(lease, {"team_id": "t-1"}, ttl=60) is False
assert cache.get_cache(team) is None
def _native_spend_counters() -> SpendCounterStore:
return SpendCounterStore(connect(None).spend_counters())
def test_connect_invalidation_is_none_without_a_redis_client() -> None:
assert (
connect_invalidation(connect(None), None, UserApiKeyCache().store, _native_spend_counters(), PythonCaches())
is None
)
@pytest.mark.parametrize(
("auth_cache", "spend_counters"),
[
(shared_cache()[0].store, _native_spend_counters()),
(UserApiKeyCache().store, FakeSpendCounters().store()),
],
ids=["auth-cache-not-native", "spend-counters-not-native"],
)
def test_connect_invalidation_refuses_a_store_that_cannot_take_a_native_eviction(
auth_cache: AuthCacheStore, spend_counters: SpendCounterStore
) -> None:
redis: Final = connect(RedisCache(host="127.0.0.1", port=1))
with pytest.raises(TypeError, match="not the native store"):
_ = connect_invalidation(redis, None, auth_cache, spend_counters, PythonCaches())
def test_connect_invalidation_builds_the_channel_over_native_stores() -> None:
invalidation: Final = connect_invalidation(
connect(RedisCache(host="127.0.0.1", port=1, namespace="tenant")),
"tenant",
UserApiKeyCache().store,
_native_spend_counters(),
PythonCaches(),
)
assert invalidation is not None
assert invalidation.channel == "tenant:litellm_proxy.auth_cache_invalidation"
class _TargetRecordingChannel(FakeChannel):
targets: tuple[str | None, ...] = ()
async def broadcast_evictions(self, cache_keys: Sequence[str]) -> None:
self.targets = (*self.targets, current_service_target())
await super().broadcast_evictions(cache_keys)
@pytest.mark.asyncio
async def test_broadcast_evictions_skips_an_empty_batch_and_sends_the_rest_in_one() -> None:
handle: Final = _TargetRecordingChannel()
invalidation: Final = CacheInvalidation(handle)
await invalidation.broadcast_evictions([])
await invalidation.broadcast_evictions(["team_id:t-1", "user-1"])
assert handle.bulk == [("team_id:t-1", "user-1")]
assert handle.targets == (AUTH_OBJECTS_TARGET,)