litellm/tests/unit/router_strategy/test_base_routing_strategy.py
yujonglee b88e4bff6b
refactor(router): count the whole router_usage family on the native store (#50862)
* refactor(router): count the whole router_usage family on the native store

usage-based-routing-v2, the model rate limit check (tpm, rpm, tpd, rpd) and the
io-token check (itpm, otpm) count through the native router_usage store, next
to the router core's global_router tpm and rpm. The pick's usage read rides the
native pre-call batch and settles on the batch reply, keeping DualCache's
per-key read throttle, and the success tpm increment rides the native
post-call batch after counting in memory. io-token reservations stash their
counter's fields instead of a Redis key. Redis keys and values are unchanged.

A Redis service event is reported in a context named for whose it is, either
the calling store op's, the request whose post-call batch its deadline sends,
or nobody's for breaker transitions and unscoped calls. The deadline's tag is
built when a post-call declaration arms it, so that flush parents under the
request's span even though auth sets the span after the batch scope opens. An
SDK call anchors the span its caller passed, so its usage reads and io-token
refunds parent under it without a span argument threaded through the family.

* fix(redis): keep an int counter past i64 above the limit instead of wrapping

Number::add summed two ints with plain i64 addition. With Redis off and the OTPM counter at 1, a request with max_tokens=2**63-1 passed the MAX_INCREMENT check, and the memory count wrapped negative in a release build, so it passed admission and let other requests past the cap. Python's int never overflows, so main sees a count above the limit, rolls it back and answers 429

An int sum past i64 now becomes the nearest float, which compares above any limit the way Python's int does. The rollback after such a refusal can leave the count one token low, since the float cannot hold 2**63 exactly

* fix(logging): run every callback under the span an SDK caller passed

Native Redis service spans take their parent from the request span contextvar. The proxy sets it at auth and the SDK router scopes it around the routed call, but a streamed response is iterated after that scope closes, so its callbacks saw no span. Three callbacks reopened the scope from kwargs by hand, and the sync stream path had no wrap at all because its success handler runs on an executor thread

The four Logging handlers now anchor the span from model_call_details around their dispatch, so every CustomLogger callback sees it, streamed or not, sync or async, with or without a Router. The per-callback wraps in lowest_tpm_rpm_v2 and model_rate_limit_check are gone. A span already anchored, as on the proxy, is kept

* test(logging): cover a mid-stream failure, and drop the span wrap in Router._release

The callback span test now also breaks a stream after its first chunk, sync and async, through a custom provider, so the failure handlers the stream wrapper starts on a bare thread are covered too

A probe through the Router showed Router._release only runs inside the routed attempt, where the router has already anchored the span, and never after a stream returns. Its own wrap was a no-op, so it is gone

* fix(router): refuse an io-token reservation past its limit before counting it

The overflow fix let a reservation near i64::MAX become a float, so the count still read above the limit and the request got its 429. But the rollback subtracted the same amount from that float, and with OTPM usage at 40 the count came back as 0.0, so later requests reused capacity already spent

A reservation above its limit now gets the 429 before the store is touched, in the async and sync paths. On main the count went up and straight back down for such a reservation, so the answer and the count after it are the same as main's. Only the usage named in the error message differs, which now shows the reservation instead of the count plus the reservation

* test(redis): send the failed SDK call's refund through a real completion

The refund span test called ModelRateLimitingCheck.async_log_failure_event directly, so it relied on the span wrap that callback used to carry. The Logging failure handlers now anchor the span for every callback, so the test sends a failing litellm.acompletion with the reservation in its metadata and checks the refund's Redis span still lands under the caller's span
2026-11-13 03:22:28 +00:00

126 lines
5.7 KiB
Python

import asyncio
import logging
import threading
from collections.abc import Sequence
from typing import Final
import pytest
from fakeredis import TcpFakeServer
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.router_strategy.base_routing_strategy import BaseRoutingStrategy
from litellm.rust_bridge._native import NativeRedisStoreError
from tests.unit.redis.stores.router_usage_double import FakeUsageHandle, usage_store
_A: Final = UsageCounter.for_deployment("dep-a", "openai/gpt-5.4-nano", "rpm", "12-34")
_B: Final = UsageCounter.for_deployment("dep-b", "openai/gpt-5.4-nano", "rpm", "12-34")
def _strategy(handle: FakeUsageHandle) -> BaseRoutingStrategy:
return BaseRoutingStrategy(usage=usage_store(handle), should_batch_redis_writes=False, default_sync_interval=1)
@pytest.mark.asyncio
async def test_an_increment_counts_in_memory_now_and_queues_the_redis_write():
handle: Final = FakeUsageHandle(redis={})
strategy: Final = _strategy(handle)
counted: Final = await strategy._increment_value_in_current_window(_A, 1, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
assert counted == 1
assert handle.local == {_A: 1}
assert handle.redis == {}
assert strategy.redis_increment_operation_queue == [CounterIncrement(_A, 1, 60)]
assert strategy.get_in_memory_keys_to_update() == {_A}
@pytest.mark.asyncio
async def test_a_push_sends_each_counters_queued_increments_summed_in_one_pipeline():
handle: Final = FakeUsageHandle(redis={_A: 10})
strategy: Final = _strategy(handle)
for counter in (_A, _B, _A):
await strategy._increment_value_in_current_window(counter, 1, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
totals: Final = await strategy._push_in_memory_increments_to_redis() # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
assert handle.calls == [("remote", (CounterIncrement(_A, 2, 60), CounterIncrement(_B, 1, 60)))]
assert totals == {_A: 12, _B: 1}
assert strategy.redis_increment_operation_queue == []
@pytest.mark.asyncio
async def test_a_sync_moves_memory_up_to_what_every_pod_counted_in_redis():
handle: Final = FakeUsageHandle(redis={_A: 20})
strategy: Final = _strategy(handle)
await strategy._increment_value_in_current_window(_A, 3, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
await strategy._sync_in_memory_spend_with_redis() # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
assert handle.redis == {_A: 23}
assert handle.local == {_A: 23}
@pytest.mark.asyncio
async def test_without_redis_a_sync_leaves_the_queue_and_memory_alone():
handle: Final = FakeUsageHandle()
strategy: Final = _strategy(handle)
await strategy._increment_value_in_current_window(_A, 3, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
await strategy._sync_in_memory_spend_with_redis() # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
assert handle.local == {_A: 3}
assert handle.calls == []
assert strategy.redis_increment_operation_queue == [CounterIncrement(_A, 3, 60)]
@pytest.mark.asyncio
async def test_cache_keys_management():
strategy: Final = _strategy(FakeUsageHandle())
strategy.add_to_in_memory_keys_to_update(_A)
strategy.add_to_in_memory_keys_to_update(_B)
strategy.add_to_in_memory_keys_to_update(_A)
assert strategy.get_in_memory_keys_to_update() == {_A, _B}
strategy.reset_in_memory_keys_to_update()
assert strategy.get_in_memory_keys_to_update() == set()
class _RefusedHandle(FakeUsageHandle):
def increment_remote(self, increments: Sequence[CounterIncrement]) -> asyncio.Future[list[float] | None]:
raise NativeRedisStoreError("breaker_open", "the Redis circuit breaker is open")
@pytest.mark.asyncio
async def test_push_refused_by_the_open_circuit_breaker_is_not_logged_as_an_error(caplog):
"""The sync loop pushes every 100 ms under usage-based routing, so an open breaker must not add an error line per cycle."""
strategy: Final = _strategy(_RefusedHandle(redis={}))
await strategy._increment_value_in_current_window(_A, 1, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
with caplog.at_level(logging.ERROR):
await strategy._push_in_memory_increments_to_redis() # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
assert caplog.records == []
assert strategy.redis_increment_operation_queue == []
@pytest.mark.asyncio
async def test_an_increment_counted_after_retire_still_reaches_redis():
server: Final = TcpFakeServer(("127.0.0.1", 0), server_type="redis")
threading.Thread(target=server.serve_forever, daemon=True).start()
redis_cache: Final = RedisCache(host="127.0.0.1", port=server.server_address[1])
strategy: Final = BaseRoutingStrategy(
usage=RouterUsageStore(connect(redis_cache).router_usage()),
should_batch_redis_writes=True,
default_sync_interval=60,
)
try:
strategy.retire()
await strategy._increment_value_in_current_window(_A, 3, 60) # pyright: ignore[reportPrivateUsage] # a step of the sync loop the strategy runs on a timer
await asyncio.sleep(0.2)
assert float(await redis_cache.async_get_cache("dep-a:openai/gpt-5.4-nano:rpm:12-34")) == 3
finally:
server.shutdown()
server.server_close()