litellm/tests/unit/redis/stores/test_spend_counters.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

201 lines
8.2 KiB
Python

import json
from typing import Final
import pytest
from litellm._internal_context import current_service_target
from litellm.caching.redis_batch import Batch, request_redis_batch_scope
from litellm.caching.redis_cache import RedisCache
from litellm.redis.stores.connection import RedisStores, connect
from litellm.redis.stores.spend_counters import (
SPEND_COUNTERS_TARGET,
SpendCounterStore,
committed_counter,
end_user_counter,
is_unavailable,
key_counter,
key_window_counter,
model_access_group_counter,
org_counter,
project_counter,
shadow_eval_counter,
tag_counter,
team_counter,
team_member_counter,
team_window_counter,
user_counter,
)
from litellm.redis.store_settings import RedisStoreSettings
from litellm.rust_bridge._native import NativeRedisClient, NativeRedisStoreError, NativeSpendCounters, SpendRead
from tests.unit.caching.redis_batch_double import FakeNatives, fake_send
from .spend_counters_double import FakeSpendCounters
_KEYS: Final = (
(
key_counter("88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b"),
"spend:key:88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",
),
(key_window_counter("88dc28d0", "30d"), "spend:key:88dc28d0:window:30d"),
(team_counter("team-a"), "spend:team:team-a"),
(team_window_counter("team-a", "1h"), "spend:team:team-a:window:1h"),
(team_member_counter("user:with:colons", "team-a"), "spend:team_member:user:with:colons:team-a"),
(user_counter("user@example.com"), "spend:user:user@example.com"),
(end_user_counter("customer é 1"), "spend:end_user:customer é 1"),
(org_counter("org-1"), "spend:org:org-1"),
(tag_counter("prod:eu"), "spend:tag:prod:eu"),
(project_counter("proj-1"), "spend:project:proj-1"),
(model_access_group_counter("gpt-group"), "spend:model_access_group:gpt-group"),
(shadow_eval_counter("job-7"), "spend:shadow_eval:job-7"),
("spend:customer_org:tenant:lifetime", "spend:customer_org:tenant:lifetime"),
(
"spend:customer_team:tenant:team:2026-01-01T00:00:00+00:00",
"spend:customer_team:tenant:team:2026-01-01T00:00:00+00:00",
),
("spend:customer_member:user@example.com:lifetime", "spend:customer_member:user@example.com:lifetime"),
(committed_counter(key_counter("88dc28d0")), "spend:committed:key:88dc28d0"),
(committed_counter(team_counter("team-a")), "spend:committed:team:team-a"),
(committed_counter(user_counter("user@example.com")), "spend:committed:user:user@example.com"),
(committed_counter(org_counter("org-1")), "spend:committed:org:org-1"),
(committed_counter(end_user_counter("customer é 1")), "spend:committed:end_user:customer é 1"),
)
@pytest.mark.parametrize(("built", "key"), _KEYS, ids=[key for _, key in _KEYS])
def test_python_builds_every_key_the_native_store_formats(built: str, key: str) -> None:
store: Final = NativeSpendCounters(None)
store.set_local(built, 1.5)
assert built == key
assert store.snapshot() == {key: 1.5}
@pytest.mark.parametrize(
("spend", "wire"), [(0.0, "0.0"), (12, "12"), (1e-05, "1e-05"), (0.30000000000000004, "0.30000000000000004")]
)
def test_a_reset_writes_what_redis_cache_set_cache_writes(spend: float, wire: str) -> None:
assert json.dumps(spend) == wire
@pytest.mark.parametrize(("spend", "wire"), [(2.5, "2.5"), (100, "100"), (1e-05, "1e-05")])
def test_a_repair_writes_what_redis_cache_set_max_writes(spend: float, wire: str) -> None:
assert str(spend) == wire
@pytest.mark.parametrize(("wire", "spend"), [("7.25", 7.25), ("3", 3), ("0.0", 0.0), ("1e-05", 1e-05)])
def test_a_read_decodes_what_redis_cache_decodes(wire: str, spend: float) -> None:
decoded: Final = RedisCache._get_cache_logic( # pyright: ignore[reportPrivateUsage] # main's codec is the contract
RedisCache.__new__(RedisCache), wire.encode()
)
assert decoded == spend
assert type(decoded) is type(spend)
@pytest.mark.parametrize(
"key",
[
"spend_db_floor:spend:key:k",
"virtual_key_spend:k:gpt:1d",
"spend:unknown:k",
"spend:committed:key:k:window:1d",
"spend:committed:tag:prod",
"spend:committed:committed:key:k",
],
)
def test_the_native_store_refuses_keys_outside_the_spend_counter_keyspace(key: str) -> None:
with pytest.raises(ValueError, match="a spend counter is a spend:\* key"):
NativeSpendCounters(None).get_local(key)
@pytest.mark.asyncio
async def test_without_redis_the_native_store_counts_and_answers_from_memory() -> None:
store: Final = SpendCounterStore(connect(None).spend_counters())
first: Final = await store.increment("spend:key:k", 2)
second: Final = await store.increment_many((("spend:key:k", 0.5), ("spend:team:t", 1.0)))
seeded: Final = await store.seed("spend:org:o", 4.0, increment_if_lost=False)
repaired: Final = await store.set_max("spend:key:k", 9.0)
assert (first, second, seeded, repaired) == (2, (2.5, 1.0), 4.0, None)
assert await store.read("spend:key:k") == (9.0, False)
assert await store.read_many(("spend:key:k",), batch=Batch.NONE) is None
assert not store.has_redis
assert not store.increment_many_post_call((("spend:key:k", 1.0),))
@pytest.mark.parametrize(
"kind, dropped",
[("timeout", True), ("breaker_open", True), ("transport", False), ("rejected", False), ("memory", False)],
)
def test_only_a_timeout_or_an_open_breaker_lets_a_post_call_increment_drop(kind: str, dropped: bool) -> None:
assert is_unavailable(NativeRedisStoreError(kind, "message")) is dropped
assert not is_unavailable(TimeoutError(kind))
def _connection(host: str, *, ttl: int) -> RedisStores:
client: Final = NativeRedisClient.connect(
RedisStoreSettings(redis_kwargs={"host": host, "port": 1}, namespace=None, default_ttl=ttl, breaker=None)
)
assert client is not None
return RedisStores(client)
def test_redis_attaches_once_keeping_memory_and_its_ttl_is_the_lease_the_store_reports() -> None:
store: Final = SpendCounterStore(connect(None).spend_counters())
store.set_local(team_counter("team-a"), 4.5)
store.attach_redis(connect(None))
assert not store.has_redis
store.attach_redis(_connection("127.0.0.1", ttl=30))
store.attach_redis(_connection("127.0.0.2", ttl=90))
assert store.has_redis
assert store.redis_ttl == 30
assert store.get_local(team_counter("team-a")) == 4.5
@pytest.mark.asyncio
async def test_post_call_increments_go_on_the_requests_native_post_call_batch_under_the_spend_counters_target() -> None:
natives: Final = FakeNatives()
targets: Final[list[str | None]] = []
class Recording(FakeSpendCounters):
def increment_many_post_call(self, request: object, increments: object) -> bool:
targets.append(current_service_target())
return super().increment_many_post_call(request, increments) # pyright: ignore[reportArgumentType] # recorded as given
spend: Final = Recording()
store: Final = spend.store()
outside: Final = store.increment_many_post_call((("spend:key:k", 1.0),))
with request_redis_batch_scope(native_factory=natives, native_send_factory=fake_send): # pyright: ignore[reportArgumentType] # test double
inside: Final = store.increment_many_post_call((("spend:key:k", 1.0),))
empty: Final = store.increment_many_post_call(())
assert (outside, inside, empty) == (False, True, False)
assert spend.post_call == [(natives.built[0], (("spend:key:k", 1.0),))]
assert targets == [SPEND_COUNTERS_TARGET]
@pytest.mark.asyncio
async def test_an_unreachable_redis_fails_writes_as_transport_and_serves_reads_from_memory() -> None:
store: Final = NativeSpendCounters(
NativeRedisClient.connect(
RedisStoreSettings(
redis_kwargs={"host": "127.0.0.1", "port": 1, "socket_timeout": 0.2},
namespace=None,
default_ttl=60,
breaker=None,
)
)
)
store.set_local("spend:key:k", 4.0)
with pytest.raises(NativeRedisStoreError) as failure:
await store.increment("spend:key:k", 1.0)
assert failure.value.args[0] == "transport"
assert not is_unavailable(failure.value)
assert await store.read("spend:key:k") == SpendRead(None, from_redis=False)