Skip to content

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]

test(prometheus): cover caller-identity config failure cases (#38380)

yucheng-berriede4f3e8ab39
diff --git a/tests/test_litellm/integrations/test_prometheus_caller_identity.py b/tests/test_litellm/integrations/test_prometheus_caller_identity.py
index 30c1a2e2476..abe54cc4d99 100644
--- a/tests/test_litellm/integrations/test_prometheus_caller_identity.py
+++ b/tests/test_litellm/integrations/test_prometheus_caller_identity.py
@@ -16,9 +16,12 @@ from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.integrations.prometheus import (
DEFINED_PROMETHEUS_METRICS,
PROMETHEUS_DEPLOYMENT_AND_LATENCY_CALLER_IDENTITY_METRICS,
+ LabelValidationError,
PrometheusMetricLabels,
UserAPIKeyLabelNames,
UserAPIKeyLabelValues,
+ validate_caller_identity_settings,
+ validate_prometheus_deployment_and_latency_caller_identity,
)
from litellm.types.utils import StandardLoggingPayload
@@ -379,6 +382,195 @@ def test_deployment_failure_email_fallbacks_reach_both_real_counters(
async def test_proxy_config_loads_caller_identity_before_initializing_callbacks(tmp_path: Path):
from litellm.proxy.proxy_server import ProxyConfig
+ config_path = _write_proxy_config(
+ tmp_path,
+ {
+ "callbacks": ["prometheus"],
+ "prometheus_deployment_and_latency_caller_identity": "both",
+ },
+ )
+ observed_modes: list[str] = []
+
+ def capture_mode(*args: object, **kwargs: object) -> None:
+ observed_modes.append(litellm.prometheus_deployment_and_latency_caller_identity)
+
+ with patch( # test-quality-ok: callback interception verifies schema selection before construction
+ "litellm.proxy.proxy_server.initialize_callbacks_on_proxy", side_effect=capture_mode
+ ):
+ await ProxyConfig().load_config(router=None, config_file_path=str(config_path))
+
+ assert observed_modes == ["both"]
+ assert litellm.prometheus_deployment_and_latency_caller_identity == "both"
+
+
+def _identity_settings(mode: object, metrics_config: object = None) -> dict[str, object]:
+ settings: dict[str, object] = {"prometheus_deployment_and_latency_caller_identity": mode}
+ if metrics_config is not None:
+ settings["prometheus_metrics_config"] = metrics_config
+ return settings
+
+
+def test_validate_mode_returns_each_accepted_value_and_defaults_to_api_key_alias(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ for mode in IDENTITY_MODES:
+ _set_caller_identity(monkeypatch, mode)
+ assert validate_prometheus_deployment_and_latency_caller_identity() == mode
+
+ monkeypatch.delattr(litellm, "prometheus_deployment_and_latency_caller_identity")
+ assert validate_prometheus_deployment_and_latency_caller_identity() == "api_key_alias"
+
+
+def test_accepted_values_constant_matches_parametrized_modes():
+ from litellm.types.integrations.prometheus import (
+ PROMETHEUS_DEPLOYMENT_AND_LATENCY_CALLER_IDENTITY_VALUES,
+ )
+
+ assert PROMETHEUS_DEPLOYMENT_AND_LATENCY_CALLER_IDENTITY_VALUES == IDENTITY_MODES
+ assert len(TARGET_METRICS) == 9
+
+
+ "invalid_mode",
+ ("user-email", "USER_EMAIL", "", None, True, 1, ["user_email"], {"mode": "user_email"}),
+)
+def test_validate_mode_rejects_invalid_values_and_names_accepted_ones(
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_mode: object,
+):
+ monkeypatch.setattr(litellm, "prometheus_deployment_and_latency_caller_identity", invalid_mode)
+
+ with pytest.raises(ValueError, match="prometheus_deployment_and_latency_caller_identity") as exc_info:
+ validate_prometheus_deployment_and_latency_caller_identity()
+
+ message = str(exc_info.value)
+ assert repr(invalid_mode) in message
+ for accepted_value in IDENTITY_MODES:
+ assert accepted_value in message
+
+
+def test_validate_caller_identity_settings_without_key_leaves_mode_untouched(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ _set_caller_identity(monkeypatch, "both")
+
+ validate_caller_identity_settings({"prometheus_metrics_config": []})
+
+ assert litellm.prometheus_deployment_and_latency_caller_identity == "both"
+
+
[email protected]("mode", IDENTITY_MODES)
+def test_validate_caller_identity_settings_stores_each_valid_mode(mode: str):
+ validate_caller_identity_settings(_identity_settings(mode))
+
+ assert litellm.prometheus_deployment_and_latency_caller_identity == mode
+
+
[email protected]("invalid_mode", ("user-email", None))
+def test_validate_caller_identity_settings_rejects_invalid_and_null_modes(invalid_mode: object):
+ with pytest.raises(ValueError, match="prometheus_deployment_and_latency_caller_identity"):
+ validate_caller_identity_settings(_identity_settings(invalid_mode))
+
+
+def test_user_email_mode_conflict_error_names_every_conflicting_metric_and_only_those():
+ metrics_config = [
+ {
+ "group": "non_target",
+ "metrics": ["litellm_overhead_with_guardrails_latency_metric"],
+ "include_labels": ["api_key_alias"],
+ },
+ {
+ "group": "target_pair",
+ "metrics": ["litellm_deployment_total_requests", "litellm_llm_api_latency_metric"],
+ "include_labels": ["api_key_alias"],
+ },
+ {
+ "group": "target_single",
+ "metrics": ["litellm_request_queue_time_seconds"],
+ "include_labels": ["api_key_alias"],
+ },
+ ]
+
+ with pytest.raises(ValueError, match="prometheus_deployment_and_latency_caller_identity") as exc_info:
+ validate_caller_identity_settings(_identity_settings("user_email", metrics_config))
+
+ message = str(exc_info.value)
+ for conflicting_metric in (
+ "litellm_deployment_total_requests",
+ "litellm_llm_api_latency_metric",
+ "litellm_request_queue_time_seconds",
+ ):
+ assert conflicting_metric in message
+ assert "litellm_overhead_with_guardrails_latency_metric" not in message
+ assert "prometheus_deployment_and_latency_caller_identity" in message
+ assert "user_email" in message
+
+
+ ("mode", "metrics_config"),
+ (
+ (
+ "user_email",
+ [
+ {
+ "group": "g",
+ "metrics": ["litellm_deployment_total_requests"],
+ "include_labels": ["user_email"],
+ }
+ ],
+ ),
+ (
+ "user_email",
+ [
+ {
+ "group": "g",
+ "metrics": ["litellm_overhead_with_guardrails_latency_metric"],
+ "include_labels": ["api_key_alias"],
+ }
+ ],
+ ),
+ (
+ "api_key_alias",
+ [
+ {
+ "group": "g",
+ "metrics": ["litellm_deployment_total_requests"],
+ "include_labels": ["api_key_alias"],
+ }
+ ],
+ ),
+ (
+ "both",
+ [
+ {
+ "group": "g",
+ "metrics": ["litellm_deployment_total_requests"],
+ "include_labels": ["api_key_alias"],
+ }
+ ],
+ ),
+ ("user_email", None),
+ ("user_email", ["not-a-dict"]),
+ (
+ "user_email",
+ [{"group": "g", "metrics": ["litellm_deployment_total_requests"], "include_labels": None}],
+ ),
+ ("user_email", [{"group": "g", "metrics": None, "include_labels": ["api_key_alias"]}]),
+ ),
+)
+def test_validate_caller_identity_settings_accepts_non_conflicting_configs(
+ mode: str,
+ metrics_config: object,
+):
+ settings = _identity_settings(mode)
+ settings["prometheus_metrics_config"] = metrics_config
+
+ validate_caller_identity_settings(settings)
+
+ assert litellm.prometheus_deployment_and_latency_caller_identity == mode
+
+
+def _write_proxy_config(tmp_path: Path, litellm_settings: dict[str, object]) -> Path:
config_path = tmp_path / "config.yaml"
config_path.write_text(
yaml.safe_dump(
@@ -389,23 +581,107 @@ async def test_proxy_config_loads_caller_identity_before_initializing_callbacks(
"litellm_params": {"model": "openai/gpt-4", "api_key": "test-key"},
}
],
- "litellm_settings": {
- "callbacks": ["prometheus"],
- "prometheus_deployment_and_latency_caller_identity": "both",
- },
+ "litellm_settings": litellm_settings,
},
sort_keys=False,
)
)
- observed_modes: list[str] = []
+ return config_path
- def capture_mode(*args: object, **kwargs: object) -> None:
- observed_modes.append(litellm.prometheus_deployment_and_latency_caller_identity)
- with patch( # test-quality-ok: callback interception verifies schema selection before construction
- "litellm.proxy.proxy_server.initialize_callbacks_on_proxy", side_effect=capture_mode
- ):
- await ProxyConfig().load_config(router=None, config_file_path=str(config_path))
+ "litellm_settings",
+ (
+ {
+ "callbacks": ["prometheus"],
+ "prometheus_deployment_and_latency_caller_identity": "user-email",
+ },
+ {
+ "callbacks": ["prometheus"],
+ "prometheus_deployment_and_latency_caller_identity": None,
+ },
+ {
+ "callbacks": ["prometheus"],
+ "prometheus_deployment_and_latency_caller_identity": "user_email",
+ "prometheus_metrics_config": [
+ {
+ "group": "g",
+ "metrics": ["litellm_deployment_total_requests"],
+ "include_labels": ["api_key_alias"],
+ }
+ ],
+ },
+ ),
+ ids=("typo-mode", "null-mode", "include-labels-conflict"),
+)
+async def test_proxy_config_fails_boot_before_callbacks_on_invalid_caller_identity_config(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ litellm_settings: dict[str, object],
+):
+ from litellm.proxy.proxy_server import ProxyConfig
- assert observed_modes == ["both"]
- assert litellm.prometheus_deployment_and_latency_caller_identity == "both"
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)
+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", False)
+ monkeypatch.delenv("LITELLM_CONFIG_BUCKET_NAME", raising=False)
+ config_path = _write_proxy_config(tmp_path, litellm_settings)
+
+ with patch( # test-quality-ok: asserts boot fails before any callback initialization
+ "litellm.proxy.proxy_server.initialize_callbacks_on_proxy"
+ ) as callback_init:
+ with pytest.raises(ValueError, match="prometheus_deployment_and_latency_caller_identity"):
+ await ProxyConfig().load_config(router=None, config_file_path=str(config_path))
+
+ callback_init.assert_not_called()
+
+
+def test_failed_init_leaves_registry_clean_so_a_corrected_retry_succeeds(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ _set_caller_identity(monkeypatch, "user-email")
+ with pytest.raises(ValueError, match="prometheus_deployment_and_latency_caller_identity"):
+ PrometheusLogger()
+
+ assert list(REGISTRY._collector_to_names) == [] # pyright: ignore[reportPrivateUsage]
+
+ _set_caller_identity(monkeypatch, "user_email")
+ logger = PrometheusLogger()
+ assert "user_email" in logger.get_labels_for_metric("litellm_deployment_total_requests")
+
+
[email protected]("invalid_label", ("api_key_alias", "user_email"))
+def test_label_validation_error_names_mode_setting_for_identity_labels_on_target_metric(
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_label: str,
+):
+ _set_caller_identity(monkeypatch, "user_email")
+
+ error = LabelValidationError(
+ metric_name="litellm_deployment_total_requests",
+ invalid_labels=[invalid_label],
+ valid_labels=["user_email"],
+ )
+
+ assert "prometheus_deployment_and_latency_caller_identity='user_email'" in error.message
+ assert invalid_label in error.message
+
+
+def test_label_validation_error_keeps_base_message_for_non_identity_cases(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ _set_caller_identity(monkeypatch, "user_email")
+ non_target_metric = LabelValidationError(
+ metric_name="litellm_overhead_with_guardrails_latency_metric",
+ invalid_labels=["api_key_alias"],
+ valid_labels=[],
+ )
+ non_identity_label = LabelValidationError(
+ metric_name="litellm_deployment_total_requests",
+ invalid_labels=["bogus_label"],
+ valid_labels=[],
+ )
+
+ for error in (non_target_metric, non_identity_label):
+ assert "caller-identity" not in error.message
+ assert error.message.startswith("Invalid labels for metric")