litellm/tests/unit/proxy/hooks/test_parallel_request_limiter.py
zoveki ac943f6ef5
fix(passthrough): bill OpenAI Agents API turns from the session's turn usage (#51237)
* fix(passthrough): bill OpenAI Agents API turns from the session's turn usage

* fix(proxy): keep agent turn polls in the caller's OpenAI project, claim turns across workers, and price only from the session's agent

* fix(proxy): free the key's parallel request slot when an agent turn's spend row waits for usage

A call that starts an agent turn holds its spend row until OpenAI reports the turn's usage, 10 s to 1 h later. The key's max_parallel_requests slot stayed held for that whole wait, so a key with a limit of 1 got 429 on its next call. The request has ended once the row is deferred, so the billing task now releases the slot first

* fix(proxy): bill subagent turns and web searches, retry transient polls, and log waiting agent rows at shutdown

* fix(proxy): match agent turns to their call by message text and free the legacy limiter slot once

Each call now claims only a turn whose user messages hold its own text, allowing 60 s of clock skew, since OpenAI can merge messages into one turn and create a turn after the call returns. Credential errors in a poll are retried, any other poll error logs the row at $0, only subagents open during the call's turn are polled, and the legacy parallel limiter frees the slot when the row starts waiting without freeing it again when the row logs

* fix(proxy): keep a late agent turn row from blocking the key and log it when freeing the slot or costing fails

On the legacy parallel limiter, a turn row that logs in a later minute than its call no longer writes a request in flight for that minute, so a key with max_parallel_requests 1 can call again

A failure while freeing the slot early still bills the row, and a failure while costing the turns logs the row at $0 with a warning instead of losing it

* fix(proxy): log agent rows at $0 when a proxy shutdown runs out of time to poll them

When the shutdown drain's budget ran out before a waiting agent row finished its last poll, the row was dropped and the call logged nothing, where the base logged a $0 row at once

The drain now gives polls three quarters of its budget, then stops them and logs each row still waiting at $0 with a warning naming the session before it returns, so the final spend flush still writes it

* fix(proxy): retry transient reads of a settled agent turn's session and searches, and keep a later turn's subagents off earlier rows

* fix(openai_agents): never follow poll redirects or claim a turn whose items cannot be read

Polls pass follow_redirects=False so the proxy's OpenAI key never leaves
api.openai.com, a failed read of a turn's items skips that turn instead of
claiming it, and the turn claim declares its Redis key family

* fix(openai_agents): log unreadable poll bodies without their values

* fix(proxy): bill an Agents API turn once per worker and retry a failed turn read

Two calls on one worker could both pass the local claim check while the shared claim store call was in flight, so with Redis down or absent one turn was billed twice. The local claim is now written before that call

A retryable failure reading a candidate turn's items now makes the poll try again instead of skipping to a later turn that shares the call's text

Also keeps the legacy limiter's released-slot check and the module's type variables within main's lint rules after the main merge

* fix(proxy): skip turns another call claimed before reading their messages

A call checks the session's candidate turns oldest first and stops at the
first retryable failure reading a turn's messages, so it never claims a later
turn with the same text by mistake. An earlier turn that another call already
billed could keep failing that read, which held every later call on the
session at $0 until the one hour poll timeout. The call now checks this
worker's claims and the shared claim store first and skips a turn that is
already claimed.

The two helpers this module imports from the shared HTTP and logging code have
untyped parameters, so their imports carry the same reportUnknownVariableType
suppression other modules use. Main's type cleanup had removed the unknowns
this branch paid them back with.

* fix(proxy): log every waiting agent row at shutdown and count agent turns in legacy TPM

A drain the success callback budget cuts short now still stops polling, and
shutdown waits up to 5 s more for waiting agent rows to finish logging before
the final spend flush, so a short GRACEFUL_SHUTDOWN_TIMEOUT no longer drops them

The legacy limiter now counts an agent turn row's tokens toward the key's TPM
limit, reading the row's combined usage when the relayed response has none

A turn another worker claimed stays taken on this worker once seen, so a later
Redis outage cannot hand it to a second call, and the subagent list is read
across every page so an open subagent past the first 100 is billed

* fix(proxy): read every page of an agent session's turns back to the call's start

The turns list was read one page at a time, so a session or subagent with more than 100
turns after the call's start could hide the call's turn or a subagent turn from billing.
The poll now follows the list's pages until it reaches a turn older than the call (or the
claimed root turn), so sessions under 100 turns still make one request per list.

* fix(proxy): count combined usage toward legacy TPM only on agent turn rows

The legacy limiter read the row's combined usage whenever the response
carried none, so /v1/responses and /v1/messages tokens started counting
toward a key's TPM limit too. It now reads it only on rows whose slot the
agent biller released before logging, so those routes stay uncounted as
before while agent turns still count

* fix(proxy): bill percent-encoded Agents API paths and keep turn usage read before shutdown

OpenAI decodes percent-encoded path segments, so a call to
/v1/agents/sessions/<id>/%65vents reaches the events endpoint and starts
a turn. The route matcher read the raw path, so that call skipped turn
billing. It now matches the path httpx sends, decoded and with dot
segments removed

A shutdown that ran out of drain time while a turn's cost was being
looked up logged the row with no tokens, even though its usage was
already read. Now only the lookups of the agent model and web search
count are cut short, and the row keeps the usage, priced without web
searches when the agent model is known

* fix(proxy): bill Agents API paths whose dot segments are percent-encoded

A path like /v1/agents/sessions/<id>/x/%2E%2E/events reaches the events
endpoint at OpenAI, which decodes the escapes and then resolves the dot
segments. The route matcher read the decoded path, but httpx removes
only literal dot segments before it decodes, so the matcher saw x/../events
and the call skipped turn billing. The matcher now resolves dot segments
after decoding, for events calls and session creates

* fix(proxy): price an events call's turn at call-time agent settings and read all its items

An events call carries no agent, so the biller read the session's agent only
once the turn settled. A session update sent while the turn ran changed the
model or service tier the turn was priced at. The biller now reads the session
right after the call and prices the turn with that agent, falling back to the
settled read when the early read fails. Creates already carry their agent and
skip the read.

To find the turn a call started, the biller matches the call's text against the
user messages in the turn's items, but it read only the first page of 100. A
turn whose text came after 100 other items was never claimed and logged $0
after the claim window. The items are now read page by page.

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-24 11:54:08 -08:00

587 lines
24 KiB
Python

"""
Unit Tests for the max parallel request limiter v1 for the proxy
"""
import itertools
from collections.abc import Callable, Iterator, Mapping
from datetime import datetime
from typing import Final
import pytest
from litellm.caching.caching import DualCache
from litellm.constants import USAGE_ONLY_SETTLEMENT_KEY
from litellm.interactions.background_cost_polling import rebuild_logging_obj
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.common_utils.proxy_rate_limit_error import ProxyRateLimitError
from litellm.proxy.hooks.parallel_request_limiter import (
PROXY_MaxParallelRequestsHandler,
)
from litellm.proxy.utils import InternalUsageCache, ProxyLogging, hash_token
from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
from litellm.types.utils import CallTypes, EmbeddingResponse, ModelResponse, TextCompletionResponse, Usage
FROZEN_INSTANT: Final = datetime(2026, 1, 31, 23, 59, 30)
LAST_MICROSECOND_OF_JANUARY: Final = datetime(2026, 1, 31, 23, 59, 59, 999999)
FIRST_MICROSECOND_OF_FEBRUARY: Final = datetime(2026, 2, 1, 0, 0, 0, 1)
LAST_MINUTE_OF_JANUARY: Final = "2026-01-31-23-59"
FIRST_MINUTE_OF_FEBRUARY: Final = "2026-02-01-00-00"
TORN_MINUTE_OF_JANUARY: Final = "2026-01-31-00-00"
def _frozen_clock() -> datetime:
return FROZEN_INSTANT
def _clock_reading(instants: Iterator[datetime]) -> Callable[[], datetime]:
return lambda: next(instants)
def _clock_rolling_over_after_first_read() -> Callable[[], datetime]:
return _clock_reading(
itertools.chain([LAST_MICROSECOND_OF_JANUARY], itertools.repeat(FIRST_MICROSECOND_OF_FEBRUARY))
)
@pytest.mark.parametrize(
"current,rpm_limit",
[
(None, 0),
({"current_requests": 0, "current_tpm": 0, "current_rpm": 1}, 1),
],
)
@pytest.mark.asyncio
async def test_model_per_key_rate_limit_error_carries_descriptor_key(
current: Mapping[str, int] | None, rpm_limit: int
):
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache())
)
with pytest.raises(ProxyRateLimitError) as exc_info:
await handler.check_key_in_limits(
user_api_key_dict=UserAPIKeyAuth(),
cache=DualCache(),
data={"model": "gpt-4o-mini"},
call_type="completion",
max_parallel_requests=10,
tpm_limit=100,
rpm_limit=rpm_limit,
current=dict(current) if current is not None else None,
request_count_api_key="test-key:model_per_key",
rate_limit_type="model_per_key",
values_to_update_in_cache=[],
)
assert exc_info.value.descriptor_key == "model_per_key"
@pytest.mark.asyncio
async def test_pre_call_hook_counts_a_cli_session_under_the_per_user_alias_not_the_login_token():
handler = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock
)
session = UserAPIKeyAuth(
api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa",
user_id="alice",
key_alias="cli-session-alice",
is_session_token=True,
max_parallel_requests=5,
)
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
precise_minute = FROZEN_INSTANT.strftime("%Y-%m-%d-%H-%M")
counted = await handler.internal_usage_cache.async_get_cache(
key=f"cli-session-alice::{precise_minute}::request_count", litellm_parent_otel_span=None
)
assert counted == {"current_requests": 1, "current_tpm": 0, "current_rpm": 1}, counted
@pytest.mark.parametrize(
"response_obj",
[
EmbeddingResponse(
model="text-embedding-3-small",
usage=Usage(prompt_tokens=50, completion_tokens=0, total_tokens=50),
),
TextCompletionResponse(
model="gpt-3.5-turbo-instruct",
usage=Usage(prompt_tokens=20, completion_tokens=30, total_tokens=50),
),
],
)
@pytest.mark.parametrize("opened_this_minute", [True, False], ids=["opened-this-minute", "opened-last-minute"])
@pytest.mark.asyncio
async def test_async_log_success_event_counts_non_chat_response_tokens(response_obj, opened_this_minute):
"""
Embedding and text completion responses must increment the per key, user,
team, and end user TPM counters, not just chat completion ModelResponse
objects.
"""
_api_key = hash_token("sk-98765")
user_id = "ishaan"
team_id = "litellm-team"
end_user_id = "customer-1"
parallel_request_handler = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock
)
precise_minute = FROZEN_INSTANT.strftime("%Y-%m-%d-%H-%M")
scope_ids = [_api_key, user_id, team_id, end_user_id]
for scope_id in scope_ids if opened_this_minute else ():
await parallel_request_handler.internal_usage_cache.async_set_cache(
key=f"{scope_id}::{precise_minute}::request_count",
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
kwargs = {
"litellm_params": {
"metadata": {
"user_api_key": _api_key,
"user_api_key_user_id": user_id,
"user_api_key_team_id": team_id,
"user_api_key_model_max_budget": {},
}
},
"user": end_user_id,
}
await parallel_request_handler.async_log_success_event(
kwargs=kwargs,
response_obj=response_obj,
start_time=FROZEN_INSTANT,
end_time=FROZEN_INSTANT,
)
for scope_id in scope_ids:
current = await parallel_request_handler.internal_usage_cache.async_get_cache(
key=f"{scope_id}::{precise_minute}::request_count",
litellm_parent_otel_span=None,
)
assert current["current_tpm"] == 50, (
f"expected 50 tokens counted for {scope_id}, "
f"got {current['current_tpm']}"
)
def _socket_turn_events(input_tokens: int, output_tokens: int) -> list[dict[str, object]]:
usage: Final = {
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
}
return [
{"type": "response.created", "response": {"id": "resp_ws_turn", "status": "in_progress", "output": []}},
{"type": "response.completed", "response": {"id": "resp_ws_turn", "status": "completed", "usage": usage}},
]
@pytest.mark.parametrize(
"call_type, events, tokens",
[
(CallTypes.aresponses_websocket.value, _socket_turn_events(input_tokens=590, output_tokens=10), 600),
(CallTypes.aresponses.value, _socket_turn_events(input_tokens=590, output_tokens=10), 0),
],
ids=["responses-websocket-turn", "events-of-a-non-socket-call"],
)
@pytest.mark.parametrize("opened_this_minute", [True, False], ids=["opened-this-minute", "opened-last-minute"])
@pytest.mark.asyncio
async def test_async_log_success_event_counts_socket_session_tokens(
call_type: str, events: list[dict[str, object]], tokens: int, opened_this_minute: bool
):
api_key: Final = hash_token("sk-socket-session")
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock
)
precise_minute: Final = FROZEN_INSTANT.strftime("%Y-%m-%d-%H-%M")
scope_ids: Final = (api_key, "socket-user", "socket-team", "socket-end-user")
for scope_id in scope_ids if opened_this_minute else ():
await handler.internal_usage_cache.async_set_cache(
key=f"{scope_id}::{precise_minute}::request_count",
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
await handler.async_log_success_event(
kwargs={
"call_type": call_type,
"litellm_params": {
"metadata": {
"user_api_key": api_key,
"user_api_key_user_id": "socket-user",
"user_api_key_team_id": "socket-team",
"user_api_key_model_max_budget": {},
}
},
"user": "socket-end-user",
},
response_obj=events,
start_time=FROZEN_INSTANT,
end_time=FROZEN_INSTANT,
)
counted: Final = [
(
await handler.internal_usage_cache.async_get_cache(
key=f"{scope_id}::{precise_minute}::request_count", litellm_parent_otel_span=None
)
)["current_tpm"]
for scope_id in scope_ids
]
assert counted == [tokens, tokens, tokens, tokens]
@pytest.mark.asyncio
async def test_a_pre_call_across_a_minute_rollover_lands_in_the_bucket_of_its_first_clock_read():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache, clock=_clock_rolling_over_after_first_read()
)
session: Final = UserAPIKeyAuth(api_key="sk-torn-pre", max_parallel_requests=5)
api_key: Final = session.api_key
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count", litellm_parent_otel_span=None
) == {"current_requests": 1, "current_tpm": 0, "current_rpm": 1}
for torn_minute in (FIRST_MINUTE_OF_FEBRUARY, TORN_MINUTE_OF_JANUARY):
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{torn_minute}::request_count", litellm_parent_otel_span=None
) is None
@pytest.mark.asyncio
async def test_a_success_event_across_a_minute_rollover_lands_in_the_bucket_of_its_first_clock_read():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache, clock=_clock_rolling_over_after_first_read()
)
api_key: Final = hash_token("sk-torn-success")
await internal_usage_cache.async_set_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count",
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
await handler.async_log_success_event(
kwargs={
"litellm_params": {
"metadata": {"user_api_key": api_key, "user_api_key_model_max_budget": {}}
}
},
response_obj=ModelResponse(usage=Usage(prompt_tokens=5, completion_tokens=2, total_tokens=7)),
start_time=LAST_MICROSECOND_OF_JANUARY,
end_time=FIRST_MICROSECOND_OF_FEBRUARY,
)
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count", litellm_parent_otel_span=None
) == {"current_requests": 0, "current_tpm": 7, "current_rpm": 1}
for torn_minute in (FIRST_MINUTE_OF_FEBRUARY, TORN_MINUTE_OF_JANUARY):
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{torn_minute}::request_count", litellm_parent_otel_span=None
) is None
@pytest.mark.asyncio
async def test_a_failure_event_across_a_minute_rollover_lands_in_the_bucket_of_its_first_clock_read():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache, clock=_clock_rolling_over_after_first_read()
)
api_key: Final = hash_token("sk-torn-failure")
await internal_usage_cache.async_set_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count",
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
await handler.async_log_failure_event(
kwargs={
"litellm_params": {"metadata": {"user_api_key": api_key}},
"exception": Exception("upstream boom"),
},
response_obj=None,
start_time=LAST_MICROSECOND_OF_JANUARY,
end_time=FIRST_MICROSECOND_OF_FEBRUARY,
)
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count", litellm_parent_otel_span=None
) == {"current_requests": 0, "current_tpm": 0, "current_rpm": 1}
for torn_minute in (FIRST_MINUTE_OF_FEBRUARY, TORN_MINUTE_OF_JANUARY):
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::{torn_minute}::request_count", litellm_parent_otel_span=None
) is None
@pytest.mark.asyncio
async def test_a_post_call_headers_read_across_a_minute_rollover_uses_the_bucket_of_its_first_clock_read():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache, clock=_clock_rolling_over_after_first_read()
)
user_api_key_dict: Final = UserAPIKeyAuth(api_key="sk-torn-post", rpm_limit=5, tpm_limit=100)
api_key: Final = user_api_key_dict.api_key
await internal_usage_cache.async_set_cache(
key=f"{api_key}::{LAST_MINUTE_OF_JANUARY}::request_count",
value={"current_requests": 1, "current_tpm": 10, "current_rpm": 1},
litellm_parent_otel_span=None,
)
response: Final = ModelResponse()
response._hidden_params = {}
await handler.async_post_call_success_hook(
data={"model": "gpt-4o-mini"},
user_api_key_dict=user_api_key_dict,
response=response,
)
assert response._hidden_params["additional_headers"] == {
"x-ratelimit-remaining-requests": 4,
"x-ratelimit-limit-requests": 5,
"x-ratelimit-remaining-tokens": 90,
"x-ratelimit-limit-tokens": 100,
}
@pytest.mark.asyncio
async def test_a_request_in_one_minute_is_not_counted_by_a_pre_call_in_the_next_minute():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache,
clock=_clock_reading(iter([datetime(2026, 3, 10, 12, 0, 0), datetime(2026, 3, 10, 12, 1, 0)])),
)
session: Final = UserAPIKeyAuth(api_key="sk-minute-reset", rpm_limit=1)
api_key: Final = session.api_key
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
assert await internal_usage_cache.async_get_cache(
key=f"{api_key}::2026-03-10-12-01::request_count", litellm_parent_otel_span=None
) == {"current_requests": 1, "current_tpm": 0, "current_rpm": 1}
@pytest.mark.asyncio
async def test_retry_after_is_the_seconds_until_the_next_minute_of_the_injected_clock():
internal_usage_cache: Final = InternalUsageCache(DualCache())
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=internal_usage_cache,
clock=_clock_reading(itertools.repeat(datetime(2026, 3, 10, 12, 0, 45, 500000))),
)
session: Final = UserAPIKeyAuth(api_key="sk-retry-after", rpm_limit=1)
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
with pytest.raises(ProxyRateLimitError) as exc_info:
await handler.async_pre_call_hook(
user_api_key_dict=session, cache=DualCache(), data={"model": "gpt-4o-mini"}, call_type="completion"
)
assert exc_info.value.headers["retry-after"] == "14.5"
@pytest.mark.asyncio
async def test_websocket_turn_callbacks_keep_the_sockets_slot_until_the_disconnect_release():
api_key = hash_token("sk-websocket")
handler = PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock)
bucket = f"{api_key}::{FROZEN_INSTANT.strftime('%Y-%m-%d-%H-%M')}::request_count"
await handler.internal_usage_cache.async_set_cache(
key=bucket,
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
turn_kwargs = {
"call_type": CallTypes.aresponses_websocket.value,
"litellm_params": {"metadata": {"user_api_key": api_key}},
"exception": RuntimeError("provider rejected the turn"),
}
await handler.async_log_success_event(
kwargs=turn_kwargs, response_obj=None, start_time=FROZEN_INSTANT, end_time=FROZEN_INSTANT
)
await handler.async_log_failure_event(
kwargs=turn_kwargs, response_obj=None, start_time=FROZEN_INSTANT, end_time=FROZEN_INSTANT
)
after_two_turns = await handler.internal_usage_cache.async_get_cache(key=bucket, litellm_parent_otel_span=None)
assert after_two_turns["current_requests"] == 1, after_two_turns
await handler.async_release_max_parallel_requests_on_disconnect(UserAPIKeyAuth(api_key=api_key))
after_disconnect = await handler.internal_usage_cache.async_get_cache(key=bucket, litellm_parent_otel_span=None)
assert after_disconnect["current_requests"] == 0, after_disconnect
@pytest.mark.asyncio
async def test_a_background_usage_settlement_counts_its_tokens_without_freeing_another_requests_slot():
api_key = hash_token("sk-background-creator")
handler = PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock)
bucket = f"{api_key}::{FROZEN_INSTANT.strftime('%Y-%m-%d-%H-%M')}::request_count"
await handler.internal_usage_cache.async_set_cache(
key=bucket,
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 2},
litellm_parent_otel_span=None,
)
settlement = rebuild_logging_obj(
model="gpt-5.4-mini",
custom_llm_provider="openai",
call_type="pass_through_endpoint",
litellm_call_id="background-create",
function_id="background-create",
litellm_trace_id="background-trace",
start_time=FROZEN_INSTANT,
litellm_params={"metadata": {"user_api_key": api_key, "user_api_key_model_max_budget": {}}},
)
await handler.async_log_success_event(
kwargs={**settlement.model_call_details, USAGE_ONLY_SETTLEMENT_KEY: True},
response_obj=ModelResponse(usage=Usage(prompt_tokens=8, completion_tokens=4, total_tokens=12)),
start_time=FROZEN_INSTANT,
end_time=FROZEN_INSTANT,
)
after_settlement = await handler.internal_usage_cache.async_get_cache(key=bucket, litellm_parent_otel_span=None)
assert after_settlement == {"current_requests": 1, "current_tpm": 12, "current_rpm": 2}, after_settlement
@pytest.mark.asyncio
async def test_a_background_usage_settlement_in_an_uncounted_minute_leaves_the_creator_free_to_send_its_next_request():
api_key: Final = hash_token("sk-background-creator-new-minute")
minute: Final = FROZEN_INSTANT.strftime("%Y-%m-%d-%H-%M")
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock
)
settlement: Final = rebuild_logging_obj(
model="gpt-5.4-mini",
custom_llm_provider="openai",
call_type="pass_through_endpoint",
litellm_call_id="background-create",
function_id="background-create",
litellm_trace_id="background-trace",
start_time=FROZEN_INSTANT,
litellm_params={
"metadata": {
"user_api_key": api_key,
"user_api_key_user_id": "creator-user",
"user_api_key_team_id": "creator-team",
"user_api_key_model_max_budget": {},
"model_group": "gpt-5.4-mini",
}
},
)
await handler.async_log_success_event(
kwargs={**settlement.model_call_details, USAGE_ONLY_SETTLEMENT_KEY: True, "user": "creator-end-user"},
response_obj=ModelResponse(usage=Usage(prompt_tokens=8, completion_tokens=4, total_tokens=12)),
start_time=FROZEN_INSTANT,
end_time=FROZEN_INSTANT,
)
bucket_keys: Final = (
f"{api_key}::{minute}::request_count",
f"{api_key}::gpt-5.4-mini::{minute}::request_count",
f"creator-user::{minute}::request_count",
f"creator-team::{minute}::request_count",
f"creator-end-user::{minute}::request_count",
)
buckets: Final = tuple(
[await handler.internal_usage_cache.async_get_cache(key=key, litellm_parent_otel_span=None) for key in bucket_keys]
)
assert buckets == ({"current_requests": 0, "current_tpm": 12, "current_rpm": 0},) * 5, buckets
await handler.async_pre_call_hook(
user_api_key_dict=UserAPIKeyAuth(api_key=api_key, max_parallel_requests=1),
cache=DualCache(),
data={"model": "gpt-5.4-mini"},
call_type="completion",
)
@pytest.mark.parametrize(
"call_type,response_obj",
[
(
CallTypes.aresponses.value,
ResponsesAPIResponse(
id="resp_uncounted",
created_at=0,
output=[],
status="completed",
usage=ResponseAPIUsage(input_tokens=1407, output_tokens=10, total_tokens=1417),
),
),
(
CallTypes.anthropic_messages.value,
{"type": "message", "usage": {"input_tokens": 1407, "output_tokens": 10}},
),
],
ids=["responses", "messages"],
)
@pytest.mark.asyncio
async def test_a_response_the_legacy_limiter_does_not_count_stays_uncounted_when_its_row_carries_combined_usage(
call_type: str, response_obj: object
):
api_key: Final = hash_token("sk-uncounted-route")
handler: Final = PROXY_MaxParallelRequestsHandler(
internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock
)
key: Final = UserAPIKeyAuth(api_key=api_key, tpm_limit=1000)
async def call() -> None:
await handler.async_pre_call_hook(
user_api_key_dict=key, cache=DualCache(), data={"model": "gpt-5.4-mini"}, call_type=call_type
)
await call()
await handler.async_log_success_event(
kwargs={
"call_type": call_type,
"litellm_params": {"metadata": {"user_api_key": api_key, "user_api_key_model_max_budget": {}}},
"combined_usage_object": Usage(prompt_tokens=1407, completion_tokens=10, total_tokens=1417),
},
response_obj=response_obj,
start_time=FROZEN_INSTANT,
end_time=FROZEN_INSTANT,
)
await call()
counted: Final = await handler.internal_usage_cache.async_get_cache(
key=f"{api_key}::{FROZEN_INSTANT.strftime('%Y-%m-%d-%H-%M')}::request_count", litellm_parent_otel_span=None
)
assert counted == {"current_requests": 1, "current_tpm": 0, "current_rpm": 2}, counted
@pytest.mark.asyncio
async def test_a_rejected_realtime_attempt_does_not_free_a_slot_it_never_took():
api_key = hash_token("sk-at-limit")
handler = PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(DualCache()), clock=_frozen_clock)
bucket = f"{api_key}::{FROZEN_INSTANT.strftime('%Y-%m-%d-%H-%M')}::request_count"
await handler.internal_usage_cache.async_set_cache(
key=bucket,
value={"current_requests": 1, "current_tpm": 0, "current_rpm": 1},
litellm_parent_otel_span=None,
)
proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())
proxy_logging_obj.proxy_hook_mapping["parallel_request_limiter"] = handler
auth = UserAPIKeyAuth(api_key=api_key, max_parallel_requests=1)
await proxy_logging_obj.arelease_max_parallel_requests_on_disconnect(auth)
after_rejection = await handler.internal_usage_cache.async_get_cache(key=bucket, litellm_parent_otel_span=None)
assert after_rejection["current_requests"] == 1, after_rejection
await proxy_logging_obj.arelease_responses_websocket_slot(auth)
after_socket_close = await handler.internal_usage_cache.async_get_cache(key=bucket, litellm_parent_otel_span=None)
assert after_socket_close["current_requests"] == 0, after_socket_close