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
Handle cleanup delete races and accurate counts
Milan22439a119e60
diff --git a/litellm/proxy/common_utils/expired_ui_session_key_cleanup_manager.py b/litellm/proxy/common_utils/expired_ui_session_key_cleanup_manager.pyindex 61872603fb2..c25d8533128 100644--- a/litellm/proxy/common_utils/expired_ui_session_key_cleanup_manager.py+++ b/litellm/proxy/common_utils/expired_ui_session_key_cleanup_manager.py@@ -5,7 +5,7 @@ Deletes expired virtual keys created for LiteLLM dashboard sessions."""from datetime import datetime, timezone-from typing import List+from typing import Any, Dict, List, Optionalfrom litellm._logging import verbose_proxy_loggerfrom litellm.caching import DualCache@@ -85,11 +85,22 @@ class ExpiredUISessionKeyCleanupManager:user_api_key_dict=system_user,litellm_changed_by=LITELLM_INTERNAL_JOBS_SERVICE_ACCOUNT_NAME,)+ deleted_count = self._get_deleted_token_count(+ tokens=tokens,+ response=response,+ )verbose_proxy_logger.info(- "Deleted %s expired UI session key(s)", len(tokens)+ "Deleted %s expired UI session key(s)", deleted_count)- return len(tokens)+ return deleted_countexcept Exception as e:+ if getattr(e, "status_code", None) == 404:+ verbose_proxy_logger.debug(+ "Expired UI session key cleanup skipped because selected keys "+ "were already deleted: %s",+ e,+ )+ return 0verbose_proxy_logger.error(f"Expired UI session key cleanup failed: {e}")return 0finally:@@ -102,6 +113,35 @@ class ExpiredUISessionKeyCleanupManager:cronjob_id=EXPIRED_UI_SESSION_KEY_CLEANUP_JOB_NAME,)+ @staticmethod+ def _get_deleted_token_count(+ tokens: List[str],+ response: Optional[Dict[str, Any]],+ ) -> int:+ """+ Return the number of tokens actually deleted from the delete helper response.+ """+ if response is None:+ return len(tokens)++ deleted_keys = response.get("deleted_keys")+ if isinstance(deleted_keys, list):+ return len(deleted_keys)+ if isinstance(deleted_keys, int):+ return deleted_keys+ if isinstance(deleted_keys, dict):+ nested_deleted_keys = deleted_keys.get("deleted_keys")+ if isinstance(nested_deleted_keys, list):+ return len(nested_deleted_keys)+ if isinstance(nested_deleted_keys, int):+ return nested_deleted_keys++ failed_tokens = response.get("failed_tokens") or []+ if failed_tokens:+ return max(len(tokens) - len(set(failed_tokens)), 0)++ return len(tokens)+async def _find_expired_ui_session_keys(self) -> List[LiteLLM_VerificationToken]:"""Find expired LiteLLM dashboard session keys.diff --git a/tests/test_litellm/proxy/common_utils/test_expired_ui_session_key_cleanup_manager.py b/tests/test_litellm/proxy/common_utils/test_expired_ui_session_key_cleanup_manager.pyindex 85f4e9dd6f6..3efeeee9a27 100644--- a/tests/test_litellm/proxy/common_utils/test_expired_ui_session_key_cleanup_manager.py+++ b/tests/test_litellm/proxy/common_utils/test_expired_ui_session_key_cleanup_manager.py@@ -8,6 +8,7 @@ from datetime import datetime, timedelta, timezonefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from fastapi import HTTPException, statussys.path.insert(0, os.path.abspath("../../../.."))@@ -162,6 +163,123 @@ class TestExpiredUISessionKeyCleanupManager:assert hook_kwargs["keys_being_deleted"] == expired_keysassert hook_kwargs["response"] == {"deleted_keys": tokens, "failed_tokens": []}+ @pytest.mark.asyncio+ async def test_cleanup_expired_keys_returns_successful_delete_count(self):+ mock_prisma_client = AsyncMock()+ mock_cache = MagicMock()+ manager = ExpiredUISessionKeyCleanupManager(+ prisma_client=mock_prisma_client,+ user_api_key_cache=mock_cache,+ )+ expired_keys = [+ LiteLLM_VerificationToken(+ token="expired-dashboard-token-1",+ team_id=UI_SESSION_TOKEN_TEAM_ID,+ expires=datetime.now(timezone.utc) - timedelta(seconds=1),+ ),+ LiteLLM_VerificationToken(+ token="expired-dashboard-token-2",+ team_id=UI_SESSION_TOKEN_TEAM_ID,+ expires=datetime.now(timezone.utc) - timedelta(seconds=1),+ ),+ ]+ tokens = [key.token for key in expired_keys]+ manager._find_expired_ui_session_keys = AsyncMock(return_value=expired_keys)++ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.delete_verification_tokens",+ new_callable=AsyncMock,+ ) as mock_delete_verification_tokens:+ mock_delete_verification_tokens.return_value = (+ {+ "deleted_keys": ["expired-dashboard-token-1"],+ "failed_tokens": ["expired-dashboard-token-2"],+ },+ [expired_keys[0]],+ )+ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.KeyManagementEventHooks.async_key_deleted_hook",+ new_callable=AsyncMock,+ ):+ deleted_count = await manager.cleanup_expired_keys()++ assert deleted_count == 1+ assert mock_delete_verification_tokens.call_args.kwargs["tokens"] == tokens++ @pytest.mark.asyncio+ async def test_cleanup_expired_keys_counts_nested_delete_response(self):+ mock_prisma_client = AsyncMock()+ mock_cache = MagicMock()+ manager = ExpiredUISessionKeyCleanupManager(+ prisma_client=mock_prisma_client,+ user_api_key_cache=mock_cache,+ )+ expired_keys = [+ LiteLLM_VerificationToken(+ token="expired-dashboard-token-1",+ team_id=UI_SESSION_TOKEN_TEAM_ID,+ expires=datetime.now(timezone.utc) - timedelta(seconds=1),+ ),+ LiteLLM_VerificationToken(+ token="expired-dashboard-token-2",+ team_id=UI_SESSION_TOKEN_TEAM_ID,+ expires=datetime.now(timezone.utc) - timedelta(seconds=1),+ ),+ ]+ tokens = [key.token for key in expired_keys]+ manager._find_expired_ui_session_keys = AsyncMock(return_value=expired_keys)++ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.delete_verification_tokens",+ new_callable=AsyncMock,+ ) as mock_delete_verification_tokens:+ mock_delete_verification_tokens.return_value = (+ {+ "deleted_keys": {"deleted_keys": 2},+ "failed_tokens": tokens,+ },+ expired_keys,+ )+ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.KeyManagementEventHooks.async_key_deleted_hook",+ new_callable=AsyncMock,+ ):+ deleted_count = await manager.cleanup_expired_keys()++ assert deleted_count == 2++ @pytest.mark.asyncio+ async def test_cleanup_expired_keys_treats_missing_keys_as_noop(self):+ mock_prisma_client = AsyncMock()+ mock_cache = MagicMock()+ manager = ExpiredUISessionKeyCleanupManager(+ prisma_client=mock_prisma_client,+ user_api_key_cache=mock_cache,+ )+ expired_key = LiteLLM_VerificationToken(+ token="expired-dashboard-token",+ team_id=UI_SESSION_TOKEN_TEAM_ID,+ expires=datetime.now(timezone.utc) - timedelta(seconds=1),+ )+ manager._find_expired_ui_session_keys = AsyncMock(return_value=[expired_key])++ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.delete_verification_tokens",+ new_callable=AsyncMock,+ ) as mock_delete_verification_tokens:+ mock_delete_verification_tokens.side_effect = HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail={"error": "No keys found"},+ )+ with patch(+ "litellm.proxy.common_utils.expired_ui_session_key_cleanup_manager.KeyManagementEventHooks.async_key_deleted_hook",+ new_callable=AsyncMock,+ ) as mock_key_deleted_hook:+ deleted_count = await manager.cleanup_expired_keys()++ assert deleted_count == 0+ mock_key_deleted_hook.assert_not_called()+@pytest.mark.asyncioasync def test_cleanup_expired_keys_noops_when_no_keys_found(self):mock_prisma_client = AsyncMock()