litellm/tests/proxy_unit_tests
Deepanshu Lulla 0580465384
feat(router): add per-deployment allowed_fails_policy and cooldown_time override support (#34416)
* feat(router): add per-deployment allowed_fails_policy and cooldown_time override support

Three bugs fixed in the router cooldown system: (1) deployment-level allowed_fails and
allowed_fails_policy in model_info now take precedence over router-level settings in
_should_cooldown_deployment; (2) failed fallback deployments now get evaluated for
cooldown via _trigger_cooldown_for_failed_deployment, bypassing the Logging dedup gate;
(3) DualCache promotes Redis cooldown entries using default 600s TTL instead of true
remaining cooldown time -- _corrected_active_cooldown now evicts expired entries and
corrects stale in-memory TTLs on backfill. Adds ServiceUnavailableError, BadGatewayError,
and NotFoundError fields to AllowedFailsPolicy and cooldown_time to LiteLLMParamsTypedDict.

* fix(router): gate fallback cooldown trigger on has_logged_async_failure; use only litellm_metadata for deployment ID

* fix(router): use X | Y union syntax to fix UP007 strict lint gate

* test(router_utils): add coverage for _trigger_cooldown_for_failed_deployment and has_logged_async_failure gate

* test(router_utils): cover deployment cooldown override and exception swallow paths

* fix(router): add InternalServerError/ServiceUnavailableError/BadGatewayError/NotFoundError to router-level get_allowed_fails_from_policy

* fix(router): format router.py and add router-level policy tests

* test(router): add CI-visible coverage for per-deployment cooldown policy

Tests for `_get_deployment_cooldown_policy`, `_resolve_allowed_fails_from_policy`,
and `_should_cooldown_based_on_deployment_policy` (cooldown_handlers.py), the
`_corrected_active_cooldown` branches in CooldownCache, and the four new
exception-type branches in `Router.get_allowed_fails_from_policy` (router.py) --
all in `tests/test_litellm/` which the enterprise-routing CI job runs.

* fix(router): use is not None guard for cooldown_time_override in should_cooldown_based_on_allowed_fails_policy

A cooldown_time_override of 0 was previously treated as falsy and silently
fell through to the router-level cooldown_time value. Switched to an explicit
is not None check so that zero is honored as a valid override.

Added a regression test covering the zero case.

* fix(router): honor has_logged_async_failure and metadata for fallback cooldown; support both model_info and litellm_params locations

Manual verification against a live proxy surfaced that the fallback-cooldown-gap
trigger never actually fired: the has_logged_async_failure check read a plain
attribute that Logging never sets (the real flag lives in model_call_details),
and the deployment_id lookup only trusted litellm_metadata, which regular chat
completions never populate (only batch/thread/file endpoints do). Router
overwrites model_info on whichever key is present before every attempt, so
metadata is equally authoritative there, not caller-controlled as previously
assumed. Also let allowed_fails/allowed_fails_policy/cooldown_time be set under
either model_info or litellm_params, each preferring its own canonical location.

* fix(router): fix ContentPolicyViolationError policy shadowing and partial-policy zero-threshold

Two bugs from Greptile review on PR #34416:

- ContentPolicyViolationError subclasses BadRequestError, so listing
  BadRequestError first in _EXCEPTION_POLICY_FIELDS made the isinstance
  check always match BadRequestError for content-policy errors, using the
  wrong allowed_fails threshold. Reordered so the subclass is checked first.

- A deployment with a partial allowed_fails_policy and no deployment-wide
  allowed_fails forced allowed_fails_override=0 for any exception type its
  policy didn't cover, cooling the deployment down on the first unrelated
  failure. Now defers to router-level behavior for uncovered exception
  types instead of forcing an immediate cooldown.

* fix(router): only trust a metadata/litellm_metadata bucket the router itself wrote deployment info into

veria-ai flagged that preferring litellm_metadata whenever present could pick up a
caller-supplied litellm_metadata.model_info.id (preserved via allow_client_pricing_override)
instead of the metadata bucket the router actually populated for a regular completion's
fallback attempt, naming an arbitrary "victim" deployment for cooldown.

Router._update_kwargs_with_deployment() always writes model_info and
deployment_model_name into the same bucket together. Only trust a bucket that
carries deployment_model_name alongside model_info, since that marker is only
ever set by the router itself, not by request-body metadata.

* test(router): add regression coverage for ContentPolicyViolationError policy shadowing

The subclass-ordering fix in commit 38fe4e4490 had no regression test.
Verified the new test fails on the pre-fix ordering (asserts 2, got 10)
before restoring the fix, and confirmed the same behavior through the full
_should_cooldown_deployment call path against a real Router instance.

* fix(router): let explicit allowed_fails_policy entries override the generic 4XX cooldown exclusion

_is_cooldown_required skips cooldown evaluation for any 4XX status outside
{429, 401, 408, 404} by default, since a generic client error is usually not
the deployment's fault. BadRequestError and ContentPolicyViolationError both
carry status 400, so their AllowedFailsPolicy fields (BadRequestErrorAllowedFails,
ContentPolicyViolationErrorAllowedFails, both router-level pre-existing and the
new deployment-level ones) were silently unreachable: an operator could set
them to any value with no effect, since _is_cooldown_required blocked cooldown
evaluation before that policy was ever consulted.

_should_run_cooldown_logic now also checks whether an explicit allowed_fails_policy
entry (deployment-level or router-level) covers the exception's type, and if so,
proceeds with cooldown evaluation regardless of the generic status-code exclusion.
The exclusion remains the default for exception types with no explicit policy.

Verified live against a mock-triggered ContentPolicyViolationError (config-level
mock_response, azure/gpt-4.1-mini deployment) with BadRequestErrorAllowedFails=100
and ContentPolicyViolationErrorAllowedFails=0 on the same deployment: it now cools
down after exactly one ContentPolicyViolationError instead of never cooling down.

* fix(router): use the router-stamped failed_deployment_id for fallback cooldown targeting

Greptile flagged a real gap in the metadata-bucket-based deployment lookup:
for a generic-API-call fallback, the router writes the current attempt into
litellm_metadata, but a stale "metadata" bucket carrying the same
deployment_model_name marker (from an earlier point) would be picked first,
cooling the wrong deployment.

Router already has a more robust, pre-existing mechanism for this exact
problem: _set_failed_deployment_id_on_exception stamps the failing
deployment's id directly onto the exception at the point of failure,
immune to metadata-bucket ambiguity since a caller can't influence it and
it doesn't depend on which bucket the current call type happens to use.
It just wasn't called from _ageneric_api_call_with_fallbacks_helper's
except block, unlike _completion/_acompletion.

Added the missing call there (matching the existing pattern exactly), and
changed _trigger_cooldown_for_failed_deployment to prefer
exception.failed_deployment_id when present, falling back to metadata-bucket
inspection only for call paths that don't stamp it yet.

Verified live: the standard fallback-cooldown-gap scenario (two bad-key
deployments in a fallback chain) still correctly cools down both the
originally-called and fallback deployment.

* fix(router): address human review on per-deployment cooldown overrides

Scope allowed_fails_policy override to deployment-level only (a router-level
policy predates this feature and must keep its existing behavior), exempt
advisor-orchestration failures from the fallback cooldown trigger, keep the
single-deployment model group protection intact against a generic
deployment-level allowed_fails, make cooldown_time precedence consistent
across resolution paths, fix a falsy-zero swallowing bug in the router-level
allowed_fails fallback, and make allowed_fails_policy resolution fall through
to the next matching exception type instead of stopping at the first unset
field.

Also restrict allowed_fails/allowed_fails_policy/cooldown_time to model_info:
litellm_params gets copied into the actual provider request, so a router-only
setting placed there would leak into that request.

* test(router): update test_cooldown_handlers.py for the deployment-policy signature change

Surfaced by the rebase: this mirrored test file (tests/test_litellm/ mirrors
litellm/) predates the router_unit_tests/ coverage added earlier in this PR and
was still calling _should_cooldown_based_on_deployment_policy with its old
4-argument signature and asserting the now-removed litellm_params cooldown_time
location.

* test(router): update test_fallback_event_handlers.py for model_info-only cooldown_time

Another mirrored test file surfaced by the rebase that still asserted the
now-removed litellm_params.cooldown_time location.

* fix(router): match cooldown-duration precedence in the fallback path to the primary path

_trigger_cooldown_for_failed_deployment only checked deployment config before
falling back to the router default, skipping the response Retry-After header
step that Router.deployment_callback_on_failure applies on the primary path.

* fix(router): restore litellm_params.cooldown_time as a pre-existing fallback

cooldown_time already had litellm_params support on Router.deployment_callback_on_failure
before this PR; the earlier model_info-only restriction (aimed at the leak concern
for the genuinely new allowed_fails/allowed_fails_policy fields) incorrectly dropped
that pre-existing capability too. model_info still takes priority when both are set.

* fix(router): keep the fallback-cooldown trigger in sync with #35104's review fixes

Applies the same two fixes landed on the split-out PR #35104 (which #34416
still duplicates until it's rebased onto the merged base): increment the
deployment's per-minute failure counter before evaluating cooldown, and
require the server-stamped failed_deployment_id instead of trusting a
metadata bucket, since neither "metadata" nor "litellm_metadata" can be told
apart from a caller-supplied one without knowing the call's function_name.

* fix(router): freeze the model_info fallback mapping to satisfy the type-discipline gate

* fix(router): defer f-string interpolation in fallback-cooldown debug logs

* fix(router): annotate cooldown-path locals with Final to satisfy the LIT010 budget

* fix(router): suppress reportPrivateUsage for cross-module cooldown helpers

* fix(router): don't cool down deployments for request-scoped 404s on generic API fallbacks

* fix(router): stamp the dynamic client-side-credential deployment id, not the shared static one

* fix(router): keep up with upstream typing modernization and Final-annotation ratchet

* fix(router): don't cool down deployments for a caller-supplied x-litellm-timeout

* fix(router): stamp dynamic client-side-credential id in completion fallback paths too

The generic-API-call helper already stamped the effective (dynamic-if-client-side-credential)
deployment id on exceptions, but the regular _completion/_acompletion exception handlers still
stamped the static shared deployment's id. A tenant using invalid forwarded credentials could
generate repeated failures attributed to, and eventually cooling down, the shared deployment
other tenants rely on. Extracted the stamping logic into one shared helper used by all three
call sites (generic API, sync completion, async completion) so the fix and future changes to it
stay in one place.

* fix(proxy): recognize body-supplied timeout/request_timeout/stream_timeout as caller-controlled

client_side_timeout was only set when the caller used the x-litellm-timeout header, but
Router._get_timeout also resolves the effective timeout from kwargs["timeout"],
kwargs["request_timeout"], and kwargs["stream_timeout"], all settable directly in the
request body (and x-litellm-stream-timeout wasn't marked either). A caller could set any
of those to a near-zero value, force a 408 on every deployment in a fallback chain, and
cool down deployments other tenants rely on without the guard in
_trigger_cooldown_for_failed_deployment recognizing it as caller-controlled. Also strip
any client-forged client_side_timeout from the request body so the marker is always
server-computed.

---------

Co-authored-by: Deepanshu <deepanshu.lulla@alpha-sense.com>
2026-08-10 11:02:06 -07:00
..
example_config_yaml test: test 2026-03-28 19:17:38 -07:00
test_configs test: test 2026-03-28 19:17:38 -07:00
test_model_response_typing fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
azure_fine_tune.jsonl fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
batch_job_results_furniture.jsonl fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
conftest copy.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
conftest.py [Fix] conftest: flush cache instances and warn on silent skips 2026-04-20 22:19:36 -07:00
data_map.txt fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
eagle.wav fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
gettysburg.wav fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
large_text.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
messages_with_counts.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
model_cost.json fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
openai_batch_completions.jsonl fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
openai_batch_completions_router.jsonl fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
speech_vertex.mp3 fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_aproxy_startup.py (Security fix) - Upgrade to fastapi==0.115.5 (#7447) 2024-12-28 17:08:19 -08:00
test_audit_logs_proxy.py fix(proxy): require opt in for audit header fallback 2026-04-30 11:17:04 -07:00
test_auth_checks.py fix(proxy-auth): deny provider-wildcard access inferred through an unrecognized model namespace 2026-07-11 19:00:03 -07:00
test_banned_keyword_list.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_blog_posts_endpoint.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_check_batch_cost.py fix(batches): keep batch state in sync on a poll without claiming attribution (#34456) 2026-08-08 16:01:47 -07:00
test_check_responses_cost.py fix(proxy): fall back to the SDK when a queued response's deployment is missing 2026-08-05 23:13:15 -07:00
test_custom_callback_input.py fix: use fastuuid helper (#14903) 2025-09-25 15:47:01 -07:00
test_custom_logger_s3_gcs.py chore(tests): thread config_file_path through s3/gcs custom-logger tests 2026-05-13 01:13:52 +00:00
test_custom_tokenizer_bug.py test: make custom_tokenizer proxy tests hermetic (#29643) 2026-06-04 12:51:37 -07:00
test_db_schema_changes.py test: initial test to enforce all functions in user_api_key_auth.py h… (#7797) 2025-01-15 21:52:45 -08:00
test_default_end_user_budget_simple.py Litellm oss staging 030626 (#29578) 2026-06-03 11:01:51 -07:00
test_deployed_proxy_keygen.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_deprecated_key_grace_period.py Litellm key rotation bug (#27756) 2026-05-12 17:16:37 -07:00
test_e2e_pod_lock_manager.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_gemini_agents_endpoints.py Gemini managed agents support (#28270) 2026-05-19 16:02:03 -07:00
test_get_favicon.py test(proxy): align favicon remote asset expectations 2026-04-30 11:46:45 -07:00
test_get_image.py fix(static-assets): browser-load remote branding assets 2026-04-30 11:30:57 -07:00
test_google_endpoint_routing.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_google_gemini_proxy_request.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_jwt.py test(proxy): stop running real-DB tests in GitHub Actions unit jobs (#29700) 2026-06-04 14:56:02 -07:00
test_jwt_key_mapping.py feat(auth): resolve caller identity once into a Principal at the auth seam (#30887) 2026-06-20 18:49:41 -07:00
test_key_generate_dynamodb.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_key_generate_prisma.py fix(spend-tracking): drop orphaned imports; align tests with alias contract 2026-04-29 18:53:12 +00:00
test_models_fallback_endpoint.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_multipart_bypass_repro.py fix: harden /key/update authorization checks (#27878) 2026-05-14 04:16:04 +00:00
test_prisma_client_backoff_retry.py fix(tests): mock prisma.Prisma in backoff retry tests to avoid 'prisma generate' 2026-02-17 19:29:20 -03:00
test_prompt_test_endpoint.py fix: harden /key/update authorization checks (#27878) 2026-05-14 04:16:04 +00:00
test_proxy_config_unit_test.py fix(proxy): yaml store_prompts_in_spend_logs should take precedence over DB cached value (#35769) 2026-08-06 09:32:44 -07:00
test_proxy_custom_auth.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_proxy_custom_logger.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_proxy_encrypt_decrypt.py test: fix test 2025-07-27 09:52:22 -07:00
test_proxy_exception_mapping.py [Perf] Embeddings: Use router's O(1) lookup and shared sessions (#16344) 2025-11-14 09:21:45 -08:00
test_proxy_gunicorn.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_proxy_pass_user_config.py test: test 2026-03-28 19:17:38 -07:00
test_proxy_reject_logging.py [internal copy of #29089] fix: duplicate claude code traces (#29311) 2026-05-29 22:23:24 -07:00
test_proxy_routes.py chore(ci): merge dev branch (#28801) 2026-05-25 13:44:49 -07:00
test_proxy_server.py feat(router): add per-deployment allowed_fails_policy and cooldown_time override support (#34416) 2026-08-10 11:02:06 -07:00
test_proxy_server_caching.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_proxy_server_keys.py fix tests 2025-10-25 10:19:24 -07:00
test_proxy_server_langfuse.py (Security fix) - Upgrade to fastapi==0.115.5 (#7447) 2024-12-28 17:08:19 -08:00
test_proxy_server_spend.py fix(pattern_match_deployments.py): default to user input if unable to… (#6632) 2024-11-08 00:55:57 +05:30
test_proxy_setting_guardrails.py fix(lakera-guardrail): use os.environ.get() to avoid KeyError on missing LAKERA_API_KEY 2026-02-17 19:30:22 -03:00
test_proxy_token_counter.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_proxy_utils.py fix(proxy): skip team model aliases that point at deleted deployments 2026-07-28 19:45:00 +00:00
test_realtime_cache.py feat: litellm oss 110626 (#30202) 2026-06-11 22:30:26 -07:00
test_reducto_ocr_route.py Litellm oss staging 04 21 2026 2 (#26569) 2026-05-20 21:25:19 -07:00
test_request_size_limit_middleware.py Fix early proxy request size enforcement (#27311) 2026-05-06 12:29:11 -07:00
test_response_polling_handler.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_response_polling_pre_call_checks.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_search_api_logging.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_server_root_path.py fix: server rooth path (#19790) 2026-01-26 09:48:06 -08:00
test_skills_db.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_ui_path_detection.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_unit_test_max_model_budget_limiter.py feat(proxy): add key-level budget_fallbacks to reroute requests when a per-model budget is exceeded (#31783) 2026-07-03 12:20:12 -07:00
test_unit_test_proxy_hooks.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_update_daily_tag_spend.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
test_update_spend.py feat(spend): rebuild the auto-router benchmarks backend as a per-session rollup (#35910) 2026-08-05 20:06:32 +00:00
test_user_api_key_auth.py revert(proxy)!: stop enforcing user budget on team keys (#35271) 2026-07-30 20:19:49 +00:00
test_zero_cost_model_budget_bypass.py style: run black formatter on files from main merge 2026-04-17 13:02:59 -07:00
vertex_key.json test: update to new vertex ai keys 2026-03-28 20:19:05 -07:00