litellm/tests/unit/router_strategy/test_budget_limiter.py
devin-ai-integration[bot] c80f1c2ec8
fix(router)!: count native Responses WebSocket turns toward deployment limits and budgets (#45727)
* fix(responses): write one spend-log row per native WebSocket turn

Each response.create turn on a native Responses WebSocket connection now logs its own call as it finishes, with its own usage and the resp_ id the client saw as request_id. A failed turn is booked alone and no longer flips the other turns.

* fix(responses): bill the usage a failed native WebSocket turn reports

* fix(proxy): pin the limiter slot owner to the proxy call id and refund unsettled reservations on disconnect

The v3 limiter stashed whichever litellm_call_id the request body carried as
the slot owner, so a client-supplied id on a pass-through body left the
proxy's own success and failure events unable to release the slot. The owner
is now the proxy's logging call id. A WebSocket connection whose turns log
under their own ids never settles the TPM, ITPM, or OTPM estimate the
connection reserved, so the disconnect release now refunds any reservation
no callback settled, once.

* fix(proxy): bill failed WebSocket turns and refund only the reserved window on disconnect

A failed turn's reported usage now counts toward the key's TPM and the
project ITPM/OTPM scopes the same way a success does, and closing the
socket hands back only the estimate still unused in the window that
holds it, so a window that already rolled is left alone.

An id-less error event is booked against the newest pending turn, the
one the backend rejected at parse time, and a turn that nests its input
under response logs its user message. A connection's one budget
reservation goes to the first turn that settles it, every later turn
charging its cost directly.

* test(proxy): expect the settling call id on a pass-through budget reservation

* fix(proxy): charge successful Responses WebSocket turns to TPM and ITPM/OTPM

A native Responses WebSocket turn reaches the rate limiter's success
callback with its raw event list as the response and no
combined_usage_object, so the turn's tokens never reached the key's TPM
window or the project's input and output token limits. Read the usage
from the turn's events when the call type is a Responses WebSocket turn.

* fix(proxy): release a rejected pass-through's slot and count each websocket turn once toward project quotas

The limiter's failure hook looked up the parallel slot by the request
body's litellm_call_id, while the slot belongs to the proxy's logging
call id, so a pass-through request a pre-call hook rejected held its
slot for an hour when its body carried an id. Both now resolve the id
the same way.

Each response.create frame already charges its estimate to project
ITPM/OTPM, so the turn's own usage no longer adds a second count.

The cost callback's failure hook read the body's litellm_call_id
through a strict model and raised on a non-string value, which dropped
the failure row. It now reads a string id or none.

* fix(proxy): keep per-turn WebSocket limits, request bodies and collector reservations right

Free a rejected request's parallel slot through the request it runs in, and skip
native Responses WebSocket connections, whose disconnect frees the slot. Count
WebSocket turns toward the connection's tag TPM. In collector mode, claim the
shared budget reservation before the spend event is built, so only the first
turn settles it. Store each turn's own frame as its request body, and send an
id-less error to the oldest waiting turn unless an earlier turn is streaming.

* fix(proxy): store a failed WebSocket turn's own request and count tag TPM only for calls that carry the tag

* fix(responses): log the client's turn frame, keep the payload id and reservation shape for non-WebSocket calls

* fix(proxy): keep the legacy limiter's WebSocket slot until the socket closes

* fix(router): count native Responses WebSocket turns toward deployment limits and budgets

* fix(router): re-check deployment budget and RPM on each Responses WebSocket turn

* test(router): list the WebSocket turn admission method as covered through its partial

* fix(responses): give a refused WebSocket turn's error frame a 429 status so Codex ends the turn

* fix(router): leave ITPM/OTPM to socket open and record a refused WebSocket turn as the socket's failure

* fix(proxy): log the routed model group on a WebSocket turn's failure row

* fix(router): count WebSocket turn tokens toward TPM and re-run routing strategy checks on each turn

* test(integration): cover per-turn admission on Responses WebSockets

Adds integration cells for budget, RPM, TPM, a mid-socket TPM edit, usage-based-routing-v2, the
project quota frame, and the open-time failure frame on the native and managed relays, plus HTTP
controls for TPM counting and the failure row model_group

* fix(responses): count WebSocket turn tokens once and end a socket whose turn check fails

A native Responses WebSocket turn is now logged as an async call, so a proxy with a sync success
callback such as the response cache no longer runs each CustomLogger's sync success hook on top of
the async one. That second run counted every turn's tokens twice toward deployment TPM.

A turn whose admission check raises an unexpected error now gets a 500 error frame, the socket
closes with 1011, and the error becomes the socket's failure, on both the native and the managed
relay, instead of the socket dropping with no frame and no failure row.

A refused turn's failure row now carries the request's tags from the router's metadata, the same
way it already carries the model group.

* test(integration): cover a crashed WebSocket turn check and failure-row tags

A turn whose admission check raises gets a 500 server_error frame, the
socket closes with 1011 and its one failure row carries the error, on
both relays. The refused turn's failure row keeps the caller's tags, and
HTTP failure rows on chat, responses and messages keep them too.

* fix(responses): keep a WebSocket open after a crashed turn check and keep only string tags on failure rows

A turn whose admission check raises an unexpected error still gets a 500 error frame, but the socket
now stays open, like a refused turn. Closing it cut any turn still streaming on the same socket, which
a client that sends its next response.create early would lose.

A refused turn's failure row now takes the router's tags only when every tag is a string, so the
fallback never copies a caller's unvalidated tags onto the row.

* test(integration): cover a turn still streaming when the next WebSocket turn's check crashes

A native turn still streaming when the next turn's admission check raises now has its own cell. It
must complete and be billed at the turn's price. The crashed-check cell also keeps the fault set for
one more turn, so a relay that stopped checking turns after a crash goes red.

* fix(responses): run per-turn guardrails before the deployment's turn check on WebSockets

A turn after the first now runs the project quota check, then the proxy's
pre_call guardrails, then the deployment's turn admission, on both the
native and the managed relay, the order HTTP calls use. A turn a guardrail
blocks gets the guardrail's error even past the budget and no longer counts
toward the deployment's rpm or runs its pre-call checks.

* fix(responses): bill a WebSocket turn's guardrail cost when the deployment refuses it

A turn the per-turn guardrail passes and the deployment then refuses now writes
its own failed spend row with that turn's guardrail information, on both relays,
the way a guardrail-blocked frame and an HTTP refusal already do

* fix(responses): bill a refused WebSocket turn on one row only

A refused turn whose guardrails recorded a cost is already billed on its own row,
so it no longer also becomes the connection's close-time failure row

* fix(responses): bill a refused WebSocket turn's guardrail cost on the socket's failure row

The turns a deployment refuses after their guardrails passed now add their guardrail records to the socket's close-time failure row instead of a row of their own, so that row's failure hooks, model group and call type cover them

* fix(responses): bill a WebSocket's refused turns when the session limit closes it

* fix(responses): bill refused WebSocket turns when the session limit cancels the relay

* fix(responses): free the WebSocket slot at the session limit without waiting on the failure row

* fix(responses): keep the session limit's second cancel so a relay that swallows the first frees the slot

* fix(responses): free the WebSocket slot before the close-time failure row and drain pending rows at shutdown

* fix(proxy): commit spend before waiting on pending logging tasks at shutdown and again after

* fix(responses): start the close-time failure row before the slot release so a late cancel cannot drop it

* fix(responses): build the close-time failure row inside its task so a bad guardrail record cannot skip the crash close

* fix(proxy): always commit spend again after the shutdown wait for pending logging tasks

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-10-19 15:35:20 +00:00

451 lines
15 KiB
Python

"""
Spend tracking in RouterBudgetLimiting.async_log_success_event.
Only chat completions puts custom_llm_provider into litellm_params. The responses,
anthropic_messages, embedding and rerank surfaces leave it unset, which used to make
the callback raise before any spend was recorded, so those budgets never moved.
"""
from datetime import datetime, timezone
from typing import Final
import litellm
import pytest
from litellm import Router
from litellm.caching.caching import DualCache
from litellm.caching.in_memory_cache import InMemoryCache
from litellm.router_strategy.budget_limiter import RouterBudgetLimiting
from litellm.types.utils import BudgetConfig
import sys, os, asyncio, time, random
@pytest.fixture
def disable_budget_sync(monkeypatch):
async def noop(*args, **kwargs):
return None
monkeypatch.setattr(
"litellm.router_strategy.budget_limiter.RouterBudgetLimiting.periodic_sync_in_memory_spend_with_redis",
noop,
)
def _success_kwargs(
*,
provider_in_litellm_params: str | None,
provider_in_payload: str | None,
call_type: str = "aresponses",
response_cost: float = 0.25,
model_id: str = "deployment-1",
) -> dict[str, object]:
provider_params: Final[dict[str, str]] = (
{} if provider_in_litellm_params is None else {"custom_llm_provider": provider_in_litellm_params}
)
litellm_params: Final[dict[str, str]] = {"model": "openai/gpt-4o", **provider_params}
return {
"call_type": call_type,
"litellm_params": litellm_params,
"standard_logging_object": {
"response_cost": response_cost,
"model_id": model_id,
"custom_llm_provider": provider_in_payload,
},
}
async def _log_success(limiter: RouterBudgetLimiting, kwargs: dict[str, object]) -> None:
await limiter.async_log_success_event(kwargs=kwargs, response_obj=None, start_time=None, end_time=None)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"call_type", ["aresponses", "_aresponses_websocket", "anthropic_messages", "aembedding", "arerank"]
)
async def test_provider_spend_tracked_when_litellm_params_omits_provider(disable_budget_sync, call_type):
"""Non-chat surfaces carry the provider only on the standard logging payload."""
limiter = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config={"openai": {"budget_limit": 10.0, "time_period": "1d"}},
)
await _log_success(
limiter,
_success_kwargs(
provider_in_litellm_params=None,
provider_in_payload="openai",
call_type=call_type,
),
)
assert await limiter.dual_cache.async_get_cache("provider_spend:openai:1d") == 0.25
@pytest.mark.asyncio
async def test_chat_completions_spend_still_tracked(disable_budget_sync):
"""Chat completions fills in both sources and must keep accumulating."""
limiter = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config={"openai": {"budget_limit": 10.0, "time_period": "1d"}},
)
await _log_success(
limiter,
_success_kwargs(
provider_in_litellm_params="openai",
provider_in_payload="openai",
call_type="acompletion",
),
)
assert await limiter.dual_cache.async_get_cache("provider_spend:openai:1d") == 0.25
@pytest.mark.asyncio
async def test_budget_of_other_provider_is_untouched(disable_budget_sync):
"""A provider without its own budget must not bleed into a configured one."""
limiter = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config={"openai": {"budget_limit": 10.0, "time_period": "1d"}},
)
await _log_success(
limiter,
_success_kwargs(provider_in_litellm_params=None, provider_in_payload="anthropic"),
)
assert await limiter.dual_cache.async_get_cache("provider_spend:openai:1d") in (None, 0.0)
@pytest.mark.asyncio
async def test_tag_spend_is_incremented_for_request_metadata(
disable_budget_sync: None,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(litellm, "tag_budget_config", {"release": {"budget_limit": 5.0, "time_period": "1h"}})
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
limiter = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config=None)
kwargs: Final = {
**_success_kwargs(
provider_in_litellm_params=None,
provider_in_payload=None,
response_cost=0.73,
),
"metadata": {"tags": ["release"]},
}
await _log_success(limiter, kwargs)
assert await limiter.dual_cache.async_get_cache("tag_spend:release:1h") == 0.73
@pytest.mark.asyncio
async def test_deployment_budget_tracked_when_provider_is_unresolvable(disable_budget_sync):
"""An unresolvable provider must not abort the deployment and tag budgets that follow it."""
limiter = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config=None,
model_list=[
{
"model_name": "some-model",
"litellm_params": {
"model": "openai/gpt-4o",
"max_budget": 10.0,
"budget_duration": "1d",
},
"model_info": {"id": "deployment-1"},
}
],
)
await _log_success(
limiter,
_success_kwargs(provider_in_litellm_params=None, provider_in_payload=None),
)
assert await limiter.dual_cache.async_get_cache("deployment_spend:deployment-1:1d") == 0.25
_MONTHLY_DEPLOYMENT: Final = {
"model_name": "some-model",
"litellm_params": {"model": "openai/gpt-4o", "max_budget": 10.0, "budget_duration": "1mo"},
"model_info": {"id": "deployment-1"},
}
@pytest.mark.asyncio
@pytest.mark.parametrize(
("limiter_config", "tag_budget_config", "spend_key", "start_time_key"),
[
(
{"provider_budget_config": {"openai": {"budget_limit": 10.0, "time_period": "1mo"}}},
None,
"provider_spend:openai:1mo",
"provider_budget_start_time:openai",
),
(
{"provider_budget_config": None, "model_list": [_MONTHLY_DEPLOYMENT]},
None,
"deployment_spend:deployment-1:1mo",
"deployment_budget_start_time:deployment-1",
),
(
{"provider_budget_config": None},
{"release": {"budget_limit": 10.0, "time_period": "1mo"}},
"tag_spend:release:1mo",
"tag_budget_start_time:release",
),
],
ids=["provider", "deployment", "tag"],
)
@pytest.mark.parametrize(
("opened_at", "charged_at", "closes_at"),
[
(
datetime(2026, 1, 15, 12, tzinfo=timezone.utc),
datetime(2026, 2, 1, 12, tzinfo=timezone.utc),
datetime(2026, 2, 15, 12, tzinfo=timezone.utc),
),
(
datetime(2026, 2, 15, 12, tzinfo=timezone.utc),
datetime(2026, 3, 1, 12, tzinfo=timezone.utc),
datetime(2026, 3, 15, 12, tzinfo=timezone.utc),
),
],
ids=["opened_in_a_long_month", "opened_in_february"],
)
async def test_a_monthly_router_budget_ends_a_calendar_month_after_it_opens(
disable_budget_sync,
monkeypatch,
limiter_config,
tag_budget_config,
spend_key,
start_time_key,
opened_at,
charged_at,
closes_at,
):
"""
The spend counter's Redis expiry is when the router lets the provider,
deployment or tag take traffic again.
Regression: it was a month counted from the charge, so a window opened on January 15
and charged on February 1 unblocked on February 12 instead of February 15.
"""
monkeypatch.setattr(litellm, "tag_budget_config", tag_budget_config)
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
limiter = RouterBudgetLimiting(
dual_cache=DualCache(in_memory_cache=InMemoryCache(clock=charged_at.timestamp)),
clock=charged_at.timestamp,
**limiter_config,
)
await limiter.dual_cache.async_set_cache(key=start_time_key, value=opened_at.timestamp())
await _log_success(
limiter,
{
**_success_kwargs(provider_in_litellm_params="openai", provider_in_payload="openai"),
"metadata": {"tags": ["release"]},
},
)
assert await limiter.dual_cache.async_get_cache(spend_key) == 0.25
assert limiter.dual_cache.in_memory_cache.ttl_dict[spend_key] == closes_at.timestamp()
@pytest.mark.asyncio
async def test_get_budget_config_for_provider():
"""
Test the _get_budget_config_for_provider helper method
"""
cleanup_redis()
config = {
"openai": BudgetConfig(budget_duration="1d", max_budget=100),
"anthropic": BudgetConfig(budget_duration="7d", max_budget=500),
}
provider_budget = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config=config)
# Test existing providers
openai_config = provider_budget._get_budget_config_for_provider("openai")
assert openai_config is not None
assert openai_config.budget_duration == "1d"
assert openai_config.max_budget == 100
anthropic_config = provider_budget._get_budget_config_for_provider("anthropic")
assert anthropic_config is not None
assert anthropic_config.budget_duration == "7d"
assert anthropic_config.max_budget == 500
# Test non-existent provider
assert provider_budget._get_budget_config_for_provider("unknown") is None
@pytest.mark.asyncio
async def test_get_current_provider_spend():
"""
Test _get_current_provider_spend helper method
Scenarios:
1. Provider with no budget config returns None
2. Provider with budget config but no spend returns 0.0
3. Provider with budget config and spend returns correct value
"""
cleanup_redis()
provider_budget = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config={
"openai": BudgetConfig(time_period="1d", budget_limit=100),
},
)
# Test provider with no budget config
spend = await provider_budget._get_current_provider_spend("anthropic")
assert spend is None
# Test provider with budget config but no spend
spend = await provider_budget._get_current_provider_spend("openai")
assert spend == 0.0
# Test provider with budget config and spend
spend_key = "provider_spend:openai:1d"
await provider_budget.dual_cache.async_set_cache(key=spend_key, value=50.5)
spend = await provider_budget._get_current_provider_spend("openai")
assert spend == 50.5
@pytest.mark.asyncio
async def test_get_llm_provider_for_deployment_resolves_provider_prefixes() -> None:
provider_budget: Final = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={})
assert provider_budget._get_llm_provider_for_deployment({"litellm_params": {"model": "openai/gpt-4o"}}) == "openai"
assert (
provider_budget._get_llm_provider_for_deployment(
{"litellm_params": {"model": "azure/gpt-4o", "api_base": "https://example.azure.com"}}
)
== "azure"
)
assert provider_budget._get_llm_provider_for_deployment({}) is None
@pytest.mark.asyncio
async def test_budget_start_time_is_created_once() -> None:
provider_budget: Final = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={})
first_start: Final = await provider_budget._get_or_set_budget_start_time(
start_time_key="provider_budget_start_time:openai",
current_time=1000.0,
ttl_seconds=86400,
)
later_start: Final = await provider_budget._get_or_set_budget_start_time(
start_time_key="provider_budget_start_time:openai",
current_time=2000.0,
ttl_seconds=86400,
)
assert first_start == 1000.0
assert later_start == 1000.0
@pytest.mark.asyncio
async def test_new_budget_window_sets_spend_and_start_time() -> None:
provider_budget: Final = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={})
start_time: Final = await provider_budget._handle_new_budget_window(
spend_key="provider_spend:openai:1d",
start_time_key="provider_budget_start_time:openai",
current_time=1000.0,
response_cost=0.5,
ttl_seconds=86400,
)
assert start_time == 1000.0
assert await provider_budget.dual_cache.async_get_cache("provider_spend:openai:1d") == 0.5
assert await provider_budget.dual_cache.async_get_cache("provider_budget_start_time:openai") == 1000.0
@pytest.mark.asyncio
async def test_redis_less_limiter_tracks_spend_without_queueing_redis_increments(disable_budget_sync) -> None:
"""With no Redis there is nothing to flush to, so queued increments would be retained for the life of the process."""
limiter: Final = RouterBudgetLimiting(
dual_cache=DualCache(),
provider_budget_config={"openai": {"budget_limit": 10.0, "time_period": "1d"}},
)
for _ in range(3):
await _log_success(limiter, _success_kwargs(provider_in_litellm_params="openai", provider_in_payload="openai"))
assert await limiter.dual_cache.async_get_cache("provider_spend:openai:1d") == pytest.approx(0.75)
assert limiter.redis_increment_operation_queue == []
@pytest.mark.asyncio
async def test_deployment_budget_filter_keeps_unspent_deployment(
disable_budget_sync: None,
) -> None:
deployments: Final = [
{
"model_name": "shared",
"litellm_params": {
"model": "openai/gpt-4o-mini",
"mock_response": "spent deployment",
"max_budget": 1.0,
"budget_duration": "1d",
},
"model_info": {"id": "spent"},
},
{
"model_name": "shared",
"litellm_params": {
"model": "openai/gpt-4o-mini",
"mock_response": "available deployment",
"max_budget": 10.0,
"budget_duration": "1d",
},
"model_info": {"id": "available"},
},
]
router: Final = Router(
model_list=deployments,
provider_budget_config=None,
num_retries=0,
)
await router.cache.async_set_cache(key="deployment_spend:spent:1d", value=1.0)
response: Final = await router.acompletion(
model="shared",
messages=[{"role": "user", "content": "budget check"}],
)
assert response.choices[0].message.content == "available deployment"
assert response._hidden_params["model_id"] == "available"
def cleanup_redis():
"""Cleanup Redis cache before each test"""
try:
import redis
print("cleaning up redis..")
redis_client = redis.Redis(
host=os.getenv("REDIS_HOST"),
port=int(os.getenv("REDIS_PORT")),
password=os.getenv("REDIS_PASSWORD"),
)
print("scan iter result", redis_client.scan_iter("provider_spend:*"))
# Delete all provider spend keys
for key in redis_client.scan_iter("provider_spend:*"):
print("deleting key", key)
redis_client.delete(key)
for key in redis_client.scan_iter("deployment_spend:*"):
print("deleting key", key)
redis_client.delete(key)
for key in redis_client.scan_iter("tag_spend:*"):
print("deleting key", key)
redis_client.delete(key)
except Exception as e:
print(f"Error cleaning up Redis: {str(e)}")