litellm/tests/unit/proxy/test_proxy_config_unit_test.py
norkelbyte fd6e4fb6a5
fix(sdk): stop global model_fallbacks from recursing on every completion call (#51817)
* fix(sdk): stop global model_fallbacks from recursing on every completion call

With litellm.model_fallbacks set, acompletion and completion read the global
chain on every call, including the calls the fallback runner itself makes for
each attempt. Each attempt started a new fallback run, so the calls grew into a
tree until Python hit RecursionError and no provider was ever reached.

The fallback runner now marks every attempt with an internal _litellm_ kwarg,
and one resolver in fallback_utils decides the chain for a call. A marked
attempt gets no chain. Otherwise a per-call fallbacks value wins, including an
empty list to opt out, and the global list is used only when the call sets
none. An empty chain skips the runner. The resolved chain is what the runner
gets, so completion's sync path passes it explicitly. The marker is dropped
from provider params and cache keys like every other _litellm_ kwarg

* fix(fallbacks): keep each provider's credentials, typed errors, sync streams and one success log

A fallback to another provider drops the original request's credentials and
endpoint, and a fallback to another model drops per-call custom pricing.
When every attempt fails, the original model's typed error is re-raised.
The sync runner calls litellm.completion directly so sync streams work, and
the sync wrapper leaves the success log to the attempt inside the runner.
Health checks never fall back, and every attempt keeps the caller's
litellm_call_id.

* fix(fallbacks): set up fallbacks only when tried and keep health checks off the global list in every mode

Each fallback is now built only when the runner reaches it, using the provider
lookup that never starts a ChatGPT or GitHub Copilot device login, so an unused
fallback cannot block a healthy call

Health checks run inside a scope that turns the global model_fallbacks off,
which also covers modes bridged to chat. The per-site fallbacks=() overrides
are removed

The sync logging test now forces the inner and outer success handlers to
overlap with a barrier instead of sleeping

* fix(fallbacks): keep guardrails on sync attempts and keep the global list out of Router calls

The sync fallback runner now runs the deployment pre and post call hooks around every attempt, so guardrails a sync call names still run on each model, and it skips the post hook for streams like the async wrapper does

Router deployment calls run with the global list turned off, so on the proxy the Router owns fallbacks and a fallback answer is never priced or logged as the failed deployment

A fallback to another provider now also drops the request's headers and litellm_credential_name, and an original model whose provider cannot be looked up counts as a switch

When every model fails the caller gets main's documented "All fallback attempts failed" error again

* fix(fallbacks): keep custom provider settings for unprefixed fallbacks and never cache a rejected answer

An unprefixed fallback whose name resolves to no provider on its own now inherits the request's custom_llm_provider, so a fallback on the same OpenAI-compatible server keeps its api_base and key as it did on main

Sync fallback attempts no longer write to the cache, since their guardrail runs after the inner call returns. The outer call still caches the answer that passed, so a rejected answer never lands in the cache

* fix(fallbacks): run a sync attempt's output guardrail before it is cached or logged

The sync runner ran the post-call guardrail after litellm.completion returned, so the attempt's success log already held the raw answer and a rejected answer was logged as a success. The sync wrapper now runs the guardrail for a fallback attempt at the same point the async wrapper does, before the cache write and the success log, which also replaces the no-store workaround

* fix(fallbacks): keep search grants, deployment hooks and logs intact

Router deployment calls wrap their handler to turn the global list off, which hid asearch from the search fallback grant check. The check now unwraps the handler down to asearch

A failed sync fallback attempt runs the post-call failure deployment hook again, as main did through its async detour

atext_completion through the global list uses the async runner so it logs one success, and check_valid_key turns the global list off so a fallback answer never makes a bad key look valid

* fix(proxy): keep the global fallback list off on direct SDK calls

Pass-through models and routes the Router does not serve reach litellm directly, so the global list ran there with no check that the caller's key may use the fallback model. Those calls now turn the global list off, as Router deployment calls already do

* fix(fallbacks): price a fallback by its own model and skip the proxy global list

A fallback to another model kept the original call's base_model, so its answer was billed at the original model's rates, as on main. base_model now drops with the other per-call pricing params

The proxy turns the global fallback list off on every model call, so litellm_settings.model_fallbacks now logs a startup warning that points to router_settings.fallbacks and is not applied

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-14 16:28:38 -05:00

380 lines
13 KiB
Python

import os
from pathlib import Path
from typing import Final
import traceback
from unittest import mock
import pytest
from dotenv import load_dotenv
import litellm.proxy
import litellm.proxy.proxy_server
load_dotenv()
import io
# this file is to test litellm/proxy
import asyncio
import logging
import yaml
import litellm
from litellm.proxy.proxy_server import ProxyConfig
INVALID_FILES = ["config_with_missing_include.yaml"]
@pytest.mark.asyncio
async def test_basic_reading_configs_from_files():
"""
Test that the config is read correctly from the files in the example_config_yaml folder
"""
proxy_config_instance = ProxyConfig()
current_path = os.path.dirname(os.path.abspath(__file__))
example_config_yaml_path = os.path.join(current_path, "example_config_yaml")
# get all the files from example_config_yaml
files = [f for f in os.listdir(example_config_yaml_path) if f.endswith((".yaml", ".yml"))]
print(files)
for file in files:
if file in INVALID_FILES: # these are intentionally invalid files
continue
print("reading file=", file)
config_path = os.path.join(example_config_yaml_path, file)
config = await proxy_config_instance.get_config(config_file_path=config_path)
print(config)
@pytest.mark.asyncio
async def test_read_config_from_bad_file_path():
"""
Raise an exception if the file path is not valid
"""
proxy_config_instance = ProxyConfig()
config_path = "non-existent-file.yaml"
with pytest.raises(Exception, match="Config file not found"):
config = await proxy_config_instance.get_config(config_file_path=config_path)
@pytest.mark.asyncio
async def test_read_config_file_with_os_environ_vars():
"""
Ensures os.environ variables are read correctly from config.yaml
Following vars are set as os.environ variables in the config.yaml file
- DEFAULT_USER_ROLE
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
- AZURE_GPT_4O
- FIREWORKS
"""
_env_vars_for_testing = {
"DEFAULT_USER_ROLE": "admin",
"AWS_ACCESS_KEY_ID": "1234567890",
"AWS_SECRET_ACCESS_KEY": "1234567890",
"AZURE_GPT_4O": "1234567890",
"FIREWORKS": "1234567890",
}
_old_env_vars = {}
for key, value in _env_vars_for_testing.items():
if key in os.environ:
_old_env_vars[key] = os.environ.get(key)
os.environ[key] = value
# Read config
proxy_config_instance = ProxyConfig()
current_path = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_path, "example_config_yaml", "config_with_env_vars.yaml")
config = await proxy_config_instance.get_config(config_file_path=config_path)
print(config)
# Add assertions
assert config["litellm_settings"]["default_internal_user_params"]["user_role"] == "admin"
assert config["litellm_settings"]["s3_callback_params"]["s3_aws_access_key_id"] == "1234567890"
assert config["litellm_settings"]["s3_callback_params"]["s3_aws_secret_access_key"] == "1234567890"
for model in config["model_list"]:
if "azure" in model["litellm_params"]["model"]:
assert model["litellm_params"]["api_key"] == "1234567890"
elif "fireworks" in model["litellm_params"]["model"]:
assert model["litellm_params"]["api_key"] == "1234567890"
# cleanup
for key, value in _env_vars_for_testing.items():
if key in _old_env_vars:
os.environ[key] = _old_env_vars[key]
else:
del os.environ[key]
@pytest.mark.asyncio
async def test_basic_include_directive():
"""
Test that the include directive correctly loads and merges configs
"""
proxy_config_instance = ProxyConfig()
current_path = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_path, "example_config_yaml", "config_with_include.yaml")
config = await proxy_config_instance.get_config(config_file_path=config_path)
# Verify the included model list was merged
assert len(config["model_list"]) > 0
assert any(model["model_name"] == "included-model" for model in config["model_list"])
# Verify original config settings remain
assert config["litellm_settings"]["callbacks"] == ["prometheus"]
@pytest.mark.asyncio
async def test_missing_include_file():
"""
Test that a missing included file raises FileNotFoundError
"""
proxy_config_instance = ProxyConfig()
current_path = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_path, "example_config_yaml", "config_with_missing_include.yaml")
with pytest.raises(FileNotFoundError):
await proxy_config_instance.get_config(config_file_path=config_path)
@pytest.mark.asyncio
async def test_multiple_includes():
"""
Test that multiple files in the include list are all processed correctly
"""
proxy_config_instance = ProxyConfig()
current_path = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_path, "example_config_yaml", "config_with_multiple_includes.yaml")
config = await proxy_config_instance.get_config(config_file_path=config_path)
# Verify models from both included files are present
assert len(config["model_list"]) == 2
assert any(model["model_name"] == "included-model-1" for model in config["model_list"])
assert any(model["model_name"] == "included-model-2" for model in config["model_list"])
# Verify original config settings remain
assert config["litellm_settings"]["callbacks"] == ["prometheus"]
def test_add_callbacks_from_db_config():
"""Test that callbacks are added correctly and duplicates are prevented"""
# Setup
from litellm.integrations.langfuse.langfuse_prompt_management import (
LangfusePromptManagement,
)
proxy_config = ProxyConfig()
# Reset litellm callbacks before test
litellm.success_callback = []
litellm.failure_callback = []
# Test Case 1: Add new callbacks
config_data = {
"litellm_settings": {
"success_callback": ["langfuse", "custom_callback_api"],
"failure_callback": ["langfuse"],
}
}
proxy_config._add_callbacks_from_db_config(config_data)
# 1 instance of LangfusePromptManagement should exist in litellm.success_callback
num_langfuse_instances = sum(
isinstance(callback, LangfusePromptManagement) for callback in litellm.success_callback
)
assert num_langfuse_instances == 1
assert len(litellm.success_callback) == 2
assert len(litellm.failure_callback) == 1
# Test Case 2: Try adding duplicate callbacks
proxy_config._add_callbacks_from_db_config(config_data)
# Verify no duplicates were added
assert len(litellm.success_callback) == 2
assert len(litellm.failure_callback) == 1
# Cleanup
litellm.success_callback = []
litellm.failure_callback = []
litellm._known_custom_logger_compatible_callbacks = []
def test_add_callbacks_invalid_input():
"""Test handling of invalid input for callbacks"""
proxy_config = ProxyConfig()
# Reset callbacks
litellm.success_callback = []
litellm.failure_callback = []
# Test Case 1: Invalid callback format
config_data = {
"litellm_settings": {
"success_callback": "invalid_string_format", # Should be a list
"failure_callback": 123, # Should be a list
}
}
proxy_config._add_callbacks_from_db_config(config_data)
# Verify no callbacks were added with invalid input
assert len(litellm.success_callback) == 0
assert len(litellm.failure_callback) == 0
# Test Case 2: Missing litellm_settings
config_data = {}
proxy_config._add_callbacks_from_db_config(config_data)
# Verify no callbacks were added
assert len(litellm.success_callback) == 0
assert len(litellm.failure_callback) == 0
# Cleanup
litellm.success_callback = []
litellm.failure_callback = []
@pytest.mark.asyncio
async def test_json_logs_calls_turn_on_json():
"""
Test that json_logs: true in litellm_settings calls litellm.turn_on_json()
This is a regression test for the bug where json_logs in config file
would only set the attribute but not actually enable JSON logging.
See: https://github.com/BerriAI/litellm/issues/XXXX
"""
import tempfile
import yaml
# Create a temporary config file with json_logs: true
config_content = {
"model_list": [
{
"model_name": "test-model",
"litellm_params": {"model": "openai/gpt-4", "api_key": "test-key"},
}
],
"litellm_settings": {"json_logs": True},
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as temp_file:
yaml.dump(config_content, temp_file)
temp_file_path = temp_file.name
try:
proxy_config = ProxyConfig()
# Mock _turn_on_json to track if it gets called
with mock.patch("litellm.turn_on_json") as mock_turn_on_json:
await proxy_config.load_config(
router=None,
config_file_path=temp_file_path,
)
# Verify _turn_on_json was called
mock_turn_on_json.assert_called_once()
# Also verify the attribute was set
assert litellm.json_logs is True
finally:
# Cleanup
os.unlink(temp_file_path)
litellm.json_logs = False
class TestYamlStorePromptsDbOverride:
@pytest.mark.asyncio
async def test_yaml_value_takes_precedence_over_db(self):
proxy_config = ProxyConfig()
proxy_config.settings.load_yaml({"store_prompts_in_spend_logs": False})
with mock.patch("litellm.proxy.proxy_server.general_settings", proxy_config.settings):
await proxy_config._update_general_settings(
db_general_settings={"store_prompts_in_spend_logs": True},
)
from litellm.proxy import proxy_server
assert proxy_server.general_settings["store_prompts_in_spend_logs"] is False
assert proxy_server.general_settings.source("store_prompts_in_spend_logs") == "config"
@pytest.mark.asyncio
async def test_db_value_used_when_yaml_does_not_set_key(self):
proxy_config = ProxyConfig()
proxy_config.settings.load_yaml({"master_key": "sk-test"})
with mock.patch("litellm.proxy.proxy_server.general_settings", proxy_config.settings):
await proxy_config._update_general_settings(
db_general_settings={"store_prompts_in_spend_logs": True},
)
from litellm.proxy import proxy_server
assert proxy_server.general_settings["store_prompts_in_spend_logs"] is True
assert proxy_server.general_settings.source("store_prompts_in_spend_logs") == "db"
@pytest.mark.asyncio
async def test_admin_ui_change_works_when_yaml_omits_key(self):
proxy_config = ProxyConfig()
proxy_config.settings.load_yaml({"master_key": "sk-test"})
with mock.patch("litellm.proxy.proxy_server.general_settings", proxy_config.settings):
await proxy_config._update_general_settings(
db_general_settings={"store_prompts_in_spend_logs": True},
)
await proxy_config._update_general_settings(
db_general_settings={"store_prompts_in_spend_logs": False},
)
from litellm.proxy import proxy_server
assert proxy_server.general_settings["store_prompts_in_spend_logs"] is False
assert proxy_server.general_settings.source("store_prompts_in_spend_logs") == "db"
def test_proxy_config_settings_start_unset(self):
proxy_config = ProxyConfig()
assert proxy_config.settings.source("store_prompts_in_spend_logs") == "unset"
@pytest.mark.asyncio
@pytest.mark.parametrize("disabled", [["prompt"], "prompts", ["prompts", "tools"]])
async def test_load_config_rejects_unknown_mcp_disabled_capability(tmp_path: Path, disabled: object) -> None:
import yaml
from pydantic import ValidationError
config_path: Final = tmp_path / "config.yaml"
config_path.write_text(yaml.safe_dump({"general_settings": {"mcp_disabled_capabilities": disabled}}))
with pytest.raises(ValidationError):
await ProxyConfig().load_config(router=None, config_file_path=str(config_path))
@pytest.mark.asyncio
async def test_proxy_config_model_fallbacks_never_becomes_the_sdk_global_fallback_list(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(litellm, "model_fallbacks", None)
config_file: Final = tmp_path / "config.yaml"
_ = config_file.write_text(
yaml.safe_dump(
{
"model_list": [{"model_name": "gpt-5.4-nano", "litellm_params": {"model": "openai/gpt-5.4-nano"}}],
"litellm_settings": {"model_fallbacks": ["anthropic/claude-haiku-5-5"]},
}
)
)
_ = await ProxyConfig().load_config(router=None, config_file_path=str(config_file))
assert litellm.model_fallbacks is None