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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(router): record cooled deployments on the all-cooled failure row (#47120)
yucheng-berri3e18a4b55d5d
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 0ac216c2029..3a1dafa331c 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -151,6 +151,7 @@ from litellm.types.llms.openai import (from litellm.types.mcp import MCPPostCallResponseObjectfrom litellm.types.prompts.init_prompts import PromptSpecfrom litellm.types.rerank import RerankResponse+from litellm.types.router import RouterRateLimitErrorfrom litellm.types.utils import (DEPLOYMENT_SCOPED_PRICING_FIELDS,CachingDetails,@@ -6692,6 +6693,7 @@ class StandardLoggingPayloadSetup:rate_limit_category: Final = validate_rate_limit_category(getattr(original_exception, "category", None))rate_limit_type: Final = validate_rate_limit_type(getattr(original_exception, "rate_limit_type", None))budget_error: Final = original_exception if isinstance(original_exception, BudgetExceededError) else None+ router_error: Final = original_exception if isinstance(original_exception, RouterRateLimitError) else Noneprovider_request_id: Final = _get_provider_request_id(original_exception) if original_exception else Nonereturn StandardLoggingPayloadErrorInformation(@@ -6707,6 +6709,7 @@ class StandardLoggingPayloadSetup:error_budget_entity_id=budget_error.entity_id if budget_error else None,error_budget_limit=budget_error.max_budget if budget_error else None,error_budget_spend=budget_error.current_cost if budget_error else None,+ error_cooldown_deployments=router_error.cooldown_deployments if router_error else None,normalized_error=normalize_error(original_exception, error_status, error_message),)diff --git a/litellm/router.py b/litellm/router.pyindex 113565fecaa..af79fa763c4 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -222,6 +222,7 @@ from litellm.router_utils.cooldown_handlers import (_first_present, # pyright: ignore[reportPrivateUsage] - shared internal helper across router_utils submodules, matching the other cooldown_handlers imports on this lineasync_get_cooldown_deployments,async_get_cooldown_deployments_with_debug_info,+ get_cooldown_deployment_info,get_cooldown_deployments,is_advisor_orchestration_failure,is_background_response_poll_not_found,@@ -12598,6 +12599,80 @@ class Router:if isinstance(model_info, Mapping) and model_info.get("id") is not None)+ def _region_routable_deployments(+ self,+ deployments: Sequence[DeploymentTypedDict],+ request_kwargs: Mapping[str, object] | None,+ has_request_input: bool,+ ) -> tuple[Mapping[str, Any], ...]:+ """+ `deployments` without the ones `_pre_call_checks` keeps this request away from for being outside its allowed+ region, typed for the tag routing filter+ """+ allowed_model_region: Final = None if request_kwargs is None else request_kwargs.get("allowed_model_region")+ if allowed_model_region is None or not self.enable_pre_call_checks or not has_request_input:+ return tuple(deployments)+ if not isinstance(allowed_model_region, str):+ return ()+ return tuple(+ deployment+ for deployment in deployments+ if is_region_allowed(+ litellm_params=LiteLLM_Params.model_validate(deployment["litellm_params"]),+ allowed_model_region=allowed_model_region,+ )+ )++ async def _async_routable_cooled_deployment_ids(+ self,+ model: str,+ request_deployments: Sequence[DeploymentTypedDict],+ cooldown_deployments: Iterable[str],+ request_kwargs: Mapping[str, object],+ has_request_input: bool,+ ) -> frozenset[str]:+ """+ Ids of the cooling deployments in `request_deployments` that region and tag routing would send this request+ to, each tag routing pick counted along with the picks it falls back to once that one is unavailable, judged+ without recording a tag match on the request+ """+ cooled_ids: Final = frozenset(cooldown_deployments)+ metadata_variable_name: Final = get_metadata_variable_name_from_kwargs(request_kwargs)+ metadata: Final = request_kwargs.get(metadata_variable_name)+ if metadata_variable_name in request_kwargs and not isinstance(metadata, Mapping):+ return frozenset()+ tag_request: Final[Mapping[str, Any]] = (+ {**request_kwargs, metadata_variable_name: {**metadata}}+ if isinstance(metadata, Mapping)+ else request_kwargs+ )+ routable_ids = frozenset[str]() # rebind-ok: gains each pass's tag routing picks+ remaining = tuple( # rebind-ok: each pass drops what tag routing just picked+ deployment+ for deployment in self._region_routable_deployments(request_deployments, request_kwargs, has_request_input)+ if self._deployment_ids((deployment,)) <= cooled_ids+ )+ while remaining:+ try:+ picked = await get_deployments_for_tag(+ llm_router_instance=self,+ model=model,+ healthy_deployments=remaining,+ request_kwargs=tag_request,+ metadata_variable_name=metadata_variable_name,+ )+ except ValueError: # tag routing sends this request to none of the rest+ break+ picked_identities = frozenset(id(deployment) for deployment in picked)+ rest = tuple(deployment for deployment in remaining if id(deployment) not in picked_identities)+ if len(rest) == len(remaining):+ break+ routable_ids |= self._deployment_ids(+ tuple(deployment for deployment in remaining if id(deployment) in picked_identities)+ )+ remaining = rest+ return routable_ids+def has_model_id(self, candidate_id: str) -> bool:"""O(1) membership check for a deployment ID without allocating large lists.@@ -14457,6 +14532,13 @@ class Router:litellm_router_instance=self,model=model,parent_otel_span=parent_otel_span,+ route_model_ids=await self._async_routable_cooled_deployment_ids(+ model=model,+ request_deployments=request_deployments,+ cooldown_deployments=cooldown_deployments,+ request_kwargs=cast(Mapping[str, object], request_kwargs), # cast-ok: str-keyed request kwargs+ has_request_input=messages is not None or input is not None,+ ),)raise exception@@ -15656,6 +15738,17 @@ class Router:enable_pre_call_checks=self.enable_pre_call_checks,cooldown_list=_cooldown_list,model_ids=model_ids,+ cooldown_deployments=get_cooldown_deployment_info(+ self,+ self._deployment_ids(+ self._region_routable_deployments(+ request_deployments,+ cast(Mapping[str, object] | None, request_kwargs), # cast-ok: str-keyed request kwargs+ messages is not None or input is not None,+ )+ ),+ _cooldown_list,+ ),)if strategy == "simple-shuffle":@@ -15830,6 +15923,17 @@ class Router:enable_pre_call_checks=self.enable_pre_call_checks,cooldown_list=_cooldown_list,model_ids=pass_through_model_ids,+ cooldown_deployments=get_cooldown_deployment_info(+ self,+ self._deployment_ids(+ self._region_routable_deployments(+ request_deployments,+ cast(Mapping[str, object] | None, request_kwargs), # cast-ok: str-keyed request kwargs+ messages is not None or input is not None,+ )+ ),+ _cooldown_list,+ ),)# 6. Apply load balancing strategydiff --git a/litellm/router_utils/cooldown_handlers.py b/litellm/router_utils/cooldown_handlers.pyindex bbd895320bd..7ed4864ebc3 100644--- a/litellm/router_utils/cooldown_handlers.py+++ b/litellm/router_utils/cooldown_handlers.py@@ -8,7 +8,7 @@ Router cooldown handlersimport asyncioimport math-from collections.abc import Mapping+from collections.abc import Collection, Mapping, Sequencefrom datetime import datetimefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final@@ -28,12 +28,14 @@ from litellm.constants import ()from litellm.exceptions import MidStreamFallbackErrorfrom litellm.litellm_core_utils.credential_accessor import CredentialAccessor+from litellm.litellm_core_utils.litellm_logging import mask_api_base_credentialsfrom litellm.router_utils.cooldown_cache import ROUTER_COOLDOWNS_TARGET, CooldownCacheValuefrom litellm.router_utils.cooldown_callbacks import router_cooldown_event_callbackfrom litellm.types.router import Deploymentfrom litellm.types.utils import (BACKGROUND_RESPONSE_COST_POLL_CALL_ORIGIN,BACKGROUND_RESPONSE_STATUS_POLL_CALL_ORIGIN,+ CooldownDeploymentInfo,InternalCallOrigin,)@@ -644,6 +646,26 @@ def get_cooldown_deployments(litellm_router_instance: LitellmRouter, parent_otel_get_cooldown_deployments = get_cooldown_deployments+def _deployment_api_base(litellm_router_instance: LitellmRouter, model_id: str) -> str | None:+ deployment: Final = litellm_router_instance.get_deployment(model_id=model_id)+ api_base: Final = deployment.litellm_params.api_base if deployment else None+ return None if api_base is None else mask_api_base_credentials(api_base)+++def get_cooldown_deployment_info(+ litellm_router_instance: LitellmRouter, route_model_ids: Collection[str], cooldown_list: Sequence[str]+) -> tuple[CooldownDeploymentInfo, ...]:+ """+ The deployments the router resolved for this request (`route_model_ids`) that are in `cooldown_list`, each+ with its masked api_base+ """+ return tuple(+ CooldownDeploymentInfo(model_id=model_id, api_base=_deployment_api_base(litellm_router_instance, model_id))+ for model_id in cooldown_list+ if model_id in route_model_ids+ )++def should_cooldown_based_on_allowed_fails_policy(litellm_router_instance: LitellmRouter,deployment: str,diff --git a/litellm/router_utils/handle_error.py b/litellm/router_utils/handle_error.pyindex 14ed6ed2adc..38d9ef05706 100644--- a/litellm/router_utils/handle_error.py+++ b/litellm/router_utils/handle_error.py@@ -1,9 +1,11 @@+from collections.abc import Collectionfrom typing import TYPE_CHECKING, Any, Finalfrom litellm._logging import redact_secrets, verbose_router_loggerfrom litellm.constants import MAX_EXCEPTION_MESSAGE_LENGTHfrom litellm.router_utils.cooldown_handlers import (async_get_cooldown_deployments_with_debug_info,+ get_cooldown_deployment_info,)from litellm.types.integrations.slack_alerting import AlertTypefrom litellm.types.router import RouterRateLimitError@@ -69,7 +71,10 @@ async def send_llm_exception_alert(async def async_raise_no_deployment_exception(- litellm_router_instance: LitellmRouter, model: str, parent_otel_span: Span | None+ litellm_router_instance: LitellmRouter,+ model: str,+ parent_otel_span: Span | None,+ route_model_ids: Collection[str] | None = None,):"""Raises a RouterRateLimitError if no deployment is found for the given model.@@ -94,4 +99,9 @@ async def async_raise_no_deployment_exception(enable_pre_call_checks=litellm_router_instance.enable_pre_call_checks,cooldown_list=cooldown_list_ids,model_ids=model_ids,+ cooldown_deployments=(+ None+ if route_model_ids is None+ else get_cooldown_deployment_info(litellm_router_instance, route_model_ids, cooldown_list_ids)+ ),)diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 68dbc701c9e..46617e1b753 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -43,6 +43,7 @@ from .llms.bedrock import AwsSessionTagfrom .llms.openai import OpenAIFileObjectfrom .search import SearchProviderfrom .utils import (+ CooldownDeploymentInfo,CustomPricingLiteLLMParams,MirroredPricingParams,ModelResponse,@@ -1106,6 +1107,7 @@ class RouterErrorTypes(str, enum.Enum):class RouterRateLimitError(ValueError):status_code: Final = 429+ cooldown_deployments: tuple[CooldownDeploymentInfo, ...] | None = Nonedef __init__(self,@@ -1114,11 +1116,13 @@ class RouterRateLimitError(ValueError):enable_pre_call_checks: bool,cooldown_list: list,model_ids: Sequence[str] = (),+ cooldown_deployments: Sequence[CooldownDeploymentInfo] | None = None,) -> None:self.model = modelself.cooldown_time = cooldown_timeself.enable_pre_call_checks = enable_pre_call_checksself.cooldown_list = cooldown_list+ self.cooldown_deployments = None if cooldown_deployments is None else tuple(cooldown_deployments)self.all_deployments_in_cooldown = bool(model_ids) and frozenset(model_ids) <= frozenset(cooldown_list)self.type = (RouterErrorTypes.all_deployments_in_cooldown.valuediff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex fd1d58adafb..2e05107f82d 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -3386,6 +3386,11 @@ class StandardLoggingZeroCostDiagnostic(TypedDict):missing_pricing_keys: ReadOnly[tuple[str, ...]]+class CooldownDeploymentInfo(TypedDict):+ model_id: ReadOnly[str]+ api_base: ReadOnly[str | None]++class StandardLoggingPayloadErrorInformation(TypedDict, total=False):error_code: str | Noneerror_class: str | None@@ -3414,6 +3419,7 @@ class StandardLoggingPayloadErrorInformation(TypedDict, total=False):error_budget_entity_id: str | Noneerror_budget_limit: float | Noneerror_budget_spend: float | None+ error_cooldown_deployments: ReadOnly[tuple[CooldownDeploymentInfo, ...] | None]normalized_error: ReadOnly[str | None]diff --git a/tests/integration/spend/test_router_cooldown_failure_row.py b/tests/integration/spend/test_router_cooldown_failure_row.pynew file mode 100644index 00000000000..04e36785823--- /dev/null+++ b/tests/integration/spend/test_router_cooldown_failure_row.py@@ -0,0 +1,358 @@+import asyncio+import json+import uuid+from collections.abc import Callable, Iterator, Mapping+from concurrent.futures import ThreadPoolExecutor+from contextlib import ExitStack+from dataclasses import dataclass+from itertools import product+from pathlib import Path+from typing import Final++import anthropic+import httpx+import openai+import pytest+import yaml+from integration._support.client import GATEWAY_LIMITS, Gateway, eventually, gateway_from_environment, object_value+from integration._support.database import read_rows+from integration._support.process import owned_proxy_process+from integration._support.redis_process import OwnedRedis, owned_redis+from integration._support.wire import Reply, Request, Wire, wire_server+from pydantic import JsonValue+from redis import Redis++pytestmark: Final = pytest.mark.timeout(300)++COOLDOWN_SECONDS: Final = 120+NO_DEPLOYMENTS: Final = "No deployments available"+ROW_SECONDS: Final = 70+CHAT: Final = "/v1/chat/completions"+MESSAGES: Final = "/v1/messages"+RESPONSES: Final = "/v1/responses"+FAILURE_ROW: Final = (+ "SELECT status, model_group, model_id, api_base, metadata::jsonb -> 'error_information' AS error "+ 'FROM "LiteLLM_SpendLogs" WHERE request_id = %s'+)+ENDPOINT_CELLS: Final = tuple((path, stream) for path in (CHAT, MESSAGES, RESPONSES) for stream in (False, True))+ENDPOINT_GROUPS: Final = tuple(+ f"{path.rsplit('/', 1)[-1]}-{'stream' if stream else 'json'}" for path, stream in ENDPOINT_CELLS+)+SDK_CELLS: Final = ("openai-sync", "openai-async-stream", "anthropic-sync")+TAGGED: Final = "tagged"+REGIONAL: Final = "regional"+GROUPS: Final = (*ENDPOINT_GROUPS, *SDK_CELLS, "neighbour", "scoped", "burst", TAGGED, REGIONAL)+LANES: Final = ("a", "b")+LANE_PARAMS: Final[Mapping[tuple[str, str], Mapping[str, JsonValue]]] = {+ (TAGGED, "a"): {"tags": ["tenant-a"]},+ (TAGGED, "b"): {"tags": ["default"]},+ (REGIONAL, "a"): {"region_name": "eu"},+ (REGIONAL, "b"): {"region_name": "us"},+}+TENANT_A: Final[Mapping[str, JsonValue]] = {"metadata": {"tags": ["tenant-a"]}}+UNTAGGED: Final[Mapping[str, JsonValue]] = {}+++@dataclass(frozen=True, slots=True)+class Rig:+ gateway: Gateway+ cache: OwnedRedis+ prefix: str+ wire: Wire++ def group(self, name: str) -> str:+ return f"{self.prefix}-{name}"++ def deployments(self, name: str) -> Mapping[str, str]:+ return {f"{self.group(name)}-{lane}": f"{self.wire.url}/{self.group(name)}/{lane}/v1" for lane in LANES}+++@dataclass(frozen=True, slots=True)+class Outcome:+ status: int+ detail: str+ call_id: str+++def is_model_probe(request: Request) -> bool:+ return (request.method, request.target) == ("GET", "/v1/models")+++def rate_limited(request: Request) -> Reply:+ if is_model_probe(request):+ return Reply(body=b'{"object": "list", "data": []}')+ body: Final = {"error": {"message": "scripted 429", "type": "rate_limit_error", "code": "rate_limit_exceeded"}}+ return Reply(status=429, body=json.dumps(body).encode())+++def cooldown_config(directory: Path, cache: OwnedRedis, prefix: str, wire: Wire) -> Path:+ base: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ assert isinstance(base, dict)+ model_list: Final = [+ {+ "model_name": f"{prefix}-{name}",+ "litellm_params": {+ "model": "openai/gpt-5.4",+ "api_base": f"{wire.url}/{prefix}-{name}/{lane}/v1",+ "api_key": "synthetic-openai-key",+ **LANE_PARAMS.get((name, lane), {}),+ },+ "model_info": {+ "id": f"{prefix}-{name}-{lane}",+ **({"enable_tag_filtering": True} if name == TAGGED else {}),+ },+ }+ for name, lane in product(GROUPS, LANES)+ ]+ config: Final = {+ **base,+ "model_list": model_list,+ "router_settings": {+ "num_retries": 0,+ "allowed_fails": 0,+ "cooldown_time": COOLDOWN_SECONDS,+ "enable_pre_call_checks": True,+ "redis_host": cache.host,+ "redis_port": cache.port,+ },+ }+ path: Final = directory / f"cooldown-{prefix}.yaml"+ path.write_text(yaml.safe_dump(config))+ return path++[email protected](scope="module")+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:+ directory: Final = tmp_path_factory.mktemp("router-cooldown-failure-row")+ prefix: Final = f"cooldown-{uuid.uuid4().hex[:8]}"+ with ExitStack() as stack:+ upstream: Final = stack.enter_context(gateway_from_environment())+ cache: Final = stack.enter_context(owned_redis(directory))+ wire: Final = stack.enter_context(wire_server(rate_limited))+ config: Final = cooldown_config(directory, cache, prefix, wire)+ owned: Final = stack.enter_context(owned_proxy_process(upstream, directory, {}, config=config, workers=2))+ yield Rig(owned.gateway, cache, prefix, wire)+++def cooled(cache: OwnedRedis, deployment_id: str) -> bool:+ with Redis(host=cache.host, port=cache.port) as client:+ return int(client.exists(f"deployment:{deployment_id}:cooldown")) == 1+++def request_body(path: str, group: str, stream: bool) -> dict[str, JsonValue]:+ content: Final = f"cooldown row {uuid.uuid4().hex}"+ match path:+ case "/v1/messages":+ return {+ "model": group,+ "max_tokens": 8,+ "messages": [{"role": "user", "content": content}],+ "stream": stream,+ }+ case "/v1/responses":+ return {"model": group, "input": content, "stream": stream}+ case _:+ return {"model": group, "messages": [{"role": "user", "content": content}], "stream": stream}+++def send(gateway: Gateway, path: str, group: str, stream: bool = False) -> Outcome:+ response: Final = gateway.request("POST", path, request_body(path, group, stream), headers={"Connection": "close"})+ return Outcome(response.status_code, response.text, response.headers["x-litellm-call-id"])+++def send_chat(rig: Rig, name: str, extra: Mapping[str, JsonValue]) -> Outcome:+ body: Final = {**request_body(CHAT, rig.group(name), False), **extra}+ response: Final = rig.gateway.request("POST", CHAT, body, headers={"Connection": "close"})+ return Outcome(response.status_code, response.text, response.headers["x-litellm-call-id"])+++def failure_row(call_id: str) -> dict[str, JsonValue]:+ rows: Final = eventually(+ lambda: read_rows(FAILURE_ROW, (call_id,)), lambda found: len(found) == 1, seconds=ROW_SECONDS+ )+ assert rows[0]["status"] == "failure", rows+ return rows[0]+++def until_router_refusal(attempt: Callable[[], Outcome], tries: int = 10) -> tuple[Outcome, ...]:+ def walk() -> Iterator[Outcome]:+ for _ in range(tries):+ outcome: Final = attempt()+ yield outcome+ if NO_DEPLOYMENTS in outcome.detail:+ return++ history: Final = tuple(walk())+ assert NO_DEPLOYMENTS in history[-1].detail, [(o.status, o.detail[:200]) for o in history]+ return history+++def cool_group(rig: Rig, name: str) -> tuple[Outcome, ...]:+ history: Final = until_router_refusal(lambda: send(rig.gateway, CHAT, rig.group(name)))+ assert all(cooled(rig.cache, identity) for identity in rig.deployments(name)), history+ return history+++def expected_cooldown(deployments: Mapping[str, str]) -> list[JsonValue]:+ return [{"model_id": identity, "api_base": deployments[identity]} for identity in sorted(deployments)]+++def cooldown_entries(error: Mapping[str, JsonValue]) -> list[JsonValue] | None:+ entries: Final = error.get("error_cooldown_deployments")+ if not isinstance(entries, list):+ return None+ return sorted(entries, key=lambda entry: str(object_value(entry)["model_id"]))+++def assert_refusal_row(call_id: str, deployments: Mapping[str, str]) -> Mapping[str, JsonValue]:+ row: Final = failure_row(call_id)+ error: Final = object_value(row["error"])+ assert (error["error_class"], error["error_code"]) == ("RouterRateLimitError", "429"), row+ assert cooldown_entries(error) == expected_cooldown(deployments), error.get("error_message")+ assert (row["model_id"], row["api_base"]) == ("", ""), row+ return error+++def provider_row(call_id: str) -> tuple[str, str, str, JsonValue]:+ row: Final = failure_row(call_id)+ error: Final = object_value(row["error"])+ return str(row["model_id"]), str(row["api_base"]), str(error["error_code"]), error.get("error_cooldown_deployments")+++def assert_provider_rows(history: tuple[Outcome, ...], deployments: Mapping[str, str]) -> None:+ provider: Final = history[:-1]+ assert all(outcome.status == 429 and NO_DEPLOYMENTS not in outcome.detail for outcome in provider), [+ (o.status, o.detail[:200]) for o in provider+ ]+ rows: Final = tuple(provider_row(outcome.call_id) for outcome in provider)+ assert {identity for identity, _, _, _ in rows} == set(deployments), rows+ assert all(base.startswith(deployments[identity]) for identity, base, _, _ in rows), rows+ assert all((code, cooldown) == ("429", None) for _, _, code, cooldown in rows), rows++[email protected](("path", "stream"), ENDPOINT_CELLS, ids=ENDPOINT_GROUPS)+def test_all_cooled_refusal_row_records_429_and_every_cooled_deployment(rig: Rig, path: str, stream: bool) -> None:+ name: Final = ENDPOINT_GROUPS[ENDPOINT_CELLS.index((path, stream))]+ history: Final = until_router_refusal(lambda: send(rig.gateway, path, rig.group(name), stream))+ refusal: Final = history[-1]+ assert refusal.status == 429, (refusal.status, refusal.detail[:300])+ assert_refusal_row(refusal.call_id, rig.deployments(name))+ assert_provider_rows(history, rig.deployments(name))+++def openai_chat(rig: Rig, group: str) -> Outcome:+ client: Final = openai.OpenAI(base_url=f"{rig.gateway.client.base_url}/v1", api_key=rig.gateway.key, max_retries=0)+ with pytest.raises(openai.RateLimitError) as raised:+ client.chat.completions.create(model=group, messages=[{"role": "user", "content": uuid.uuid4().hex}])+ return Outcome(429, raised.value.message, raised.value.response.headers["x-litellm-call-id"])+++def openai_async_stream(rig: Rig, group: str) -> Outcome:+ async def call() -> Outcome:+ client: Final = openai.AsyncOpenAI(+ base_url=f"{rig.gateway.client.base_url}/v1", api_key=rig.gateway.key, max_retries=0+ )+ try:+ with pytest.raises(openai.RateLimitError) as raised:+ await client.chat.completions.create(+ model=group, messages=[{"role": "user", "content": uuid.uuid4().hex}], stream=True+ )+ return Outcome(429, raised.value.message, raised.value.response.headers["x-litellm-call-id"])+ finally:+ await client.close()++ return asyncio.run(call())+++def anthropic_message(rig: Rig, group: str) -> Outcome:+ client: Final = anthropic.Anthropic(+ base_url=str(rig.gateway.client.base_url), api_key=rig.gateway.key, max_retries=0+ )+ with pytest.raises(anthropic.RateLimitError) as raised:+ client.messages.create(model=group, max_tokens=8, messages=[{"role": "user", "content": uuid.uuid4().hex}])+ return Outcome(429, raised.value.message, raised.value.response.headers["x-litellm-call-id"])+++SDK_CLIENTS: Final = {+ "openai-sync": openai_chat,+ "openai-async-stream": openai_async_stream,+ "anthropic-sync": anthropic_message,+}++[email protected]("client", SDK_CELLS)+def test_sdk_clients_get_429_and_the_row_names_the_cooled_deployments(rig: Rig, client: str) -> None:+ history: Final = until_router_refusal(lambda: SDK_CLIENTS[client](rig, rig.group(client)))+ assert_refusal_row(history[-1].call_id, rig.deployments(client))+ assert_provider_rows(history, rig.deployments(client))+++def test_the_row_lists_only_the_requested_groups_deployments_while_another_group_cools(rig: Rig) -> None:+ cool_group(rig, "neighbour")+ cool_group(rig, "scoped")+ refusal: Final = eventually(+ lambda: send(rig.gateway, CHAT, rig.group("scoped")),+ lambda outcome: (+ NO_DEPLOYMENTS in outcome.detail+ and all(identity in outcome.detail for identity in rig.deployments("neighbour"))+ ),+ )+ assert_refusal_row(refusal.call_id, rig.deployments("scoped"))+++def test_a_concurrent_burst_on_a_cooled_group_writes_one_complete_row_per_refusal(rig: Rig) -> None:+ cool_group(rig, "burst")+ rig.wire.drain()+ calls: Final = tuple(ENDPOINT_CELLS[index % len(ENDPOINT_CELLS)] for index in range(30))+ with (+ httpx.Client(+ base_url=rig.gateway.client.base_url, timeout=60, trust_env=False, limits=GATEWAY_LIMITS+ ) as client,+ ThreadPoolExecutor(max_workers=30) as pool,+ ):+ patient: Final = Gateway(client, rig.gateway.key, rig.gateway.upstream_url)+ outcomes: Final = tuple(pool.map(lambda call: send(patient, call[0], rig.group("burst"), call[1]), calls))+ assert all(outcome.status == 429 for outcome in outcomes), [(o.status, o.detail[:200]) for o in outcomes]+ assert len({outcome.call_id for outcome in outcomes}) == len(outcomes), outcomes+ refusals: Final = tuple(outcome for outcome in outcomes if NO_DEPLOYMENTS in outcome.detail)+ reached: Final = tuple(outcome for outcome in outcomes if NO_DEPLOYMENTS not in outcome.detail)+ assert refusals, [(o.status, o.detail[:200]) for o in outcomes]+ assert len(tuple(request for request in rig.wire.drain() if not is_model_probe(request))) == len(reached)+ for outcome in refusals:+ assert_refusal_row(outcome.call_id, rig.deployments("burst"))+ for outcome in reached:+ identity, api_base, code, cooldown = provider_row(outcome.call_id)+ assert api_base.startswith(rig.deployments("burst")[identity]), (identity, api_base)+ assert (code, cooldown) == ("429", None), outcome+++def cool_lane(rig: Rig, name: str, lane: str, extra: Mapping[str, JsonValue]) -> None:+ identity: Final = f"{rig.group(name)}-{lane}"+ outcomes: Final = eventually(lambda: send_chat(rig, name, extra), lambda _: cooled(rig.cache, identity))+ assert NO_DEPLOYMENTS not in outcomes.detail, outcomes.detail[:300]+++def router_refusal(rig: Rig, name: str, extra: Mapping[str, JsonValue]) -> Outcome:+ refusal: Final = eventually(lambda: send_chat(rig, name, extra), lambda outcome: NO_DEPLOYMENTS in outcome.detail)+ assert refusal.status == 429, (refusal.status, refusal.detail[:300])+ return refusal+++def test_a_tag_routed_refusal_row_names_only_the_cooled_deployments_its_tags_reach(rig: Rig) -> None:+ deployments: Final = rig.deployments(TAGGED)+ tenant: Final = f"{rig.group(TAGGED)}-a"+ cool_lane(rig, TAGGED, "a", TENANT_A)+ cool_lane(rig, TAGGED, "b", UNTAGGED)+ assert_refusal_row(router_refusal(rig, TAGGED, TENANT_A).call_id, {tenant: deployments[tenant]})+ assert_refusal_row(router_refusal(rig, TAGGED, UNTAGGED).call_id, deployments)+++def test_a_region_restricted_refusal_row_names_only_the_cooled_deployments_in_its_region(rig: Rig) -> None:+ deployments: Final = rig.deployments(REGIONAL)+ european: Final = f"{rig.group(REGIONAL)}-a"+ customer: Final = f"{rig.prefix}-eu-customer"+ with ExitStack() as cleanups:+ rig.gateway.post("/customer/new", {"user_id": customer, "allowed_model_region": "eu"})+ cleanups.callback(rig.gateway.post, "/customer/delete", {"user_ids": [customer]})+ cool_group(rig, REGIONAL)+ assert_refusal_row(router_refusal(rig, REGIONAL, {"user": customer}).call_id, {european: deployments[european]})diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.pyindex d1258e43154..37a985264b7 100644--- a/tests/unit/litellm_core_utils/test_litellm_logging.py+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py@@ -4569,6 +4569,50 @@ def test_get_error_information_falls_back_to_str_when_no_message_attr():assert result["error_class"] == "ValueError"+def test_get_error_information_records_the_cooled_deployments_of_a_router_refusal():+ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup+ from litellm.types.router import RouterRateLimitError+ from litellm.types.utils import CooldownDeploymentInfo++ cooled: Final = (+ CooldownDeploymentInfo(model_id="refused-1", api_base="https://first.example/v1"),+ CooldownDeploymentInfo(model_id="refused-2", api_base=None),+ )+ refusal: Final = RouterRateLimitError(+ model="refused",+ cooldown_time=60,+ enable_pre_call_checks=False,+ cooldown_list=["refused-1", "refused-2", "neighbour-1"],+ model_ids=("refused-1", "refused-2"),+ cooldown_deployments=cooled,+ )++ result: Final = StandardLoggingPayloadSetup.get_error_information(refusal)+ assert (result["error_class"], result["error_code"], result["error_cooldown_deployments"]) == (+ "RouterRateLimitError",+ "429",+ cooled,+ ), result+ provider_429: Final = litellm.RateLimitError("scripted 429", "openai", "gpt-5.4")+ assert StandardLoggingPayloadSetup.get_error_information(provider_429)["error_cooldown_deployments"] is None+++def test_get_error_information_handles_a_router_refusal_subclass_that_skips_its_init():+ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup+ from litellm.types.router import RouterRateLimitError++ class PluginRefusal(RouterRateLimitError):+ def __init__(self, message: str) -> None:+ ValueError.__init__(self, message)++ result: Final = StandardLoggingPayloadSetup.get_error_information(PluginRefusal("plugin refused"))+ assert (result["error_class"], result["error_code"], result["error_cooldown_deployments"]) == (+ "PluginRefusal",+ "429",+ None,+ ), result++# ──────────────────────────────────────────────────────────────────────# Tests for _get_assembled_streaming_response non-streaming early return# ──────────────────────────────────────────────────────────────────────diff --git a/tests/unit/router_utils/test_cooldown_handlers.py b/tests/unit/router_utils/test_cooldown_handlers.pyindex 2376e0f4d0c..0c9d7ab9f85 100644--- a/tests/unit/router_utils/test_cooldown_handlers.py+++ b/tests/unit/router_utils/test_cooldown_handlers.py@@ -1,5 +1,7 @@import asyncio+import copyimport importlib+import itertoolsimport randomimport timefrom collections.abc import Mapping@@ -15,6 +17,7 @@ from litellm import Routerfrom litellm._internal_context import current_service_targetfrom litellm.caching.dual_cache import DualCachefrom litellm.caching.in_memory_cache import InMemoryCache+from litellm.litellm_core_utils.litellm_logging import mask_api_base_credentialsfrom litellm.router_utils.cooldown_cache import CooldownCache, CooldownCacheValuefrom litellm.router_utils.cooldown_callbacks import router_cooldown_event_callbackfrom litellm.router_utils.cooldown_handlers import (@@ -44,8 +47,9 @@ from litellm.types.router import (AllowedFailsPolicy,DeploymentTypedDict,LiteLLMParamsTypedDict,+ RouterRateLimitError,)-from litellm.types.utils import CredentialItem+from litellm.types.utils import CooldownDeploymentInfo, CredentialItemfrom tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome@@ -3004,3 +3008,358 @@ def test_shared_mode_upstream_429_still_cools_down_the_deployment(single_deploymis True)assert _should_run_cooldown_logic(single_deployment_router, "dep-1", 429, exc) is True+++REFUSAL_MESSAGES: Final = [{"role": "user", "content": "cooldown"}]+SECRET_API_BASE: Final = "https://first.example/v1?key=sk-scripted-secret"+FIRST_REFUSED: Final = CooldownDeploymentInfo(model_id="refused-1", api_base=mask_api_base_credentials(SECRET_API_BASE))+SECOND_REFUSED: Final = CooldownDeploymentInfo(model_id="refused-2", api_base=None)+THIRD_REFUSED: Final = CooldownDeploymentInfo(model_id="refused-3", api_base=None)+OTHER_TEAMS_REFUSED: Final = CooldownDeploymentInfo(model_id="refused-team-b", api_base=None)+FIRST_WILDCARD: Final = CooldownDeploymentInfo(model_id="wildcard-1", api_base="https://wildcard.example/v1")+SECOND_WILDCARD: Final = CooldownDeploymentInfo(model_id="wildcard-2", api_base=None)+ALIAS_TARGET: Final = CooldownDeploymentInfo(model_id="tier-1", api_base="https://tier.example/v1")+PROVIDER_MODEL: Final = CooldownDeploymentInfo(model_id="friendly-1", api_base=None)+EVERY_DEPLOYMENT: Final = (+ "refused-1",+ "refused-2",+ "refused-3",+ "refused-team-b",+ "neighbour-1",+ "wildcard-1",+ "wildcard-2",+ "tier-1",+ "friendly-1",+)+++def _cooled_router(routing_strategy: str, cooled: tuple[str, ...]) -> Router:+ router: Final = Router(+ routing_strategy=routing_strategy,+ model_group_alias={"entry": "tier", "tier": "refused"},+ model_list=[+ {+ "model_name": "refused",+ "litellm_params": {"model": "openai/gpt-5.4", "api_base": SECRET_API_BASE, "use_in_pass_through": True},+ "model_info": {"id": "refused-1"},+ },+ {+ "model_name": "refused",+ "litellm_params": {"model": "openai/gpt-5.4", "use_in_pass_through": True, "tpm": 1},+ "model_info": {"id": "refused-2"},+ },+ {+ "model_name": "refused",+ "litellm_params": {"model": "openai/gpt-5.4", "tpm": 1},+ "model_info": {"id": "refused-3"},+ },+ {+ "model_name": "refused",+ "litellm_params": {"model": "openai/gpt-5.4", "use_in_pass_through": True},+ "model_info": {"id": "refused-team-b", "team_id": "team-b"},+ },+ {+ "model_name": "neighbour",+ "litellm_params": {"model": "openai/gpt-5.4", "api_base": "https://neighbour.example/v1"},+ "model_info": {"id": "neighbour-1"},+ },+ {+ "model_name": "openai/*",+ "litellm_params": {"model": "openai/*", "api_base": "https://wildcard.example/v1"},+ "model_info": {"id": "wildcard-1"},+ },+ {+ "model_name": "openai/*",+ "litellm_params": {"model": "openai/*"},+ "model_info": {"id": "wildcard-2"},+ },+ {+ "model_name": "tier",+ "litellm_params": {"model": "openai/gpt-5.4", "api_base": "https://tier.example/v1"},+ "model_info": {"id": "tier-1"},+ },+ {+ "model_name": "friendly",+ "litellm_params": {"model": "anthropic/claude-friendly"},+ "model_info": {"id": "friendly-1"},+ },+ ],+ )+ for model_id in cooled:+ router.cooldown_cache.add_deployment_to_cooldown(+ model_id=model_id,+ original_exception=litellm.RateLimitError("scripted 429", "openai", "gpt-5.4"),+ exception_status=429,+ cooldown_time=60,+ )+ return router+++def _team_request(team_id: str | None) -> dict[str, object]:+ return {"metadata": {"user_api_key_team_id": team_id} if team_id else {}}+++def _select(router: Router, entrypoint: str, model: str, request_kwargs: dict[str, object]) -> object:+ match entrypoint:+ case "async":+ return asyncio.run(+ router.async_get_available_deployment(+ model=model, messages=REFUSAL_MESSAGES, request_kwargs=request_kwargs+ )+ )+ case "async-pass-through":+ return asyncio.run(+ router.async_get_available_deployment_for_pass_through(model=model, request_kwargs=request_kwargs)+ )+ case "pass-through":+ return router.get_available_deployment_for_pass_through(model=model, request_kwargs=request_kwargs)+ case "pass-through-chat":+ return router.get_available_deployment_for_pass_through(+ model=model, messages=REFUSAL_MESSAGES, request_kwargs=request_kwargs+ )+ case _:+ return router.get_available_deployment(+ model=model, messages=REFUSAL_MESSAGES, request_kwargs=request_kwargs+ )+++ALL_COOLED: Final = (FIRST_REFUSED, SECOND_REFUSED, THIRD_REFUSED)+STRATEGY_COOLED: Final = ("refused-1", "refused-team-b", "neighbour-1")+WILDCARD_COOLED: Final = (FIRST_WILDCARD, SECOND_WILDCARD)+++ ("routing_strategy", "cooled", "entrypoint", "model", "team_id", "expected"),+ (+ ("simple-shuffle", EVERY_DEPLOYMENT, "sync", "refused", "team-a", ALL_COOLED),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async", "refused", "team-a", ALL_COOLED),+ ("simple-shuffle", EVERY_DEPLOYMENT, "pass-through", "refused", "team-a", (FIRST_REFUSED, SECOND_REFUSED)),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async-pass-through", "refused", "team-a", ALL_COOLED),+ ("simple-shuffle", EVERY_DEPLOYMENT, "sync", "refused", "team-b", (*ALL_COOLED, OTHER_TEAMS_REFUSED)),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async", "refused", None, ALL_COOLED),+ ("cost-based-routing", STRATEGY_COOLED, "sync", "refused", "team-a", None),+ ("cost-based-routing", STRATEGY_COOLED, "async", "refused", "team-a", None),+ ("cost-based-routing", STRATEGY_COOLED, "pass-through", "refused", "team-a", None),+ ("simple-shuffle", EVERY_DEPLOYMENT, "sync", "openai/gpt-5.4-mini", "team-a", WILDCARD_COOLED),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async", "openai/gpt-5.4-mini", "team-a", WILDCARD_COOLED),+ ("simple-shuffle", EVERY_DEPLOYMENT, "sync", "entry", "team-a", (ALIAS_TARGET,)),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async", "entry", "team-a", (ALIAS_TARGET,)),+ ("simple-shuffle", EVERY_DEPLOYMENT, "sync", "anthropic/claude-friendly", "team-a", (PROVIDER_MODEL,)),+ ("simple-shuffle", EVERY_DEPLOYMENT, "async", "anthropic/claude-friendly", "team-a", (PROVIDER_MODEL,)),+ ),+ ids=(+ "all-cooled-sync",+ "all-cooled-async",+ "all-cooled-pass-through",+ "all-cooled-async-pass-through",+ "all-cooled-owning-team",+ "all-cooled-async-no-team",+ "strategy-refused-sync",+ "strategy-refused-async",+ "strategy-refused-pass-through",+ "wildcard-sync",+ "wildcard-async",+ "alias-chain-sync",+ "alias-chain-async",+ "provider-model-sync",+ "provider-model-async",+ ),+)+def test_no_deployment_error_names_the_cooled_deployments_the_request_could_route_to(+ routing_strategy: str,+ cooled: tuple[str, ...],+ entrypoint: str,+ model: str,+ team_id: str | None,+ expected: tuple[CooldownDeploymentInfo, ...] | None,+) -> None:+ router: Final = _cooled_router(routing_strategy, cooled)+ with pytest.raises(RouterRateLimitError) as refusal:+ _select(router, entrypoint, model, _team_request(team_id))+ assert refusal.value.cooldown_deployments == expected, refusal.value.cooldown_list++[email protected]("entrypoint", ("sync", "async"))+def test_no_deployment_error_names_only_the_cooled_part_of_a_route_emptied_by_other_filters(entrypoint: str) -> None:+ router: Final = _cooled_router("simple-shuffle", STRATEGY_COOLED)+ request_kwargs: Final = {**_team_request("team-a"), "_excluded_deployment_ids": ["refused-2", "refused-3"]}+ with pytest.raises(RouterRateLimitError) as refusal:+ _select(router, entrypoint, "refused", request_kwargs)+ assert refusal.value.cooldown_deployments == (FIRST_REFUSED,), refusal.value.cooldown_list+ assert "sk-scripted-secret" not in repr(refusal.value.cooldown_deployments)+++TENANT_A: Final = CooldownDeploymentInfo(model_id="tenant-a-1", api_base="https://tenant-a.example/v1")+TENANT_B: Final = CooldownDeploymentInfo(model_id="tenant-b-1", api_base="https://tenant-b.example/v1")+SHARED: Final = CooldownDeploymentInfo(model_id="shared-1", api_base="https://shared.example/v1")+EVERY_TENANT: Final = (TENANT_A, TENANT_B, SHARED)+TENANT_ROUTES: Final = ((TENANT_A, "tenant-a", "eu"), (TENANT_B, "tenant-b", "us"), (SHARED, "default", "eu"))+++def _tenant_router(cooled: tuple[CooldownDeploymentInfo, ...], **router_settings: bool) -> Router:+ router: Final = Router(+ model_list=[+ {+ "model_name": "tenants",+ "litellm_params": {+ "model": "openai/gpt-5.4",+ "api_base": deployment["api_base"],+ "tags": [tag],+ "region_name": region,+ "use_in_pass_through": True,+ },+ "model_info": {"id": deployment["model_id"]},+ }+ for deployment, tag, region in TENANT_ROUTES+ ],+ **router_settings,+ )+ for deployment in cooled:+ router.cooldown_cache.add_deployment_to_cooldown(+ model_id=deployment["model_id"],+ original_exception=litellm.RateLimitError("scripted 429", "openai", "gpt-5.4"),+ exception_status=429,+ cooldown_time=60,+ )+ return router+++TAGS_ON: Final = {"enable_tag_filtering": True}+REGION_CHECKS_ON: Final = {"enable_pre_call_checks": True}+BOTH_ON: Final = {**TAGS_ON, **REGION_CHECKS_ON}+++ ("router_settings", "entrypoint", "request_kwargs", "expected"),+ (+ (TAGS_ON, "async", {"metadata": {"tags": ["tenant-a"]}}, (TENANT_A,)),+ (TAGS_ON, "async", {"metadata": {"tags": ["tenant-b"]}}, (TENANT_B,)),+ (TAGS_ON, "async", {"metadata": {}}, EVERY_TENANT),+ (TAGS_ON, "async", {}, EVERY_TENANT),+ (TAGS_ON, "async", {"metadata": "unparsed"}, ()),+ (TAGS_ON, "async", {"litellm_metadata": {"tags": ["tenant-a"]}}, (TENANT_A,)),+ (TAGS_ON, "async", {"metadata": {"tags": ["!tenant-a", "&tenant-b"]}}, (TENANT_B,)),+ (TAGS_ON, "async", {"metadata": {"tags": ["!tenant-a"]}}, (TENANT_B, SHARED)),+ (TAGS_ON, "async", {"metadata": {"tags": ["tenant-z"]}}, (SHARED,)),+ (TAGS_ON, "async-pass-through", {"metadata": {"tags": ["tenant-a"]}}, (TENANT_A,)),+ ({}, "async", {"metadata": {"tags": ["tenant-a"]}, "enable_tag_filtering": True}, (TENANT_A,)),+ ({}, "async", {"metadata": {"tags": ["tenant-a"]}}, EVERY_TENANT),+ (REGION_CHECKS_ON, "async", {"metadata": {}, "allowed_model_region": "eu"}, (TENANT_A, SHARED)),+ (REGION_CHECKS_ON, "sync", {"metadata": {}, "allowed_model_region": "eu"}, (TENANT_A, SHARED)),+ (REGION_CHECKS_ON, "pass-through-chat", {"metadata": {}, "allowed_model_region": "eu"}, (TENANT_A, SHARED)),+ (REGION_CHECKS_ON, "pass-through", {"metadata": {}, "allowed_model_region": "eu"}, EVERY_TENANT),+ ({}, "sync", {"metadata": {}, "allowed_model_region": "eu"}, EVERY_TENANT),+ (REGION_CHECKS_ON, "sync", {"metadata": {}, "allowed_model_region": 1}, ()),+ (+ {**TAGS_ON, **REGION_CHECKS_ON},+ "async",+ {"metadata": {"tags": ["tenant-a"]}, "allowed_model_region": "us"},+ (),+ ),+ ),+ ids=(+ "tag-a",+ "tag-b",+ "untagged-falls-back-past-the-default",+ "no-metadata",+ "metadata-not-a-mapping",+ "tag-litellm-metadata",+ "tag-constraints",+ "tag-exclusion-falls-back-in-tiers",+ "unknown-tag-gets-default",+ "tag-async-pass-through",+ "tag-request-level-switch",+ "tags-off",+ "region-async",+ "region-sync",+ "region-pass-through",+ "region-pass-through-without-input",+ "region-without-pre-call-checks",+ "region-not-a-string",+ "region-and-tag-allow-none",+ ),+)+def test_no_deployment_error_names_only_the_cooled_deployments_tag_and_region_routing_allow(+ router_settings: dict[str, bool],+ entrypoint: str,+ request_kwargs: dict[str, object],+ expected: tuple[CooldownDeploymentInfo, ...],+) -> None:+ router: Final = _tenant_router(EVERY_TENANT, **router_settings)+ with pytest.raises(RouterRateLimitError) as refusal:+ _select(router, entrypoint, "tenants", request_kwargs)+ assert refusal.value.cooldown_deployments == expected, refusal.value.cooldown_list+++def test_naming_tag_routed_deployments_leaves_the_request_metadata_untouched() -> None:+ metadata: Final[dict[str, object]] = {"tags": ["tenant-a"]}+ with pytest.raises(RouterRateLimitError) as refusal:+ _select(_tenant_router(EVERY_TENANT, **TAGS_ON), "async", "tenants", {"metadata": metadata})+ assert refusal.value.cooldown_deployments == (TENANT_A,)+ assert metadata == {"tags": ["tenant-a"]}+++ ("has_request_input", "expected"), ((True, (TENANT_A, SHARED)), (False, EVERY_TENANT)), ids=("chat", "no-input")+)+def test_region_routable_deployments_follow_the_pre_call_region_check(+ has_request_input: bool, expected: tuple[CooldownDeploymentInfo, ...]+) -> None:+ router: Final = _tenant_router((), **REGION_CHECKS_ON)+ kept: Final = router._region_routable_deployments(+ router.get_model_list(model_name="tenants") or [], {"allowed_model_region": "eu"}, has_request_input+ )+ assert router._deployment_ids(kept) == frozenset(deployment["model_id"] for deployment in expected)+++def test_routable_cooled_deployment_ids_skip_healthy_deployments_and_peel_tag_fallbacks() -> None:+ router: Final = _tenant_router((TENANT_A, SHARED), **TAGS_ON)+ routable: Final = asyncio.run(+ router._async_routable_cooled_deployment_ids(+ model="tenants",+ request_deployments=router.get_model_list(model_name="tenants") or [],+ cooldown_deployments=(TENANT_A["model_id"], SHARED["model_id"]),+ request_kwargs={"metadata": {}},+ has_request_input=True,+ )+ )+ assert routable == frozenset((TENANT_A["model_id"], SHARED["model_id"]))+++REACHABILITY_REQUESTS: Final = (+ {"metadata": {"tags": ["tenant-a"]}},+ {"metadata": {}},+ {"metadata": {"tags": ["!tenant-a"]}},+ {"metadata": {"tags": ["tenant-z"]}},+ {"metadata": {"tags": ["!tenant-a", "&tenant-b"]}},+ {"metadata": {}, "allowed_model_region": "eu"},+ {"metadata": {"tags": ["tenant-a"]}, "allowed_model_region": "us"},+)+HEALTH_STATES: Final = tuple(+ itertools.chain.from_iterable(+ itertools.combinations(EVERY_TENANT, size) for size in range(1, len(EVERY_TENANT) + 1)+ )+)+++def _routable_while_up(up: tuple[CooldownDeploymentInfo, ...], request_kwargs: dict[str, object]) -> set[str]:+ router: Final = _tenant_router(tuple(deployment for deployment in EVERY_TENANT if deployment not in up), **BOTH_ON)+ try:+ pool: Final = asyncio.run(+ router.async_get_healthy_deployments(+ model="tenants", request_kwargs=copy.deepcopy(request_kwargs), messages=REFUSAL_MESSAGES+ )+ )+ except ValueError:+ return set()+ return {str(deployment["model_info"]["id"]) for deployment in pool}++[email protected]("request_kwargs", REACHABILITY_REQUESTS)+def test_the_refusal_names_each_cooled_deployment_some_cooldown_state_routes_the_request_to(+ request_kwargs: dict[str, object],+) -> None:+ reachable: Final = set().union(*(_routable_while_up(up, request_kwargs) for up in HEALTH_STATES))+ with pytest.raises(RouterRateLimitError) as refusal:+ _select(_tenant_router(EVERY_TENANT, **BOTH_ON), "async", "tenants", copy.deepcopy(request_kwargs))+ assert {deployment["model_id"] for deployment in refusal.value.cooldown_deployments or ()} == reachable