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): skip failure rows for expired Admin UI session keys on dashboard info routes (#45881)
jesus-berrifead47fa7b63
diff --git a/litellm/proxy/auth/route_checks.py b/litellm/proxy/auth/route_checks.pyindex ebfa3211c64..ae129ca47b5 100644--- a/litellm/proxy/auth/route_checks.py+++ b/litellm/proxy/auth/route_checks.py@@ -7,6 +7,7 @@ from fastapi import HTTPException, Request, statusfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import (+ UI_TEAM_ID,CommonProxyErrors,KeyManagementRoutes,LiteLLM_UserTable,@@ -502,6 +503,13 @@ class RouteChecks:"""return route in LiteLLMRoutes.info_routes.value+ @staticmethod+ def is_dashboard_session_info_route(route: str, team_id: str | None) -> bool:+ """+ Check if an Admin UI session key is calling an info route the dashboard polls in the background+ """+ return team_id == UI_TEAM_ID and RouteChecks.is_info_route(route)+@staticmethoddef _is_azure_openai_route(route: str) -> bool:"""diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex 0938d3f35c3..5c31bce6f33 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -186,6 +186,8 @@ class _ProxyDBLogger(CustomLogger):and not (RouteChecks.is_llm_api_route(route=request_route) or RouteChecks.is_info_route(route=request_route))+ or request_route is not None+ and RouteChecks.is_dashboard_session_info_route(request_route, user_api_key_dict.team_id)):returndiff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 302f55eadf4..5bcba4a5992 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -3356,6 +3356,7 @@ class ProxyLogging:original_exception=original_exception,error_type=error_type,route=user_api_key_dict.request_route,+ team_id=user_api_key_dict.team_id,):await self._handle_logging_proxy_only_error(request_data=request_data,@@ -3413,6 +3414,7 @@ class ProxyLogging:original_exception: Exception,error_type: ProxyErrorTypes | None = None,route: str | None = None,+ team_id: str | None = None,) -> bool:"""Return True if the error is a Proxy Only LLM API Error@@ -3437,6 +3439,9 @@ class ProxyLogging:return Falseif not (RouteChecks.is_llm_api_route(route) or RouteChecks.is_info_route(route)):return False+ # Dashboard session keys poll info routes in the background; their failures are not user requests.+ if RouteChecks.is_dashboard_session_info_route(route, team_id):+ return Falsereturn isinstance(original_exception, _PROXY_ONLY_LLM_API_ERRORS) or (error_type == ProxyErrorTypes.auth_error)diff --git a/tests/integration/spend/test_expired_ui_session_failure_rows.py b/tests/integration/spend/test_expired_ui_session_failure_rows.pynew file mode 100644index 00000000000..0acdc86709e--- /dev/null+++ b/tests/integration/spend/test_expired_ui_session_failure_rows.py@@ -0,0 +1,127 @@+import uuid+from collections.abc import Iterator+from dataclasses import dataclass+from typing import Final++import jwt+import pytest+from integration._support.client import Gateway, eventually, gateway_from_environment, held, string_value+from integration._support.database import read_rows+from integration._support.process import OwnedProxy, graceful_stop_seconds, owned_proxy_process++from litellm.proxy._types import hash_token++pytestmark: Final = pytest.mark.timeout(2 * graceful_stop_seconds() + 240)++SESSION_SECONDS: Final = 3+DASHBOARD_INFO_ROUTES: Final = (+ "/key/list",+ "/v2/user/info",+ "/team/list",+ "/organization/list",+ "/v2/model/info",+ "/get/user_banner",+)+SPEND_LOG_FLUSH_SECONDS: Final = 25+++@dataclass(frozen=True, slots=True)+class ExpiredKeys:+ session: str+ virtual: str++[email protected](scope="module")+def owned(tmp_path_factory: pytest.TempPathFactory) -> Iterator[OwnedProxy]:+ with (+ gateway_from_environment() as base,+ owned_proxy_process(+ base,+ tmp_path_factory.mktemp("expired-ui-session"),+ {"LITELLM_UI_SESSION_DURATION": f"{SESSION_SECONDS}s", "LITELLM_DISABLE_NO_REDIS_WARNING": "true"},+ workers=2,+ ) as proxy,+ ):+ yield proxy+++def _session_key(gateway: Gateway) -> str:+ response: Final = gateway.client.post("/v2/login", json={"username": "admin", "password": gateway.key})+ assert response.status_code == 200, response.text+ claims: Final = jwt.decode(string_value(response.json()["token"]), options={"verify_signature": False})+ key: Final = string_value(claims["key"])+ rows: Final = read_rows('SELECT team_id FROM "LiteLLM_VerificationToken" WHERE token = %s', (hash_token(key),))+ assert [row["team_id"] for row in rows] == ["litellm-dashboard"], rows+ return key+++def _rejected_as_expired(gateway: Gateway, key: str, route: str) -> None:+ response: Final = eventually(+ lambda: gateway.request("GET", route, key=key),+ lambda reply: reply.status_code == 401,+ seconds=30,+ )+ assert "Expired Key" in response.text, response.text+++def _failure_rows(key: str) -> list[str]:+ rows: Final = read_rows(+ 'SELECT call_type FROM "LiteLLM_SpendLogs" WHERE api_key = %s AND status = %s',+ (hash_token(key), "failure"),+ )+ return sorted(string_value(row["call_type"]) for row in rows)+++def expired(owned: OwnedProxy) -> Iterator[ExpiredKeys]:+ with owned.gateway.scenario() as scenario:+ keys: Final = ExpiredKeys(+ session=_session_key(owned.gateway),+ virtual=scenario.key(duration="1s", key_alias=f"integration-expired-{uuid.uuid4().hex[:12]}"),+ )+ _rejected_as_expired(owned.gateway, keys.session, "/key/info")+ _rejected_as_expired(owned.gateway, keys.virtual, "/key/info")+ yield keys+++def test_an_expired_dashboard_session_key_writes_no_failure_rows_for_dashboard_info_calls(+ owned: OwnedProxy, expired: ExpiredKeys+) -> None:+ for route in DASHBOARD_INFO_ROUTES:+ _rejected_as_expired(owned.gateway, expired.session, route)+ _rejected_as_expired(owned.gateway, expired.virtual, route)++ virtual_rows: Final = eventually(+ lambda: _failure_rows(expired.virtual),+ lambda rows: len(rows) == len(DASHBOARD_INFO_ROUTES) + 1,+ seconds=70,+ )+ assert virtual_rows == sorted(("/key/info", *DASHBOARD_INFO_ROUTES))+ assert (+ held(+ lambda: _failure_rows(expired.session),+ lambda rows: rows == [],+ holding=SPEND_LOG_FLUSH_SECONDS,+ seconds=SPEND_LOG_FLUSH_SECONDS + 5,+ )+ == []+ )+++def test_an_expired_dashboard_session_key_still_logs_a_failed_llm_call(owned: OwnedProxy, expired: ExpiredKeys) -> None:+ response: Final = owned.gateway.request(+ "POST",+ "/v1/chat/completions",+ {"model": "integration-unrouted", "messages": [{"role": "user", "content": "expired session"}]},+ key=expired.session,+ )+ assert response.status_code == 401, response.text+ assert "Expired Key" in response.text, response.text+ assert (+ eventually(+ lambda: _failure_rows(expired.session),+ lambda rows: "acompletion" in rows,+ seconds=70,+ ).count("acompletion")+ == 1+ )diff --git a/tests/unit/proxy/hooks/test_proxy_track_cost_callback.py b/tests/unit/proxy/hooks/test_proxy_track_cost_callback.pyindex 100e79e371d..833af4c03a3 100644--- a/tests/unit/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/unit/proxy/hooks/test_proxy_track_cost_callback.py@@ -457,6 +457,35 @@ async def test_async_post_call_failure_hook_non_llm_route():mock_update_database.assert_not_called()+ ("team_id", "route", "written"),+ [+ ("litellm-dashboard", "/key/list", False),+ ("litellm-dashboard", "/v2/user/info", False),+ ("litellm-dashboard", "/chat/completions", True),+ ("team-1", "/key/list", True),+ (None, "/key/list", True),+ ],+)+async def test_async_post_call_failure_hook_skips_dashboard_session_info_route_failures( # test-quality-ok: update_database is the DB write boundary, so whether it is awaited is the observable outcome+ team_id: str | None, route: str, written: bool+) -> None:+ """An expired Admin UI session key refetching dashboard info routes must not+ write a failure SpendLog row, while its LLM calls and other keys' info calls still do."""+ with patch(+ "litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter.update_database",+ new_callable=AsyncMock,+ ) as mock_update_database:+ await ProxyDBLogger().async_post_call_failure_hook(+ request_data={},+ original_exception=Exception("Authentication Error - Expired Key"),+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-session", team_id=team_id, request_route=route),+ )++ assert mock_update_database.await_count == (1 if written else 0)++@pytest.mark.asyncioasync def test_async_post_call_failure_hook_releases_budget_reservation_before_route_skip():logger = ProxyDBLogger()diff --git a/tests/unit/proxy/utils/proxy_logging/test_post_call_failure_hook.py b/tests/unit/proxy/utils/proxy_logging/test_post_call_failure_hook.pyindex 0e007429789..84aa1798da4 100644--- a/tests/unit/proxy/utils/proxy_logging/test_post_call_failure_hook.py+++ b/tests/unit/proxy/utils/proxy_logging/test_post_call_failure_hook.py@@ -66,6 +66,48 @@ def test_is_proxy_only_llm_api_truth_table(proxy_logging):}+def test_is_proxy_only_llm_api_skips_dashboard_session_info_route_failures(proxy_logging):+ """An expired Admin UI session key refetching dashboard info routes must not+ write Request Log failure rows, while its LLM calls and other keys still do."""++ def decide(route: str, team_id: str | None) -> bool:+ return proxy_logging._is_proxy_only_llm_api_error(+ original_exception=Exception("Authentication Error - Expired Key"),+ error_type=ProxyErrorTypes.auth_error,+ route=route,+ team_id=team_id,+ )++ assert {+ "dashboard_key_list": decide("/key/list", "litellm-dashboard"),+ "dashboard_user_info": decide("/v2/user/info", "litellm-dashboard"),+ "dashboard_model_info": decide("/v2/model/info", "litellm-dashboard"),+ "dashboard_chat": decide("/chat/completions", "litellm-dashboard"),+ "team_key_list": decide("/key/list", "team-1"),+ "teamless_key_list": decide("/key/list", None),+ } == {+ "dashboard_key_list": False,+ "dashboard_user_info": False,+ "dashboard_model_info": False,+ "dashboard_chat": True,+ "team_key_list": True,+ "teamless_key_list": True,+ }+++async def test_post_call_failure_hook_skips_logging_for_dashboard_session_info_route(proxy_logging):+ proxy_logging._handle_logging_proxy_only_error = AsyncMock()+ await proxy_logging.post_call_failure_hook(+ request_data={},+ original_exception=Exception("Authentication Error - Expired Key"),+ user_api_key_dict=UserAPIKeyAuth(team_id="litellm-dashboard", request_route="/key/list"),+ error_type=ProxyErrorTypes.auth_error,+ route="/key/list",+ )+ proxy_logging._handle_logging_proxy_only_error.assert_not_awaited()++def test_is_proxy_only_llm_api_missing_exception_raises(proxy_logging):"""Passing nothing should TypeError on the missing positional kwarg."""with pytest.raises(TypeError):