mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-01 01:18:34 +00:00
* 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
336 lines
14 KiB
Python
336 lines
14 KiB
Python
import asyncio
|
|
import queue
|
|
import threading
|
|
from collections.abc import Iterator
|
|
from dataclasses import asdict
|
|
from typing import Final
|
|
|
|
import pytest
|
|
from fakeredis import TcpFakeServer
|
|
from opentelemetry import trace
|
|
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
|
|
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
|
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
|
from opentelemetry.trace import Span
|
|
from prometheus_client import REGISTRY
|
|
from redis import exceptions as redis_exceptions
|
|
|
|
import litellm
|
|
from litellm import Router
|
|
from litellm._internal_context import service_target, set_request_parent_otel_span
|
|
from litellm.caching.redis_batch import request_redis_batch_scope
|
|
from litellm.caching.redis_cache import RedisCache
|
|
from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig
|
|
from litellm.integrations.otel import OpenTelemetryV2Config
|
|
from litellm.integrations.otel.logger import OpenTelemetryV2
|
|
from litellm.integrations.otel.plumbing import providers
|
|
from litellm.redis.stores.auth_cache import AUTH_CACHE_TARGET, AuthCacheSettings, AuthCacheStore
|
|
from litellm.redis.stores.connection import connect
|
|
from litellm.redis.stores.router_usage import RouterUsageStore, UsageCounter
|
|
from litellm.redis.stores.spend_counters import SpendCounterStore
|
|
from litellm.router_utils.pre_call_checks.io_token_rate_limit_check import (
|
|
ITPM_COUNTER_KEY,
|
|
ITPM_RESERVED_KEY,
|
|
OTPM_COUNTER_KEY,
|
|
OTPM_RESERVED_KEY,
|
|
)
|
|
from litellm.router_utils.pre_call_checks.model_rate_limit_check import ModelRateLimitingCheck
|
|
from litellm.rust_bridge.host import redis_events
|
|
|
|
|
|
def _sample(name: str, labels: dict[str, str]) -> float:
|
|
return REGISTRY.get_sample_value(name, labels) or 0.0
|
|
|
|
|
|
@pytest.fixture
|
|
def prometheus(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(litellm, "service_callback", ["prometheus_system"])
|
|
redis_events._service_logging.cache_clear()
|
|
yield
|
|
redis_events._service_logging.cache_clear()
|
|
|
|
|
|
def _failed_requests(error: type[redis_exceptions.RedisError]) -> tuple[str, dict[str, str]]:
|
|
return (
|
|
"litellm_redis_failed_requests_total",
|
|
{"redis": "redis", "error_class": error.__name__, "function_name": "async_increment"},
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("failure", "error", "failure_class"),
|
|
[
|
|
("timeout", redis_exceptions.TimeoutError, "timeout"),
|
|
("transport", redis_exceptions.ConnectionError, "connectivity"),
|
|
],
|
|
)
|
|
def test_a_health_failure_counts_as_a_failed_request_of_its_redis_py_class_and_a_breaker_failure(
|
|
prometheus: None, failure: redis_events.Failure, error: type[redis_exceptions.RedisError], failure_class: str
|
|
):
|
|
breaker: Final = ("litellm_redis_circuit_breaker_failures_total", {"failure_class": failure_class})
|
|
before: Final = (_sample(*_failed_requests(error)), _sample(*breaker))
|
|
|
|
redis_events.record_redis_call(None, "async_increment", 10.0, 10.25, failure)
|
|
|
|
assert (_sample(*_failed_requests(error)), _sample(*breaker)) == (before[0] + 1, before[1] + 1)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("failure", "error"),
|
|
[("server", redis_exceptions.ResponseError), ("decode", redis_exceptions.InvalidResponse)],
|
|
)
|
|
def test_a_rejected_command_is_a_failed_request_of_its_redis_py_class_but_not_a_breaker_failure(
|
|
prometheus: None, failure: redis_events.Failure, error: type[redis_exceptions.RedisError]
|
|
):
|
|
breaker: Final = {
|
|
failure_class: _sample("litellm_redis_circuit_breaker_failures_total", {"failure_class": failure_class})
|
|
for failure_class in ("timeout", "connectivity")
|
|
}
|
|
before: Final = _sample(*_failed_requests(error))
|
|
|
|
redis_events.record_redis_call(None, "async_increment", 10.0, 10.25, failure)
|
|
|
|
assert _sample(*_failed_requests(error)) == before + 1
|
|
assert {
|
|
failure_class: _sample("litellm_redis_circuit_breaker_failures_total", {"failure_class": failure_class})
|
|
for failure_class in ("timeout", "connectivity")
|
|
} == breaker
|
|
|
|
|
|
def test_a_success_is_counted_and_a_breaker_rejection_is_not(prometheus: None):
|
|
total: Final = ("litellm_redis_total_requests_total", {"redis": "redis"})
|
|
before: Final = _sample(*total)
|
|
|
|
redis_events.record_redis_call(None, "async_get_cache", 10.0, 10.01, None)
|
|
redis_events.record_redis_call(None, "async_get_cache", 10.0, 10.0, "breaker_open")
|
|
|
|
assert _sample(*total) == before + 1
|
|
|
|
|
|
def test_a_call_whose_loop_has_closed_is_still_counted(prometheus: None):
|
|
total: Final = ("litellm_redis_total_requests_total", {"redis": "redis"})
|
|
closed: Final = asyncio.new_event_loop()
|
|
closed.close()
|
|
before: Final = _sample(*total)
|
|
|
|
redis_events.record_redis_call(closed, "async_get_cache", 10.0, 10.01, None)
|
|
|
|
assert _sample(*total) == before + 1
|
|
|
|
|
|
@pytest.mark.parametrize("state", ["open", "half_open", "closed"])
|
|
def test_breaker_transitions_are_counted_by_state(prometheus: None, state: redis_events.BreakerState):
|
|
labels: Final = {"state": state}
|
|
before: Final = _sample("litellm_redis_circuit_breaker_transitions_total", labels)
|
|
|
|
redis_events.record_redis_breaker(state)
|
|
|
|
assert _sample("litellm_redis_circuit_breaker_transitions_total", labels) == before + 1
|
|
|
|
|
|
@pytest.fixture
|
|
def otel(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[TracerProvider, InMemorySpanExporter]]:
|
|
config: Final = OpenTelemetryV2Config(exporter="in_memory")
|
|
exporter: Final = InMemorySpanExporter()
|
|
provider: Final = providers.build_tracer_provider(config, exporter=exporter)
|
|
monkeypatch.setattr(litellm, "service_callback", [OpenTelemetryV2(config=config, tracer_provider=provider)])
|
|
yield provider, exporter
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_redis_port() -> Iterator[int]:
|
|
server: Final = TcpFakeServer(("127.0.0.1", 0), server_type="redis")
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
yield server.server_address[1]
|
|
server.shutdown()
|
|
server.server_close()
|
|
|
|
|
|
def _children(exporter: InMemorySpanExporter, parent: Span) -> tuple[ReadableSpan, ...]:
|
|
parent_id: Final = parent.get_span_context().span_id
|
|
return tuple(
|
|
span for span in exporter.get_finished_spans() if span.parent is not None and span.parent.span_id == parent_id
|
|
)
|
|
|
|
|
|
async def _spans_under(exporter: InMemorySpanExporter, parent: Span, polls: int = 100) -> tuple[tuple[str, str], ...]:
|
|
children: Final = _children(exporter, parent)
|
|
if children or polls == 0:
|
|
return tuple(sorted((span.name, span.status.status_code.name) for span in children))
|
|
await asyncio.sleep(0.05)
|
|
return await _spans_under(exporter, parent, polls - 1)
|
|
|
|
|
|
async def test_a_native_auth_cache_read_reports_the_redis_span_redis_cache_reported(
|
|
fake_redis_port: int, otel: tuple[TracerProvider, InMemorySpanExporter]
|
|
):
|
|
provider, exporter = otel
|
|
tracer: Final = provider.get_tracer(__name__)
|
|
redis_cache: Final = RedisCache(host="127.0.0.1", port=fake_redis_port)
|
|
store: Final = AuthCacheStore(connect(redis_cache).auth_cache(AuthCacheSettings(200, 60)))
|
|
python_request: Final = tracer.start_span("python request")
|
|
native_request: Final = tracer.start_span("native request")
|
|
|
|
with trace.use_span(python_request, end_on_exit=True):
|
|
with service_target(AUTH_CACHE_TARGET):
|
|
await redis_cache.async_get_cache("python-key", parent_otel_span=python_request)
|
|
with trace.use_span(native_request, end_on_exit=True):
|
|
await store.get("native-key")
|
|
|
|
reported_by_redis_cache: Final = await _spans_under(exporter, python_request)
|
|
assert reported_by_redis_cache
|
|
assert await _spans_under(exporter, native_request) == reported_by_redis_cache
|
|
|
|
|
|
async def test_a_post_call_batch_flushed_by_its_deadline_reports_its_redis_span_under_the_request(
|
|
fake_redis_port: int, otel: tuple[TracerProvider, InMemorySpanExporter]
|
|
):
|
|
provider, exporter = otel
|
|
tracer: Final = provider.get_tracer(__name__)
|
|
store: Final = SpendCounterStore(connect(RedisCache(host="127.0.0.1", port=fake_redis_port)).spend_counters())
|
|
request: Final = tracer.start_span("request")
|
|
|
|
async def native_post_call() -> tuple[tuple[str, str], ...]:
|
|
with trace.use_span(request, end_on_exit=True):
|
|
set_request_parent_otel_span(request)
|
|
with request_redis_batch_scope(post_call_deadline=0.05):
|
|
assert store.increment_many_post_call((("spend:key:k", 1.0),))
|
|
return await _spans_under(exporter, request)
|
|
|
|
assert await asyncio.create_task(native_post_call())
|
|
|
|
|
|
@pytest.fixture
|
|
def legacy_otel(monkeypatch: pytest.MonkeyPatch) -> tuple[TracerProvider, InMemorySpanExporter]:
|
|
exporter: Final = InMemorySpanExporter()
|
|
provider: Final = TracerProvider()
|
|
provider.add_span_processor(SimpleSpanProcessor(exporter))
|
|
logger: Final = OpenTelemetry(config=OpenTelemetryConfig(exporter=exporter), tracer_provider=provider)
|
|
monkeypatch.setattr(litellm, "service_callback", [logger])
|
|
return provider, exporter
|
|
|
|
|
|
async def test_a_native_read_in_a_legacy_otel_request_reports_its_redis_span_under_the_request(
|
|
fake_redis_port: int, legacy_otel: tuple[TracerProvider, InMemorySpanExporter]
|
|
):
|
|
provider, exporter = legacy_otel
|
|
tracer: Final = provider.get_tracer(__name__)
|
|
redis_cache: Final = RedisCache(host="127.0.0.1", port=fake_redis_port)
|
|
store: Final = AuthCacheStore(connect(redis_cache).auth_cache(AuthCacheSettings(200, 60)))
|
|
python_request: Final = tracer.start_span("python request")
|
|
native_request: Final = tracer.start_span("native request")
|
|
|
|
async def native_request_read() -> None:
|
|
set_request_parent_otel_span(native_request)
|
|
await store.get("native-key")
|
|
|
|
with service_target(AUTH_CACHE_TARGET):
|
|
await redis_cache.async_get_cache("python-key", parent_otel_span=python_request)
|
|
await asyncio.create_task(native_request_read())
|
|
|
|
reported_by_redis_cache: Final = await _spans_under(exporter, python_request)
|
|
assert reported_by_redis_cache
|
|
assert await _spans_under(exporter, native_request) == reported_by_redis_cache
|
|
|
|
|
|
async def _redis_calls_under(exporter: InMemorySpanExporter, parent: Span, polls: int = 100) -> frozenset[str]:
|
|
calls: Final = frozenset(
|
|
str(span.attributes["call_type"])
|
|
for span in _children(exporter, parent)
|
|
if span.attributes is not None and span.attributes.get("service") == "redis"
|
|
)
|
|
if calls or polls == 0:
|
|
return calls
|
|
await asyncio.sleep(0.05)
|
|
return await _redis_calls_under(exporter, parent, polls - 1)
|
|
|
|
|
|
async def test_a_deadline_flush_reports_under_the_request_span_auth_set_after_the_scope_opened(
|
|
fake_redis_port: int, legacy_otel: tuple[TracerProvider, InMemorySpanExporter]
|
|
):
|
|
provider, exporter = legacy_otel
|
|
store: Final = SpendCounterStore(connect(RedisCache(host="127.0.0.1", port=fake_redis_port)).spend_counters())
|
|
request: Final = provider.get_tracer(__name__).start_span("request")
|
|
|
|
async def proxy_request() -> frozenset[str]:
|
|
with request_redis_batch_scope(post_call_deadline=0.05):
|
|
set_request_parent_otel_span(request)
|
|
assert store.increment_many_post_call((("spend:key:k", 1.0),))
|
|
return await _redis_calls_under(exporter, request)
|
|
|
|
assert await asyncio.create_task(proxy_request()) == {"post_call_redis_batch"}
|
|
|
|
|
|
async def test_a_failed_sdk_calls_io_token_refund_reports_its_redis_span_under_the_span_its_caller_passed(
|
|
fake_redis_port: int, legacy_otel: tuple[TracerProvider, InMemorySpanExporter], monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
provider, exporter = legacy_otel
|
|
usage: Final = RouterUsageStore(connect(RedisCache(host="127.0.0.1", port=fake_redis_port)).router_usage())
|
|
monkeypatch.setattr(litellm, "callbacks", [ModelRateLimitingCheck(usage)])
|
|
caller: Final = provider.get_tracer(__name__).start_span("sdk caller")
|
|
itpm: Final = UsageCounter("global_router", "d1", "openai/gpt-x", "12-00", "itpm")
|
|
otpm: Final = UsageCounter("global_router", "d1", "openai/gpt-x", "12-00", "otpm")
|
|
|
|
with pytest.raises(Exception, match="provider down"):
|
|
await litellm.acompletion(
|
|
model="gpt-4o-mini",
|
|
messages=[{"role": "user", "content": "hi"}],
|
|
mock_response=Exception("provider down"),
|
|
metadata={
|
|
"litellm_parent_otel_span": caller,
|
|
ITPM_RESERVED_KEY: 5,
|
|
OTPM_RESERVED_KEY: 7,
|
|
ITPM_COUNTER_KEY: asdict(itpm),
|
|
OTPM_COUNTER_KEY: asdict(otpm),
|
|
},
|
|
)
|
|
|
|
assert await _redis_calls_under(exporter, caller) == {"async_increment"}
|
|
|
|
|
|
async def test_an_sdk_router_call_reports_its_usage_read_under_the_span_its_caller_passed(
|
|
fake_redis_port: int, legacy_otel: tuple[TracerProvider, InMemorySpanExporter]
|
|
):
|
|
provider, exporter = legacy_otel
|
|
caller: Final = provider.get_tracer(__name__).start_span("sdk caller")
|
|
router: Final = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "m",
|
|
"litellm_params": {"model": "openai/gpt-x", "api_key": "sk-fake", "mock_response": "hi", "tpm": 1000},
|
|
"model_info": {"id": "d1"},
|
|
}
|
|
],
|
|
routing_strategy="usage-based-routing-v2",
|
|
redis_host="127.0.0.1",
|
|
redis_port=fake_redis_port,
|
|
)
|
|
|
|
await router.acompletion(
|
|
model="m", messages=[{"role": "user", "content": "hi"}], metadata={"litellm_parent_otel_span": caller}
|
|
)
|
|
|
|
assert "async_batch_get_cache" in await _redis_calls_under(exporter, caller)
|
|
|
|
|
|
class _EndedSpans(SpanProcessor):
|
|
def __init__(self) -> None:
|
|
self.ended: Final = queue.SimpleQueue[tuple[ReadableSpan, int]]()
|
|
|
|
def on_end(self, span: ReadableSpan) -> None:
|
|
self.ended.put((span, threading.get_ident()))
|
|
|
|
|
|
async def test_a_call_reported_from_a_worker_thread_is_traced_on_the_callers_loop_with_its_times(
|
|
otel: tuple[TracerProvider, InMemorySpanExporter],
|
|
):
|
|
provider, _exporter = otel
|
|
ended: Final = _EndedSpans()
|
|
provider.add_span_processor(ended)
|
|
|
|
await asyncio.to_thread(
|
|
redis_events.record_redis_call, asyncio.get_running_loop(), "async_get_cache", 10.0, 10.25, None
|
|
)
|
|
|
|
span, thread = await asyncio.to_thread(ended.ended.get, timeout=5)
|
|
assert (span.start_time, span.end_time, thread) == (10_000_000_000, 10_250_000_000, threading.get_ident())
|