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(proxy): yaml store_prompts_in_spend_logs should take precedence over DB cached value (#35769)
Praveena Mundolimoole2d2994c9e9f4
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 539b68c1aee..07eaed9fe45 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -3909,6 +3909,10 @@ class ProxyConfig:# whether an existing request predates the prices it just fetched, and re-serving one# costs a single fetch where skipping one leaves it priced wrong indefinitelyself.model_cost_map_applied_revision: int = 0+ # Keys explicitly set in the YAML config file. Used to give YAML+ # precedence over stale DB-cached values for these specific keys+ # during periodic config reloads (_update_general_settings).+ self._yaml_general_settings_keys: set[str] = set() # mutable-ok: populated once at startup, read-only thereafter # fmt: skipdef is_yaml(self, config_file_path: str) -> bool:if not os.path.isfile(config_file_path):@@ -4839,6 +4843,11 @@ class ProxyConfig:_hc_staleness = None_hc_ignore_transient = Falseif general_settings:+ # Record which keys were explicitly set in the YAML config file.+ # These keys take precedence over DB-cached values during periodic+ # reloads (see _update_general_settings).+ self._yaml_general_settings_keys = set(general_settings.keys()) # mutable-ok: snapshot of YAML keys at load time # fmt: skip+### LOAD KEY MANAGEMENT SETTINGS FIRST (needed for custom secret manager) ###key_management_settings: Final = general_settings.get("key_management_settings", None)if key_management_settings is not None:@@ -6049,7 +6058,15 @@ class ProxyConfig:## STORE PROMPTS IN SPEND LOGS ##if "store_prompts_in_spend_logs" in _general_settings:- value = _general_settings["store_prompts_in_spend_logs"]+ # If the YAML config explicitly set this key, prefer the YAML value+ # over the DB-cached value. This ensures config changes deployed via+ # CI/CD take effect without requiring a manual /config/update call.+ # When YAML does not set this key, the DB value is used (preserving+ # admin UI runtime changes).+ if "store_prompts_in_spend_logs" in self._yaml_general_settings_keys:+ value = general_settings.get("store_prompts_in_spend_logs")+ else:+ value = _general_settings["store_prompts_in_spend_logs"]# Normalize case: handle True/true/TRUE, False/false/FALSE, None/nullif value is None:general_settings["store_prompts_in_spend_logs"] = Nonediff --git a/tests/proxy_unit_tests/test_proxy_config_unit_test.py b/tests/proxy_unit_tests/test_proxy_config_unit_test.pyindex 36cd08fa5f5..e6b38f31b48 100644--- a/tests/proxy_unit_tests/test_proxy_config_unit_test.py+++ b/tests/proxy_unit_tests/test_proxy_config_unit_test.py@@ -15,9 +15,7 @@ import os# this file is to test litellm/proxy-sys.path.insert(- 0, os.path.abspath("../..")-) # Adds the parent directory to the system path+sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system pathimport asyncioimport logging@@ -88,25 +86,14 @@ async def test_read_config_file_with_os_environ_vars():# Read configproxy_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_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"- )+ 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"]:@@ -129,17 +116,13 @@ async def test_basic_include_directive():"""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_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 mergedassert len(config["model_list"]) > 0- assert any(- model["model_name"] == "included-model" for model in config["model_list"]- )+ assert any(model["model_name"] == "included-model" for model in config["model_list"])# Verify original config settings remainassert config["litellm_settings"]["callbacks"] == ["prometheus"]@@ -152,9 +135,7 @@ async def test_missing_include_file():"""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"- )+ 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)@@ -167,20 +148,14 @@ async def test_multiple_includes():"""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_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 presentassert 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"]- )+ 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 remainassert config["litellm_settings"]["callbacks"] == ["prometheus"]@@ -211,8 +186,7 @@ def test_add_callbacks_from_db_config():# 1 instance of LangfusePromptManagement should exist in litellm.success_callbacknum_langfuse_instances = sum(- isinstance(callback, LangfusePromptManagement)- for callback in litellm.success_callback+ isinstance(callback, LangfusePromptManagement) for callback in litellm.success_callback)assert num_langfuse_instances == 1assert len(litellm.success_callback) == 2@@ -290,9 +264,7 @@ async def test_json_logs_calls_turn_on_json():"litellm_settings": {"json_logs": True},}- with tempfile.NamedTemporaryFile(- mode="w", suffix=".yaml", delete=False- ) as temp_file:+ with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as temp_file:yaml.dump(config_content, temp_file)temp_file_path = temp_file.name@@ -316,3 +288,71 @@ async def test_json_logs_calls_turn_on_json():# Cleanupos.unlink(temp_file_path)litellm.json_logs = False+++class TestYamlStorePromptsDbOverride:+ """+ Test that YAML store_prompts_in_spend_logs takes precedence over DB-cached value.++ When store_model_in_db=true, LiteLLM persists general_settings to the DB.+ On periodic reloads, _update_general_settings() must NOT override+ YAML-explicit values with stale DB values.+ """++ def _make_proxy_config_with_yaml_keys(self, yaml_keys: set) -> "ProxyConfig":+ """Helper: create ProxyConfig with pre-populated _yaml_general_settings_keys."""+ proxy_config = ProxyConfig()+ proxy_config._yaml_general_settings_keys = yaml_keys+ return proxy_config++ @pytest.mark.asyncio+ async def test_yaml_value_takes_precedence_over_db(self):+ """When YAML sets store_prompts_in_spend_logs=false, DB value (true) should be ignored."""+ proxy_config = self._make_proxy_config_with_yaml_keys({"store_prompts_in_spend_logs"})++ test_general_settings = {"store_prompts_in_spend_logs": False}++ with mock.patch("litellm.proxy.proxy_server.general_settings", test_general_settings):+ await proxy_config._update_general_settings(+ db_general_settings={"store_prompts_in_spend_logs": True},+ )++ assert test_general_settings["store_prompts_in_spend_logs"] is False++ @pytest.mark.asyncio+ async def test_db_value_used_when_yaml_does_not_set_key(self):+ """When YAML does NOT set store_prompts_in_spend_logs, DB value should be used."""+ proxy_config = self._make_proxy_config_with_yaml_keys({"master_key", "database_url"})++ test_general_settings = {"master_key": "sk-test"}++ with mock.patch("litellm.proxy.proxy_server.general_settings", test_general_settings):+ await proxy_config._update_general_settings(+ db_general_settings={"store_prompts_in_spend_logs": True},+ )++ assert test_general_settings["store_prompts_in_spend_logs"] is True++ @pytest.mark.asyncio+ async def test_admin_ui_change_works_when_yaml_omits_key(self):+ """Admin UI change (DB update) should work when YAML doesn't set the key."""+ proxy_config = self._make_proxy_config_with_yaml_keys({"master_key"})++ test_general_settings = {"master_key": "sk-test"}++ with mock.patch("litellm.proxy.proxy_server.general_settings", test_general_settings):+ await proxy_config._update_general_settings(+ db_general_settings={"store_prompts_in_spend_logs": True},+ )+ assert test_general_settings["store_prompts_in_spend_logs"] is True++ await proxy_config._update_general_settings(+ db_general_settings={"store_prompts_in_spend_logs": False},+ )++ assert test_general_settings["store_prompts_in_spend_logs"] is False++ def test_yaml_general_settings_keys_populated_on_load(self):+ """_yaml_general_settings_keys should be empty on init."""+ proxy_config = ProxyConfig()+ assert proxy_config._yaml_general_settings_keys == set()