litellm/tests/_support/rust_parallel_request_limiter.py
hcl 8fb724f7da
fix(gemini): return an error instead of an empty 200 when a Gemini image request gets no image (#29125)
* fix(gemini): surface finishReason on image-gen safety blocks

Image-gen transforms iterated candidates[].content.parts[] for inlineData
and ignored finishReason, so an IMAGE_SAFETY / IMAGE_PROHIBITED_CONTENT
block returned an empty ImageResponse with no exception. The chat path
already surfaces these (get_flagged_finish_reasons + ContentPolicyViolationError);
mirror that for image gen by raising on a flagged finishReason when no image
data was produced. Covers gemini/ and vertex_ai/ via one shared helper.

Fixes #28989

* fix(gemini): also surface blocked prompts and image-edit safety blocks

promptFeedback.blockReason with no candidates now raises
ContentPolicyViolationError like a flagged finishReason, and the gemini/
and vertex_ai/ image-edit transforms use the same check when they return
no image.

* fix(gemini): return an error instead of an empty 200 when a Gemini image request gets no image

A refused image or a blocked prompt answers 400 content_policy_violation with
Gemini's finishReason and finishMessage, or its blockReason. Any other answer
without an image answers 422 with the model's text. Both cover AI Studio and
Vertex on image generations and image edits, and neither is billed or retried

* fix(gemini): bill a no-image answer's tokens and keep model text out of the 422

A Gemini or Vertex image answer without an image and without a refusal still bills its tokens on the failure log, as main billed the empty 200. Refusals and blocked prompts stay at $0. The 422 message names only the finishReason, so model output never reaches the exception text or logs

* fix(gemini): bill images served beside a failed answer when n is above 1

A refused or image-less answer in a fan-out no longer drops the cost of the
images its siblings returned. OTHER and LANGUAGE now answer 422 like
IMAGE_OTHER, and the 422 no longer carries the model's text in its response

* fix(gemini): bill Gemini image refusals Google charges for and keep token details on failure logs

Google charges for an image refusal that comes back as HTTP 200, except IMAGE_RECITATION, whose answer says the request is not charged. Those refusals now bill their tokens on the failure log, as a blocked prompt does. Billed failure rows keep reasoning, cached and image token details

* fix(images): report a billed failure's cost header and keep refused image health probes healthy

A failed image request that bills tokens now answers with an
x-litellm-response-cost header that matches its failure spend row. The
generations route sent no cost header on errors, and errors that went
through the shared error handler reported 0 unless the logging object
had a finalized cost

The image_generation health probe now counts a refusal or a Gemini
answer without an image as healthy, like the image_edit probe already
did for refusals, so a refused probe prompt does not mark the
deployment unhealthy

* fix(images): return served images when another of n answers has no image

With n above 1, an answer Gemini refused or answered without an image no
longer fails the whole request when another answer served an image. The
served images come back and the refusals Google charges for are billed
with them. The request fails only when no answer served an image

* fix(proxy): record what a refused image health probe billed

A health probe that the provider billed but that ends in an image error now writes a failure spend row under the internal health check key in both spend modes, and the text-only Vertex integration cases expect 422 with the same spend

* fix(images): bill a failed Gemini image attempt when a fallback serves the request

A billed text-only or blocked answer was dropped from spend once a fallback returned the image. The cost header, spend row and key spend now include it

* fix(images): keep the failed attempt charge on unpriced fallbacks and collector rows

* fix(images): keep billing, alerts, and errors correct when Gemini answers without an image

* fix(gemini): count billed image refusals in budgets once and never as deployment failures

A billed refusal or no-image answer now counts once toward deployment,
provider, tag, key model and session budgets, and a served fallback's
success counts only its own cost there. Only these errors opt the budget
hooks into per-attempt failure events. They no longer count toward a
deployment's failure rate, and a failure row after an already logged
success lifts only the attempts that success did not bill, so Prometheus
counts a served image's spend once.

* fix(gemini): bill image refusals once across stream headers, Prometheus and token columns, and ignore request params named after billing fields

* fix(prometheus): keep a deployment that answered an image prompt without an image marked healthy

A refusal or an answer without an image skipped the deployment state update, so a deployment that only refused had no litellm_deployment_state sample. It now writes 0, as a served answer does on main

* fix(prometheus): count an image prompt answered without an image as a deployment success

A refusal or an answer without an image added to litellm_deployment_total_requests but to neither the success nor the failure counter, so a refusing deployment's success rate dropped. It now counts as a success, as it did when these answers were 200s

* fix(router): return a fallback's image refusal after an earlier failure

A 5xx followed by a fallback refusal raised the 5xx, so the OpenAI SDK
retried and billed the whole chain 3 times. Refused and empty image
answers also keep the request's custom Prometheus metadata labels, and a
no-log refusal no longer adds to the spend and token counters.

* fix(proxy): log a fallback's image refusal on the deployment that answered

When the client gets a fallback's refusal or 422 after an earlier model
failed another way, its failure row, Prometheus spend and request labels
now go on that fallback's deployment instead of the first one. Prometheus
also counts that attempt in the fallback deployment's success and total
counters, and the billed spend metrics label requested_model with the
group that answered.

* fix(router): count an image answer without an image toward deployment tpm limits, return the first refusal in a fallback chain, and keep refusals out of the Slack failed-request report

* fix(router): count an image refusal toward deployment tpm limits on sync calls and on fallback attempts

* fix(router): store an attempt's answered tokens as a 32-bit count so rust-lint passes

The answered_tokens field 20fadb7 added made the router's attempt error
large enough for clippy's result_large_err lint. A 32-bit count fits the
error's existing padding and holds any token count Gemini reports.

* fix(proxy): count a billed image refusal toward key, team and user tpm limits even with no output tokens

* fix(router): store an attempt's exception classes as a boxed slice so rust-lint passes after merging main

* fix(proxy): count every billed image refusal of a fallback chain toward token limits

* test(proxy): annotate the refusal-after-settlement test bindings as Final

* fix(images): bill every refused answer of an n>1 image request toward the router's model group usage

A refusing multi-image request raised its first unserved answer with only that
answer's billing, so the router's model group usage missed the sibling answers'
tokens. The raised error now carries the summed billing of every answer.

Also waits for the sync success log in the usage-based-routing-v2 sync fallback
test, which raced the logging thread.

* fix(prometheus): keep custom metadata labels off a no-log image refusal's request counters

* fix(rate limits): count a billed image refusal like a served answer in the limiter, and give back an unbilled recitation's reservation

A billed refusal now settles in the Rust limiter the way a served answer does, so its
tokens count toward the key, team and user tpm limits also with token reservation off,
and toward the model limit on the key of the fallback that refused. A recitation bills
nothing, so it takes the plain failure path and gives back its tpm and otpm reservation
instead of being settled as a billed answer with no tokens.

* fix(rate limits): count a billed refusal's input tokens toward project itpm on every fallback attempt under an output token limit

* test(rate limits): assert project itpm after each refused fallback attempt instead of looping

* test(rust router): build call_loop exception classes as a boxed slice

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-25 20:55:23 +00:00

281 lines
12 KiB
Python

import copy
import dataclasses
import uuid
from collections.abc import Mapping
from types import SimpleNamespace
from typing import Final
from pydantic import TypeAdapter
from litellm.caching.caching import DualCache
from litellm.integrations.custom_logger_v2.call import CallContext
from litellm.integrations.custom_logger_v2.enforcement import FieldView
from litellm.integrations.custom_logger_v2.enums import Field, Hook
from litellm.integrations.custom_logger_v2.field_sources import FieldSource, HookArgs, with_sources
from litellm.integrations.custom_logger_v2.legacy import PROXY_REQUEST_KEYS, KwargsFields
from litellm.integrations.custom_logger_v2.outcomes import Abort, Patch
from litellm.integrations.custom_logger_v2.patches import apply_patch
from litellm.integrations.custom_logger_v2.rust import WireManifest
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.hooks.parallel_request_limiter_v3 import (
_NATIVE_STASH, # pyright: ignore[reportPrivateUsage] # the replicas read the native's stash in the limiter's own shape
ParallelRequestLimiterHook,
ParallelSlotAcquisition,
RateLimitDescriptor,
RateLimitedModel,
RateLimitResponse,
RequestRateLimiterStash,
_window_identities, # pyright: ignore[reportPrivateUsage] # the replicas read the native's stash in the limiter's own shape
reservation_operation,
)
from litellm.proxy.hooks.parallel_request_limiter_v3 import (
estimate_input_and_output_tokens as limiter_estimate_input_and_output_tokens,
)
from litellm.proxy.hooks.parallel_request_limiter_v3 import (
estimate_tokens_for_request as limiter_estimate_tokens_for_request,
)
from litellm.proxy.hooks.parallel_request_limiter_v3 import get_request_stash as _live_request_stash
from litellm.proxy.hooks.parallel_request_limiter_v3_native import (
ParallelRequestLimiterNativeLogger,
PreCallAuthScope,
native_parallel_request_limiter,
)
from litellm.proxy.utils import HookRun, hook_fields
from litellm.proxy.v2_proxy_fields import DERIVED_POST_CALL_FAILURE_PROXY_FIELDS, PRE_CALL_SOURCES, proxy_call_facts
from litellm.redis.stores.rate_limits import RateLimitScope
from litellm.rust_bridge._native import NativeParallelRequestLimiter
from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType
from litellm.types.utils import CallTypes
_DESCRIPTORS: Final = TypeAdapter(list[RateLimitDescriptor])
def _view(
data: dict[str, object], auth: object, call_type: str | None, sources: Mapping[Field, FieldSource]
) -> FieldView:
return FieldView(
with_sources(
KwargsFields(data, PROXY_REQUEST_KEYS),
sources,
HookArgs(auth=auth, request=data, call_type=call_type),
)
)
def _failure_view(data: dict[str, object], auth: object, error: Exception) -> FieldView:
return FieldView(
with_sources(
hook_fields(data, HookRun(response=error), Field.error),
DERIVED_POST_CALL_FAILURE_PROXY_FIELDS,
HookArgs(auth=auth, request=data, result=error),
)
)
def _context(
hook: Hook, data: dict[str, object], call_type: str | None, auth: object, endpoint_type: str
) -> CallContext[object]:
return CallContext(hook=hook, call=proxy_call_facts(data, call_type, auth, endpoint_type), state=None)
def _raise(outcome: object) -> None:
if isinstance(outcome, Abort) and outcome.exception is not None:
raise outcome.exception
_NATIVES: Final[list[NativeParallelRequestLimiter]] = []
def get_request_stash() -> RequestRateLimiterStash | None:
live: Final = _live_request_stash()
if live is None or live.native_state is None or not _NATIVES:
return live
native: Final = _NATIVES[-1]
if not native.owned(live.native_state):
return live
exported: Final = _NATIVE_STASH.validate_python(native.view(live.native_state))
slot: Final = exported["parallel_slot"]
model: Final = exported["reserved_model"]
response: Final = exported["rate_limit_response"]
itpm: Final = exported["itpm"]
otpm: Final = exported["otpm"]
return dataclasses.replace(
live,
rate_limit_response=None
if response is None
else RateLimitResponse(overall_code=response["overall_code"], statuses=list(response["statuses"])),
parallel_slot=None
if slot is None
else ParallelSlotAcquisition(
slot_id=slot["slot_id"], gauges=tuple(RateLimitScope(key, value) for key, value in slot["gauges"])
),
reserved_tokens=exported["reserved_tokens"],
reserved_model=None if model is None else RateLimitedModel(requested=model[0], group=model[1]),
reserved_scopes=frozenset(exported["reserved_scopes"]),
fallback_models=frozenset(exported["fallback_models"]),
reservation_released=exported["reservation_released"],
io_reservation_released=exported["io_reservation_released"],
tpm_limited_tags=frozenset(exported["tpm_limited_tags"]),
ptu_reserved_tokens=exported["ptu_reserved_tokens"],
ptu_reserved_window_identities=_window_identities(exported["ptu_windows"]),
itpm_reserved_tokens=itpm["tokens"],
itpm_reserved_scopes=frozenset(itpm["scopes"]),
itpm_reserved_window_identities=_window_identities(itpm["windows"]),
otpm_reserved_tokens=otpm["tokens"],
otpm_reserved_scopes=frozenset(otpm["scopes"]),
otpm_reserved_window_identities=_window_identities(otpm["windows"]),
batch_enqueued_reservation=exported["batch_enqueued_reservation"],
batch_tpd_refund_ops=tuple(reservation_operation(op) for op in exported["batch_tpd_refunds"]),
)
def rate_limit_descriptors() -> list[RateLimitDescriptor] | None:
live: Final = _live_request_stash()
if live is None or live.native_state is None or not _NATIVES:
return None
native: Final = _NATIVES[-1]
if not native.owned(live.native_state):
return None
return _DESCRIPTORS.validate_python(native.descriptors(live.native_state)) or None
class RustParallelRequestLimiter(ParallelRequestLimiterHook):
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, **kwargs) # pyright: ignore[reportArgumentType] # the replicas pass the limiter's own arguments
_NATIVES.append(self.native_companion)
self.native_logger: Final[ParallelRequestLimiterNativeLogger] = native_parallel_request_limiter(self)
self.minted_call_ids: Final[set[str]] = set()
def _proxy_call_id(
self, data: dict[str, object], call_type: str
) -> None: # mutable-ok: the proxy stamps the call id into the body
current: Final = data.get("litellm_call_id")
if (current is not None and current not in self.minted_call_ids) or call_type == CallTypes.call_mcp_tool.value:
return
minted: Final = str(uuid.uuid4())
self.minted_call_ids.add(minted)
data["litellm_call_id"] = minted
async def async_pre_call_hook(
self,
user_api_key_dict: UserAPIKeyAuth,
cache: DualCache,
data: dict, # pyright: ignore[reportMissingTypeArgument] # the legacy hook's signature
call_type: str,
endpoint_type: EndpointType = EndpointType.GENERIC,
) -> Exception | str | dict[str, object] | None:
self._proxy_call_id(data, call_type)
with PreCallAuthScope(user_api_key_dict):
outcome: Final = await self.native_logger.run_rust(
Hook.pre_call,
declared_reads(self.native_logger, Hook.pre_call),
_view(data, user_api_key_dict, call_type, PRE_CALL_SOURCES),
_context(Hook.pre_call, data, call_type, user_api_key_dict, endpoint_type.value),
)
_raise(outcome)
return None
async def async_post_call_success_hook(self, data: dict, user_api_key_dict: UserAPIKeyAuth, response) -> None: # pyright: ignore[reportMissingTypeArgument, reportMissingParameterType] # the legacy hook's signature
outcome: Final = await self.native_logger.run_rust(
Hook.post_call_success,
declared_reads(self.native_logger, Hook.post_call_success),
SimpleNamespace(deprecated_kwargs=data, deprecated_response_obj=response),
_context(Hook.post_call_success, data, None, user_api_key_dict, EndpointType.GENERIC.value),
)
_raise(outcome)
return await super().async_post_call_success_hook(data, user_api_key_dict, response)
async def async_logging_hook(self, kwargs: dict, result, call_type: str): # pyright: ignore[reportMissingTypeArgument, reportMissingParameterType] # the legacy hook's signature
payload: Final = kwargs.get("standard_logging_object")
prepared: Final = await self.native_logger.run_rust(
Hook.log_prepare,
declared_reads(self.native_logger, Hook.log_prepare),
SimpleNamespace(deprecated_kwargs=kwargs, standard_logging_payload=payload),
_context(Hook.log_prepare, kwargs, call_type, None, EndpointType.GENERIC.value),
)
if isinstance(prepared, Patch) and payload is not None:
kwargs["standard_logging_object"] = apply_patch(
{Field.standard_logging_payload: copy.deepcopy(payload)}, prepared
)[Field.standard_logging_payload]
return await super().async_logging_hook(kwargs, result, call_type)
async def async_post_call_failure_hook(
self,
request_data: dict[str, object], # mutable-ok: the base hook declares this parameter as a dict
original_exception: Exception,
user_api_key_dict: UserAPIKeyAuth,
traceback_str: str | None = None,
) -> None:
await self.native_logger.run_rust(
Hook.post_call_failure,
declared_reads(self.native_logger, Hook.post_call_failure),
_failure_view(request_data, user_api_key_dict, original_exception),
_context(Hook.post_call_failure, request_data, None, user_api_key_dict, EndpointType.GENERIC.value),
)
return await super().async_post_call_failure_hook(
request_data, original_exception, user_api_key_dict, traceback_str
)
def estimate_tokens_for_request(
handler: ParallelRequestLimiterHook,
data: object,
call_type: str | None = None,
min_configured_tpm_limit: int | None = None,
configured_output_tokens: int | None = None,
) -> int:
native: Final = handler.native_companion
assert native is not None
estimated: Final = native.estimate_tokens_for_request(
data, call_type or "", min_configured_tpm_limit, configured_output_tokens
)
if estimated is not None:
return estimated
return limiter_estimate_tokens_for_request( # the Python estimate the native's media host call hands back to
data,
min_configured_tpm_limit=min_configured_tpm_limit,
call_type=call_type,
configured_output_tokens=configured_output_tokens,
media_model_resolver=handler.media_model_resolver,
)
def estimate_input_and_output_tokens(
handler: ParallelRequestLimiterHook,
data: object,
call_type: str | None = None,
min_configured_tpm_limit: int | None = None,
configured_output_tokens: int | None = None,
include_media: bool = True,
) -> tuple[int, int]:
native: Final = handler.native_companion
assert native is not None
estimated: Final = native.estimate_input_and_output_tokens(
data, call_type or "", min_configured_tpm_limit, configured_output_tokens, include_media
)
if estimated is not None:
return estimated
return limiter_estimate_input_and_output_tokens( # the Python estimate the native's media host call hands back to
data,
min_configured_tpm_limit=min_configured_tpm_limit,
call_type=call_type,
configured_output_tokens=configured_output_tokens,
include_media=include_media,
)
PROXY_MaxParallelRequestsHandler_v3 = RustParallelRequestLimiter
__all__ = [
"PROXY_MaxParallelRequestsHandler_v3",
"RustParallelRequestLimiter",
"estimate_input_and_output_tokens",
"estimate_tokens_for_request",
"get_request_stash",
"rate_limit_descriptors",
]
def declared_reads(native: ParallelRequestLimiterNativeLogger, hook: Hook) -> frozenset[Field]:
manifest: Final = WireManifest.model_validate_json(native.bridge.manifest())
return next(subscription.reads for subscription in manifest.subscriptions if subscription.hook is hook)