litellm/tests/unit/redis/stores/test_router_usage.py
yujonglee 4616174c45
refactor(redis): move per-request miss, settlement and shutdown-drain tracking from Python into Rust (#51384)
Rust already sent each request's Redis batches, but Python kept the rules about them. Three pieces of per-request
state now live on the Rust RequestRedis: the keys the request's MGET found absent, the flag saying its committed
spend increment has its reply, and the registry of requests whose post-call writes are still unsent at shutdown.
Python only passes the request to the store call, and the Python test doubles no longer re-implement those rules

Auth write-backs and prefetch reads always ride the request's pre-call batch, so a write inside a request cannot
leave its key marked absent. One post-call flush runs at a time, and the shutdown drain waits for it
2026-11-20 17:57:37 +09:00

166 lines
6.8 KiB
Python

import asyncio
from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Final, TypeVar
import pytest
from litellm import Router
from litellm._internal_context import current_service_target
from litellm.caching.redis_batch import request_redis_batch_scope
from litellm.caching.redis_cache import RedisCache
from litellm.redis.stores.connection import connect
from litellm.redis.stores.router_usage import CounterIncrement, RouterUsageStore, UsageCounter
from litellm.rust_bridge._native import NativeRedisClient
from litellm.types.utils import ModelResponse
from tests.unit.caching.redis_batch_double import FakeNatives, fake_send
T = TypeVar("T")
def _done(value: T) -> "asyncio.Future[T]":
future: Final[asyncio.Future[T]] = asyncio.get_running_loop().create_future()
future.set_result(value)
return future
@dataclass
class FakeUsage:
has_redis: bool = False
counts: dict[UsageCounter, float] = field(default_factory=dict)
calls: list[tuple[str, object, str | None]] = field(default_factory=list)
def attach(self, client: NativeRedisClient, /) -> bool:
attached: Final = not self.has_redis
self.has_redis = True
return attached
def increment_sync(self, counter: UsageCounter, value: float, ttl_seconds: int) -> float:
self.calls.append(("increment", (counter, value, ttl_seconds), current_service_target()))
self.counts[counter] = self.counts.get(counter, 0) + value
return self.counts[counter]
def increment(self, counter: UsageCounter, value: float, ttl_seconds: int) -> "asyncio.Future[float]":
return _done(self.increment_sync(counter, value, ttl_seconds))
def increment_deployment_sync(
self,
deployment_id: str,
model: str | None,
minute: str,
tokens: float,
requests: int,
) -> None:
self.calls.append(("deployment", (deployment_id, model, minute, tokens, requests), current_service_target()))
tpm: Final = UsageCounter("global_router", deployment_id, model, minute, "tpm")
rpm: Final = UsageCounter("global_router", deployment_id, model, minute, "rpm")
self.counts[tpm] = self.counts.get(tpm, 0) + tokens
self.counts[rpm] = self.counts.get(rpm, 0) + requests
def increment_deployment(
self,
deployment_id: str,
model: str | None,
minute: str,
tokens: float,
requests: int,
) -> "asyncio.Future[None]":
self.increment_deployment_sync(deployment_id, model, minute, tokens, requests)
return _done(None)
def get_many_sync(self, counters: Sequence[UsageCounter]) -> list[float | None]:
return [self.counts.get(counter) for counter in counters]
def get_many(self, counters: Sequence[UsageCounter]) -> "asyncio.Future[list[float | None]]":
return _done(self.get_many_sync(counters))
def flush_local_counters(self) -> None:
self.counts.clear()
def snapshot(self) -> dict[str, float]:
return {}
@pytest.mark.asyncio
async def test_counters_cross_the_bridge_as_domain_tuples_under_the_router_usage_target() -> None:
handle: Final = FakeUsage()
store: Final = RouterUsageStore(handle) # pyright: ignore[reportArgumentType] # implements what the test calls
counter: Final = UsageCounter("global_router", "dep", None, "12-34", "rpm")
await store.increment(counter, 1, 60)
await store.increment_deployment("dep", "model", "12-34", 7.5, 1)
assert handle.calls == [
("increment", (counter, 1, 60), "router_usage"),
("deployment", ("dep", "model", "12-34", 7.5, 1), "router_usage"),
]
assert await store.get_many((counter, UsageCounter("global_router", "dep", "model", "12-34", "tpm"))) == [1, 7.5]
@pytest.mark.parametrize(
("counter", "key"),
[
(UsageCounter("global_router", "dep", None, "09-05", "rpm"), "global_router:dep:None:rpm:09-05"),
(
UsageCounter.for_deployment("dep", "openai/gpt-5.4-nano", "rpm", "12-34"),
"dep:openai/gpt-5.4-nano:rpm:12-34",
),
(UsageCounter.for_deployment(f"{7}", f"{None}", "tpd", "2026-11-10"), "7:None:tpd:2026-11-10"),
],
)
def test_counters_count_under_mains_keys(counter: UsageCounter, key: str) -> None:
store: Final = RouterUsageStore(connect(None).router_usage())
store.increment_local(CounterIncrement(counter, 3, 60))
assert store.snapshot() == {key: 3}
@pytest.mark.asyncio
async def test_late_attach_keeps_the_counts_this_router_already_holds() -> None:
store: Final = RouterUsageStore(connect(None).router_usage())
counters: Final = (
UsageCounter("global_router", "dep", "model", "12-34", "tpm"),
UsageCounter("global_router", "dep", "model", "12-34", "rpm"),
)
await store.increment_deployment("dep", "model", "12-34", 7.5, 1)
store.attach_redis(connect(RedisCache(host="redis.internal")))
assert await store.get_many(counters) == [7.5, 1]
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ("flush_cache", "reset"))
async def test_router_reset_clears_usage_and_failure_counters(operation: str) -> None:
router: Final = Router(
model_list=[
{
"model_name": "g",
"litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-test", "rpm": 10},
"model_info": {"id": "dep"},
}
]
)
cooldowns: Final = router.health().cooldowns.cooldown_store
served: Final = ModelResponse(usage={"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7})
metadata: Final = {"model_info": {"id": "dep"}, "deployment": "openai/gpt-4o", "model_group": "g"}
await router.increment_deployment_usage_for_response(served, {"model": "g", "metadata": metadata})
assert await router.health().usage("g") == (7, 1)
assert cooldowns.increment_allowed_fails("dep", None, 30.0) == 1
getattr(router, operation)()
assert await router.health().usage("g") == (None, None)
assert cooldowns.increment_allowed_fails("dep", None, 30.0) == 1
@pytest.mark.asyncio
async def test_inside_a_request_deployment_increments_go_out_on_their_own_trip_like_main():
handle: Final = FakeUsage()
store: Final = RouterUsageStore(handle) # pyright: ignore[reportArgumentType] # implements what the test calls
natives: Final = FakeNatives()
await store.increment_deployment("dep", "model", "12-34", 7.5, 1)
with request_redis_batch_scope(post_call_deadline=60, native_factory=natives, native_send_factory=fake_send) as request: # pyright: ignore[reportArgumentType] # test double
await store.increment_deployment("dep", "model", "12-34", 2, 1)
await request.flush_post_call()
assert [call[0] for call in handle.calls] == ["deployment", "deployment"]
assert all(not native.events for native in natives.built)