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
chore: merge litellm_internal_staging into litellm_e2e_reliability_module_cells
mateo-berri036a380fa0de
diff --cc tests/e2e/batches/conftest.pyindex 73e8918e2ee,91a365b6b92..82828655e09--- a/tests/e2e/batches/conftest.py+++ b/tests/e2e/batches/conftest.py@@@ -12,13 -12,16 +12,14 @@@ the proxy configfrom __future__ import annotations- from typing import Iterator-import os+ from typing import Final, Iteratorimport pytestfrom batch_client import BatchClient, build_clientfrom capabilities import PROVIDERS-from e2e_config import MANAGED_FILES_OPT_IN_ENVfrom e2e_http import NoBody+ from lifecycle import ResourceManagerfrom proxy_client import ProxyClientdiff --cc tests/e2e/conftest.pyindex 4442a3bd56a,36569896125..b1a75d5f862--- a/tests/e2e/conftest.py+++ b/tests/e2e/conftest.py@@@ -22,36 -21,48 +22,68 @@@ from typing import Finaimport pytestimport requests-from e2e_config import CONTROL_PLANE_BASE_URL, FIXTURE_DIR, FIXTURE_MODE_RAW, PROXY_BASE_URL, unique_marker++from e2e_config import (+ CONTROL_PLANE_BASE_URL,+ FIXTURE_DIR,+ FIXTURE_MODE_RAW,+ MANAGED_FILES_OPT_IN_ENV,+ PROMPT_CACHING_OPT_IN_ENV,+ PROXY_BASE_URL,++ REDIS_CHAOS_OPT_IN_ENV,+ WEEKLY_ANOMALY_OPT_IN_ENV,++ unique_marker,+)from e2e_db import RESET_OPT_IN_ENV, reset_spend_logs, run_spend_log_cleanup+ from e2e_http import unwrapfrom fixture_mode import fixture_mode_collection_error, fixture_report_lines- from provider_edge import replay_leftover_error+ from idp import Identity, Keycloak, keycloak_from_envfrom junit_properties import attach_result_propertiesfrom lifecycle import ProxyClientProvider, ResourceManager+ from models import TeamNewBody, UserNewBody, UserNewResponse+ from provider_edge import replay_leftover_errorfrom proxy_client import ProxyClient, build_proxy_client-_E2E_TEST_RAN = pytest.StashKey[bool]()_CALL_PASSED = pytest.StashKey[bool]()+OPT_IN_MARKERS: Final = MappingProxyType(+ {+ "weekly": WEEKLY_ANOMALY_OPT_IN_ENV,+ "managed_files": MANAGED_FILES_OPT_IN_ENV,+ "prompt_caching_stack": PROMPT_CACHING_OPT_IN_ENV,++ "redis_chaos": REDIS_CHAOS_OPT_IN_ENV,+ }+)++ @pytest.fixture(scope="session")+ def idp() -> Keycloak:+ return keycloak_from_env()+++ @pytest.fixture+ def jwt_identity(idp: Keycloak, resources: ResourceManager, proxy: ProxyClient) -> Identity:+ marker: Final = unique_marker()+ identity: Final = idp.provision(marker=marker, group=f"e2e-jwt-team-{marker}", defer=resources.defer)+ resources.defer(lambda: proxy.delete_user(identity.user_id))+ # Seed the canonical user before any JWT call populates the auth cache.+ # Group claims grant team access; management membership is added by the test.+ unwrap(+ proxy.transport.post(+ "/user/new",+ headers=proxy.transport.master,+ json=UserNewBody(+ user_id=identity.user_id, user_email=f"{identity.username}@example.com", user_role="internal_user"+ ),+ response_type=UserNewResponse,+ )+ )+ team_id: Final = proxy.create_team(TeamNewBody(team_alias=f"e2e-jwt-{marker}", team_id=identity.group))+ resources.defer(lambda: proxy.delete_team(team_id))+ return identity++def pytest_configure(config: pytest.Config) -> None:config.addinivalue_line("markers",@@@ -78,11 -89,11 +110,16 @@@"markers","managed_files: needs a proxy running with require_managed_files enabled; deselected unless E2E_MANAGED_FILES_STACK is set",)+ config.addinivalue_line(+ "markers",+ "prompt_caching_stack: needs a proxy running with router_settings.optional_pre_call_checks including "+ "prompt_caching; deselected unless E2E_PROMPT_CACHING_STACK is set",+ )+ config.addinivalue_line(+ "markers",+ "redis_chaos: load test that pauses the proxy's Redis outright mid-run; needs a proxy booted from "+ "gateway/redis_chaos_ci_config.yml on the same host, and is deselected unless E2E_REDIS_CHAOS is set",+ )def pytest_sessionstart(session: pytest.Session) -> None:diff --cc tests/e2e/coverage_registry/reliability.yamlindex ff0a786e325,e95d27bab84..65354100f58--- a/tests/e2e/coverage_registry/reliability.yaml+++ b/tests/e2e/coverage_registry/reliability.yaml@@@ -1,22 -1,22 +1,22 @@@# Reliability & Performance (behavior features). Grounded in litellm/router.py + router_strategy/ + router_utils/.-- {id: reliability.fallback.5xx.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: "5xx", assertions: [routes_to_fallback], exercised_on: [chat_completions, messages], source: "litellm/router.py:2024", rationale: "Reroute on provider 5xx to alternate deployment"}-- {id: reliability.fallback.context_window.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: context_window, assertions: [routes_to_fallback], exercised_on: [chat_completions, messages], source: "litellm/router.py:6108", rationale: "Fallback when model exceeds context limit"}-- {id: reliability.fallback.content_policy.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: content_policy, assertions: [routes_to_fallback], exercised_on: [chat_completions, messages], source: "litellm/router.py:6023", rationale: "Reroute on content-policy violation"}-- {id: reliability.fallback.timeout.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: "timeout", assertions: [routes_to_fallback], exercised_on: [chat_completions, messages], source: "litellm/router.py:2766", rationale: "Fallback on request timeout"}-- {id: reliability.retry.5xx.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: "5xx", assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "litellm/router.py:6414", rationale: "Transient 5xx often succeeds on retry"}-- {id: reliability.retry.timeout.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: timeout, assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "get_retry_from_policy.py:44", rationale: "Timeout retried per policy"}-- {id: reliability.retry.429.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: "429", assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "get_retry_from_policy.py:46", rationale: "429 retried per RateLimitErrorRetries policy"}-- {id: reliability.retry.auth.succeeds_within_retries, module: reliability, tier: P1, behavior: retry, variant: auth, assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "get_retry_from_policy.py:42", rationale: "Transient auth glitch retry"}-- {id: reliability.retry.context_window.succeeds_within_retries, module: reliability, tier: P1, behavior: retry, variant: context_window, assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "get_retry_from_policy.py:51", fail_before_fix: proven, rationale: "A context-window 400 under BadRequestErrorRetries retries onto a sibling deployment in the same model group, instead of coming straight back as the 400 the deployment that just refused it returned"}-- {id: reliability.cooldown.5xx.trips_then_recovers, module: reliability, tier: P0, behavior: cooldown, variant: "5xx", assertions: [trips_then_recovers], exercised_on: [chat_completions, messages], source: "cooldown_handlers.py:40", rationale: "Deployment cools after repeated 5xx, recovers after cooldown_time"}-- {id: reliability.cooldown.429.trips_then_recovers, module: reliability, tier: P0, behavior: cooldown, variant: "429", assertions: [trips_then_recovers], exercised_on: [chat_completions, messages], source: "cooldown_handlers.py:69", rationale: "Cools on 429, avoids hammering exhausted provider"}-- {id: reliability.cooldown.auth.trips_then_recovers, module: reliability, tier: P1, behavior: cooldown, variant: auth, assertions: [trips_then_recovers], exercised_on: [chat_completions, messages], source: "cooldown_handlers.py:74", rationale: "Cools on 401 auth error"}-- {id: reliability.cooldown.timeout.trips_then_recovers, module: reliability, tier: P1, behavior: cooldown, variant: timeout, assertions: [trips_then_recovers], exercised_on: [chat_completions, messages], source: "cooldown_handlers.py:77", rationale: "Cools on 408 timeout"}-- {id: reliability.routing.simple_shuffle.picks_healthy_deployment, module: reliability, tier: P1, behavior: routing, variant: simple_shuffle, assertions: [picks_healthy_deployment], exercised_on: [chat_completions, messages], source: "router_strategy/simple_shuffle.py", rationale: "Baseline weighted/uniform pick"}-- {id: reliability.routing.latency_based.picks_lowest_latency, module: reliability, tier: P1, behavior: routing, variant: latency_based, assertions: [picks_lowest_latency], exercised_on: [chat_completions, messages], source: "router_strategy/lowest_latency.py", rationale: "Routes to lowest-latency deployment"}-- {id: reliability.routing.cost_based.picks_lowest_cost, module: reliability, tier: P1, behavior: routing, variant: cost_based, assertions: [picks_lowest_cost], exercised_on: [chat_completions, messages], source: "router_strategy/lowest_cost.py", rationale: "Spend-aware routing"}-- {id: reliability.routing.usage_based.picks_under_tpm, module: reliability, tier: P0, behavior: routing, variant: usage_based, assertions: [picks_under_tpm], exercised_on: [chat_completions, messages], source: "router_strategy/lowest_tpm_rpm_v2.py", rationale: "Routes to lowest-TPM deployment; prevents over-allocation"}-- {id: reliability.routing.least_busy.picks_lowest_traffic, module: reliability, tier: P1, behavior: routing, variant: least_busy, assertions: [picks_lowest_traffic], exercised_on: [chat_completions, messages], source: "router_strategy/least_busy.py", rationale: "Fewest in-flight requests"}+- {id: reliability.fallback.5xx.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: "5xx", assertions: [routes_to_fallback], exercised_on: [chat_completions], source: "litellm/router.py:2024", rationale: "Reroute on provider 5xx to alternate deployment"}+- {id: reliability.fallback.context_window.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: context_window, assertions: [routes_to_fallback], exercised_on: [chat_completions], source: "litellm/router.py:6108", rationale: "Fallback when model exceeds context limit"}+- {id: reliability.fallback.content_policy.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: content_policy, assertions: [routes_to_fallback], exercised_on: [chat_completions], source: "litellm/router.py:6023", rationale: "Reroute on content-policy violation"}+- {id: reliability.fallback.timeout.routes_to_fallback, module: reliability, tier: P0, behavior: fallback, variant: "timeout", assertions: [routes_to_fallback], exercised_on: [chat_completions], source: "litellm/router.py:2766", rationale: "Fallback on request timeout"}+- {id: reliability.retry.5xx.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: "5xx", assertions: [succeeds_within_retries], exercised_on: [chat_completions], source: "litellm/router.py:6414", rationale: "Transient 5xx often succeeds on retry"}+- {id: reliability.retry.timeout.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: timeout, assertions: [succeeds_within_retries], exercised_on: [chat_completions], source: "get_retry_from_policy.py:44", rationale: "Timeout retried per policy"}+- {id: reliability.retry.429.succeeds_within_retries, module: reliability, tier: P0, behavior: retry, variant: "429", assertions: [succeeds_within_retries], exercised_on: [chat_completions], source: "get_retry_from_policy.py:46", rationale: "429 retried per RateLimitErrorRetries policy"}+- {id: reliability.retry.auth.succeeds_within_retries, module: reliability, tier: P1, behavior: retry, variant: auth, assertions: [succeeds_within_retries], exercised_on: [chat_completions], source: "get_retry_from_policy.py:42", rationale: "Transient auth glitch retry"}- - {id: reliability.retry.context_window.succeeds_within_retries, module: reliability, tier: P1, behavior: retry, variant: context_window, assertions: [succeeds_within_retries], exercised_on: [chat_completions, messages], source: "get_retry_from_policy.py:51", rationale: "Multi-attempt on context error"}++- {id: reliability.retry.context_window.succeeds_within_retries, module: reliability, tier: P1, behavior: retry, variant: context_window, assertions: [succeeds_within_retries], exercised_on: [chat_completions], source: "get_retry_from_policy.py:51", fail_before_fix: proven, rationale: "A context-window 400 under BadRequestErrorRetries retries onto a sibling deployment in the same model group, instead of coming straight back as the 400 the deployment that just refused it returned"}+- {id: reliability.cooldown.5xx.trips_then_recovers, module: reliability, tier: P0, behavior: cooldown, variant: "5xx", assertions: [trips_then_recovers], exercised_on: [chat_completions], source: "cooldown_handlers.py:40", rationale: "Deployment cools after repeated 5xx, recovers after cooldown_time"}+- {id: reliability.cooldown.429.trips_then_recovers, module: reliability, tier: P0, behavior: cooldown, variant: "429", assertions: [trips_then_recovers], exercised_on: [chat_completions], source: "cooldown_handlers.py:69", rationale: "Cools on 429, avoids hammering exhausted provider"}+- {id: reliability.cooldown.auth.trips_then_recovers, module: reliability, tier: P1, behavior: cooldown, variant: auth, assertions: [trips_then_recovers], exercised_on: [chat_completions], source: "cooldown_handlers.py:74", rationale: "Cools on 401 auth error"}+- {id: reliability.cooldown.timeout.trips_then_recovers, module: reliability, tier: P1, behavior: cooldown, variant: timeout, assertions: [trips_then_recovers], exercised_on: [chat_completions], source: "cooldown_handlers.py:77", rationale: "Cools on 408 timeout"}+- {id: reliability.routing.simple_shuffle.picks_healthy_deployment, module: reliability, tier: P1, behavior: routing, variant: simple_shuffle, assertions: [picks_healthy_deployment], exercised_on: [chat_completions], source: "router_strategy/simple_shuffle.py", rationale: "Baseline weighted/uniform pick"}+- {id: reliability.routing.latency_based.picks_lowest_latency, module: reliability, tier: P1, behavior: routing, variant: latency_based, assertions: [picks_lowest_latency], exercised_on: [chat_completions], source: "router_strategy/lowest_latency.py", rationale: "Routes to lowest-latency deployment"}+- {id: reliability.routing.cost_based.picks_lowest_cost, module: reliability, tier: P1, behavior: routing, variant: cost_based, assertions: [picks_lowest_cost], exercised_on: [chat_completions], source: "router_strategy/lowest_cost.py", rationale: "Spend-aware routing"}+- {id: reliability.routing.usage_based.picks_under_tpm, module: reliability, tier: P0, behavior: routing, variant: usage_based, assertions: [picks_under_tpm], exercised_on: [chat_completions], source: "router_strategy/lowest_tpm_rpm_v2.py", rationale: "Routes to lowest-TPM deployment; prevents over-allocation"}+- {id: reliability.routing.least_busy.picks_lowest_traffic, module: reliability, tier: P1, behavior: routing, variant: least_busy, assertions: [picks_lowest_traffic], exercised_on: [chat_completions], source: "router_strategy/least_busy.py", rationale: "Fewest in-flight requests"}- {id: reliability.routing.complexity_llm_classifier.routes_by_llm_tier, module: reliability, tier: P1, behavior: routing, variant: complexity_llm_classifier, assertions: [routes_by_llm_tier], exercised_on: [chat_completions], source: "router_strategy/complexity_router/complexity_router.py", fail_before_fix: proven, rationale: "v2 auto-router LLM complexity classifier runs over the proxy and routes by semantic tier instead of silently crashing on absent litellm_metadata and falling back to heuristic scoring"}- {id: reliability.routing.tagged_marker.request_tag_selects_marker, module: reliability, tier: P0, behavior: routing, variant: tagged_marker, assertions: [request_tag_selects_marker], exercised_on: [chat_completions], source: "litellm/router.py:11445", rationale: "Tagged request selects the tagged strategy marker under a shared model_name instead of the plain deployment registered first (GitHub issue #36619)"}- {id: reliability.routing.tagged_marker.untagged_request_served_by_plain_deployment, module: reliability, tier: P0, behavior: routing, variant: tagged_marker, assertions: [untagged_request_served_by_plain_deployment], exercised_on: [chat_completions, messages, responses], source: "litellm/router.py:11445", rationale: "Untagged requests to a shared model_name are served by the plain deployment on every call, never captured or errored by the tagged marker (GitHub issue #36620)"}@@@ -29,8 -29,9 +29,9 @@@- {id: reliability.routing.strategy_alias.custom_pricing_ignored, module: reliability, tier: P1, behavior: routing, variant: strategy_alias, assertions: [custom_pricing_ignored], exercised_on: [chat_completions], source: "litellm/router.py:11489", rationale: "Custom pricing on a strategy-router alias never prices the routed request; spend logs at the routed tier deployment's own rate (GitHub PR #36691)"}- {id: reliability.routing.complexity_heuristic.scores_current_ask_only, module: reliability, tier: P1, behavior: routing, variant: complexity_heuristic, assertions: [scores_current_ask_only], exercised_on: [chat_completions], source: "router_strategy/complexity_router/complexity_router.py:942", rationale: "The heuristic complexity classifier scores the caller's current ask only, so a keyword-heavy agent system prompt cannot inflate the tier (GitHub PR #36721)"}- {id: reliability.cache.exact.returns_cached, module: reliability, tier: P1, behavior: cache, variant: exact, assertions: [returns_cached], exercised_on: [chat_completions, messages, embeddings], source: "litellm/caching/caching.py", rationale: "Response cache returns cached on exact match"}-- {id: reliability.cache.prompt_caching_model_select.returns_cached, module: reliability, tier: P1, behavior: cache, variant: prompt_caching_model_select, assertions: [returns_cached], exercised_on: [chat_completions], source: "router_utils/prompt_caching_cache.py", rationale: "Selects model supporting prompt caching for cacheable prefix"}+- {id: reliability.cache.prompt_caching_model_select.returns_cached, module: reliability, tier: P1, behavior: cache, variant: prompt_caching_model_select, assertions: [returns_cached], exercised_on: [chat_completions], source: "router_utils/prompt_caching_cache.py", rationale: "Selects model supporting prompt caching for cacheable prefix; runs only on a stack with the prompt_caching pre-call check enabled (E2E_PROMPT_CACHING_STACK)"}- {id: reliability.circuit_breaker.redis.trips_then_recovers, module: reliability, tier: P0, behavior: circuit_breaker, variant: redis, assertions: [trips_then_recovers], exercised_on: [chat_completions, messages, embeddings], source: "litellm/caching/redis_cache.py:99", rationale: "Redis breaker CLOSED->OPEN->HALF_OPEN; guards all cache/rate-limit ops"}+ - {id: reliability.circuit_breaker.redis_timeout.stays_responsive, module: reliability, tier: P1, behavior: circuit_breaker, variant: redis_timeout, assertions: [stays_responsive], exercised_on: [chat_completions, messages], source: "litellm/proxy/hooks/proxy_track_cost_callback.py:386", fail_before_fix: proven, rationale: "Under locust load split round robin over /chat/completions and /v1/messages with every request retrying through failing mock deployments, holding Redis in CLIENT PAUSE ALL for the phase trips the breaker and every request still succeeds, with latency, RSS, and CPU reported as p50/p90/p99 against the pre-pause baseline; on v1.100.0 the failed-tracking alert body doubled per request until the worker OOMed (LIT-6780)"}- {id: reliability.timeout.request_timeout.exceeds_deadline, module: reliability, tier: P1, behavior: timeout, variant: request_timeout, assertions: [exceeds_deadline], exercised_on: [chat_completions, messages], source: "litellm/router.py:545-551", rationale: "Per-request timeout raises Timeout"}- {id: reliability.timeout.stream_timeout.exceeds_deadline, module: reliability, tier: P1, behavior: timeout, variant: stream_timeout, assertions: [exceeds_deadline], exercised_on: [chat_completions], source: "litellm/router.py:551", rationale: "Streaming chunk-delivery timeout"}- {id: reliability.perf.throughput.under_slo, module: reliability, tier: P1, behavior: perf, variant: throughput, assertions: [under_slo], exercised_on: [chat_completions, messages], source: grammar, rationale: "Throughput SLO under load"}diff --cc tests/e2e/e2e_config.pyindex 629ad927d42,e15a0cd0f8f..896cb3e7efe--- a/tests/e2e/e2e_config.py+++ b/tests/e2e/e2e_config.py@@@ -134,7 -143,7 +143,8 @@@ LOAD_MIN_CONCURRENCY_EFFICIENCY = floatWEEKLY_ANOMALY_OPT_IN_ENV = "E2E_WEEKLY_ANOMALY"MANAGED_FILES_OPT_IN_ENV = "E2E_MANAGED_FILES_STACK"+PROMPT_CACHING_OPT_IN_ENV = "E2E_PROMPT_CACHING_STACK"+ REDIS_CHAOS_OPT_IN_ENV = "E2E_REDIS_CHAOS"ANOMALY_SESSIONS = int(os.environ.get("E2E_ANOMALY_SESSIONS", "6"))ANOMALY_TURNS_PER_SESSION = int(os.environ.get("E2E_ANOMALY_TURNS_PER_SESSION", "6"))ANOMALY_TURN_ATTEMPTS = int(os.environ.get("E2E_ANOMALY_TURN_ATTEMPTS", "3"))diff --cc tests/e2e/e2e_http.pyindex 6ab3b75c6c3,ce069720c6e..dfb23866783--- a/tests/e2e/e2e_http.py+++ b/tests/e2e/e2e_http.py@@@ -229,9 -271,14 +262,15 @@@ def assert_auth_denied(result: Streaminf"{context}: expected 401/403, got {result.status_code}: {result.body[:300]}")+- def _headers(headers: BaseModel) -> dict[str, str]:- dumped: dict[str, object] = headers.model_dump(by_alias=True, exclude_none=True)+ def wire_body(json: BaseModel) -> dict[str, object]:+ if isinstance(json, PartialBody):+ return json.model_dump(by_alias=True, exclude_unset=True)+ return json.model_dump(by_alias=True, exclude_none=True)+++ def _flat(model: BaseModel) -> dict[str, str]:+ dumped: dict[str, object] = model.model_dump(by_alias=True, exclude_none=True)return {key: str(value) for key, value in dumped.items()}@@@ -427,10 -551,12 +543,10 @@@ def put[R: BaseModel])except requests.RequestException as exc:return NetworkError(message=str(exc))- return _classify(resp, response_type)+ return classify(resp, response_type)-def probe(- url: URL, *, headers: BaseModel, params: BaseModel, timeout: float = 30.0-) -> ProbeResult:+def probe(url: URL, *, headers: BaseModel, params: BaseModel, timeout: float = 30.0) -> ProbeResult:try:resp = request_with_retry(lambda: requests.get(@@@ -532,10 -662,12 +652,10 @@@ def send)except requests.RequestException as exc:return StreamingResponse(status_code=-1, body=str(exc))- return _streaming_outcome(resp, stream)+ return streaming_outcome(resp, stream, sent_at=sent_at)-def stream(- url: URL, *, headers: BaseModel, json: BaseModel, timeout: float = 60.0-) -> StreamingResponse:+def stream(url: URL, *, headers: BaseModel, json: BaseModel, timeout: float = 60.0) -> StreamingResponse:"""Streaming (SSE) call: consumes the stream counting events, and captures thex-litellm-call-id + content-type headers. Body is elided."""return send(url, headers=headers, json=json, stream=True, timeout=timeout)diff --cc tests/e2e/models.pyindex c4c02470fe5,3cab0334dea..639ac805bea--- a/tests/e2e/models.py+++ b/tests/e2e/models.py@@@ -289,7 -316,7 +327,8 @@@ class RouterSettingsOverride(BaseModel)context_window_fallbacks: list[dict[str, list[str]]] | None = Nonecontent_policy_fallbacks: list[dict[str, list[str]]] | None = Nonenum_retries: int | None = None+ routing_strategy: RoutingStrategy | None = None+ model_group_retry_policy: dict[str, dict[str, int]] | None = Noneenable_tag_filtering: bool | None = None@@@ -834,13 -935,12 +966,14 @@@ class LiteLLMParamsBody(BaseModel)auto_router_default_model: str | None = Noneauto_router_embedding_model: str | None = Nonetags: list[str] | None = None- mock_response: str | None = None+ mock_response: str | list[float] | None = Nonetimeout: float | None = None+ max_retries: int | None = None+ cooldown_time: float | None = None+ extra_body: DeploymentExtraBody | None = Nonetpm: int | None = Noneweight: int | None = None- cooldown_time: float | None = None+ order: int | None = NoneModelMode = Literal["batch", "realtime", "image_generation"]diff --cc tests/e2e/pytest.iniindex 5ea630459fa,774d9644497..1fdd3bd28ad--- a/tests/e2e/pytest.ini+++ b/tests/e2e/pytest.ini@@@ -9,4 -9,4 +9,5 @@@ markersload: heavy throughput/load test; collected last so it never perturbs latency-sensitive suitesweekly: real-provider anomaly load test that spends real money; deselected unless E2E_WEEKLY_ANOMALY is setmanaged_files: needs a proxy running with require_managed_files enabled; deselected unless E2E_MANAGED_FILES_STACK is set+ prompt_caching_stack: needs a proxy running with router_settings.optional_pre_call_checks including prompt_caching; deselected unless E2E_PROMPT_CACHING_STACK is set+ redis_chaos: load test that pauses the proxy's Redis outright mid-run; needs a proxy booted from gateway/redis_chaos_ci_config.yml on the same host, and is deselected unless E2E_REDIS_CHAOS is setdiff --cc tests/e2e/router/reliability_support.pyindex 50c35b46660,df2ff03aa4a..976c05ffceb--- a/tests/e2e/router/reliability_support.py+++ b/tests/e2e/router/reliability_support.py@@@ -133,83 -82,25 +140,98 @@@ def _register_benched_on_first_failure)+def create_always_timing_out_deployment(proxy: ProxyClient, name: str, cooldown_time: float | None = None) -> str:+ """A 1ms deadline the real backend always exceeds, benched on its first Timeout."""+ return _register_benched_on_first_failure(+ proxy,+ name,+ LiteLLMParamsBody(model=REAL_MODEL, api_key=REAL_KEY, timeout=0.001, weight=1, cooldown_time=cooldown_time),+ "TimeoutErrorAllowedFails",+ )+++def create_always_unauthorized_deployment(proxy: ProxyClient, name: str, cooldown_time: float | None = None) -> str:+ """A key the real backend rejects with a 401, benched on its first AuthenticationError."""+ return _register_benched_on_first_failure(+ proxy,+ name,+ LiteLLMParamsBody(+ model=REAL_MODEL, api_key="sk-not-a-real-key", max_retries=0, weight=1, cooldown_time=cooldown_time+ ),+ "AuthenticationErrorAllowedFails",+ )+++def _nested_proxy_params(upstream_group: str, upstream_key: str, cooldown_time: float | None) -> LiteLLMParamsBody:+ """A deployment whose upstream is this same proxy serving `upstream_group` with+ `upstream_key`: whatever that group answers (a 500 from an unreachable base, a+ 429 from a key out of rpm) arrives as a real provider status, with the inner+ proxy's and the client's own retries off so it arrives at once."""+ return LiteLLMParamsBody(+ model=f"openai/{upstream_group}",+ api_key=upstream_key,+ api_base=f"{PROXY_BASE_URL}/v1",+ max_retries=0,+ extra_body=DeploymentExtraBody(router_settings_override=RouterSettingsOverride(num_retries=0)),+ weight=1,+ cooldown_time=cooldown_time,+ )+++def create_always_5xx_deployment(+ proxy: ProxyClient, name: str, upstream_group: str, upstream_key: str, cooldown_time: float | None = None+) -> str:+ """Fronts an upstream group that cannot answer, so every call is a real 500,+ benched on its first InternalServerError."""+ return _register_benched_on_first_failure(+ proxy,+ name,+ _nested_proxy_params(upstream_group, upstream_key, cooldown_time),+ "InternalServerErrorAllowedFails",+ )+++def create_always_rate_limited_deployment(+ proxy: ProxyClient, name: str, upstream_group: str, upstream_key: str, cooldown_time: float | None = None+) -> str:+ """Fronts a healthy upstream group with a key that is out of rpm, so every call+ is a real 429, benched on its first RateLimitError."""+ return _register_benched_on_first_failure(+ proxy, name, _nested_proxy_params(upstream_group, upstream_key, cooldown_time), "RateLimitErrorAllowedFails"+ )+++def spend_only_request_of(proxy: ProxyClient, spent_key: str) -> None:+ """Uses up the one request an rpm_limit=1 key allows. The proxy's rate limiter+ opens the key's 60s window on this call, so it goes right before the calls that+ need the 429 and after the registrations, whose propagation waits could+ otherwise eat the window."""+ primed = chat_override(proxy, spent_key, CHEAP_OPENAI_MODEL, f"say hi {unique_marker()}")+ assert primed.status_code == 200, (+ f"the one request the rpm-limited key allows should have succeeded, got {primed.status_code}: "+ f"{primed.body[:300]}"+ )+++ def create_always_picked_small_context_deployment(proxy: ProxyClient, name: str) -> str:+ """The always-picked half of a retry pair on the smallest-context model OpenAI+ still serves: it holds all of the model group's shuffle weight, so an oversized+ prompt opens on it and earns a real context-window refusal, which never benches+ a deployment, so only the retry itself can steer the request off it."""+ return proxy.register_model(+ ModelNewBody(+ model_name=name,+ litellm_params=LiteLLMParamsBody(model=SMALL_CONTEXT_MODEL, api_key=REAL_KEY, weight=1),+ model_info=ModelInfoBody(),+ )+ )++def create_zero_weight_backup_deployment(proxy: ProxyClient, name: str) -> str:- """The other half of a failing pair: healthy, but weight 0, so the weighted shuffle- never opens on it. It is reachable only once its sibling is benched and the- weighted pick falls through to a uniform one over what is left."""+ """The other half of a retry pair: healthy, but weight 0, so the weighted shuffle+ never opens on it. It is reachable only once its sibling is out of the running,+ benched by a cooldown or skipped by the retry, and the weighted pick falls through+ to a uniform one over what is left."""return proxy.register_model(ModelNewBody(model_name=name,@@@ -246,49 -137,6 +268,56 @@@ def chat_turns_override)+def chat_override(+ proxy: ProxyClient,+ key: str,+ model: str,+ content: str,+ override: RouterSettingsOverride | None = None,+ stream: bool = False,+ cache: dict[str, bool] | None = {"no-cache": True},++ history: Sequence[ChatMessage] = (),+) -> StreamingResponse:+ """`chat_turns_override` for the single user turn most reliability tests send."""+ return chat_turns_override(- proxy, key, model, [ChatMessage(role="user", content=content)], override=override, stream=stream, cache=cache++ proxy,++ key,++ model,++ [*history, ChatMessage(role="user", content=content)],++ override=override,++ stream=stream,++ cache=cache,+ )+++def open_chat_stream(+ proxy: ProxyClient,+ key: str,+ model: str,+ content: str,+ override: RouterSettingsOverride | None = None,+ max_tokens: int = 512,+) -> StreamHead | NetworkError:+ """Open a streaming /chat/completions and return as soon as its head arrives, so+ the request stays in flight (its body unread) while the test sends others."""+ return proxy.transport.open_stream(+ "/chat/completions",+ headers=proxy.transport.bearer(key),+ json=ReliabilityChatBody(+ model=model,+ messages=[ChatMessage(role="user", content=content)],+ max_tokens=max_tokens,+ stream=True,+ router_settings_override=override,+ ),+ )+++def model_id_of(resp: StreamingResponse) -> str | None:+ """The deployment the proxy served this response from, as it reports it."""+ return resp.headers.get("x-litellm-model-id")++def _parsed(resp: StreamingResponse) -> ChatResponse | None:try:return ChatResponse.model_validate_json(resp.body)diff --cc tests/e2e/router/test_reliability_retries_e2e.pyindex b8eba4d3d62,da45cb46a46..a90efa52b5f--- a/tests/e2e/router/test_reliability_retries_e2e.py+++ b/tests/e2e/router/test_reliability_retries_e2e.py@@@ -1,25 -1,17 +1,26 @@@"""Live e2e: a request that fails on its first deployment is retried inside its ownmodel group and still comes back a completion.-Each model group is a pair: a deployment that always refuses and holds all of the-group's shuffle weight, plus a healthy backup at weight 0. The weighted pick always-opens on the refusing one, so the customer sees a completion only if the retry-lands on the backup, and the proxy reports that it took a retry to get there, with-no random first pick in the middle of it.--The timeout pair relies on cooldown: the first Timeout benches the timing-out-deployment (an `allowed_fails_policy` of `TimeoutErrorAllowedFails: 0`) and the-retry falls through to the only deployment left. The context-window pair cannot:-a 400 never benches a deployment, so the retry policy's `BadRequestErrorRetries`-has to steer the retry off the deployment that just refused the prompt.+Every model group is a pair: a deployment that always fails in one specific way+and holds all of the group's shuffle weight, and a healthy backup at weight 0.- The weighted pick always opens on the failing one, its first failure benches it- (an `allowed_fails_policy` of zero for that error class), and the retry falls- through to the only deployment left. So the customer sees a completion and the- proxy reports that it took a retry to get there, with no random first pick in- the middle of it.++The weighted pick always opens on the failing one, so the customer sees a++completion only if the retry lands on the backup, and the proxy reports that it++took a retry to get there, with no random first pick in the middle of it.++The failures are real. A timeout is a 1ms deadline on the real backend and a 401+is a bogus key on it. A 500 and a 429 come from this same proxy standing in as+the upstream: the failing deployment fronts a group of this proxy whose only+deployment is unreachable (a real 500), or a healthy group called with a key that+has already spent its one request per minute (a real 429), so the router sees the- same statuses a customer's provider would send.-- The context-window retry cell has no test on purpose: the router refuses to- retry a 400-class error, and a context-window refusal is one, so the documented- `ContextWindowExceededErrorRetries` policy never fires. That row stays uncovered- until the product either retries it or drops it from the docs.++same statuses a customer's provider would send. A context-window refusal is an++oversized prompt on the smallest-context model OpenAI still serves.++++The timeout, 5xx, 429, and auth pairs rely on cooldown: the first failure benches++the failing deployment (an `allowed_fails_policy` of zero for that error class)++and the retry falls through to the only deployment left. The context-window pair++cannot: a 400 never benches a deployment, so the retry policy's++`BadRequestErrorRetries` has to steer the retry off the deployment that just++refused the prompt."""from __future__ import annotations@@@ -35,14 -27,11 +36,16 @@@ from reliability_support importchat_override,completion_tokens_of,content_of,+ create_always_5xx_deployment,+ create_always_picked_small_context_deployment,+ create_always_rate_limited_deployment,create_always_timing_out_deployment,+ create_always_unauthorized_deployment,+ create_bad_base_deployment,create_zero_weight_backup_deployment,finish_reason_of,+ oversized_prompt,+ spend_only_request_of,)pytestmark = pytest.mark.e2e@@@ -90,50 -73,35 +93,73 @@@ class TestReliabilityRetriesbackup = create_zero_weight_backup_deployment(client.proxy, group)resources.defer(lambda: client.proxy.delete_model(backup))- resp = chat_override(- client.proxy,- scoped_key,- group,- f"say hi {unique_marker()}",- override=RouterSettingsOverride(num_retries=2),+ _assert_served_after_retry(_retry_once(client, scoped_key, group))++ @pytest.mark.covers("reliability.retry.5xx.succeeds_within_retries")+ def test_5xx_on_first_deployment_succeeds_on_retry(+ self, client: ComplexityRouterClient, resources: ResourceManager, scoped_key: str+ ) -> None:+ upstream = f"reliability-5xx-upstream-{unique_marker()}"+ upstream_id = create_bad_base_deployment(client.proxy, upstream)+ resources.defer(lambda: client.proxy.delete_model(upstream_id))++ group = f"reliability-retry-5xx-{unique_marker()}"+ failing = create_always_5xx_deployment(client.proxy, group, upstream, scoped_key)+ resources.defer(lambda: client.proxy.delete_model(failing))+ backup = create_zero_weight_backup_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(backup))++ _assert_served_after_retry(_retry_once(client, scoped_key, group))++ @pytest.mark.covers("reliability.retry.429.succeeds_within_retries")+ def test_429_on_first_deployment_succeeds_on_retry(+ self, client: ComplexityRouterClient, resources: ResourceManager, scoped_key: str+ ) -> None:+ spent_key = client.proxy.generate_key(+ KeyGenerateBody(models=[CHEAP_OPENAI_MODEL], rpm_limit=1, user_id="e2e-test-user"))+ resources.defer(lambda: client.proxy.delete_key(spent_key))- assert_retry_landed_on_backup(resp)+ group = f"reliability-retry-429-{unique_marker()}"+ failing = create_always_rate_limited_deployment(client.proxy, group, CHEAP_OPENAI_MODEL, spent_key)+ resources.defer(lambda: client.proxy.delete_model(failing))+ backup = create_zero_weight_backup_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(backup))++ spend_only_request_of(client.proxy, spent_key)+ _assert_served_after_retry(_retry_once(client, scoped_key, group))++ @pytest.mark.covers("reliability.retry.auth.succeeds_within_retries")+ def test_auth_failure_on_first_deployment_succeeds_on_retry(+ self, client: ComplexityRouterClient, resources: ResourceManager, scoped_key: str+ ) -> None:+ group = f"reliability-retry-auth-{unique_marker()}"+ failing = create_always_unauthorized_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(failing))+ backup = create_zero_weight_backup_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(backup))++ _assert_served_after_retry(_retry_once(client, scoped_key, group))++ @pytest.mark.covers("reliability.retry.context_window.succeeds_within_retries")+ def test_context_window_refusal_on_first_deployment_succeeds_on_retry(+ self, client: ComplexityRouterClient, resources: ResourceManager, scoped_key: str+ ) -> None:- group = f"reliability-retry-{unique_marker()}"++ group = f"reliability-retry-context-{unique_marker()}"+ small_context = create_always_picked_small_context_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(small_context))+ backup = create_zero_weight_backup_deployment(client.proxy, group)+ resources.defer(lambda: client.proxy.delete_model(backup))++ resp = chat_override(+ client.proxy,+ scoped_key,+ group,+ oversized_prompt(unique_marker()),+ override=RouterSettingsOverride(+ num_retries=2,+ model_group_retry_policy={group: {"BadRequestErrorRetries": 2}},+ ),+ )+- assert_retry_landed_on_backup(resp)++ _assert_served_after_retry(resp)