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): serialize model reconciles so concurrent model writes stop evicting each other (#36687)
yuneng-jiang32535987e859
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 1a06906fdf9..bb330d00756 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -3,7 +3,7 @@ import jsonimport osfrom collections.abc import Callable, Mappingfrom datetime import datetime-from typing import TYPE_CHECKING, Any, Final, Literal+from typing import TYPE_CHECKING, Any, Final, Literal, NamedTupleimport httpxfrom pydantic import (@@ -73,6 +73,27 @@ else:Span = Any+class ReconcileOutcome(NamedTuple):+ """What a model reconcile observed, captured while it still held the reconcile+ lock.++ Both fields have to be read under that lock to be worth anything. ``live_after``+ in particular is the router's serving state the instant this reconcile finished,+ which is NOT the same as what a later snapshot would see: any other model write+ admitted in between briefly un-serves every db model (see ``clear_cache``), so a+ caller that re-snapshots at verdict time can observe that hole and blame its own+ reload for it.++ - ``still_desired``: the db + config ids the reconcile reconciled against, or None+ when no reconcile ran and the desired set is therefore unknown.+ - ``live_after``: the ids the router served immediately after the reconcile, or+ None when no reconcile ran.+ """++ still_desired: frozenset[str] | None+ live_after: frozenset[str] | None++class SupportedDBObjectType(str, enum.Enum):"""Supported database object types for fine-grained DB storage control.diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.pyindex 8a52b0d1abb..47566d6b6d5 100644--- a/litellm/proxy/management_endpoints/model_management_endpoints.py+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py@@ -35,6 +35,7 @@ from litellm.proxy._types import (PrismaCompatibleUpdateDBModel,ProxyErrorTypes,ProxyException,+ ReconcileOutcome,TeamModelAddRequest,TeamModelDeleteRequest,UserAPIKeyAuth,@@ -534,7 +535,7 @@ async def patch_model(# Clear cache and reload models (uses config setting or defaults to preserving config models for DB updates)live_before_reload: Final = live_model_ids_snapshot()- still_desired_ids: Final = await clear_cache()+ reload_outcome: Final = await clear_cache()## CREATE AUDIT LOG ##asyncio.create_task(@@ -554,7 +555,8 @@ async def patch_model(before=live_before_reload,written_models=[(model_id, getattr(updated_model, "model_info", None))],action="update",- still_desired=still_desired_ids,+ still_desired=reload_outcome.still_desired,+ live_after=reload_outcome.live_after,)return updated_model@@ -640,7 +642,7 @@ async def _set_model_blocked_status()live_before_reload: Final = live_model_ids_snapshot()- still_desired_ids: Final = await clear_cache()+ reload_outcome: Final = await clear_cache()asyncio.create_task(create_object_audit_log(@@ -661,7 +663,8 @@ async def _set_model_blocked_status(before=live_before_reload,written_models=[(data.model_id, getattr(updated_model, "model_info", None))],action=action,- still_desired=still_desired_ids,+ still_desired=reload_outcome.still_desired,+ live_after=reload_outcome.live_after,)return updated_model@@ -1033,9 +1036,15 @@ async def delete_team_models(if deleted_model_ids:await publish_config_change(redis_cache=coordination_redis_cache(), object_type="litellm_proxymodeltable")+ # Under MODEL_RECONCILE_LOCK, for the same reason as delete_model: the rows are+ # gone, but a reconcile holding a pre-delete snapshot would upsert these ids back+ # onto this pod. The lock orders the eviction after any in-flight reconcile.if llm_router is not None:- for model_id in deleted_model_ids:- llm_router.delete_deployment(id=model_id)+ from litellm.proxy.proxy_server import MODEL_RECONCILE_LOCK++ async with MODEL_RECONCILE_LOCK:+ for model_id in deleted_model_ids:+ llm_router.delete_deployment(id=model_id)return deleted_model_ids@@ -1355,6 +1364,7 @@ async def delete_model("""from litellm.proxy.proxy_server import (+ MODEL_RECONCILE_LOCK,llm_router,premium_user,prisma_client,@@ -1403,8 +1413,15 @@ async def delete_model()## DELETE FROM ROUTER ##+ # Under MODEL_RECONCILE_LOCK. The db row is already gone, but a reconcile+ # that snapshotted the db BEFORE that delete still lists this id as desired,+ # and its _add_deployment upserts the deployment straight back -- leaving+ # this pod serving a model the database no longer has, until the next+ # reconcile. Taking the lock orders this eviction after any such in-flight+ # reconcile's re-add, so the eviction is the last word.if llm_router is not None:- llm_router.delete_deployment(id=model_info.id)+ async with MODEL_RECONCILE_LOCK:+ llm_router.delete_deployment(id=model_info.id)# Runs after the row delete so the sibling check sees post-delete state.if model_params.model_info.team_id is not None:@@ -1579,7 +1596,7 @@ async def add_new_model("""live_before_reload: Final = live_model_ids_snapshot()- still_desired_ids: frozenset[str] | None = None+ reload_outcome: ReconcileOutcome = ReconcileOutcome(still_desired=None, live_after=None)try:_original_litellm_model_name: Final = model_params.model_nameif model_params.model_info.team_id is None:@@ -1594,7 +1611,7 @@ async def add_new_model(user_api_key_dict=user_api_key_dict,prisma_client=prisma_client,)- still_desired_ids = await proxy_config.add_deployment(+ reload_outcome = await proxy_config.add_deployment(prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj)# don't let failed slack alert block the /model/new response@@ -1641,7 +1658,8 @@ async def add_new_model(before=live_before_reload,written_models=[(model_response.model_id, getattr(model_response, "model_info", None))],action="create",- still_desired=still_desired_ids,+ still_desired=reload_outcome.still_desired,+ live_after=reload_outcome.live_after,)return model_response@@ -1768,7 +1786,7 @@ async def update_model(# Clear cache and reload models (uses config setting or defaults to preserving config models for DB updates)live_before_reload: Final = live_model_ids_snapshot()- still_desired_ids: Final = await clear_cache()+ reload_outcome: Final = await clear_cache()## CREATE AUDIT LOG ##asyncio.create_task(create_object_audit_log(@@ -1795,7 +1813,8 @@ async def update_model(before=live_before_reload,written_models=[(_model_id, getattr(model_response, "model_info", None))],action="update",- still_desired=still_desired_ids,+ still_desired=reload_outcome.still_desired,+ live_after=reload_outcome.live_after,)return model_response@@ -2100,6 +2119,7 @@ def reload_serving_verdict(written_models: Sequence[tuple[str, object]],written_must_serve: bool,still_desired: frozenset[str] | None = None,+ live_after: frozenset[str] | None = None,) -> tuple[tuple[str, ...], tuple[str, ...]]:"""Judge a write-triggered reload by diffing the router's serving state instead oftrusting any layer of the reload stack to report its own failure.@@ -2121,9 +2141,16 @@ def reload_serving_verdict(yet polled, so the reload dropping it is the reconcile working rather than damage.Without it (no reconcile ran) every drop is reported, which is the safe direction.+ ``live_after`` is the router's serving state captured by the reload itself, while it+ still held MODEL_RECONCILE_LOCK. Pass it whenever the caller has it: re-reading the+ router here instead means sampling it after the lock was released, where the NEXT+ reconcile's leading wipe (clear_cache un-serves every db model before reloading+ them) shows up as this reload having dropped them. Falling back to a fresh read is+ only correct when no reconcile ran and there is nothing to be concurrent with.+Returns (written ids violating their obligation, collateral ids no longer served)."""- now: Final = live_model_ids_snapshot()+ now: Final = live_model_ids_snapshot() if live_after is None else live_afterwritten_ids: Final = frozenset(model_id for model_id, _ in written_models)if written_must_serve:missing = tuple(@@ -2143,16 +2170,23 @@ def raise_if_reload_degraded_serving(written_models: Sequence[tuple[str, object]],action: str,still_desired: frozenset[str] | None = None,+ live_after: frozenset[str] | None = None,) -> None:"""The caller-visible error this pod's model-write endpoints owe their caller whenthe model they wrote is not being served after the reload they triggered. The DBwrite is durable either way and every other pod reloads on its own interval; this- speaks only for the handling pod."""+ speaks only for the handling pod.++ Callers hold a ReconcileOutcome from the reload; pass BOTH of its fields. Supplying+ still_desired without live_after mixes a snapshot taken under the reconcile lock+ with one taken after it was released, which is what makes a concurrent model write+ look like collateral damage."""missing, collateral = reload_serving_verdict(before=before,written_models=written_models,written_must_serve=True,still_desired=still_desired,+ live_after=live_after,)if not missing and not collateral:return@@ -2179,14 +2213,20 @@ def raise_if_reload_degraded_serving()-async def clear_cache() -> frozenset[str] | None:+async def clear_cache() -> ReconcileOutcome:"""Clear router caches and reload models.- Returns the db + config id set the reload reconciled against, or None when no- reload ran, so callers can pass it to raise_if_reload_degraded_serving.+ Returns what the reload saw (see ReconcileOutcome) so callers can pass it to+ raise_if_reload_degraded_serving.++ Runs under MODEL_RECONCILE_LOCK for its whole extent, not just the reload at the+ end, so the auto-router reset and the reload that rebuilds those routers are atomic+ to any other reconcile. The inner call is _add_deployment_locked because+ add_deployment would re-acquire the same non-reentrant lock and deadlock."""from litellm.proxy.proxy_server import (+ MODEL_RECONCILE_LOCK,llm_router,prisma_client,proxy_config,@@ -2196,61 +2236,88 @@ async def clear_cache() -> frozenset[str] | None:if llm_router is None or prisma_client is None:verbose_proxy_logger.debug("llm_router or prisma_client is None, skipping cache clear")- return None-- try:- # Only clear DB models, preserve config models- verbose_proxy_logger.debug("Clearing only DB models, preserving config models")-- # Get current models and filter out DB models- current_models: Final = llm_router.model_list.copy()- config_models: Final = []- db_model_ids: Final = []-- for model in current_models:- model_info = model.get("model_info", {})- if model_info.get("db_model", False):- # This is a DB model, mark for deletion- db_model_ids.append(model_info.get("id"))- else:- # This is a config model, preserve it- config_models.append(model)-- # Clear only DB models- for model_id in db_model_ids:- llm_router.delete_deployment(id=model_id)-- # Clear only DB-backed auto-router-family entries, keyed by model_name, so the- # reload below rebuilds them fresh. A blanket .clear() would also drop config-defined- # routers, which are never re-added below (add_deployment only reloads DB models),- # leaving them permanently unroutable until a full proxy restart for every tenant.- # Restrict to deployments whose model is actually an auto_router/* so a config- # router that merely shares a model_name with a regular DB model isn't evicted. The- # auto_router/ prefix also covers quality_router/ and adaptive_router/, so pop the- # name from every router registry (no-op where absent); missing quality/adaptive- # entries would otherwise make init raise "already exists" on reload and abort it.- db_router_names: Final = {- model.get("model_name")- for model in current_models- if model.get("model_name") is not None- and model.get("model_info", {}).get("db_model", False)- and str(model.get("litellm_params", {}).get("model", "")).startswith("auto_router/")- }- for model_name in db_router_names:- llm_router.auto_routers.pop(model_name, None)- llm_router.complexity_routers.pop(model_name, None)- llm_router.adaptive_routers.pop(model_name, None)- llm_router.quality_routers.pop(model_name, None)-- # Reload only DB models- still_desired_ids: Final = await proxy_config.add_deployment(- prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj- )+ return ReconcileOutcome(still_desired=None, live_after=None)++ async with MODEL_RECONCILE_LOCK:+ try:+ # Only clear DB models, preserve config models+ verbose_proxy_logger.debug("Clearing only DB models, preserving config models")++ # Get current models and filter out DB models+ current_models: Final = llm_router.model_list.copy()+ config_models: Final = []+ db_model_ids: Final = []++ db_router_names: Final = set()++ for model in current_models:+ model_info = model.get("model_info", {})+ if model_info.get("db_model", False):+ db_model_ids.append(model_info.get("id"))+ # Auto-router deployments (and only those) are wiped here, in the+ # same pass, so the reload rebuilds them -- see the comment below.+ model_name = model.get("model_name")+ if model_name is not None and str(model.get("litellm_params", {}).get("model", "")).startswith(+ "auto_router/"+ ):+ db_router_names.add(model_name)+ router_model_id = model_info.get("id")+ if router_model_id is not None:+ llm_router.delete_deployment(id=router_model_id)+ else:+ # This is a config model, preserved by the reconcile below+ config_models.append(model)++ # ORDINARY db deployments are deliberately NOT wiped. This used to+ # delete_deployment() every db model before the reload put them back, which+ # left the router serving ZERO db models for the whole width of the reload+ # -- a real data-plane hole that every inference request landing in it fell+ # into. It was also redundant for them: the reload's _delete_deployment+ # evicts exactly the ids the db no longer lists, and upsert_deployment+ # pops-and-re-adds a deployment whose params changed while no-opping one+ # that did not, so the reconcile converges on its own. Every mutation is+ # visible to that comparison -- `blocked` and (for premium) `updated_at`+ # are written into model_info.+ #+ # AUTO-ROUTER db deployments are the exception and ARE wiped -- in the+ # classification pass above, together with the strategy entries popped+ # just below. Their strategy registries are keyed+ # by model_name, which no deployment-id reconcile touches, so they have to+ # be popped and rebuilt here. But the rebuild only happens on the ADD path:+ # Router.upsert_deployment returns early when a deployment is unchanged and+ # never reaches add_deployment -> _add_deployment ->+ # init_auto_router_deployment, which is what repopulates the registries.+ # Popping without deleting would therefore strip every db-backed auto,+ # complexity, adaptive and quality router on this pod and never put it back,+ # so ANY unrelated model write would leave them unroutable until a restart.+ # Deleting the deployment forces upsert down the add path, which rebuilds+ # both the deployment and its strategy entry.+ #+ # That pass restricts the wipe to deployments whose model is actually an+ # auto_router/* so a config router that merely shares a model_name with a+ # regular db model isn't evicted -- config routers are never re-added by the+ # reload (it only reloads db models) and would be permanently unroutable.+ # The auto_router/ prefix also covers quality_router/ and adaptive_router/,+ # so pop the name from every registry (no-op where absent); a missing+ # quality/adaptive entry would otherwise make init raise "already exists"+ # on reload and abort it.+ for model_name in db_router_names:+ llm_router.auto_routers.pop(model_name, None)+ llm_router.complexity_routers.pop(model_name, None)+ llm_router.adaptive_routers.pop(model_name, None)+ llm_router.quality_routers.pop(model_name, None)++ # Reload only DB models. _add_deployment_locked, not add_deployment: this+ # coroutine already holds MODEL_RECONCILE_LOCK and asyncio.Lock is not+ # reentrant, so the public wrapper would deadlock against itself.+ outcome: Final = await proxy_config._add_deployment_locked(+ prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj+ )- verbose_proxy_logger.debug(- "Cleared %s DB models, preserved %s config models", len(db_model_ids), len(config_models)- )- return still_desired_ids- except Exception as e:- verbose_proxy_logger.exception("Failed to clear cache and reload models. Due to error - %s", e)- return None+ verbose_proxy_logger.debug(+ "Reconciled %s DB models, preserved %s config models", len(db_model_ids), len(config_models)+ )+ return outcome+ except Exception as e:+ verbose_proxy_logger.exception("Failed to clear cache and reload models. Due to error - %s", e)+ return ReconcileOutcome(still_desired=None, live_after=None)diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex de891af5674..3ac002ce8cc 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -467,6 +467,7 @@ from litellm.proxy.management_endpoints.model_management_endpoints import (_add_model_to_db,_add_team_model_to_db,_deduplicate_litellm_router_models,+ live_model_ids_snapshot,)from litellm.proxy.management_endpoints.model_management_endpoints import (router as model_management_router,@@ -2166,6 +2167,15 @@ experimental = False#### GLOBAL VARIABLES ####llm_router: Router | None = Nonellm_model_list: list | None = None+# Serializes every model reconcile (ProxyConfig.add_deployment and clear_cache) so the+# read-modify-write of llm_router above is atomic. Without it, two concurrent model+# writes each reconcile the router against their OWN db snapshot, and the one holding+# the older snapshot evicts the deployment the newer one just added -- the db keeps the+# row, this pod stops serving it. Control-plane only (model create/update/delete and+# the config-sync tick), never on a completion path, so the serialization is free.+# Module-level rather than per-ProxyConfig because llm_router is a module global and a+# second ProxyConfig instance must not get its own independent lock over it.+MODEL_RECONCILE_LOCK: Final = asyncio.Lock()general_settings: dict = {}config_passthrough_endpoints: list[dict[str, Any]] | None = Nonelog_file: Final = "api_log.json"@@ -6456,16 +6466,37 @@ class ProxyConfig:self,prisma_client: PrismaClient,proxy_logging_obj: ProxyLogging,- ) -> frozenset[str] | None:+ ) -> ReconcileOutcome:"""- Check db for new models- Check if model id's in router already- If not, add to router- Returns the ids the db + config say should be served after the reconcile, or- None when no reconcile ran. Callers that judge their own reload need it to tell- a deliberate eviction from a deployment that went missing.+ Serialized against every other model reconcile by MODEL_RECONCILE_LOCK, because+ the work below is a read-modify-write of the shared ``llm_router`` global: it+ reads the db into a snapshot and then makes the router match that snapshot. Two+ of those interleaving is not a lost update but an eviction -- the request whose+ snapshot predates the other's commit reconciles the newer model *out* of the+ router, since _delete_deployment removes every live deployment absent from the+ snapshot it was handed. The model stays in the db and this pod stops serving it+ until some later reload puts it back.++ Returns what the reconcile saw, captured before the lock is released so a+ caller's verdict cannot be corrupted by the next reconcile's own in-flight+ window. See ReconcileOutcome."""+ async with MODEL_RECONCILE_LOCK:+ return await self._add_deployment_locked(prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj)++ async def _add_deployment_locked(+ self,+ prisma_client: PrismaClient,+ proxy_logging_obj: ProxyLogging,+ ) -> ReconcileOutcome:+ """add_deployment's body, minus the locking. MODEL_RECONCILE_LOCK MUST already+ be held. Split out for the one caller that has to hold the lock across more than+ this reconcile -- clear_cache, which un-serves every db model before calling it+ and would deadlock on a re-acquire."""global llm_router, llm_model_list, master_key, general_settingsstill_desired_ids: frozenset[str] | None = None@@ -6508,7 +6539,12 @@ class ProxyConfig:except Exception as e:verbose_proxy_logger.exception("litellm.proxy.proxy_server.py::ProxyConfig:add_deployment - %s", e)- return still_desired_ids+ # Read while the lock is still held: once it is released the next reconcile can+ # begin, and clear_cache's leading wipe would make this look like a mass drop.+ return ReconcileOutcome(+ still_desired=still_desired_ids,+ live_after=None if still_desired_ids is None else live_model_ids_snapshot(),+ )def start_config_sync_subscriber(self,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 454849d6430..aafd84e4c83 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@@ -1,3 +1,4 @@+import asyncioimport jsonimport osimport sys@@ -18,6 +19,7 @@ from litellm.proxy._types import (LiteLLM_TeamTable,LitellmUserRoles,Member,+ ReconcileOutcome,UserAPIKeyAuth,)from litellm.proxy.management_endpoints.model_management_endpoints import (@@ -103,11 +105,11 @@ class MockProxyConfig:self.success = successself.deployment_called = False- async def add_deployment(self, prisma_client, proxy_logging_obj):+ async def _add_deployment_locked(self, prisma_client, proxy_logging_obj):self.deployment_called = Trueif not self.success:raise Exception("Failed to add deployment")- return True+ return ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())class TestModelManagementAuthChecks:@@ -409,7 +411,9 @@ class TestClearCache:mock_router.model_list = ["openai/gpt-4o", "openai/gpt-4o-mini"]mock_config = MagicMock()- mock_config.add_deployment = AsyncMock(return_value=True)+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )mock_prisma = MagicMock()mock_logging = MagicMock()@@ -430,7 +434,9 @@ class TestClearCache:@pytest.mark.asyncioasync def test_clear_cache_preserve_config_models(self):"""- Test that clear_cache clears DB models and preserves config models.+ clear_cache resets DB-backed auto-router entries and delegates every deployment+ change to the reload, leaving config models untouched. It must not wipe+ deployments itself -- see the delete_deployment assertion below."""from litellm.proxy.management_endpoints.model_management_endpoints import (clear_cache,@@ -463,7 +469,9 @@ class TestClearCache:mock_router.complexity_routers = {"db-complexity-router": MagicMock(), "config-router": MagicMock()}mock_config = MagicMock()- mock_config.add_deployment = AsyncMock(return_value=True)+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )mock_prisma = MagicMock()mock_logging = MagicMock()@@ -477,7 +485,10 @@ class TestClearCache:):await clear_cache()- # Should have called delete_deployment for both DB models+ # clear_cache must wipe ONLY the db auto-router deployments -- the ones whose+ # strategy entries are popped below and can only be rebuilt via the add path.+ # Ordinary db models are left alone: wiping them un-served every db model for+ # the width of the reload, and the reconcile converges without it.assert mock_router.delete_deployment.call_count == 2mock_router.delete_deployment.assert_any_call(id="db-model-1")mock_router.delete_deployment.assert_any_call(id="db-model-2")@@ -491,11 +502,70 @@ class TestClearCache:assert "config-router" in mock_router.auto_routersassert "config-router" in mock_router.complexity_routers- # Should have called add_deployment to reload DB models- mock_config.add_deployment.assert_called_once_with(+ # Should have called the already-locked reload to restore DB models+ mock_config._add_deployment_locked.assert_called_once_with(prisma_client=mock_prisma, proxy_logging_obj=mock_logging)+ @pytest.mark.asyncio+ async def test_clear_cache_wipes_auto_routers_but_leaves_ordinary_db_models(self):+ """An ordinary db model must survive clear_cache; a db auto-router must not.++ Two separate hazards meet here, and fixing one naively breaks the other:++ - Wiping ordinary db models un-serves EVERY db model for the width of the+ reload. The reconcile converges without that, so the wipe is a pure+ data-plane hole.+ - NOT wiping a db auto-router strands it. Its strategy registries are keyed by+ model_name and are popped here, but Router.upsert_deployment returns early+ for an unchanged deployment and never reaches the add path that rebuilds+ them. Any unrelated model write would then leave every db-backed auto,+ complexity, adaptive and quality router unroutable until a restart.++ So the wipe is scoped to exactly the auto-router deployments.+ """+ from litellm.proxy.management_endpoints.model_management_endpoints import (+ clear_cache,+ )++ mock_router = MagicMock()+ mock_router.model_list = [+ {+ "model_name": "ordinary-db-model",+ "model_info": {"id": "db-ordinary-1", "db_model": True},+ "litellm_params": {"model": "openai/gpt-4o"},+ },+ {+ "model_name": "db-auto-router",+ "model_info": {"id": "db-auto-1", "db_model": True},+ "litellm_params": {"model": "auto_router/db-auto-router"},+ },+ ]+ mock_router.delete_deployment = MagicMock(return_value=True)+ mock_router.auto_routers = {"db-auto-router": MagicMock()}+ mock_router.complexity_routers = {}+ mock_router.adaptive_routers = {}+ mock_router.quality_routers = {}++ mock_config = MagicMock()+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )++ with (+ patch("litellm.proxy.proxy_server.llm_router", mock_router),+ patch("litellm.proxy.proxy_server.proxy_config", mock_config),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),+ patch("litellm.proxy.proxy_server.verbose_proxy_logger"),+ ):+ await clear_cache()++ # The auto-router deployment is wiped so the reload takes the add path and+ # rebuilds its strategy entry; the ordinary db model is never touched.+ mock_router.delete_deployment.assert_called_once_with(id="db-auto-1")+ assert "db-auto-router" not in mock_router.auto_routers+class TestClearCachePreservesConfigRouters:"""@@ -534,7 +604,9 @@ class TestClearCachePreservesConfigRouters:}mock_config = MagicMock()- mock_config.add_deployment = AsyncMock(return_value=True)+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )with (patch("litellm.proxy.proxy_server.llm_router", mock_router),@@ -574,7 +646,9 @@ class TestClearCachePreservesConfigRouters:mock_router.complexity_routers = {"shared-name": MagicMock()}mock_config = MagicMock()- mock_config.add_deployment = AsyncMock(return_value=True)+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )with (patch("litellm.proxy.proxy_server.llm_router", mock_router),@@ -616,7 +690,9 @@ class TestClearCachePreservesConfigRouters:mock_router.adaptive_routers = {"a1": MagicMock()}mock_config = MagicMock()- mock_config.add_deployment = AsyncMock(return_value=True)+ mock_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )with (patch("litellm.proxy.proxy_server.llm_router", mock_router),@@ -839,7 +915,9 @@ class TestUpdateModel:),patch("litellm.proxy.management_endpoints.model_management_endpoints.clear_cache",- new=AsyncMock(return_value=None),+ new=AsyncMock(+ return_value=ReconcileOutcome(still_desired=None, live_after=None)+ ),) as mock_clear_cache,):await update_model(@@ -1885,7 +1963,9 @@ class TestAddAndDeleteModelLifecycle:mock_prisma.db.litellm_proxymodeltable.delete = AsyncMock(return_value=db_row)mock_proxy_config = MagicMock()- mock_proxy_config.add_deployment = AsyncMock()+ mock_proxy_config._add_deployment_locked = AsyncMock(+ return_value=ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())+ )mock_router = MagicMock()mock_router.delete_deployment = MagicMock()@@ -3223,7 +3303,9 @@ class TestPatchModelBlockedAuthGate:),patch("litellm.proxy.management_endpoints.model_management_endpoints.clear_cache",- new=AsyncMock(return_value=None),+ new=AsyncMock(+ return_value=ReconcileOutcome(still_desired=None, live_after=None)+ ),),):result = await patch_model(@@ -3381,6 +3463,281 @@ class TestWriteSurfacesReloadDrop:)+class TestConcurrentModelWritesDoNotEvictEachOther:+ """Two model writes racing on one pod must not un-serve each other's deployments,+ and neither may report the other's in-flight reload as damage of its own.++ The reconcile is a read-modify-write of the shared ``llm_router`` global: read the db+ into a snapshot, then make the router match that snapshot. Unserialized, the request+ holding the older snapshot deletes the deployment the newer one just added, because+ _delete_deployment evicts every live id absent from the snapshot it was handed. The+ row survives in the db, so the damage is invisible there -- the pod just stops+ serving a model it was told to serve.+ """++ @pytest.mark.asyncio+ async def test_reconciles_serialize_so_no_stale_snapshot_can_evict(self, monkeypatch):+ """MODEL_RECONCILE_LOCK admits one reconcile at a time.++ The fake body awaits, which is the whole point: without the lock the gather below+ parks all five inside the critical section at that await and observed depth goes+ to 5. Asserting depth never exceeds 1 is what pins the fix -- deleting the+ `async with` makes this fail rather than merely getting slower.+ """+ import asyncio++ from litellm.proxy._types import ReconcileOutcome+ from litellm.proxy.proxy_server import ProxyConfig++ depth = 0+ observed_max = 0++ async def fake_locked(self, **kwargs):+ nonlocal depth, observed_max+ depth += 1+ observed_max = max(observed_max, depth)+ await asyncio.sleep(0)+ depth -= 1+ return ReconcileOutcome(still_desired=frozenset(), live_after=frozenset())++ monkeypatch.setattr(ProxyConfig, "_add_deployment_locked", fake_locked)+ config = ProxyConfig()++ await asyncio.gather(+ *[+ config.add_deployment(prisma_client=MagicMock(), proxy_logging_obj=MagicMock())+ for _ in range(5)+ ]+ )++ assert observed_max == 1++ @pytest.mark.asyncio+ async def test_clear_cache_reloads_under_the_lock_without_deadlocking(self, monkeypatch):+ """clear_cache un-serves every db model before reloading, so it has to hold the+ lock across the pair -- and therefore must call the already-locked reload.++ asyncio.Lock is not reentrant: routing this back through the public+ add_deployment would block forever on a lock this coroutine already owns, taking+ every model write on the pod down with it. The timeout is the assertion.+ """+ import asyncio++ import litellm+ from litellm.proxy._types import ReconcileOutcome+ from litellm.proxy.management_endpoints.model_management_endpoints import clear_cache+ from litellm.proxy.proxy_server import ProxyConfig++ live_router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-4o",+ "litellm_params": {"model": "gpt-4o"},+ "model_info": {"id": "m-db", "db_model": True},+ }+ ]+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", live_router)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())++ async def fake_locked(self, **kwargs):+ return ReconcileOutcome(still_desired=frozenset({"m-db"}), live_after=frozenset({"m-db"}))++ monkeypatch.setattr(ProxyConfig, "_add_deployment_locked", fake_locked)++ outcome = await asyncio.wait_for(clear_cache(), timeout=5)++ assert outcome.still_desired == frozenset({"m-db"})+ assert outcome.live_after == frozenset({"m-db"})++ def test_verdict_trusts_the_lock_captured_snapshot_over_a_live_reread(self, monkeypatch):+ """Given live_after, the verdict judges the router as it stood when the reload+ finished -- not as it stands now.++ Re-reading here would sample the router after the lock was released, which is+ exactly where the next writer's clear_cache has every db model deleted and not+ yet re-added. That hole is another request's in-flight state; blaming this+ request's reload for it is the 500 that made concurrent model creates fail.+ """+ import litellm+ from litellm.proxy._types import ProxyException+ from litellm.proxy.management_endpoints.model_management_endpoints import (+ raise_if_reload_degraded_serving,+ reload_serving_verdict,+ )++ # The router as another writer's clear_cache leaves it mid-wipe: db models gone.+ mid_wipe_router = litellm.Router(model_list=[])+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", mid_wipe_router)++ healthy_after_reload = frozenset({"m-live", "m-neighbour"})++ _, collateral = reload_serving_verdict(+ before=frozenset({"m-live", "m-neighbour"}),+ written_models=[("m-live", None)],+ written_must_serve=True,+ still_desired=healthy_after_reload,+ live_after=healthy_after_reload,+ )+ assert collateral == ()++ assert (+ raise_if_reload_degraded_serving(+ before=frozenset({"m-live", "m-neighbour"}),+ written_models=[("m-live", None)],+ action="create",+ still_desired=healthy_after_reload,+ live_after=healthy_after_reload,+ )+ is None+ )++ # Same inputs, no lock-captured snapshot: the mid-wipe router is read live and+ # the neighbour looks like collateral. This is the pre-fix behaviour, kept to+ # show the parameter is what carries the difference.+ with pytest.raises(ProxyException, match="m-neighbour"):+ raise_if_reload_degraded_serving(+ before=frozenset({"m-live", "m-neighbour"}),+ written_models=[("m-live", None)],+ action="create",+ still_desired=healthy_after_reload,+ )+++class TestDeleteEvictionsHoldTheReconcileLock:+ """A delete evicts from ``llm_router`` directly instead of reconciling, so it must+ take MODEL_RECONCILE_LOCK to do it.++ The db row is gone by then, but a reconcile that snapshotted the db BEFORE the row+ was deleted still lists that id as desired, and its ``_add_deployment`` upserts the+ deployment back. Unserialized, the eviction can land while that reconcile is+ mid-flight and simply be undone -- the pod keeps serving a model the database no+ longer has, until the next reconcile happens to notice. Taking the lock orders the+ eviction after any in-flight reconcile, making it the last word.+ """++ @staticmethod+ async def _assert_evicts_under_lock(monkeypatch, call_endpoint, model_id: str) -> None:+ """Run ``call_endpoint`` with the lock already held and assert it blocks.++ Holding MODEL_RECONCILE_LOCK stands in for a reconcile that is mid-flight. If+ the eviction takes the lock it cannot run until we release; if it does not, it+ runs straight through and the deployment is evicted while the "reconcile" is+ still in its critical section -- exactly the interleaving that resurrects it.++ Each test gets a FRESH lock. asyncio.Lock binds itself to the event loop of its+ first contended acquire and raises on every other loop afterwards, so a shared+ module-level lock contended here would poison the next asyncio test in this+ process. The proxy has one event loop for its lifetime, so this is a test-only+ concern -- but it means any future test that contends this lock must patch its+ own, exactly as here.+ """+ lock = asyncio.Lock()+ monkeypatch.setattr("litellm.proxy.proxy_server.MODEL_RECONCILE_LOCK", lock)++ async with lock:+ task = asyncio.create_task(call_endpoint())+ # Give the endpoint every chance to reach (and get stuck on) the lock.+ for _ in range(50):+ await asyncio.sleep(0)+ assert not task.done(), (+ f"deleting {model_id} did not wait for MODEL_RECONCILE_LOCK -- an "+ f"in-flight reconcile can resurrect the deployment it just evicted"+ )+ await asyncio.wait_for(task, timeout=5)++ @pytest.mark.asyncio+ async def test_delete_model_waits_for_an_in_flight_reconcile(self, monkeypatch):+ from litellm.proxy.management_endpoints.model_management_endpoints import (+ ModelInfoDelete,+ delete_model,+ )++ model_id = "m-doomed"+ row = MagicMock()+ row.model_dump.return_value = {+ "model_name": "gpt-4o",+ "litellm_params": {"model": "openai/gpt-4o"},+ "model_info": {"id": model_id},+ }+ table = MagicMock()+ table.find_unique = AsyncMock(return_value=row)+ table.delete = AsyncMock(return_value=row)++ prisma = MagicMock()+ prisma.db.litellm_proxymodeltable = table++ router = MagicMock()+ router.delete_deployment = MagicMock(return_value=True)++ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", router)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)+ monkeypatch.setattr(+ "litellm.proxy.management_endpoints.model_management_endpoints.ModelManagementAuthChecks.can_user_make_model_call",+ AsyncMock(return_value=True),+ )++ async def call() -> None:+ await delete_model(+ model_info=ModelInfoDelete(id=model_id),+ user_api_key_dict=UserAPIKeyAuth(+ user_id="admin",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ api_key="sk-admin",+ ),+ )++ await self._assert_evicts_under_lock(monkeypatch, call, model_id)+ router.delete_deployment.assert_called_once_with(id=model_id)++ @pytest.mark.asyncio+ async def test_delete_team_models_waits_for_an_in_flight_reconcile(self, monkeypatch):+ from litellm.proxy.management_endpoints.model_management_endpoints import (+ delete_team_models,+ )++ model_id = "m-team-doomed"+ router = MagicMock()+ router.delete_deployment = MagicMock(return_value=True)++ # _get_team_deployments filters by the model_name prefix, then confirms+ # model_info["team_id"] Python-side, so the row must satisfy both.+ deleted_row = MagicMock()+ deleted_row.model_id = model_id+ deleted_row.model_name = "model_name_team-1_gpt-4o"+ deleted_row.model_info = {"id": model_id, "team_id": "team-1"}++ tx = MagicMock()+ tx.litellm_proxymodeltable.find_many = AsyncMock(return_value=[deleted_row])+ tx.litellm_proxymodeltable.delete_many = AsyncMock(return_value=1)++ tx_ctx = MagicMock()+ tx_ctx.__aenter__ = AsyncMock(return_value=tx)+ tx_ctx.__aexit__ = AsyncMock(return_value=False)++ prisma = MagicMock()+ prisma.db.tx = MagicMock(return_value=tx_ctx)++ monkeypatch.setattr(+ "litellm.proxy.management_endpoints.model_management_endpoints.publish_config_change",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "litellm.proxy.management_endpoints.model_management_endpoints.coordination_redis_cache",+ MagicMock(return_value=None),+ )++ async def call() -> None:+ await delete_team_models(+ team_ids=["team-1"], prisma_client=prisma, llm_router=router+ )++ await self._assert_evicts_under_lock(monkeypatch, call, model_id)+ router.delete_deployment.assert_called_once_with(id=model_id)++class TestModelInfoAsMapping:"""The model_info column reaches consumers as a dict or as its JSON string; this isthe single owner of that parse, and None means no usable mapping."""diff --git a/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py b/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.pyindex 30fe78d93c7..178e9379ea7 100644--- a/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py+++ b/tests/test_litellm/proxy/management_endpoints/test_ptu_model_settings.py@@ -8,7 +8,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import HTTPException-from litellm.proxy._types import LiteLLM_ProxyModelTable, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy._types import (+ LiteLLM_ProxyModelTable,+ LitellmUserRoles,+ ReconcileOutcome,+ UserAPIKeyAuth,+)from litellm.proxy.management_endpoints.model_management_endpoints import (_merged_ptu_model_info,_raise_if_ptu_cost_attribution_disabled,@@ -623,7 +628,12 @@ class TestAddNewModelPtuGate:add_team_model_to_db = AsyncMock(return_value=db_row)mock_proxy_config = MagicMock()- mock_proxy_config.add_deployment = AsyncMock(return_value=None)+ # Both fields None: no reconcile state was captured, so the serving verdict+ # falls back to reading the router live -- which is what mock_router below+ # drives. These tests are about the PTU gate, not the reload verdict.+ mock_proxy_config.add_deployment = AsyncMock(+ return_value=ReconcileOutcome(still_desired=None, live_after=None)+ )mock_router = MagicMock()mock_router.get_model_ids.return_value = [model_id]diff --git a/tests/test_litellm/test_model_block_unblock.py b/tests/test_litellm/test_model_block_unblock.pyindex ff66bedf0dc..da63ed4a95a 100644--- a/tests/test_litellm/test_model_block_unblock.py+++ b/tests/test_litellm/test_model_block_unblock.py@@ -7,6 +7,7 @@ from litellm.proxy._types import (BlockModelRequest,LitellmUserRoles,ProxyException,+ ReconcileOutcome,UserAPIKeyAuth,)from litellm.types.router import RouterRateLimitError@@ -36,7 +37,12 @@ def _setup_model_block_mocks(monkeypatch, *, updated_blocked: bool):mock_router = MagicMock()mock_router.get_model_ids.return_value = [model_id]- mock_clear_cache = AsyncMock(return_value=None)+ # No reconcile ran in these tests, so both fields are None and the verdict falls+ # back to reading the router live -- which is what the get_model_ids side_effects+ # below drive.+ mock_clear_cache = AsyncMock(+ return_value=ReconcileOutcome(still_desired=None, live_after=None)+ )mock_audit_log = AsyncMock(return_value=None)monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)