Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge upstream/litellm_internal_staging and fix batch quota review comments

Shivi Jain8a44c1492811
diff --cc basedpyright-code-budget.json
index 67b0575a0cb,06010c706e3..9237fc95f4e
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -57,7 -57,7 +57,7 @@@
"limit": 5707
},
"reportMissingTypeArgument": {
- "limit": 15641
- "limit": 15640
++ "limit": 15639
},
"reportMissingTypeStubs": {
"limit": 40
@@@ -108,7 -108,7 +108,7 @@@
"limit": 39237
},
"reportUnknownParameterType": {
- "limit": 19968
- "limit": 19967
++ "limit": 19966
},
"reportUnknownVariableType": {
"limit": 30881
diff --cc litellm/proxy/hooks/batch_rate_limiter.py
index efef246a7a6,7e33583fc9d..3b53d792ce6
--- a/litellm/proxy/hooks/batch_rate_limiter.py
+++ b/litellm/proxy/hooks/batch_rate_limiter.py
@@@ -18,12 -18,11 +18,12 @@@ Quick summary
"""
import json
-from collections.abc import Iterable
-from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn
+from collections.abc import Iterable, Mapping, Sequence
+from types import MappingProxyType
- from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn
++from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn, TypeAlias
from fastapi import HTTPException
- from pydantic import BaseModel, TypeAdapter
-from pydantic import BaseModel
++from pydantic import BaseModel, Field, TypeAdapter
import litellm
from litellm._logging import verbose_proxy_logger
@@@ -41,11 -40,10 +41,15 @@@ from litellm.proxy._types import
SpecialModelNames,
UserAPIKeyAuth,
)
++from litellm.proxy.auth.auth_utils import get_model_rate_limit_from_metadata
from litellm.proxy.common_utils.proxy_rate_limit_error import (
ProxyRateLimitError,
map_v3_rate_limit_type,
)
- from litellm.proxy.hooks.parallel_request_limiter_v3 import PROJECT_OTPM_DESCRIPTOR_KEY
++from litellm.proxy.hooks.parallel_request_limiter_v3 import (
++ PROJECT_ITPM_DESCRIPTOR_KEY,
++ PROJECT_OTPM_DESCRIPTOR_KEY,
++)
from litellm.proxy.hooks.rate_limiter_utils import resolve_llm_provider_for_rate_limit
if TYPE_CHECKING:
@@@ -78,9 -76,6 +82,11 @@@ else
RateLimitDescriptor = dict[str, Any]
+_BATCH_BODY_ADAPTER: Final = TypeAdapter(dict[str, object])
+
++IncrementAmounts: TypeAlias = dict[Literal["requests", "tokens"], int]
++
+
class BatchFileUsage(BaseModel):
"""
Internal model for batch file usage tracking, used for batch rate limiting
@@@ -88,7 -83,6 +94,16 @@@
total_tokens: int
request_count: int
+ output_tokens: int = 0
++ # Keyed by each row's own `body.model`, distinct from `total_tokens`/
++ # `output_tokens` (the whole-file totals charged to the file-bound/
++ # top-level routing model's key/team/model limits). A batch's rows can
++ # each target a different model, so the project's per-model ITPM/OTPM
++ # quota for a row's actual model must be charged with that row's own
++ # tokens -- see `_create_project_io_descriptors_for_models`.
++ per_model_usage: dict[str, dict[str, int]] = Field(
++ default_factory=dict
++ ) # mutable-ok: accumulated incrementally per row while parsing the batch file
class _PROXY_BatchRateLimiter(CustomLogger):
@@@ -204,27 -198,14 +219,74 @@@
user_api_key_dict: UserAPIKeyAuth,
data: dict,
) -> list["RateLimitDescriptor"]:
- """Build the descriptor list a batch submission is charged against.
-
- Includes the project-scoped ITPM/OTPM descriptors alongside the
- standard key/user/team/model ones so a project caller can't bypass
- its configured token quotas by submitting a batch instead of a
- synchronous request.
++ """Build the standard key/user/team/model descriptor list a batch is charged against.
++
++ Deliberately excludes the project-scoped ITPM/OTPM descriptors: those
++ are charged per the JSONL row's own `body.model` once the file is
++ parsed (`_create_project_io_descriptors_for_models`), not the
++ file-bound/top-level routing model this function resolves. Charging
++ project quotas here would let a caller bind the file to a model
++ without a quota while rows execute against a quota-limited model.
+ """
- descriptors: Final = self.parallel_request_limiter._create_rate_limit_descriptors(
+ return self.parallel_request_limiter._create_rate_limit_descriptors(
user_api_key_dict=user_api_key_dict,
data=data,
rpm_limit_type=None,
tpm_limit_type=None,
model_has_failures=False,
)
- self.parallel_request_limiter.add_project_io_token_rate_limit_descriptors_from_metadata(
- user_api_key_dict=user_api_key_dict,
- requested_model=self._get_batch_routing_model(data),
- descriptors=descriptors,
- )
- return descriptors
+
++ @staticmethod
++ def _project_has_any_io_token_limits(user_api_key_dict: UserAPIKeyAuth) -> bool:
++ """True when the project has any per-model ITPM/OTPM quota configured.
++
++ Used to stop the "skip batch input file processing" fast path from
++ bypassing a project quota configured for a model other than the
++ batch's file-bound/top-level routing model: the row models that
++ actually drive execution and billing aren't known until the JSONL
++ is parsed, so the file must be read whenever *any* model could be
++ quota-limited, not only when the routing model itself is.
++ """
++ if user_api_key_dict.project_id is None:
++ return False
++ return bool(
++ get_model_rate_limit_from_metadata(user_api_key_dict, "project_metadata", "model_itpm_limit")
++ ) or bool(get_model_rate_limit_from_metadata(user_api_key_dict, "project_metadata", "model_otpm_limit"))
++
++ def _create_project_io_descriptors_for_models(
++ self,
++ user_api_key_dict: UserAPIKeyAuth,
++ per_model_usage: Mapping[str, Mapping[str, int]],
++ ) -> tuple[list["RateLimitDescriptor"], list[IncrementAmounts]]: # mutable-ok: see below
++ """Build project ITPM/OTPM descriptors charged against each row's own model.
++
++ One descriptor pair per distinct `body.model` found in the JSONL,
++ each incremented only by that model's own counted usage -- never the
++ whole-batch total -- so a quota-limited model can't hide behind an
++ unlimited routing model, and an unrelated model's rows can't inflate
++ a different model's counter.
++ """
++ extra_descriptors: Final[list[RateLimitDescriptor]] = [] # mutable-ok: see above
++ extra_increments: Final[list[IncrementAmounts]] = [] # mutable-ok: see above
++ for model, usage in per_model_usage.items():
++ model_descriptors: list[RateLimitDescriptor] = [] # mutable-ok: reset per loop iteration, not module state
++ self.parallel_request_limiter.add_project_io_token_rate_limit_descriptors_from_metadata(
++ user_api_key_dict=user_api_key_dict,
++ requested_model=model,
++ descriptors=model_descriptors,
++ )
++ for descriptor in model_descriptors:
++ extra_descriptors.append(descriptor)
++ extra_increments.append(
++ { # mutable-ok: atomic limiter API requires mutable increment records
++ "requests": 0,
++ "tokens": usage.get("output_tokens", 0)
++ if descriptor["key"] == PROJECT_OTPM_DESCRIPTOR_KEY
++ else usage.get("total_tokens", 0),
++ }
++ )
++ return extra_descriptors, extra_increments
+
def _should_skip_batch_input_file_processing(
self,
data: dict,
@@@ -251,6 -232,6 +313,11 @@@
routing deployment's trusted credentials and the batch is constrained
to run on that provider.
++ The no-limits check also treats any project-configured ITPM/OTPM
++ quota as an applicable limit, even when it isn't scoped to the
++ routing model: a row can target a different, quota-limited model,
++ and that isn't knowable without parsing the JSONL.
++
Returns ``(should_skip, descriptors)`` where ``descriptors`` is the
rate-limit descriptor list computed for the no-limits check, so the
caller can reuse it for counter enforcement without recomputing.
@@@ -276,7 -257,7 +343,9 @@@
user_api_key_dict=user_api_key_dict,
data=data,
)
-- if not self._has_applicable_batch_rate_limits(descriptors):
++ if not self._has_applicable_batch_rate_limits(descriptors) and not self._project_has_any_io_token_limits(
++ user_api_key_dict
++ ):
verbose_proxy_logger.debug("Skipping batch input file processing: no rate limits configured")
return True, None
@@@ -430,9 -382,9 +499,22 @@@
"""Raise :class:`ProxyRateLimitError` (a 429) for batch rate limit exceeded."""
from datetime import datetime
-- # Find the descriptor for this status
++ # Find the descriptor for this status. Matching on (key, value) is
++ # required, not key alone: a batch can carry several project ITPM/OTPM
++ # descriptors sharing one key (e.g. `model_per_project_otpm`) but
++ # scoped to different models via `value`
++ # ("{project_id}:{model}") -- key-only matching would always resolve
++ # to the first same-keyed descriptor regardless of which one was
++ # actually over its limit. Falls back to key-only matching for
++ # statuses that predate `descriptor_value` (e.g. from should_rate_limit).
++ status_descriptor_value: Final = status.get("descriptor_value")
descriptor_index: Final = next(
-- (i for i, d in enumerate(descriptors) if d.get("key") == status.get("descriptor_key")),
++ (
++ i
++ for i, d in enumerate(descriptors)
++ if d.get("key") == status.get("descriptor_key")
++ and (status_descriptor_value is None or d.get("value") == status_descriptor_value)
++ ),
0,
)
descriptor: Final[RateLimitDescriptor] = (
@@@ -455,14 -407,9 +537,27 @@@
f"Limit resets at: {reset_time_formatted}"
)
else: # tokens
++ # Project ITPM/OTPM descriptors are keyed "{project_id}:{model}" and
++ # charged with that model's own rows (see
++ # `_create_project_io_descriptors_for_models`), not the whole
++ # batch's totals -- report the matching per-model figure when one
++ # is available so the error reflects what was actually charged.
++ descriptor_model: Final = (
++ descriptor.get("value", "").split(":", 1)[-1]
++ if descriptor.get("key") in (PROJECT_ITPM_DESCRIPTOR_KEY, PROJECT_OTPM_DESCRIPTOR_KEY)
++ else None
++ )
++ model_usage: Final = batch_usage.per_model_usage.get(descriptor_model) if descriptor_model else None
+ batch_token_count: Final = (
- batch_usage.output_tokens
++ (model_usage or {}).get("output_tokens", batch_usage.output_tokens)
+ if descriptor.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
++ else (model_usage or {}).get("total_tokens", batch_usage.total_tokens)
++ if descriptor.get("key") == PROJECT_ITPM_DESCRIPTOR_KEY
+ else batch_usage.total_tokens
+ )
detail = (
f"Batch rate limit exceeded for {descriptor.get('key', 'unknown')}: {descriptor.get('value', 'unknown')}. "
- f"Batch contains {batch_usage.total_tokens} tokens but only {remaining_display} tokens remaining "
+ f"Batch contains {batch_token_count} tokens but only {remaining_display} tokens remaining "
f"out of {current_limit} TPM limit. "
f"Limit resets at: {reset_time_formatted}"
)
@@@ -497,7 -444,7 +592,10 @@@
falls back to a per-process asyncio.Lock + in-memory operation.
``descriptors`` may be passed in by the pre-call hook to reuse the list
-- already computed when deciding whether to skip file processing.
++ already computed when deciding whether to skip file processing. It
++ never contains project ITPM/OTPM descriptors (those are model-specific
++ and only knowable once ``batch_usage.per_model_usage`` is populated by
++ parsing the JSONL), so this always builds and appends them here.
"""
if descriptors is None:
descriptors = self._create_batch_rate_limit_descriptors(
@@@ -505,16 -452,12 +603,21 @@@
data=data,
)
- increments: Final = [ # mutable-ok: atomic limiter API requires mutable increment records
- increment: Final[dict[Literal["requests", "tokens"], int]] = {
- "requests": batch_usage.request_count,
- "tokens": batch_usage.total_tokens,
- }
- increments: Final[list[dict[Literal["requests", "tokens"], int]]] = [increment for _ in descriptors]
++ increments: list[IncrementAmounts] = [ # mutable-ok: reassigned below to append project IO increments
+ { # mutable-ok: atomic limiter API requires mutable increment records
+ "requests": batch_usage.request_count,
- "tokens": batch_usage.output_tokens
- if d.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
- else batch_usage.total_tokens,
++ "tokens": batch_usage.total_tokens,
+ }
- for d in descriptors
++ for _d in descriptors
+ ]
+
++ project_io_descriptors, project_io_increments = self._create_project_io_descriptors_for_models(
++ user_api_key_dict=user_api_key_dict,
++ per_model_usage=batch_usage.per_model_usage,
++ )
++ descriptors = [*descriptors, *project_io_descriptors]
++ increments = [*increments, *project_io_increments]
+
rate_limit_response: Final = await self.parallel_request_limiter.atomic_check_and_increment_by_n(
descriptors=descriptors,
increments=increments,
@@@ -548,21 -490,10 +651,37 @@@
file_id: The file ID to read
custom_llm_provider: The custom LLM provider to use for token encoding
user_api_key_dict: User authentication information for file access (required for managed files)
+ descriptors: Rate limit descriptors already computed for this batch, so the
+ configured project OTPM limit can scale the no-``max_tokens`` output floor
Returns:
- BatchFileUsage with total_tokens, output_tokens, and request_count
- BatchFileUsage with total_tokens and request_count
++ BatchFileUsage with total_tokens, output_tokens, request_count, and
++ per_model_usage (each row's own totals, keyed by its `body.model`)
"""
- otpm_limits: Final = tuple(
++ descriptor_otpm_limits: Final = tuple(
+ int(v)
+ for d in (descriptors or ())
+ if d.get("key") == PROJECT_OTPM_DESCRIPTOR_KEY
+ for rate_limit in (d.get("rate_limit"),)
+ for v in (rate_limit.get("tokens_per_unit") if rate_limit is not None else None,)
+ if v is not None
+ )
- min_configured_otpm_limit: Final = min(otpm_limits) if otpm_limits else None
++ # `descriptors` only ever carries the routing model's own OTPM limit
++ # (see `_create_batch_rate_limit_descriptors`), but a row can target
++ # any project-configured model. Folding in every configured model's
++ # OTPM limit keeps the no-`max_tokens` floor from drifting wide just
++ # because a row's specific model isn't known until parsed below.
++ project_otpm_limits: Final = (
++ tuple(int(v) for v in project_otpm_limit_map.values())
++ if user_api_key_dict is not None
++ and (
++ project_otpm_limit_map := get_model_rate_limit_from_metadata(
++ user_api_key_dict, "project_metadata", "model_otpm_limit"
++ )
++ )
++ else ()
++ )
++ min_configured_otpm_limit: Final = min((*descriptor_otpm_limits, *project_otpm_limits), default=None)
try:
# Check if this is a managed file (base64 encoded unified file ID)
from litellm.proxy.openai_files_endpoints.common_utils import (
@@@ -614,28 -545,23 +733,51 @@@
# Counting stays best-effort, so a legitimate (e.g. multimodal) row
# the counter can't measure is estimated, not hard-rejected.
models: Final[set] = set()
++ # Keyed by each row's own `body.model`, so the project ITPM/OTPM
++ # quota for that model is charged with only its own rows' tokens,
++ # never the whole batch's -- see `_create_project_io_descriptors_for_models`.
++ per_model_usage: Final[dict[str, dict[str, int]]] = {}
total_tokens = 0
+ output_tokens = 0 # rebind-ok: accumulated per JSONL row in the loop below
request_count = 0
for raw_line in _iter_batch_input_lines(file_content_bytes):
request_count += 1
try:
entry = json.loads(raw_line)
except Exception:
-- total_tokens += _estimate_batch_entry_tokens(raw_line)
- output_tokens += self.parallel_request_limiter.no_max_tokens_output_floor(min_configured_otpm_limit)
++ entry_total_tokens = _estimate_batch_entry_tokens(raw_line)
++ entry_output_tokens = self.parallel_request_limiter.no_max_tokens_output_floor(
++ min_configured_otpm_limit
++ )
++ total_tokens += entry_total_tokens
++ output_tokens += entry_output_tokens
continue
++
++ model: str | None = (entry.get("body") or {}).get("model") if isinstance(entry, dict) else None
++ if model:
++ models.add(model)
++
if isinstance(entry, dict):
-- model = (entry.get("body") or {}).get("model")
-- if model:
-- models.add(model)
- output_tokens += self._estimate_entry_output_tokens(entry, min_configured_otpm_limit)
++ entry_output_tokens = self._estimate_entry_output_tokens(entry, min_configured_otpm_limit)
+ else:
- output_tokens += self.parallel_request_limiter.no_max_tokens_output_floor(min_configured_otpm_limit)
++ entry_output_tokens = self.parallel_request_limiter.no_max_tokens_output_floor(
++ min_configured_otpm_limit
++ )
++ output_tokens += entry_output_tokens
++
try:
-- total_tokens += _count_entry_tokens(entry)
++ entry_total_tokens = _count_entry_tokens(entry)
except Exception:
-- total_tokens += _estimate_batch_entry_tokens(raw_line)
++ entry_total_tokens = _estimate_batch_entry_tokens(raw_line)
++ total_tokens += entry_total_tokens
++
++ if model:
++ model_usage = per_model_usage.setdefault(
++ model, {"total_tokens": 0, "output_tokens": 0, "request_count": 0}
++ )
++ model_usage["total_tokens"] += entry_total_tokens
++ model_usage["output_tokens"] += entry_output_tokens
++ model_usage["request_count"] += 1
# Validate every model named in the batch JSONL against the
# caller's per-key model allowlist. Without this, a caller
@@@ -652,7 -578,6 +794,8 @@@
return BatchFileUsage(
total_tokens=total_tokens,
request_count=request_count,
+ output_tokens=output_tokens,
++ per_model_usage=per_model_usage,
)
except HTTPException as e:
diff --cc litellm/proxy/hooks/parallel_request_limiter_v3.py
index f858fd2af98,94ef08782d9..80d58abee7d
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@@ -409,6 -341,6 +409,12 @@@ class RateLimitStatus(TypedDict)
limit_remaining: int
rate_limit_type: Literal["requests", "tokens", "max_parallel_requests"]
descriptor_key: str
++ # Only populated by the atomic_check_and_increment_by_n path. A caller
++ # matching a status back to its descriptor must key on (descriptor_key,
++ # descriptor_value) when this is present, not descriptor_key alone --
++ # e.g. a batch charging several models' project ITPM/OTPM in one call
++ # produces multiple statuses sharing the same descriptor_key.
++ descriptor_value: NotRequired[ReadOnly[str]]
class RateLimitResponse(TypedDict):
@@@ -441,6 -362,6 +447,7 @@@ class WindowKeyMetadata(TypedDict)
class AtomicCounterMeta(TypedDict):
descriptor_key: str
++ descriptor_value: ReadOnly[str]
current_limit: int
rate_limit_type: Literal["requests", "tokens"]
window_key: str
@@@ -1732,6 -1463,6 +1739,7 @@@ class _PROXY_MaxParallelRequestsHandler
meta.append(
{
"descriptor_key": descriptor_key,
++ "descriptor_value": descriptor_value,
"current_limit": int(limit_value),
"rate_limit_type": rlt,
"window_key": window_key,
@@@ -1865,6 -1585,6 +1873,7 @@@
limit_remaining=max(0, limit - current_counter),
rate_limit_type=meta["rate_limit_type"],
descriptor_key=meta["descriptor_key"],
++ descriptor_value=meta["descriptor_value"],
)
],
)
@@@ -1879,20 -1598,9 +1888,21 @@@
limit_remaining=max(0, meta["current_limit"] - int(new_counter)),
rate_limit_type=meta["rate_limit_type"],
descriptor_key=meta["descriptor_key"],
++ descriptor_value=meta["descriptor_value"],
)
)
- return RateLimitResponse(overall_code="OK", statuses=statuses)
+ return RateLimitResponse(
+ overall_code="OK",
+ statuses=statuses,
+ reservation_windows=frozenset(
+ (
+ meta["counter_key"],
+ str(int(raw[2 + index * 2])),
+ "redis",
+ )
+ for index, meta in enumerate(per_counter_meta)
+ ),
+ )
async def _atomic_check_and_increment_in_memory(
self,
@@@ -1945,6 -1653,6 +1955,7 @@@
limit_remaining=max(0, meta["current_limit"] - current_counter),
rate_limit_type=meta["rate_limit_type"],
descriptor_key=meta["descriptor_key"],
++ descriptor_value=meta["descriptor_value"],
)
],
)
@@@ -1982,16 -1684,9 +1993,17 @@@
limit_remaining=max(0, meta["current_limit"] - new_counter),
rate_limit_type=meta["rate_limit_type"],
descriptor_key=meta["descriptor_key"],
++ descriptor_value=meta["descriptor_value"],
)
)
- return RateLimitResponse(overall_code="OK", statuses=statuses)
+ return RateLimitResponse(
+ overall_code="OK",
+ statuses=statuses,
+ reservation_windows=frozenset(
+ (meta["counter_key"], state["window_start"], "local")
+ for meta, state in zip(per_counter_meta, descriptor_state)
+ ),
+ )
async def reserve_tpm_tokens(
self,
diff --cc tests/test_litellm/proxy/hooks/test_batch_file_validation.py
index c2e1ed4a0c1,7ff1bc11d81..ee37cf7d302
--- a/tests/test_litellm/proxy/hooks/test_batch_file_validation.py
+++ b/tests/test_litellm/proxy/hooks/test_batch_file_validation.py
@@@ -1382,121 -1382,6 +1382,315 @@@ async def test_check_and_increment_comp
parallel_request_limiter._create_rate_limit_descriptors.assert_called_once()
+async def test_pre_call_enforces_project_otpm_limit_for_batch():
+ """VERIA regression: ``_create_batch_rate_limit_descriptors`` only asked
+ for the generic key/user/team/model descriptors, so a project caller
+ could submit a batch that consumed none of its configured project OTPM
+ quota. The project OTPM descriptor must now be present and charged with
+ the batch's estimated *output* tokens, not its input tokens."""
+ from litellm import DualCache
+ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
+ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
+ _PROXY_MaxParallelRequestsHandler_v3,
+ )
+ from litellm.proxy.utils import InternalUsageCache
+
+ local_cache = DualCache()
+ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ rate_limiter = _PROXY_BatchRateLimiter(
+ internal_usage_cache=InternalUsageCache(local_cache),
+ parallel_request_limiter=parallel_request_limiter,
+ )
+
+ user = UserAPIKeyAuth(
+ api_key="sk-project-batch-otpm",
+ models=["*"],
+ project_id="proj-mantle-batch",
+ project_metadata={"model_otpm_limit": {"gpt-4o-mini": 50}},
+ )
+
+ # Two rows each declaring max_tokens=40: 80 output tokens total, over the
+ # configured 50-token project OTPM limit but negligible input tokens.
+ mock_content = MagicMock()
+ mock_content.content = (
+ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 40, '
+ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
+ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 40, '
+ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
+ )
+
+ with (
+ patch("litellm.proxy.proxy_server.general_settings", {}),
+ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
+ patch(
+ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
+ return_value={"custom_llm_provider": "openai"},
+ ),
+ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
+ ):
+ with pytest.raises(HTTPException) as exc:
+ await rate_limiter.async_pre_call_hook(
+ user_api_key_dict=user,
+ cache=local_cache,
+ data={"input_file_id": "file-abc123", "model": "gpt-4o-mini"},
+ call_type="acreate_batch",
+ )
+
+ assert exc.value.status_code == 429
+ assert "model_per_project_otpm" in str(exc.value.detail)
+
+
+async def test_pre_call_enforces_project_itpm_limit_for_batch():
+ """Companion to the OTPM regression above: a project's ITPM quota must
+ also apply to batch submissions."""
+ from litellm import DualCache
+ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
+ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
+ _PROXY_MaxParallelRequestsHandler_v3,
+ )
+ from litellm.proxy.utils import InternalUsageCache
+
+ local_cache = DualCache()
+ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
+ internal_usage_cache=InternalUsageCache(local_cache)
+ )
+ rate_limiter = _PROXY_BatchRateLimiter(
+ internal_usage_cache=InternalUsageCache(local_cache),
+ parallel_request_limiter=parallel_request_limiter,
+ )
+
+ user = UserAPIKeyAuth(
+ api_key="sk-project-batch-itpm",
+ models=["*"],
+ project_id="proj-mantle-batch",
+ project_metadata={"model_itpm_limit": {"gpt-4o-mini": 1}},
+ )
+
+ mock_content = MagicMock()
+ mock_content.content = (
+ b'{"body": {"model": "gpt-4o-mini", "max_tokens": 1, '
+ b'"messages": [{"role": "user", "content": "well over one token of input"}]}}\n'
+ )
+
+ with (
+ patch("litellm.proxy.proxy_server.general_settings", {}),
+ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
+ patch(
+ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
+ return_value={"custom_llm_provider": "openai"},
+ ),
+ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
+ ):
+ with pytest.raises(HTTPException) as exc:
+ await rate_limiter.async_pre_call_hook(
+ user_api_key_dict=user,
+ cache=local_cache,
+ data={"input_file_id": "file-abc123", "model": "gpt-4o-mini"},
+ call_type="acreate_batch",
+ )
+
+ assert exc.value.status_code == 429
+ assert "model_per_project_itpm" in str(exc.value.detail)
+
+
++async def test_pre_call_enforces_project_otpm_limit_for_non_routing_row_model():
++ """VERIA regression: project ITPM/OTPM descriptors were built only for the
++ file-bound/top-level routing model, so a caller could bind the batch file
++ to an unlimited model while a JSONL row's own `body.model` named a
++ different, quota-limited model. That row's tokens must still be charged
++ against its own model's project OTPM quota."""
++ from litellm import DualCache
++ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
++ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
++ _PROXY_MaxParallelRequestsHandler_v3,
++ )
++ from litellm.proxy.utils import InternalUsageCache
++
++ local_cache = DualCache()
++ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
++ internal_usage_cache=InternalUsageCache(local_cache)
++ )
++ rate_limiter = _PROXY_BatchRateLimiter(
++ internal_usage_cache=InternalUsageCache(local_cache),
++ parallel_request_limiter=parallel_request_limiter,
++ )
++
++ # The routing model ("unlimited-model") has no configured quota; only
++ # "quota-limited-model" -- named inside the JSONL row, not the routing
++ # model -- has a project OTPM limit.
++ user = UserAPIKeyAuth(
++ api_key="sk-project-batch-cross-model",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={"model_otpm_limit": {"quota-limited-model": 50}},
++ )
++
++ mock_content = MagicMock()
++ mock_content.content = (
++ b'{"body": {"model": "quota-limited-model", "max_tokens": 80, '
++ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
++ )
++
++ with (
++ patch("litellm.proxy.proxy_server.general_settings", {}),
++ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
++ patch(
++ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
++ return_value={"custom_llm_provider": "openai"},
++ ),
++ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
++ ):
++ with pytest.raises(HTTPException) as exc:
++ await rate_limiter.async_pre_call_hook(
++ user_api_key_dict=user,
++ cache=local_cache,
++ data={"input_file_id": "file-abc123", "model": "unlimited-model"},
++ call_type="acreate_batch",
++ )
++
++ assert exc.value.status_code == 429
++ assert "model_per_project_otpm" in str(exc.value.detail)
++ assert "quota-limited-model" in str(exc.value.detail)
++
++
++async def test_pre_call_charges_each_row_model_against_its_own_project_quota():
++ """A batch whose rows target two different project-quota-limited models
++ must charge each row's tokens only against its own model's quota, never
++ the other model's or the whole batch's combined total. The under-limit
++ model's request must succeed even though the over-limit model's row
++ would fail on its own."""
++ from litellm import DualCache
++ from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
++ from litellm.proxy.hooks.parallel_request_limiter_v3 import (
++ PROJECT_OTPM_DESCRIPTOR_KEY,
++ _PROXY_MaxParallelRequestsHandler_v3,
++ )
++ from litellm.proxy.utils import InternalUsageCache
++
++ local_cache = DualCache()
++ parallel_request_limiter = _PROXY_MaxParallelRequestsHandler_v3(
++ internal_usage_cache=InternalUsageCache(local_cache)
++ )
++ rate_limiter = _PROXY_BatchRateLimiter(
++ internal_usage_cache=InternalUsageCache(local_cache),
++ parallel_request_limiter=parallel_request_limiter,
++ )
++
++ user = UserAPIKeyAuth(
++ api_key="sk-project-batch-two-models",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={
++ "model_otpm_limit": {"model-a": 1000, "model-b": 10},
++ },
++ )
++
++ # model-a stays comfortably under its 1000 OTPM limit; model-b's single
++ # row alone exceeds its 10 OTPM limit. If the two were combined into one
++ # counter (the pre-fix behavior for the routing model), model-a's ample
++ # headroom would mask model-b's overage.
++ mock_content = MagicMock()
++ mock_content.content = (
++ b'{"body": {"model": "model-a", "max_tokens": 5, '
++ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
++ b'{"body": {"model": "model-b", "max_tokens": 40, '
++ b'"messages": [{"role": "user", "content": "hi"}]}}\n'
++ )
++
++ with (
++ patch("litellm.proxy.proxy_server.general_settings", {}),
++ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),
++ patch(
++ "litellm.proxy.openai_files_endpoints.common_utils.get_credentials_for_model",
++ return_value={"custom_llm_provider": "openai"},
++ ),
++ patch("litellm.afile_content", new=AsyncMock(return_value=mock_content)),
++ ):
++ with pytest.raises(HTTPException) as exc:
++ await rate_limiter.async_pre_call_hook(
++ user_api_key_dict=user,
++ cache=local_cache,
++ data={"input_file_id": "file-abc123", "model": "model-a"},
++ call_type="acreate_batch",
++ )
++
++ assert exc.value.status_code == 429
++ assert "model-b" in str(exc.value.detail)
++
++ # model-a's own counter was not touched by model-b's rejection: a
++ # follow-up model-a-only batch well within its own limit must still pass.
++ model_a_status = await parallel_request_limiter.should_rate_limit(
++ descriptors=[
++ {
++ "key": PROJECT_OTPM_DESCRIPTOR_KEY,
++ "value": "proj-mantle-batch:model-a",
++ "rate_limit": {
++ "requests_per_unit": None,
++ "tokens_per_unit": 1000,
++ "window_size": parallel_request_limiter.window_size,
++ },
++ }
++ ],
++ read_only=True,
++ )
++ assert model_a_status["overall_code"] == "OK"
++
++
++def test_should_not_skip_when_project_has_io_limit_for_non_routing_model():
++ """The no-limits skip must not fire just because the file-bound/top-level
++ routing model itself has no configured quota: a JSONL row can name a
++ different model that the project *does* quota, and that isn't knowable
++ without downloading and parsing the file."""
++ rate_limiter = _make_rate_limiter()
++ # No key/team/model-level limits at all -- only a project OTPM limit for a
++ # model unrelated to the routing model below.
++ rate_limiter.parallel_request_limiter._create_rate_limit_descriptors.return_value = [
++ {"rate_limit": {}}
++ ]
++ user = UserAPIKeyAuth(
++ api_key="sk",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={"model_otpm_limit": {"some-other-model": 50}},
++ )
++ with patch("litellm.proxy.proxy_server.general_settings", {}):
++ should_skip, descriptors = rate_limiter._should_skip_batch_input_file_processing(
++ data={"model": "unlimited-model", "input_file_id": "file-abc"},
++ user_api_key_dict=user,
++ )
++ assert should_skip is False
++ assert descriptors is not None
++
++
++def test_should_skip_when_project_has_no_io_limits_and_no_other_limits():
++ """Sanity check for the new project-limits carve-out: a project caller
++ with no ITPM/OTPM configuration anywhere must still get the fast-path
++ skip when no other rate limits apply, exactly as before this fix."""
++ rate_limiter = _make_rate_limiter()
++ rate_limiter.parallel_request_limiter._create_rate_limit_descriptors.return_value = [
++ {"rate_limit": {}}
++ ]
++ user = UserAPIKeyAuth(
++ api_key="sk",
++ models=["*"],
++ project_id="proj-mantle-batch",
++ project_metadata={},
++ )
++ with patch("litellm.proxy.proxy_server.general_settings", {}):
++ should_skip, descriptors = rate_limiter._should_skip_batch_input_file_processing(
++ data={"model": "unlimited-model", "input_file_id": "file-abc"},
++ user_api_key_dict=user,
++ )
++ assert should_skip is True
++ assert descriptors is None
++
++
@pytest.mark.asyncio
async def test_count_input_file_usage_raises_on_non_bytes_content():
from litellm.proxy.hooks.batch_rate_limiter import _PROXY_BatchRateLimiter
diff --cc tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
index e55185cfa67,f7bd37b412a..e04ea66db5e
--- a/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
+++ b/tests/test_litellm/proxy/hooks/test_tpm_concurrent.py
@@@ -1248,2400 -1197,5 +1248,2401 @@@ async def test_small_tpm_cap_preserves_
assert data["max_tokens"] == 500
+async def test_project_otpm_reservation_prevents_concurrent_bypass(rate_limiter):
+ """
+ Bedrock Mantle-style OTPM: with a 100 OTPM limit and 5 concurrent
+ requests each reserving 50+ output tokens, upfront reservation must
+ reject the late arrivals -- not let all 5 through. Exercises the
+ in-memory fallback in ``atomic_check_and_increment_by_n`` for the
+ project-scoped ITPM/OTPM descriptors specifically.
+ """
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-otpm-bypass"),
+ project_id="proj-mantle-bypass",
+ project_metadata={
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 100},
+ },
+ )
+
+ request_data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 50,
+ }
+
+ async def make_request(request_id: int) -> Dict[str, Any]:
+ data = request_data.copy()
+ try:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+ return {"request_id": request_id, "success": True}
+ except Exception as e:
+ return {
+ "request_id": request_id,
+ "success": False,
+ "status_code": getattr(e, "status_code", None),
+ }
+
+ results = await asyncio.gather(*[make_request(i) for i in range(5)])
+
+ successful = [r for r in results if r["success"]]
+ rate_limited = [
+ r for r in results if not r["success"] and r.get("status_code") == 429
+ ]
+
+ assert len(rate_limited) > 0, (
+ f"Expected some OTPM-rate-limited requests but all {len(successful)} succeeded."
+ )
+
+
+async def test_project_otpm_rejects_multiple_completion_candidates(rate_limiter):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-otpm-multiple-candidates"),
+ project_id="proj-multiple-candidates",
+ project_metadata={
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 500},
+ },
+ )
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 100,
+ "n": 10,
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="acompletion",
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+async def test_project_otpm_reserves_largest_conflicting_output_cap(rate_limiter):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-otpm-conflicting-caps"),
+ project_id="proj-conflicting-caps",
+ project_metadata={
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 50},
+ },
+ )
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 1,
+ "max_completion_tokens": 100,
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="acompletion",
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+ "call_type",
+ ["agenerate_content", "agenerate_content_stream"],
+)
[email protected]("config_field", ["config", "generationConfig"])
+async def test_project_otpm_rejects_google_genai_native_output_cap(
+ rate_limiter,
+ call_type,
+ config_field,
+):
+ handler, cache = rate_limiter
+ model = "gemini/gemini-3-flash-preview"
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-google-genai-native-otpm"),
+ project_id="project-google-genai-native-otpm",
+ project_metadata={"model_otpm_limit": {model: 50}},
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": model,
+ "contents": [{"role": "user", "parts": [{"text": "Hello"}]}],
+ config_field: {"maxOutputTokens": 100},
+ },
+ call_type=call_type,
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+ "call_type",
+ ["agenerate_content", "agenerate_content_stream"],
+)
[email protected]("candidate_count_field", ["candidateCount", "candidate_count"])
+async def test_project_otpm_rejects_google_genai_native_candidate_count(
+ rate_limiter,
+ call_type,
+ candidate_count_field,
+):
+ handler, cache = rate_limiter
+ model = "gemini/gemini-3-flash-preview"
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-google-genai-native-candidate-count"),
+ project_id="project-google-genai-native-candidate-count",
+ project_metadata={"model_otpm_limit": {model: 150}},
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": model,
+ "contents": [{"role": "user", "parts": [{"text": "Hello"}]}],
+ "config": {
+ "maxOutputTokens": 50,
+ candidate_count_field: 4,
+ },
+ },
+ call_type=call_type,
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+ "call_type",
+ ["agenerate_content", "agenerate_content_stream"],
+)
[email protected]("config_field", [None, "config", "generationConfig"])
+async def test_project_otpm_injects_google_genai_native_output_cap(
+ rate_limiter,
+ call_type,
+ config_field,
+):
+ handler, cache = rate_limiter
+ model = "gemini/gemini-3-flash-preview"
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-google-genai-native-implicit-otpm"),
+ project_id="project-google-genai-native-implicit-otpm",
+ project_metadata={"model_otpm_limit": {model: 40}},
+ )
+ data = {
+ "model": model,
+ "contents": [{"role": "user", "parts": [{"text": "Hello"}]}],
+ }
+ if config_field is not None:
+ data[config_field] = {"temperature": 0}
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type=call_type,
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.otpm_reserved_tokens == 10
+ expected_config_field = config_field or "config"
+ assert data[expected_config_field]["maxOutputTokens"] == 10
+ assert "max_tokens" not in data
+
+
+async def test_project_otpm_over_limit_rolls_back_itpm_reservation(rate_limiter):
+ """
+ When ITPM reserves fine but OTPM is then over limit, the ITPM
+ reservation this same pre-call already made must be rolled back --
+ otherwise it leaks until the window's TTL, silently shrinking the ITPM
+ budget for every other request in that minute.
+ """
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-otpm-rollback"),
+ project_id="proj-mantle-rollback",
+ project_metadata={
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 1000000},
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 10},
+ },
+ )
+
+ itpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project_itpm",
+ value="proj-mantle-rollback:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 500, # blows past the 10-token OTPM limit
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+ cached_value = await cache.async_get_cache(key=itpm_counter_key, local_only=True)
+ assert int(cached_value or 0) == 0, (
+ f"ITPM reservation leaked after OTPM rejection: counter={cached_value}"
+ )
+
+
+async def test_project_itpm_reconciled_on_success_excludes_cached_tokens(rate_limiter):
+ """
+ On success, ITPM reconciles to billable input tokens (prompt_tokens
+ minus cached_tokens) -- not raw prompt_tokens. Cached prompt-read tokens
+ are free under Bedrock Mantle and must not count against the ITPM quota,
+ even though they still appear in usage/cost logging elsewhere.
+ """
+ handler, _cache = rate_limiter
+
+ itpm_scope = ("model_per_project_itpm", "proj-mantle:model")
+ otpm_scope = ("model_per_project_otpm", "proj-mantle:model")
+
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 60
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ mock_kwargs = {}
+
+ mock_response = ModelResponse(
+ id="test",
+ object="chat.completion",
+ created=int(datetime.now().timestamp()),
+ model="bedrock_mantle/claude-opus",
+ usage=Usage(
+ prompt_tokens=80,
+ completion_tokens=40,
+ total_tokens=120,
+ prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=30),
+ ),
+ choices=[],
+ )
+
+ increments = []
+
+ async def mock_increment(increment_list, **kwargs):
+ for op in increment_list:
+ increments.append({"key": op["key"], "increment": op["increment_value"]})
+
+ handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = (
+ mock_increment
+ )
+
+ await handler.async_log_success_event(
+ kwargs=mock_kwargs,
+ response_obj=mock_response,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ itpm_adjustments = [i for i in increments if "model_per_project_itpm" in i["key"]]
+ otpm_adjustments = [i for i in increments if "model_per_project_otpm" in i["key"]]
+
+ # billable_input = 80 - 30 cached = 50; delta = 50 - 100 reserved = -50
+ assert any(i["increment"] == -50 for i in itpm_adjustments), (
+ f"Expected a -50 ITPM adjustment (50 billable - 100 reserved), got: {itpm_adjustments}"
+ )
+ # delta = 40 actual completion - 60 reserved = -20
+ assert any(i["increment"] == -20 for i in otpm_adjustments), (
+ f"Expected a -20 OTPM adjustment (40 actual - 60 reserved), got: {otpm_adjustments}"
+ )
+
+
+async def test_project_reconciliation_does_not_decrement_later_window():
+ current_time = datetime(2026, 8, 5, 12, 0, 0)
+ cache = DualCache()
+ handler = RateLimitHandler(
+ internal_usage_cache=InternalUsageCache(cache),
+ time_provider=lambda: current_time,
+ )
+ handler.window_size = 60
+ scope = (PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")
+ descriptor = {
+ "key": scope[0],
+ "value": scope[1],
+ "rate_limit": {"tokens_per_unit": 1000, "window_size": 60},
+ }
+
+ reservation = await handler.atomic_check_and_increment_by_n(
+ descriptors=[descriptor],
+ increments=[{"tokens": 100}],
+ )
+ counter_key = handler.create_rate_limit_keys(*scope, rate_limit_type="tokens")
+ window_identity = next(
+ identity
+ for identity in reservation["reservation_windows"]
+ if identity[0] == counter_key
+ )
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({scope})
+ stash.itpm_reserved_window_identities = frozenset(
+ {window_identity}
+ )
+
+ current_time += timedelta(seconds=61)
+ later_reservation = await handler.atomic_check_and_increment_by_n(
+ descriptors=[descriptor],
+ increments=[{"tokens": 20}],
+ )
+ assert window_identity not in later_reservation["reservation_windows"]
+
+ await handler.async_log_success_event(
+ kwargs={},
+ response_obj=ModelResponse(
+ usage=Usage(prompt_tokens=10, completion_tokens=0, total_tokens=10)
+ ),
+ start_time=current_time,
+ end_time=current_time,
+ )
+
+ assert float(await cache.async_get_cache(key=counter_key, local_only=True) or 0) == 20
+
+
+async def test_project_reconciliation_decrements_its_active_window(rate_limiter):
+ handler, cache = rate_limiter
+ scope = (PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")
+ descriptor = {
+ "key": scope[0],
+ "value": scope[1],
+ "rate_limit": {"tokens_per_unit": 1000, "window_size": 60},
+ }
+ reservation = await handler.atomic_check_and_increment_by_n(
+ descriptors=[descriptor],
+ increments=[{"tokens": 100}],
+ )
+ counter_key = handler.create_rate_limit_keys(*scope, rate_limit_type="tokens")
+ window_identity = next(
+ identity
+ for identity in reservation["reservation_windows"]
+ if identity[0] == counter_key
+ )
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({scope})
+ stash.itpm_reserved_window_identities = frozenset(
+ {window_identity}
+ )
+
+ await handler.async_log_success_event(
+ kwargs={},
+ response_obj=ModelResponse(
+ usage=Usage(prompt_tokens=10, completion_tokens=0, total_tokens=10)
+ ),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ assert float(await cache.async_get_cache(key=counter_key, local_only=True) or 0) == 10
+
+
+async def test_redis_window_guard_uses_reservation_identity_and_never_falls_back_negative(
+ rate_limiter,
+):
+ handler, _cache = rate_limiter
+ calls = []
+
+ async def failing_guard(*, keys, args):
+ calls.append((keys, args))
+ raise RuntimeError("redis unavailable")
+
+ unguarded_calls = []
+
+ async def capture_unguarded(pipeline_operations, **_kwargs):
+ unguarded_calls.extend(pipeline_operations)
+
+ handler.window_guarded_token_increment_script = failing_guard
+ handler.async_increment_tokens_with_ttl_preservation = capture_unguarded
+ await handler.async_increment_reservation_aware_tokens(
+ pipeline_operations=[
+ {
+ "key": "{model_per_project_itpm:project:model}:tokens",
+ "increment_value": -90,
+ "ttl": 60,
+ "window_key": "{model_per_project_itpm:project:model}:window",
+ "expected_window_start": "1234",
+ "reservation_backend": "redis",
+ }
+ ]
+ )
+
+ assert calls == [
+ (
+ [
+ "{model_per_project_itpm:project:model}:window",
+ "{model_per_project_itpm:project:model}:tokens",
+ ],
+ ["1234", -90, 60],
+ )
+ ]
+ assert unguarded_calls == []
+
+
+async def test_atomic_lua_response_carries_redis_window_identity(rate_limiter):
+ handler, _cache = rate_limiter
+ counter_key = "{model_per_project_itpm:project:model}:tokens"
+ meta = [
+ {
+ "descriptor_key": PROJECT_ITPM_DESCRIPTOR_KEY,
++ "descriptor_value": "project:model",
+ "current_limit": 100,
+ "rate_limit_type": "tokens",
+ "counter_key": counter_key,
+ }
+ ]
+
+ async def successful_reservation(*, keys, args):
+ return [0, 25, 1234]
+
+ handler.check_and_increment_by_n_script = successful_reservation
+ assert await handler._atomic_lua_per_descriptor([]) == {
+ "overall_code": "OK",
+ "statuses": [],
+ }
+
+ response = await handler._atomic_lua_per_descriptor(
+ descriptor_groups=[
+ (
+ [
+ "{model_per_project_itpm:project:model}:window",
+ counter_key,
+ ],
+ [100, 25, 60, 60],
+ meta,
+ )
+ ]
+ )
+
+ assert response["statuses"][0]["limit_remaining"] == 75
+ assert response["reservation_windows"] == frozenset(
+ {(counter_key, "1234", "redis")}
+ )
+
+
+async def test_project_itpm_otpm_released_on_failure(rate_limiter):
+ """On failure, the full ITPM and OTPM reservations must be refunded."""
+ handler, _cache = rate_limiter
+
+ itpm_scope = ("model_per_project_itpm", "proj-mantle:model")
+ otpm_scope = ("model_per_project_otpm", "proj-mantle:model")
+
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 60
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ mock_kwargs = {}
+
+ increments = []
+
+ async def mock_increment(increment_list, **kwargs):
+ for op in increment_list:
+ increments.append({"key": op["key"], "increment": op["increment_value"]})
+
+ handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = (
+ mock_increment
+ )
+
+ await handler.async_log_failure_event(
+ kwargs=mock_kwargs,
+ response_obj=None,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ itpm_releases = [i for i in increments if "model_per_project_itpm" in i["key"]]
+ otpm_releases = [i for i in increments if "model_per_project_otpm" in i["key"]]
+
+ assert any(i["increment"] == -100 for i in itpm_releases), itpm_releases
+ assert any(i["increment"] == -60 for i in otpm_releases), otpm_releases
+
+
+async def test_proxy_rejection_refunds_itpm_otpm_by_their_own_amount_not_combined(
+ rate_limiter,
+):
+ """
+ Regression for a Greptile-flagged bug: when a project configures both a
+ combined model_tpm_limit and split model_itpm_limit/model_otpm_limit for
+ the same model, async_post_call_failure_hook's proxy-side refund path
+ used to decrement every token descriptor -- including the ITPM/OTPM
+ ones -- by the flat combined reservation amount, instead of each
+ bucket's own reserved amount. That drives the split counters negative
+ (or under-refunds them) instead of returning them to exactly zero.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-mixed-tpm-io")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-mixed",
+ project_metadata={
+ "model_tpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ },
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [
+ {"role": "user", "content": "hello there, this is a test message"}
+ ],
+ "max_tokens": 60,
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+
+ tpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project",
+ value="proj-mixed:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+ itpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project_itpm",
+ value="proj-mixed:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+ otpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project_otpm",
+ value="proj-mixed:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+
+ tpm_reserved = int(
+ await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0
+ )
+ itpm_reserved = int(
+ await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0
+ )
+ otpm_reserved = int(
+ await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0
+ )
+ assert tpm_reserved > 0 and itpm_reserved > 0 and otpm_reserved > 0
+
+ await handler.async_post_call_failure_hook(
+ request_data=data,
+ original_exception=Exception("guardrail rejected"),
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ tpm_after = int(
+ await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0
+ )
+ itpm_after = int(
+ await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0
+ )
+ otpm_after = int(
+ await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0
+ )
+
+ assert tpm_after == 0, f"combined TPM counter leaked: {tpm_after}"
+ assert itpm_after == 0, (
+ f"ITPM counter corrupted by combined-amount refund: {itpm_after}"
+ )
+ assert otpm_after == 0, (
+ f"OTPM counter corrupted by combined-amount refund: {otpm_after}"
+ )
+
+
+async def test_proxy_rejection_refunds_itpm_otpm_only_reservation_with_no_combined_tpm(
+ rate_limiter,
+):
+ """
+ Regression for the second half of the same bug: with only
+ model_itpm_limit/model_otpm_limit configured (no model_tpm_limit), the
+ combined reserved_tokens is 0, and the proxy-side refund path used to
+ return immediately on that -- leaking the ITPM/OTPM reservations until
+ the rate-limit window's TTL expired.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-io-only")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-io-only",
+ project_metadata={
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ },
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [
+ {"role": "user", "content": "hello there, this is a test message"}
+ ],
+ "max_tokens": 60,
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+
+ itpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project_itpm",
+ value="proj-io-only:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+ otpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project_otpm",
+ value="proj-io-only:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+ assert (
+ int(await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0) > 0
+ )
+ assert (
+ int(await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0) > 0
+ )
+
+ await handler.async_post_call_failure_hook(
+ request_data=data,
+ original_exception=Exception("guardrail rejected"),
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ itpm_after = int(
+ await cache.async_get_cache(key=itpm_counter_key, local_only=True) or 0
+ )
+ otpm_after = int(
+ await cache.async_get_cache(key=otpm_counter_key, local_only=True) or 0
+ )
+ assert itpm_after == 0, (
+ f"ITPM-only reservation leaked on proxy rejection: {itpm_after}"
+ )
+ assert otpm_after == 0, (
+ f"OTPM-only reservation leaked on proxy rejection: {otpm_after}"
+ )
+
+
+async def test_otpm_rejection_does_not_double_refund_combined_tpm(rate_limiter):
+ """
+ Regression for a High-severity review finding: when the project ITPM
+ reservation succeeds but OTPM is then over limit,
+ _reserve_project_io_tokens_or_raise rolls back the combined-TPM
+ reservation that already succeeded earlier in the same pre-call, then
+ raises. If it doesn't also mark that reservation released,
+ async_post_call_failure_hook -- which fires next in the real request
+ lifecycle, since raising from async_pre_call_hook triggers it -- sees
+ the same still-stashed reservation and refunds it a second time,
+ driving the combined TPM counter negative and letting a caller push
+ past the project's real TPM budget by repeatedly triggering OTPM
+ rejections.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-double-refund")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-double-refund",
+ project_metadata={
+ "model_tpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 100000},
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 5},
+ },
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [
+ {"role": "user", "content": "hello there, this is a test message"}
+ ],
+ "max_tokens": 60, # blows past the 5-token OTPM limit
+ }
+
+ tpm_counter_key = handler.create_rate_limit_keys(
+ key="model_per_project",
+ value="proj-double-refund:bedrock_mantle/claude-opus",
+ rate_limit_type="tokens",
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+ tpm_after_pre_call = int(
+ await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0
+ )
+ assert tpm_after_pre_call == 0, (
+ f"combined TPM reservation not rolled back: {tpm_after_pre_call}"
+ )
+
+ # In the real request lifecycle, async_post_call_failure_hook fires next
+ # for a pre-call rejection. It must not refund the same reservation again.
+ await handler.async_post_call_failure_hook(
+ request_data=data,
+ original_exception=exc_info.value,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ tpm_after_failure_hook = int(
+ await cache.async_get_cache(key=tpm_counter_key, local_only=True) or 0
+ )
+ assert tpm_after_failure_hook == 0, (
+ f"combined TPM counter went negative from a double refund: {tpm_after_failure_hook}"
+ )
+
+
+ "embedding_input",
+ [
+ list(range(51)),
+ [list(range(25)), list(range(26))],
+ ],
+)
+async def test_project_itpm_rejects_pretokenized_embedding_input(
+ rate_limiter,
+ embedding_input,
+):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-pretokenized-embedding-itpm"),
+ project_id="proj-pretokenized-embedding",
+ project_metadata={
+ "model_itpm_limit": {"text-embedding-3-small": 50},
+ },
+ )
+ data = {
+ "model": "text-embedding-3-small",
+ "input": embedding_input,
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="aembedding",
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+async def test_responses_api_not_misclassified_as_embedding_for_output_estimate(
+ rate_limiter,
+):
+ """
+ Regression for a High-severity review finding: the Responses API also
+ puts its prompt in data["input"], the same field embeddings use, so the
+ output-token estimate treated every Responses call as an embedding and
+ reserved zero output tokens. call_type now disambiguates the two: the
+ same input-only payload gets zero output tokens for an embedding call
+ but a real floor for a Responses API call.
+ """
+ handler, _cache = rate_limiter
+
+ data = {"input": "describe this image in detail"}
+
+ _, embedding_output_estimate = handler._estimate_input_and_output_tokens(
+ data=data, call_type="aembedding"
+ )
+ assert embedding_output_estimate == 0
+
+ _, responses_output_estimate = handler._estimate_input_and_output_tokens(
+ data=data, call_type="aresponses"
+ )
+ assert responses_output_estimate > 0, (
+ "Responses API call was misclassified as an embedding and reserved zero output tokens"
+ )
+
+
+ ("data", "call_type", "expected_output_tokens"),
+ [
+ (
+ {
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 100,
+ "n": 10,
+ },
+ "acompletion",
+ 1000,
+ ),
+ (
+ {
+ "prompt": "hello",
+ "max_tokens": 100,
+ "n": 2,
+ "best_of": 5,
+ },
+ "text_completion",
+ 500,
+ ),
+ (
+ {
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 100,
+ "n": 0,
+ "best_of": "invalid",
+ },
+ "acompletion",
+ 100,
+ ),
+ ],
+)
+def test_output_estimate_accounts_for_completion_candidates(
+ rate_limiter,
+ data,
+ call_type,
+ expected_output_tokens,
+):
+ handler, _cache = rate_limiter
+
+ _, estimated_output_tokens = handler._estimate_input_and_output_tokens(
+ data=data,
+ call_type=call_type,
+ )
+
+ assert estimated_output_tokens == expected_output_tokens
+
+
+async def test_responses_api_usage_reconciles_using_input_output_tokens_fields(
+ rate_limiter,
+):
+ """
+ Regression for the other half of the same finding: ResponseAPIUsage
+ exposes input_tokens/output_tokens, not prompt_tokens/completion_tokens.
+ Before this fix, _resolve_io_token_reconcile_usage couldn't resolve
+ Responses API usage at all, so the reservation was silently kept as-is
+ instead of being trued up to the much larger actual usage.
+ """
+ handler, _cache = rate_limiter
+
+ itpm_scope = ("model_per_project_itpm", "proj-responses:model")
+ otpm_scope = ("model_per_project_otpm", "proj-responses:model")
+
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 10
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 10
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ mock_kwargs = {}
+
+ mock_response = ResponsesAPIResponse(
+ id="resp_test",
+ created_at=int(datetime.now().timestamp()),
+ output=[],
+ usage=ResponseAPIUsage(input_tokens=80, output_tokens=400, total_tokens=480),
+ )
+
+ increments = []
+
+ async def mock_increment(increment_list, **kwargs):
+ for op in increment_list:
+ increments.append({"key": op["key"], "increment": op["increment_value"]})
+
+ handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = (
+ mock_increment
+ )
+
+ await handler.async_log_success_event(
+ kwargs=mock_kwargs,
+ response_obj=mock_response,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ itpm_adjustments = [i for i in increments if "model_per_project_itpm" in i["key"]]
+ otpm_adjustments = [i for i in increments if "model_per_project_otpm" in i["key"]]
+
+ # delta = 80 actual input - 10 reserved = +70
+ assert any(i["increment"] == 70 for i in itpm_adjustments), (
+ f"ITPM reservation was never trued up to actual Responses API usage: {itpm_adjustments}"
+ )
+ # delta = 400 actual output - 10 reserved = +390
+ assert any(i["increment"] == 390 for i in otpm_adjustments), (
+ f"OTPM reservation was never trued up to actual Responses API usage: {otpm_adjustments}"
+ )
+
+
+async def test_itpm_reservation_accounts_for_audio_content_not_just_text(rate_limiter):
+ """
+ Regression for the audio half of a Medium-severity review finding:
+ litellm.token_counter has no per-type handling for `input_audio`
+ content blocks (unlike images, which it does count via
+ use_default_image_token_count), so it silently contributes 0 tokens for
+ them. Without DEFAULT_AUDIO_TOKEN_ESTIMATE, a burst of audio-heavy
+ requests with minimal text would each reserve only the one-token floor
+ and blow past the project ITPM limit before post-call reconciliation.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-audio-itpm")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-audio",
+ project_metadata={
+ # Tighter than DEFAULT_AUDIO_TOKEN_ESTIMATE (300), but far bigger
+ # than the handful of tokens the bare text "hi" would cost.
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 50},
+ },
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hi"},
+ {
+ "type": "input_audio",
+ "input_audio": {"data": "base64-audio-bytes", "format": "wav"},
+ },
+ ],
+ }
+ ],
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+ assert getattr(exc_info.value, "status_code", None) == 429, (
+ "Expected the audio content to push the ITPM reservation over the "
+ "50-token limit; if this doesn't raise, audio content isn't being "
+ "counted again."
+ )
+
+
+def test_audio_token_estimate_scales_with_payload_size():
+ """
+ Regression for veria-ai Low finding: audio token reservation was flat
+ 300 per block regardless of duration. A short clip and a long clip both
+ reserved the same amount, letting a caller hide long audio in one block
+ to exhaust ITPM quota while reserving almost nothing.
+
+ The estimate must now grow proportionally with the base64 payload size
+ (len(b64) * 3 // 4 // _AUDIO_BYTES_PER_TOKEN), floored at
+ DEFAULT_AUDIO_TOKEN_ESTIMATE so reference-only blocks and genuinely
+ short clips still get a non-trivial reservation.
+
+ To exceed the floor the decoded payload must be > 300 * 1600 = 480 000
+ bytes. We synthesise a fake b64-length string of 650 000 chars
+ (decoded ≈ 487 500 bytes → 304 tokens) to avoid actually allocating
+ and encoding ~480 kB of audio in every test run.
+ """
+ large_b64 = "A" * 650_000
+ very_large_b64 = "A" * 12_900_000
+ small_b64 = "A" * 1_000
+
+ large_block = {
+ "type": "input_audio",
+ "input_audio": {"data": large_b64, "format": "wav"},
+ }
+ small_block = {
+ "type": "input_audio",
+ "input_audio": {"data": small_b64, "format": "wav"},
+ }
+ very_large_block = {
+ "type": "input_audio",
+ "input_audio": {"data": very_large_b64, "format": "wav"},
+ }
+ no_data_block = {"type": "input_audio", "input_audio": {"format": "wav"}}
+
+ large_estimate = RateLimitHandler._estimate_audio_block_tokens(large_block)
+ very_large_estimate = RateLimitHandler._estimate_audio_block_tokens(
+ very_large_block
+ )
+ small_estimate = RateLimitHandler._estimate_audio_block_tokens(small_block)
+ no_data_estimate = RateLimitHandler._estimate_audio_block_tokens(no_data_block)
+
+ assert large_estimate > small_estimate, (
+ f"Large payload ({large_estimate}) must reserve more than small payload "
+ f"({small_estimate}); flat-rate bug is back"
+ )
+ assert very_large_estimate == len(very_large_b64) * 3 // 4 // _AUDIO_BYTES_PER_TOKEN
+ assert very_large_estimate > 6_000
+ assert no_data_estimate >= 300, (
+ f"Reference-only block (no data) must use the DEFAULT_AUDIO_TOKEN_ESTIMATE floor; got {no_data_estimate}"
+ )
+ assert small_estimate >= 300, (
+ f"Small payload must be floored at DEFAULT_AUDIO_TOKEN_ESTIMATE=300; got {small_estimate}"
+ )
+
+
+async def test_itpm_rejects_large_audio_payload_that_would_pass_flat_estimate(
+ rate_limiter,
+):
+ """
+ Regression: a caller placing a long audio clip in one block previously
+ reserved only 300 tokens (the flat estimate). With the size-proportional
+ estimate, the same clip now reserves proportionally more and must trip
+ the ITPM limit when the limit is tuned to exactly expose the difference.
+
+ 1 100 000 b64 chars → decoded ≈ 825 000 bytes → 825 000 // 1600 ≈ 515
+ tokens > the 400-token limit. The flat estimate (300) would have passed.
+ """
+ handler, cache = rate_limiter
+
+ large_b64 = "A" * 1_100_000
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-large-audio"),
+ project_id="proj-large-audio",
+ project_metadata={
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 400},
+ },
+ )
+
+ data = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "transcribe this"},
+ {
+ "type": "input_audio",
+ "input_audio": {"data": large_b64, "format": "wav"},
+ },
+ ],
+ }
+ ],
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+ assert getattr(exc_info.value, "status_code", None) == 429, (
+ "Large audio payload must exceed the 400-token ITPM limit under the "
+ "size-proportional estimate; the old flat-rate estimate (300 tokens) "
+ "would have passed this limit silently"
+ )
+
+
+ ("call_type", "request_data"),
+ [
+ (
+ "acompletion",
+ {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "https://example.com/high-resolution.png",
+ "detail": "high",
+ },
+ }
+ ],
+ }
+ ]
+ },
+ ),
+ (
+ "aresponses",
+ {
+ "input": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "input_image",
+ "image_url": "https://example.com/high-resolution.png",
+ "detail": "high",
+ }
+ ],
+ }
+ ]
+ },
+ ),
+ ],
+)
+async def test_image_content_reserves_full_project_itpm(
+ rate_limiter,
+ call_type,
+ request_data,
+):
+ handler, cache = rate_limiter
+ model = "bedrock_mantle/claude-opus"
+ project_itpm_limit = 1_000
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-high-resolution-image"),
+ project_id="project-high-resolution-image",
+ project_metadata={"model_itpm_limit": {model: project_itpm_limit}},
+ )
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={"model": model, **request_data},
+ call_type=call_type,
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.itpm_reserved_tokens == project_itpm_limit
+
+
+async def test_itpm_otpm_reservation_is_kept_on_stream_disconnect(rate_limiter):
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-disconnect-test")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-disconnect",
+ project_metadata={
+ "model_itpm_limit": {"bedrock_mantle/claude-opus": 1000},
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 500},
+ },
+ )
+
+ data: Dict[str, Any] = {
+ "model": "bedrock_mantle/claude-opus",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 50,
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.itpm_reserved_tokens > 0, (
+ "pre-call hook must stash an ITPM reservation"
+ )
+ assert stash.otpm_reserved_tokens > 0, (
+ "pre-call hook must stash an OTPM reservation"
+ )
+
+ increment_calls: list[dict] = []
+
+ async def mock_increment(increment_list, litellm_parent_otel_span=None):
+ for op in increment_list:
+ increment_calls.append(
+ {"key": op["key"], "increment": op["increment_value"]}
+ )
+
+ handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = (
+ mock_increment
+ )
+
+ await handler.async_release_max_parallel_requests_on_disconnect(
+ user_api_key_dict=user_api_key_dict
+ )
+
+ itpm_refunds = [
+ c
+ for c in increment_calls
+ if "model_per_project_itpm" in c["key"] and c["increment"] < 0
+ ]
+ otpm_refunds = [
+ c
+ for c in increment_calls
+ if "model_per_project_otpm" in c["key"] and c["increment"] < 0
+ ]
+
+ assert not itpm_refunds
+ assert not otpm_refunds
+ assert stash.reservation_released is False
+
+
+async def test_responses_api_otpm_output_cap_applied_not_skipped_as_embedding(
+ rate_limiter,
+):
+ """
+ Regression for a Greptile P1 finding: _reserve_project_io_tokens_or_raise
+ classified any request with data["input"] set as an embedding (no output
+ tokens), which also misclassifies the Responses API -- it puts its prompt
+ in "input" too, but does generate output. That skipped the output cap
+ applied whenever the configured OTPM limit is small enough to need it,
+ letting an unbounded Responses generation blow past OTPM before
+ post-call reconciliation catches up.
+
+ The cap must land on data["max_output_tokens"], not data["max_tokens"]:
+ the Responses-to-chat-completion transformation only reads
+ max_output_tokens, so a max_tokens cap is silently dropped before
+ provider dispatch (a second Greptile finding on the same code path).
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-responses-otpm-cap")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-responses-otpm",
+ project_metadata={
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 40},
+ },
+ )
+
+ data: Dict[str, Any] = {
+ "model": "bedrock_mantle/claude-opus",
+ "input": "describe this image in detail",
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="aresponses",
+ )
+
+ assert data.get("max_output_tokens") is not None, (
+ "Responses call was misclassified as an embedding and skipped the OTPM output cap"
+ )
+ assert data["max_output_tokens"] == 16
+ assert data.get("max_tokens") is None, (
+ "OTPM output cap was written to max_tokens, which the Responses transformation ignores"
+ )
+
+
+async def test_explicit_zero_output_responses_call_reserves_effective_provider_minimum(
+ rate_limiter,
+):
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-responses-zero-output"),
+ project_id="proj-responses-zero-output",
+ project_metadata={
+ "model_otpm_limit": {"bedrock_mantle/claude-opus": 5},
+ },
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": "bedrock_mantle/claude-opus",
+ "input": "describe this image in detail",
+ "max_output_tokens": 0,
+ },
+ call_type="aresponses",
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+
+
+async def test_responses_api_combined_tpm_output_cap_applied_not_skipped_as_embedding(
+ rate_limiter,
+):
+ """
+ Regression for the same misclassification bug in the combined-TPM
+ output-cap block of async_pre_call_hook (a second, independent
+ `is_embedding = data.get("input") is not None` check). A project with
+ only a combined model_tpm_limit (no split itpm/otpm) configured small
+ enough to need the output cap must still apply it to a Responses call,
+ and must write it to max_output_tokens for the same reason as the OTPM
+ case above.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-responses-tpm-cap")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ project_id="proj-responses-tpm",
+ project_metadata={
+ "model_tpm_limit": {"bedrock_mantle/claude-opus": 40},
+ },
+ )
+
+ data: Dict[str, Any] = {
+ "model": "bedrock_mantle/claude-opus",
+ "input": "describe this image in detail",
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="aresponses",
+ )
+
+ assert data.get("max_output_tokens") is not None, (
+ "Responses call was misclassified as an embedding and skipped the combined-TPM output cap"
+ )
+ assert data["max_output_tokens"] == 16
+ assert data.get("max_tokens") is None, (
+ "combined-TPM output cap was written to max_tokens, which the Responses transformation ignores"
+ )
+
+
+async def test_responses_api_multimodal_input_counts_image_content(rate_limiter):
+ """
+ Regression for a Low-severity veria-ai finding: the Responses API's
+ `input` is commonly a list of message/content-block dicts, but
+ litellm.token_counter's `text` argument only joins plain string entries
+ in a list and silently drops everything else -- so an `input_image`
+ block contributed ~0 tokens to the ITPM estimate instead of the real
+ image token count. _estimate_precise_input_tokens now converts Responses
+ `input` to chat messages first (via the standard
+ transform_responses_api_input_to_messages helper) so image content is
+ counted the same way a chat completion's image content already is.
+ """
+ handler, _cache = rate_limiter
+
+ text_only_estimate = handler._estimate_precise_input_tokens(
+ data={"input": "hi"},
+ model="bedrock_mantle/claude-opus",
+ call_type="aresponses",
+ )
+
+ multimodal_estimate = handler._estimate_precise_input_tokens(
+ data={
+ "input": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": "hi"},
+ {
+ "type": "input_image",
+ "image_url": "https://example.com/some-image.png",
+ },
+ ],
+ }
+ ],
+ },
+ model="bedrock_mantle/claude-opus",
+ call_type="aresponses",
+ )
+
+ assert multimodal_estimate > text_only_estimate + 100, (
+ "Responses API input_image content block was not counted; got "
+ f"text_only={text_only_estimate}, multimodal={multimodal_estimate}"
+ )
+
+
+async def test_refund_reserved_tokens_noop_when_amount_zero(rate_limiter):
+ """_refund_reserved_tokens returns immediately without calling Redis when amount=0."""
+ handler, _cache = rate_limiter
+
+ calls = []
+
+ async def mock_increment(pipeline_operations, **kwargs):
+ calls.extend(pipeline_operations)
+
+ handler.async_increment_tokens_with_ttl_preservation = mock_increment
+
+ await handler._refund_reserved_tokens(
+ scopes=[("api_key", "sk-test")],
+ amount=0,
+ )
+
+ assert not calls, "No Redis ops expected when amount is zero"
+
+
+async def test_reserve_io_tokens_noop_when_no_itpm_otpm_descriptors(rate_limiter):
+ """reserve_io_tokens returns OK immediately when no ITPM/OTPM descriptors present."""
+ handler, _cache = rate_limiter
+
+ non_io_descriptor = {
+ "key": "api_key",
+ "value": "sk-test",
+ "rate_limit": {"tokens_per_unit": 1000, "window_size": 60},
+ }
+ response, itpm_reserved, otpm_reserved = await handler.reserve_io_tokens(
+ descriptors=[non_io_descriptor],
+ estimated_input_tokens=50,
+ estimated_output_tokens=50,
+ )
+
+ assert response["overall_code"] == "OK"
+ assert itpm_reserved == 0
+ assert otpm_reserved == 0
+
+
+async def test_reserve_io_tokens_itpm_only_no_otpm(rate_limiter):
+ """When only ITPM descriptors are present (no OTPM), returns itpm_reserved with otpm=0."""
+ handler, cache = rate_limiter
+
+ itpm_descriptor = {
+ "key": PROJECT_ITPM_DESCRIPTOR_KEY,
+ "value": "proj-a:model",
+ "rate_limit": {"tokens_per_unit": 10000, "window_size": 60},
+ }
+ response, itpm_reserved, otpm_reserved = await handler.reserve_io_tokens(
+ descriptors=[itpm_descriptor],
+ estimated_input_tokens=100,
+ estimated_output_tokens=50,
+ )
+
+ assert response["overall_code"] == "OK"
+ assert itpm_reserved == 100
+ assert otpm_reserved == 0
+
+
+def test_strip_audio_content_blocks_passthrough_non_list_messages():
+ """Non-list input is returned unchanged (early return on line 2605)."""
+ result = RateLimitHandler._strip_audio_content_blocks("not a list")
+ assert result == "not a list"
+
+
+def test_strip_audio_content_blocks_passthrough_non_dict_message():
+ """Non-dict entries in the message list are appended unchanged."""
+ messages = ["plain string message"]
+ result = RateLimitHandler._strip_audio_content_blocks(messages)
+ assert result == ["plain string message"]
+
+
+def test_strip_audio_content_blocks_passthrough_non_list_content():
+ """Messages with non-list content (e.g. plain string) pass through unchanged."""
+ messages = [{"role": "user", "content": "hello"}]
+ result = RateLimitHandler._strip_audio_content_blocks(messages)
+ assert result == [{"role": "user", "content": "hello"}]
+
+
+async def test_otpm_rejection_releases_stashed_parallel_slot(rate_limiter):
+ """
+ When OTPM is over limit and a parallel slot was already acquired, the
+ disconnect cleanup path in _reserve_project_io_tokens_or_raise must
+ release that slot. Exercises lines 2773-2777.
+ """
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-otpm-slot"),
+ project_id="proj-slot",
+ project_metadata={"model_otpm_limit": {"m": 5}},
+ )
+
+ data: Dict[str, Any] = {
+ "model": "m",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 50,
+ }
+
+ slot_released = []
+
+ async def mock_release(acquisition, parent_otel_span=None):
+ slot_released.append(acquisition)
+
+ handler._release_parallel_request_slots = mock_release
+
+ stash = get_or_create_request_stash()
+ stash.parallel_slot = {
+ "slot_id": "test-slot-id",
+ "counter_keys": ["some-key"],
+ }
+
+ otpm_descriptor = {
+ "key": PROJECT_OTPM_DESCRIPTOR_KEY,
+ "value": "proj-slot:m",
+ "rate_limit": {"tokens_per_unit": 5, "window_size": 60},
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await handler._reserve_project_io_tokens_or_raise(
+ descriptors=[otpm_descriptor],
+ data=data,
+ requested_model="m",
+ user_api_key_dict=user_api_key_dict,
+ tpm_reservation_scopes=[],
+ tpm_reservation_amount=0,
+ )
+ assert getattr(exc_info.value, "status_code", None) == 429
+ assert slot_released, "Parallel slot must be released when OTPM rejects"
+ assert stash.parallel_slot is None
+
+
+async def test_itpm_only_status_stored_when_no_prior_rate_limit_response(rate_limiter):
+ """
+ When only ITPM is configured (no combined TPM/RPM to pre-populate
+ the request stash), a successful ITPM reservation must store its status
+ there so post-call headers can read it.
+ """
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-itpm-only-store"),
+ project_id="proj-store",
+ )
+
+ data: Dict[str, Any] = {"model": "m", "messages": []}
+
+ itpm_descriptor = {
+ "key": PROJECT_ITPM_DESCRIPTOR_KEY,
+ "value": "proj-store:m",
+ "rate_limit": {"tokens_per_unit": 100000, "window_size": 60},
+ }
+
+ await handler._reserve_project_io_tokens_or_raise(
+ descriptors=[itpm_descriptor],
+ data=data,
+ requested_model="m",
+ user_api_key_dict=user_api_key_dict,
+ tpm_reservation_scopes=[],
+ tpm_reservation_amount=0,
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ stored = stash.rate_limit_response
+ assert stored is not None, (
+ "ITPM status must be stored in litellm_proxy_rate_limit_response"
+ )
+ assert stored.get("statuses"), "Stored response must contain statuses"
+
+
+def test_resolve_io_token_usage_responses_api_with_cached_tokens(rate_limiter):
+ """
+ ResponsesAPIResponse whose usage.input_tokens_details.cached_tokens is set
+ subtracts the cached portion from billable input. Covers line 3501.
+ """
+ handler, _cache = rate_limiter
+
+ response_obj = ResponsesAPIResponse(
+ id="resp_cached",
+ created_at=int(datetime.now().timestamp()),
+ output=[],
+ usage=ResponseAPIUsage(
+ input_tokens=100,
+ output_tokens=50,
+ total_tokens=150,
+ input_tokens_details=InputTokensDetails(cached_tokens=25),
+ ),
+ )
+ billable_input, completion_tokens, resolved = (
+ handler._resolve_io_token_reconcile_usage(response_obj)
+ )
+
+ assert resolved is True
+ assert billable_input == 75, f"Expected 100 - 25 cached = 75, got {billable_input}"
+ assert completion_tokens == 50
+
+
+def test_resolve_io_token_usage_dict_format(rate_limiter):
+ """
+ Dict-shaped usage on a ModelResponse (older SDK versions or raw dicts in
+ the usage field) is parsed correctly. Covers lines 3502-3506.
+ """
+ handler, _cache = rate_limiter
+
+ response_obj = ModelResponse.model_construct(
+ usage={
+ "prompt_tokens": 80,
+ "completion_tokens": 40,
+ "prompt_tokens_details": {"cached_tokens": 20},
+ }
+ )
+ billable_input, completion_tokens, resolved = (
+ handler._resolve_io_token_reconcile_usage(response_obj)
+ )
+
+ assert resolved is True
+ assert billable_input == 60, f"Expected 80 - 20 cached = 60, got {billable_input}"
+ assert completion_tokens == 40
+
+
+def test_resolve_io_token_usage_unknown_type_returns_unresolved(rate_limiter):
+ """
+ A ModelResponse whose usage attribute is not a Usage, ResponseAPIUsage,
+ or dict (e.g. a plain int) returns (0, 0, False) so the reservation is
+ kept rather than guessed. Covers lines 3507-3508.
+ """
+ handler, _cache = rate_limiter
+
+ response_obj = ModelResponse.model_construct(usage=42)
+ billable_input, completion_tokens, resolved = (
+ handler._resolve_io_token_reconcile_usage(response_obj)
+ )
+
+ assert resolved is False
+ assert billable_input == 0
+ assert completion_tokens == 0
+
+
+ ("combined_usage", "expected_increments"),
+ [
+ (None, ()),
+ (
+ Usage(prompt_tokens=40, completion_tokens=15, total_tokens=55),
+ (-60, -45),
+ ),
+ ],
+)
+def test_zero_usage_keeps_reservations_unless_measured_fallback_exists(
+ rate_limiter,
+ combined_usage,
+ expected_increments,
+):
+ handler, _cache = rate_limiter
+ itpm_scope = (PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")
+ otpm_scope = (PROJECT_OTPM_DESCRIPTOR_KEY, "project:model")
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 60
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ kwargs = {} if combined_usage is None else {"combined_usage_object": combined_usage}
+ response_obj = ModelResponse(
+ usage=Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0)
+ )
+
+ operations = handler._build_io_token_reservation_ops(kwargs, response_obj)
+
+ assert tuple(operation["increment_value"] for operation in operations) == expected_increments
+
+
+ ("usage", "expected_increments"),
+ [
+ (
+ Usage(prompt_tokens=40, completion_tokens=15, total_tokens=55),
+ (40, 15),
+ ),
+ (
+ Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0),
+ (100, 60),
+ ),
+ ],
+)
+def test_retry_success_charges_released_project_io_reservations(
+ rate_limiter,
+ usage,
+ expected_increments,
+):
+ handler, _cache = rate_limiter
+ itpm_scope = (PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")
+ otpm_scope = (PROJECT_OTPM_DESCRIPTOR_KEY, "project:model")
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 60
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ stash.reservation_released = True
+
+ operations = handler._build_io_token_reservation_ops(
+ {},
+ ModelResponse(usage=usage),
+ )
+
+ assert tuple(operation["increment_value"] for operation in operations) == expected_increments
+
+
+async def test_build_io_token_reservation_ops_skips_unresolvable_usage(rate_limiter):
+ """
+ When response_obj has no parseable usage, _build_io_token_reservation_ops
+ returns [] to keep the reservation as-is rather than zeroing it out on a
+ bad guess. Covers line 3538.
+ """
+ handler, _cache = rate_limiter
+
+ itpm_scope = ("model_per_project_itpm", "proj-b:model")
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 50
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ mock_kwargs = {}
+
+ ops = handler._build_io_token_reservation_ops(
+ kwargs=mock_kwargs,
+ response_obj=object(),
+ )
+
+ assert not ops, f"Expected empty ops for unresolvable usage, got {ops}"
+
+
+async def test_post_call_failure_skips_rpm_only_descriptor_in_tpm_refund(rate_limiter):
+ """
+ async_post_call_failure_hook skips descriptors without tokens_per_unit
+ (e.g. an RPM-only api_key scope) when building the combined-TPM refund ops,
+ so a key with rpm_limit but no tpm_limit doesn't receive a spurious refund
+ that would drive its counter negative. Covers the continue guard at line 4250.
+ """
+ handler, cache = rate_limiter
+
+ api_key = hash_token("sk-rpm-only-desc")
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=api_key,
+ rpm_limit=100,
+ project_id="proj-rpm-only-desc",
+ project_metadata={"model_tpm_limit": {"gpt-3.5-turbo": 100000}},
+ )
+
+ data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 20,
+ }
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="",
+ )
+
+ rpm_tokens_key = handler.create_rate_limit_keys(
+ key="api_key", value=api_key, rate_limit_type="tokens"
+ )
+
+ await handler.async_post_call_failure_hook(
+ request_data=data,
+ original_exception=Exception("rejected"),
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ api_key_tokens_after = int(
+ await cache.async_get_cache(key=rpm_tokens_key, local_only=True) or 0
+ )
+ assert api_key_tokens_after >= 0, (
+ f"RPM-only api_key scope must not receive a negative TPM refund; got {api_key_tokens_after}"
+ )
+
+
+async def test_max_output_tokens_prevents_cap_injection(rate_limiter):
+ """
+ Regression for veria-ai comment: when a Responses API request supplies
+ max_output_tokens (the canonical Responses output bound) but not max_tokens
+ or max_completion_tokens, the has_explicit_max_tokens check was False, so
+ the code injected data["max_tokens"] = capped_floor and silently truncated
+ the response.
+
+ With the fix, max_output_tokens is included in the explicit-cap check and
+ data["max_tokens"] must NOT be injected when max_output_tokens is already
+ set.
+ """
+ handler, cache = rate_limiter
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-max-output-tokens"),
+ project_id="proj-responses-max-output",
+ project_metadata={
+ "model_otpm_limit": {"mock-model": 100},
+ },
+ )
+
+ data: dict = {
+ "model": "mock-model",
+ "input": "Summarise the document",
+ "max_output_tokens": 80,
+ "litellm_call_id": "test-max-output-tokens",
+ "metadata": {},
+ }
+
+ try:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="responses",
+ )
+ except Exception:
+ pass
+
+ assert "max_tokens" not in data, (
+ "data['max_tokens'] must not be injected when max_output_tokens is already "
+ "set; the cap injection was overriding the caller's explicit output bound"
+ )
+
+
+ ("call_type", "request_data", "cap_field", "reserved_tokens"),
+ [
+ ("aresponses", {"input": "hello", "max_tokens": 1}, "max_output_tokens", 16),
+ (
+ "acompletion",
+ {
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_output_tokens": 1,
+ },
+ "max_tokens",
+ 10,
+ ),
+ ],
+)
+async def test_output_reservation_ignores_cap_fields_from_other_endpoints(
+ rate_limiter,
+ call_type,
+ request_data,
+ cap_field,
+ reserved_tokens,
+):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token(f"sk-{call_type}"),
+ project_id=f"project-{call_type}",
+ project_metadata={"model_otpm_limit": {"model": 40}},
+ )
+ data = {"model": "model", **request_data}
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type=call_type,
+ )
+
+ assert data[cap_field] == reserved_tokens
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.otpm_reserved_tokens == reserved_tokens
+
+
+def test_responses_input_is_counted_even_when_messages_is_present(rate_limiter):
+ handler, _cache = rate_limiter
+ small_estimate = handler._estimate_precise_input_tokens(
+ data={"input": "short", "messages": [{"role": "user", "content": "ignored"}]},
+ model="",
+ call_type="aresponses",
+ )
+ large_estimate = handler._estimate_precise_input_tokens(
+ data={"input": "large input " * 500, "messages": []},
+ model="",
+ call_type="aresponses",
+ )
+
+ assert large_estimate > small_estimate
+
+
+def test_anthropic_messages_usage_reconciles_split_project_quota(rate_limiter):
+ handler, _cache = rate_limiter
+
+ billable_input, output_tokens, resolved = handler._resolve_io_token_reconcile_usage(
+ {
+ "usage": {
+ "input_tokens": 100,
+ "output_tokens": 25,
+ "cache_read_input_tokens": 30,
+ }
+ }
+ )
+
+ assert resolved is True
+ assert billable_input == 70
+ assert output_tokens == 25
+
+
+ "request_data",
+ [
+ {"input": "continue", "previous_response_id": "resp-123"},
+ {
+ "input": [
+ {
+ "role": "user",
+ "content": [{"type": "input_file", "file_id": "file-123"}],
+ }
+ ]
+ },
+ ],
+)
+async def test_unmeasurable_responses_input_reserves_full_project_itpm(
+ rate_limiter, request_data
+):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-unmeasurable-input"),
+ project_id="project-unmeasurable-input",
+ project_metadata={"model_itpm_limit": {"model": 100}},
+ )
+ data = {"model": "model", **request_data}
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="aresponses",
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.itpm_reserved_tokens == 100
+
+
+ "media_block",
+ [
+ {
+ "type": "document",
+ "source": {
+ "type": "base64",
+ "media_type": "application/pdf",
+ "data": "dGVzdA==",
+ },
+ },
+ {
+ "type": "file",
+ "file": {
+ "filename": "document.pdf",
+ "file_data": "data:application/pdf;base64,dGVzdA==",
+ },
+ },
+ {
+ "type": "video_url",
+ "video_url": {"url": "https://example.com/video.mp4"},
+ },
+ ],
+)
+async def test_unmeasurable_chat_media_reserves_full_project_itpm(
+ rate_limiter,
+ media_block,
+):
+ handler, cache = rate_limiter
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-unmeasurable-chat-media"),
+ project_id="project-unmeasurable-chat-media",
+ project_metadata={"model_itpm_limit": {"model": 100}},
+ )
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": "model",
+ "messages": [{"role": "user", "content": [media_block]}],
+ },
+ call_type="acompletion",
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.itpm_reserved_tokens == 100
+
+
+ "call_type",
+ ["agenerate_content", "agenerate_content_stream"],
+)
+async def test_google_genai_native_contents_reserve_project_itpm(
+ rate_limiter,
+ call_type,
+):
+ handler, cache = rate_limiter
+ model = "gemini/gemini-2.5-flash"
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token("sk-google-genai-native-itpm"),
+ project_id="project-google-genai-native-itpm",
+ project_metadata={"model_itpm_limit": {model: 10_000}},
+ )
+
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": model,
+ "contents": [
+ {
+ "role": "user",
+ "parts": [{"text": "Gemini quota input " * 200}],
+ }
+ ],
+ },
+ call_type=call_type,
+ )
+
+ stash = get_request_stash()
+ assert stash is not None
+ assert stash.itpm_reserved_tokens > 100
+
+
[email protected]("call_type", ["rerank", "arerank"])
+async def test_rerank_query_and_documents_enforce_project_itpm(
+ rate_limiter,
+ monkeypatch,
+ call_type,
+):
+ handler, cache = rate_limiter
+ captured = {}
+
+ def token_counter(**kwargs):
+ captured.update(kwargs)
+ return 101
+
+ monkeypatch.setattr("litellm.token_counter", token_counter)
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key=hash_token(f"sk-{call_type}-itpm"),
+ project_id=f"project-{call_type}-itpm",
+ project_metadata={"model_itpm_limit": {"rerank-model": 100}},
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data={
+ "model": "rerank-model",
+ "query": "Which document is most relevant?",
+ "documents": ["first document", {"text": "second document"}],
+ },
+ call_type=call_type,
+ )
+
+ assert getattr(exc_info.value, "status_code", None) == 429
+ assert captured["text"] == (
+ "Which document is most relevant?\n"
+ "first document\n"
+ "{'text': 'second document'}"
+ )
+
+
+def test_rerank_input_estimate_falls_back_to_character_count(
+ rate_limiter,
+ monkeypatch,
+):
+ handler, _cache = rate_limiter
+ data = {
+ "query": "query text",
+ "documents": ["first document", "second document"],
+ }
+
+ def token_counter(**_kwargs):
+ raise ValueError("tokenizer unavailable")
+
+ monkeypatch.setattr("litellm.token_counter", token_counter)
+ rerank_text = handler._rerank_input_to_text(data)
+
+ assert handler._estimate_precise_input_tokens(
+ data,
+ model="custom-rerank-model",
+ call_type="rerank",
+ ) == len(rerank_text) // 4
+
+
+ ("response_obj", "expected"),
+ [
+ (
+ RerankResponse(
+ meta={"tokens": {"input_tokens": 42, "output_tokens": 3}}
+ ),
+ (42, 3, True),
+ ),
+ (
+ RerankResponse(
+ meta={
+ "tokens": {"input_tokens": 0, "output_tokens": 0},
+ "billed_units": {"total_tokens": 57},
+ }
+ ),
+ (57, 0, True),
+ ),
+ (
+ RerankResponse(
+ meta={
+ "tokens": {"input_tokens": 0, "output_tokens": 0},
+ "billed_units": {"total_tokens": 0},
+ }
+ ),
+ (0, 0, False),
+ ),
+ ],
+)
+def test_rerank_usage_reconciles_project_split_token_quota(
+ rate_limiter,
+ response_obj,
+ expected,
+):
+ handler, _cache = rate_limiter
+
+ assert handler._resolve_io_token_reconcile_usage(response_obj) == expected
+
+
+def test_split_quota_helpers_handle_non_mapping_inputs(rate_limiter):
+ handler, _cache = rate_limiter
+
+ assert _call_id_from_callback_kwargs(object()) is None
+ assert handler._is_embedding_request(object(), None) is False
+ assert handler._get_explicit_output_cap(object(), None) is None
+ assert handler._get_output_candidate_count(object()) == 1
+ assert (
+ handler._get_explicit_output_cap({"max_output_tokens": []}, "responses") is None
+ )
+ assert handler._apply_implicit_output_cap(object(), 100, "responses") is None
+ assert handler._estimate_input_and_output_tokens(object()) == (0, 0)
+ assert handler._build_io_token_reservation_ops(object(), object()) == ()
+
+
+ ("call_type", "data"),
+ [
+ (
+ "text_completion",
+ {
+ "messages": [{"role": "user", "content": "ignored"}],
+ "prompt": "abcd",
+ "input": "ignored",
+ "max_tokens": 1,
+ },
+ ),
+ (None, {"prompt": "abcd", "max_tokens": 1}),
+ (None, {"prompt": ["abcd", "efgh"], "max_tokens": 1}),
+ ],
+)
+def test_split_token_estimate_selects_endpoint_input(rate_limiter, call_type, data):
+ handler, _cache = rate_limiter
+
+ estimated_input, estimated_output = handler._estimate_input_and_output_tokens(
+ data=data,
+ call_type=call_type,
+ )
+
+ assert estimated_input > 0
+ assert estimated_output == 1
+
+
+def test_split_quota_multimodal_guards_handle_non_mapping_inputs(rate_limiter):
+ handler, _cache = rate_limiter
+
+ assert handler._estimate_audio_block_tokens(
+ object()
+ ) == handler._estimate_audio_block_tokens({})
+ assert handler._contains_unmeasurable_chat_media(object()) is False
+ assert handler._contains_image_content(object()) is False
+ assert handler._contains_image_content(
+ {"inline_data": {"mime_type": "image/png", "data": "dGVzdA=="}}
+ )
+ assert handler._responses_input_to_chat_messages(object()) == ()
+ assert (
+ handler._requires_conservative_responses_input_reservation(
+ object(), "responses"
+ )
+ is False
+ )
+ assert handler._estimate_precise_input_tokens(object(), model=None) == 0
+
+
+ ("call_type", "data", "expected_text"),
+ [
+ ("embedding", {"input": "embedding input"}, "embedding input"),
+ (
+ "embedding",
+ {"input": ["first embedding", "second embedding"]},
+ ["first embedding", "second embedding"],
+ ),
+ ("text_completion", {"prompt": "completion prompt"}, "completion prompt"),
+ ],
+)
+def test_precise_input_estimate_selects_endpoint_text(
+ rate_limiter,
+ monkeypatch,
+ call_type,
+ data,
+ expected_text,
+):
+ handler, _cache = rate_limiter
+ captured = {}
+
+ def token_counter(**kwargs):
+ captured.update(kwargs)
+ return 7
+
+ monkeypatch.setattr("litellm.token_counter", token_counter)
+
+ assert (
+ handler._estimate_precise_input_tokens(data, model="test", call_type=call_type)
+ == 7
+ )
+ assert captured["messages"] is None
+ assert captured["text"] == expected_text
+
+
+async def test_project_io_reservation_ignores_non_mapping_request_data(rate_limiter):
+ handler, _cache = rate_limiter
+
+ await handler._reserve_project_io_tokens_or_raise(
+ descriptors=[],
+ data=object(),
+ requested_model=None,
+ user_api_key_dict=UserAPIKeyAuth(),
+ tpm_reservation_scopes=(),
+ tpm_reservation_amount=0,
+ )
+
+
+async def test_streaming_combined_usage_reconciles_project_io_reservations(
+ rate_limiter,
+):
+ handler, _cache = rate_limiter
+ itpm_scope = (PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")
+ otpm_scope = (PROJECT_OTPM_DESCRIPTOR_KEY, "project:model")
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset({itpm_scope})
+ stash.otpm_reserved_tokens = 60
+ stash.otpm_reserved_scopes = frozenset({otpm_scope})
+ kwargs = {
+ "combined_usage_object": Usage(
+ prompt_tokens=40,
+ completion_tokens=15,
+ total_tokens=55,
+ ),
+ }
+ increments = []
+
+ async def capture_increments(increment_list, **_kwargs):
+ increments.extend(increment_list)
+
+ handler.internal_usage_cache.dual_cache.async_increment_cache_pipeline = (
+ capture_increments
+ )
+
+ await handler.async_log_success_event(
+ kwargs=kwargs,
+ response_obj={"response": "stream body"},
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+
+ itpm_adjustments = [
+ operation
+ for operation in increments
+ if PROJECT_ITPM_DESCRIPTOR_KEY in operation["key"]
+ ]
+ otpm_adjustments = [
+ operation
+ for operation in increments
+ if PROJECT_OTPM_DESCRIPTOR_KEY in operation["key"]
+ ]
+ assert [operation["increment_value"] for operation in itpm_adjustments] == [-60]
+ assert [operation["increment_value"] for operation in otpm_adjustments] == [-45]
+
+
+def test_aggregate_only_combined_usage_reconciles_project_io_reservations(rate_limiter):
+ handler, _cache = rate_limiter
+ stash = get_or_create_request_stash()
+ stash.itpm_reserved_tokens = 100
+ stash.itpm_reserved_scopes = frozenset(
+ {(PROJECT_ITPM_DESCRIPTOR_KEY, "project:model")}
+ )
+ stash.otpm_reserved_tokens = 80
+ stash.otpm_reserved_scopes = frozenset(
+ {(PROJECT_OTPM_DESCRIPTOR_KEY, "project:model")}
+ )
+ kwargs = {
+ "combined_usage_object": Usage(total_tokens=55),
+ }
+
+ operations = handler._build_io_token_reservation_ops(kwargs, object())
+
+ assert [operation["increment_value"] for operation in operations] == [-45, -25]
+
+
+def test_raw_split_usage_dict_reconciles_project_io_tokens(rate_limiter):
+ handler, _cache = rate_limiter
+
+ assert handler._resolve_io_token_reconcile_usage(
+ {
+ "input_tokens": 30,
+ "output_tokens": 12,
+ "input_tokens_details": {"cached_tokens": 5},
+ }
+ ) == (25, 12, True)
+
+
+async def test_post_call_success_hook_contains_header_merge_failures(
+ rate_limiter, monkeypatch
+):
+ handler, _cache = rate_limiter
+ response = ModelResponse()
+ response._hidden_params = {}
+
+ def raise_on_merge(**_kwargs):
+ raise RuntimeError("header merge failed")
+
+ monkeypatch.setattr(
+ handler,
+ "_merge_ratelimit_statuses_into_additional_headers",
+ raise_on_merge,
+ )
+
+ await handler.async_post_call_success_hook(
+ data={
+ "litellm_proxy_rate_limit_response": {
+ "overall_code": "OK",
+ "statuses": (),
+ }
+ },
+ user_api_key_dict=UserAPIKeyAuth(),
+ response=response,
+ )
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v", "-s"])
diff --cc type-discipline-budget.json
index 21dc0bc2791,8e55b1533ea..9f57dca217e
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"LIT001": {
- "limit": 22936
- "limit": 22938
++ "limit": 22935
},
"LIT002": {
- "limit": 27133
+ "limit": 26901
},
"LIT003": {
"limit": 269
@@@ -27,10 -27,10 +27,10 @@@
"limit": 0
},
"LIT010": {
- "limit": 16701
- "limit": 16715
++ "limit": 16689
},
"LIT011": {
- "limit": 5595
+ "limit": 5593
},
"LIT012": {
"limit": 4519