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): guard delete_model router eviction on auto_router/ prefix
Abhimanyu Kapur02137b2d12f8
diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.pyindex 0f0dedc40e6..23a3b3ce4f2 100644--- a/litellm/proxy/management_endpoints/model_management_endpoints.py+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py@@ -1040,6 +1040,22 @@ class ModelManagementAuthChecks:return True+def _deployment_name_and_model(deployment: Optional[Union[Deployment, Dict[str, object]]]) -> Tuple[Optional[str], str]:+ """Return (model_name, litellm_params.model) for a deployment.++ delete_deployment is annotated to return a Deployment but hands back the raw+ model_list dict at runtime, so both shapes are handled; the model defaults to "".+ """+ if deployment is None:+ return None, ""+ if isinstance(deployment, dict):+ name = deployment.get("model_name")+ params = deployment.get("litellm_params")+ model = params.get("model") if isinstance(params, dict) else None+ return (name if isinstance(name, str) else None), (model if isinstance(model, str) else "")+ return deployment.model_name, str(getattr(deployment.litellm_params, "model", "") or "")++#### [BETA] - This is a beta endpoint, format might change based on user feedback. - https://github.com/BerriAI/litellm/issues/964@router.post("/model/delete",@@ -1114,11 +1130,12 @@ async def delete_model(deleted_deployment = llm_router.delete_deployment(id=model_info.id)# delete_deployment only drops the deployment from model_list; the auto/# complexity router registries are keyed by model_name and would otherwise- # retain a stale (now unbacked) entry, so evict it here too.- deleted_name = getattr(deleted_deployment, "model_name", None)- if deleted_name is None and isinstance(deleted_deployment, dict):- deleted_name = deleted_deployment.get("model_name")- if deleted_name is not None:+ # retain a stale (now unbacked) entry, so evict it here too. Guard on the+ # auto_router/ prefix (as clear_cache does): a regular DB model that merely+ # shares a model_name with a config-defined router must not evict that router,+ # since add_deployment never restores config-defined routers.+ deleted_name, deleted_model = _deployment_name_and_model(deleted_deployment)+ if deleted_name is not None and deleted_model.startswith("auto_router/"):llm_router.auto_routers.pop(deleted_name, None)llm_router.complexity_routers.pop(deleted_name, None)diff --git a/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.pyindex 51411c4ae84..d9b5745807a 100644--- a/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py@@ -620,7 +620,11 @@ class TestDeleteModelClearsRouterRegistry:mock_router = MagicMock()mock_router.delete_deployment = MagicMock(- return_value={"model_name": "smart-router", "model_info": {"id": model_id}}+ return_value={+ "model_name": "smart-router",+ "litellm_params": {"model": "auto_router/complexity_router"},+ "model_info": {"id": model_id},+ })mock_router.auto_routers = {"smart-router": MagicMock()}mock_router.complexity_routers = {"smart-router": MagicMock()}@@ -644,6 +648,66 @@ class TestDeleteModelClearsRouterRegistry:assert "smart-router" not in mock_router.auto_routersassert "smart-router" not in mock_router.complexity_routers+ @pytest.mark.asyncio+ async def test_delete_regular_model_preserves_config_router_sharing_name(self):+ """Deleting a regular (non-router) DB model must not evict a config-defined router+ that merely shares its model_name. delete_deployment pops the DB model, but the+ auto/complexity registries hold a config router under the same name that+ add_deployment never restores, so an unguarded pop would make it permanently+ unroutable (the same cross-tenant DoS clear_cache was hardened against).+ """+ from litellm.proxy.management_endpoints.model_management_endpoints import (+ delete_model as delete_model_endpoint,+ )+ from litellm.proxy.management_endpoints.model_management_endpoints import ModelInfoDelete++ model_id = "regular-del-1"+ admin_user = UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN)+ db_row = LiteLLM_ProxyModelTable(+ model_id=model_id,+ model_name="shared-name",+ litellm_params={"model": "openai/gpt-4o"},+ model_info={"id": model_id},+ created_by="admin",+ updated_by="admin",+ )++ mock_prisma = MagicMock()+ mock_prisma.db = MagicMock()+ mock_prisma.db.litellm_proxymodeltable = AsyncMock()+ mock_prisma.db.litellm_proxymodeltable.find_unique = AsyncMock(return_value=db_row)+ mock_prisma.db.litellm_proxymodeltable.delete = AsyncMock(return_value=db_row)++ mock_router = MagicMock()+ mock_router.delete_deployment = MagicMock(+ return_value={+ "model_name": "shared-name",+ "litellm_params": {"model": "openai/gpt-4o"},+ "model_info": {"id": model_id},+ }+ )+ config_router = MagicMock()+ mock_router.auto_routers = {}+ mock_router.complexity_routers = {"shared-name": config_router}++ _PS = "litellm.proxy.proxy_server"+ with (+ patch(f"{_PS}.prisma_client", mock_prisma),+ patch(f"{_PS}.store_model_in_db", True),+ patch(f"{_PS}.proxy_config", MagicMock()),+ patch(f"{_PS}.proxy_logging_obj", MagicMock()),+ patch(f"{_PS}.general_settings", {}),+ patch(f"{_PS}.premium_user", True),+ patch(f"{_PS}.llm_router", mock_router),+ ):+ await delete_model_endpoint(+ model_info=ModelInfoDelete(id=model_id),+ user_api_key_dict=admin_user,+ )++ mock_router.delete_deployment.assert_called_once_with(id=model_id)+ assert mock_router.complexity_routers.get("shared-name") is config_router+class TestUpdateModel:"""