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]

fix(proxy): single-row read-through resyncs and reload-race hardening

mateo-berriac2db91b0616
diff --git a/litellm/proxy/common_utils/registry_read_through.py b/litellm/proxy/common_utils/registry_read_through.py
index b78106205d4..7ace046ae26 100644
--- a/litellm/proxy/common_utils/registry_read_through.py
+++ b/litellm/proxy/common_utils/registry_read_through.py
@@ -2,16 +2,16 @@
A management write (POST /model/new, /guardrails, /v1/agents) lands on one
replica and reaches Postgres, but sibling replicas only refresh their in-memory
-registries on the periodic config reload or the Redis config-sync resync, both
-of which lag by seconds. A request that uses the new object immediately can
-land on a sibling that has never heard of it and fail with a 400/404.
-
-On a registry miss, callers here fetch the missing object from the DB and load
-it into the local registry before giving up. A short negative-result TTL keeps
-repeated lookups of genuinely unknown names from hammering the DB.
+registries on the periodic config reload, so a request using the new object
+immediately can land on a sibling that has never heard of it and fail 400/404.
+On a registry miss, callers here fetch the missing row from the DB and load it
+into the local registry before giving up. A short negative-result TTL per key
+plus a global resync budget per window bound the DB load from lookups of
+genuinely unknown names.
"""
import asyncio
+import time
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Final
@@ -19,24 +19,57 @@ from litellm._logging import verbose_proxy_logger
from litellm.caching.in_memory_cache import InMemoryCache
if TYPE_CHECKING:
+ from prisma.types import (
+ LiteLLM_AgentsTableInclude,
+ LiteLLM_AgentsTableWhereUniqueInput,
+ LiteLLM_ProxyModelTableWhereInput,
+ )
+
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.agents import AgentResponse
READ_THROUGH_MISS_TTL_SECONDS: Final = 2.0
+READ_THROUGH_RESYNC_WINDOW_SECONDS: Final = 5.0
+READ_THROUGH_MAX_RESYNCS_PER_WINDOW: Final = 20
class RegistryReadThrough:
- __slots__ = ("_lock", "_miss_ttl_seconds", "_recent_misses", "_resync")
+ __slots__ = (
+ "_lock",
+ "_max_resyncs_per_window",
+ "_miss_ttl_seconds",
+ "_recent_misses",
+ "_resync",
+ "_resync_window_seconds",
+ "_window_resyncs",
+ "_window_started_at",
+ )
def __init__(
self,
resync: Callable[[str], Awaitable[bool]],
miss_ttl_seconds: float = READ_THROUGH_MISS_TTL_SECONDS,
+ max_resyncs_per_window: int = READ_THROUGH_MAX_RESYNCS_PER_WINDOW,
+ resync_window_seconds: float = READ_THROUGH_RESYNC_WINDOW_SECONDS,
) -> None:
self._resync = resync
self._miss_ttl_seconds = miss_ttl_seconds
+ self._max_resyncs_per_window = max_resyncs_per_window
+ self._resync_window_seconds = resync_window_seconds
self._lock = asyncio.Lock()
self._recent_misses = InMemoryCache(max_size_in_memory=1000)
+ self._window_started_at = float("-inf")
+ self._window_resyncs = 0
+
+ def _consume_resync_budget(self) -> bool:
+ now: Final = time.monotonic()
+ if now - self._window_started_at >= self._resync_window_seconds:
+ self._window_started_at = now
+ self._window_resyncs = 0
+ if self._window_resyncs >= self._max_resyncs_per_window:
+ return False
+ self._window_resyncs += 1
+ return True
async def attempt(self, key: str) -> bool:
if self._recent_misses.get_cache(key) is not None:
@@ -44,6 +77,14 @@ class RegistryReadThrough:
async with self._lock:
if self._recent_misses.get_cache(key) is not None:
return False
+ if not self._consume_resync_budget():
+ verbose_proxy_logger.warning(
+ "registry read-through for %r skipped: resync budget of %s per %ss exhausted",
+ key,
+ self._max_resyncs_per_window,
+ self._resync_window_seconds,
+ )
+ return False
try:
found: Final = await self._resync(key)
except Exception as e: # noqa: BLE001 # a failed read-through must surface the original miss error, not a 500
@@ -68,9 +109,10 @@ async def _resync_model_deployments(model_name: str) -> bool:
return False
prisma_client: Final = proxy_server.prisma_client
assert prisma_client is not None
- rows: Final = await ModelRepository(prisma_client).table.find_many(
- where={"OR": [{"model_name": model_name}, {"model_id": model_name}]}
- )
+ table: Final = ModelRepository(prisma_client).table
+ name_filter: Final[LiteLLM_ProxyModelTableWhereInput] = {"model_name": model_name}
+ id_filter: Final[LiteLLM_ProxyModelTableWhereInput] = {"model_id": model_name}
+ rows: Final = await table.find_many(where=name_filter) or await table.find_many(where=id_filter)
if not rows:
return False
if proxy_server.llm_router is None:
@@ -85,24 +127,49 @@ async def _resync_model_deployments(model_name: str) -> bool:
async def _resync_guardrails(guardrail_name: str) -> bool:
from litellm.proxy import proxy_server
+ from litellm.proxy.guardrails.guardrail_registry import (
+ IN_MEMORY_GUARDRAIL_HANDLER,
+ GuardrailRegistry,
+ )
if not _db_backed_registries_enabled():
return False
prisma_client: Final = proxy_server.prisma_client
assert prisma_client is not None
- await proxy_server.proxy_config._init_guardrails_in_db(prisma_client=prisma_client)
+ row: Final = await GuardrailRegistry().get_guardrail_by_name_from_db(
+ guardrail_name=guardrail_name, prisma_client=prisma_client
+ )
+ if row is None:
+ return False
+ IN_MEMORY_GUARDRAIL_HANDLER.sync_guardrail_from_db(guardrail=row)
return _initialized_guardrail(guardrail_name) is not None
async def _resync_agents(agent_id_or_name: str) -> bool:
from litellm.proxy import proxy_server
+ from litellm.proxy.agent_endpoints.agent_registry import (
+ agents_table,
+ global_agent_registry,
+ )
+ from litellm.types.agents import AgentResponse
if not _db_backed_registries_enabled():
return False
+ if _agent_from_registry(agent_id_or_name) is not None:
+ return True
prisma_client: Final = proxy_server.prisma_client
assert prisma_client is not None
- await proxy_server.proxy_config._init_agents_in_db(prisma_client=prisma_client)
- return _agent_from_registry(agent_id_or_name) is not None
+ table: Final = agents_table(prisma_client)
+ id_filter: Final[LiteLLM_AgentsTableWhereUniqueInput] = {"agent_id": agent_id_or_name}
+ name_filter: Final[LiteLLM_AgentsTableWhereUniqueInput] = {"agent_name": agent_id_or_name}
+ include_permission: Final[LiteLLM_AgentsTableInclude] = {"object_permission": True}
+ row: Final = await table.find_unique(where=id_filter, include=include_permission) or await table.find_unique(
+ where=name_filter, include=include_permission
+ )
+ if row is None:
+ return False
+ global_agent_registry.register_agent(agent_config=AgentResponse.model_validate(row.model_dump()))
+ return True
model_registry_read_through: Final = RegistryReadThrough(resync=_resync_model_deployments)
diff --git a/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py b/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py
index 6b5e1a5d0b5..8e8545a51cc 100644
--- a/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py
@@ -57,20 +57,20 @@ def _model_table(prisma_client: PrismaClient) -> _ModelTableClient:
return ModelRepository(prisma_client).table
-def validate_models_exist(model_names: list[str], llm_router: "Router | None") -> tuple[bool, list[str]]:
+def validate_models_exist(model_names: Sequence[str], llm_router: "Router | None") -> tuple[bool, Sequence[str]]:
"""
Validate that all requested model names exist in the router.
Checks only exact model name matches.
Returns:
- Tuple[bool, List[str]]: (all_valid, missing_models)
+ (all_valid, missing_models)
"""
if llm_router is None:
return False, model_names
- router_model_names: Final = set(llm_router.get_model_names())
- missing: Final = [m for m in model_names if m not in router_model_names]
- return (len(missing) == 0, missing)
+ router_model_names: Final = frozenset(llm_router.get_model_names())
+ missing: Final = tuple(m for m in model_names if m not in router_model_names)
+ return (not missing, missing)
async def _missing_models_after_read_through(
@@ -81,12 +81,12 @@ async def _missing_models_after_read_through(
model_registry_read_through,
)
- _, missing = validate_models_exist(model_names=list(model_names), llm_router=llm_router)
+ _, missing = validate_models_exist(model_names=model_names, llm_router=llm_router)
if not missing:
return ()
for name in missing:
await model_registry_read_through.attempt(name)
- _, still_missing = validate_models_exist(model_names=list(model_names), llm_router=proxy_server.llm_router)
+ _, still_missing = validate_models_exist(model_names=model_names, llm_router=proxy_server.llm_router)
return tuple(still_missing)
@@ -118,13 +118,21 @@ def _raise_http_if_reload_degraded_serving(
before: frozenset[str],
written_models: Sequence[tuple[str, object]],
access_group: str,
+ still_desired: frozenset[str] | None,
+ live_after: frozenset[str] | None,
) -> None:
"""Same verdict as the model-write endpoints, expressed through this file's
HTTPException error convention, with the metadata-only obligation: these writes
change group membership, not the models themselves, so a row that was already not
serving before the reload is never blamed here; only a model this reload stopped
serving is reported."""
- missing, collateral = reload_serving_verdict(before=before, written_models=written_models, written_must_serve=False)
+ missing, collateral = reload_serving_verdict(
+ before=before,
+ written_models=written_models,
+ written_must_serve=False,
+ still_desired=still_desired,
+ live_after=live_after,
+ )
gone: Final = tuple(dict.fromkeys((*missing, *collateral)))
if not gone:
return
@@ -456,11 +464,13 @@ async def create_model_group(
live_before_reload: Final = live_model_ids_snapshot()
- await clear_cache()
+ reload_outcome: Final = await clear_cache()
_raise_http_if_reload_degraded_serving(
before=live_before_reload,
written_models=updated_pairs,
access_group=data.access_group,
+ still_desired=reload_outcome.still_desired,
+ live_after=reload_outcome.live_after,
)
verbose_proxy_logger.info(
@@ -716,11 +726,13 @@ async def update_access_group(
# Clear cache and reload models to pick up the access group changes
live_before_reload: Final = live_model_ids_snapshot()
- await clear_cache()
+ reload_outcome: Final = await clear_cache()
_raise_http_if_reload_degraded_serving(
before=live_before_reload,
written_models=list({**dict(stripped_pairs), **dict(updated_pairs)}.items()),
access_group=access_group,
+ still_desired=reload_outcome.still_desired,
+ live_after=reload_outcome.live_after,
)
verbose_proxy_logger.info(
@@ -818,11 +830,13 @@ async def delete_access_group(
# Clear cache and reload models to pick up the access group changes
live_before_reload: Final = live_model_ids_snapshot()
- await clear_cache()
+ reload_outcome: Final = await clear_cache()
_raise_http_if_reload_degraded_serving(
before=live_before_reload,
written_models=removed_pairs,
access_group=access_group,
+ still_desired=reload_outcome.still_desired,
+ live_after=reload_outcome.live_after,
)
verbose_proxy_logger.info(
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.py
index 4e7f86b87d5..492c3d750a9 100644
--- a/litellm/proxy/route_llm_request.py
+++ b/litellm/proxy/route_llm_request.py
@@ -458,7 +458,7 @@ async def route_request(
async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited provider coroutines; the inferred union keeps route_request's callers typed
- data: dict, # noqa: LIT001 # request body is the proxy-wide mutable dict contract shared with route_request
+ data: dict, # mutable-ok: request body is the proxy-wide mutable dict contract shared with route_request
llm_router: LitellmRouter | None,
user_model: str | None,
route_type: RouteType,
diff --git a/litellm/router.py b/litellm/router.py
index efd3b5a527e..f3fb7c08d2c 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -8573,11 +8573,9 @@ class Router:
Returns:
- The added/updated deployment
"""
+ _deployment_model_id: Final = deployment.model_info.id or ""
+ _deployment_on_router: Final[Deployment | None] = self.get_deployment(model_id=_deployment_model_id)
try:
- # check if deployment already exists
- _deployment_model_id: Final = deployment.model_info.id or ""
-
- _deployment_on_router: Final[Deployment | None] = self.get_deployment(model_id=_deployment_model_id)
if _deployment_on_router is not None:
# deployment with this model_id exists on the router
if (
@@ -8628,10 +8626,31 @@ class Router:
deployment.model_info.id,
e,
)
+ self._restore_deployment_after_failed_upsert(
+ previous_deployment=_deployment_on_router, model_id=_deployment_model_id
+ )
return None
else:
raise e
+ def _restore_deployment_after_failed_upsert(self, previous_deployment: Deployment | None, model_id: str) -> None:
+ if previous_deployment is None or self.has_model_id(model_id):
+ return
+ try:
+ self.add_deployment(deployment=previous_deployment)
+ verbose_router_logger.info(
+ "Restored deployment %s (id=%s); it keeps serving its previous configuration.",
+ previous_deployment.model_name,
+ model_id,
+ )
+ except Exception as restore_error:
+ verbose_router_logger.warning(
+ "Could not restore previously served deployment %s (id=%s) after the failed upsert: %s",
+ previous_deployment.model_name,
+ model_id,
+ restore_error,
+ )
+
@staticmethod
def _backend_cost_map_keys(model: str, custom_llm_provider: str | None) -> tuple[str, ...]:
"""The ``litellm.model_cost`` keys a deployment's shared backend info is registered under."""
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index 6882479a344..096e039b8aa 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -12,7 +12,7 @@
"limit": 2017
},
"ANN202": {
- "limit": 855
+ "limit": 854
},
"ANN204": {
"limit": 711
diff --git a/tests/test_litellm/proxy/common_utils/test_registry_read_through.py b/tests/test_litellm/proxy/common_utils/test_registry_read_through.py
index e1c8f031579..31b41d5458e 100644
--- a/tests/test_litellm/proxy/common_utils/test_registry_read_through.py
+++ b/tests/test_litellm/proxy/common_utils/test_registry_read_through.py
@@ -94,6 +94,32 @@ async def test_distinct_keys_do_not_share_negative_cache():
assert spy.calls == ["ghost-a", "ghost-b"]
+async def test_resync_budget_exhausted_blocks_resync_without_negative_caching():
+ spy: Final = ResyncSpy(found=False)
+ read_through: Final = RegistryReadThrough(
+ resync=spy, miss_ttl_seconds=60.0, max_resyncs_per_window=2, resync_window_seconds=60.0
+ )
+
+ assert await read_through.attempt("ghost-a") is False
+ assert await read_through.attempt("ghost-b") is False
+ assert await read_through.attempt("ghost-c") is False
+ assert spy.calls == ["ghost-a", "ghost-b"]
+ assert read_through._recent_misses.get_cache("ghost-c") is None
+
+
+async def test_resync_budget_replenishes_after_window():
+ spy: Final = ResyncSpy(found=True)
+ read_through: Final = RegistryReadThrough(resync=spy, max_resyncs_per_window=1, resync_window_seconds=0.05)
+
+ assert await read_through.attempt("model-a") is True
+ assert await read_through.attempt("model-b") is False
+ await asyncio.sleep(0.1)
+ assert await read_through.attempt("model-b") is True
+ assert spy.calls == ["model-a", "model-b"]
+
+
class FakeAgentRow:
def __init__(self, agent_id: str, agent_name: str) -> None:
self.agent_id = agent_id
@@ -101,15 +127,15 @@ class FakeAgentRow:
self.object_permission = None
self.spend = 0.0
- def __iter__(self):
- return iter(
- {
- "agent_id": self.agent_id,
- "agent_name": self.agent_name,
- "agent_card_params": {"name": self.agent_name, "url": "http://db-agent"},
- "litellm_params": {},
- }.items()
- )
+ def model_dump(self):
+ return {
+ "agent_id": self.agent_id,
+ "agent_name": self.agent_name,
+ "agent_card_params": {"name": self.agent_name, "url": "http://db-agent"},
+ "litellm_params": {},
+ "object_permission": None,
+ "spend": self.spend,
+ }
@pytest.fixture
@@ -138,8 +164,8 @@ async def test_get_agent_with_read_through_recovers_agent_created_on_sibling_rep
agent_id: Final = "read-through-db-agent-id"
prisma_client: Final = MagicMock()
- prisma_client.db.litellm_agentstable.find_many = AsyncMock(
- return_value=[FakeAgentRow(agent_id, "read-through-db-agent")]
+ prisma_client.db.litellm_agentstable.find_unique = AsyncMock(
+ return_value=FakeAgentRow(agent_id, "read-through-db-agent")
)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
@@ -149,6 +175,35 @@ async def test_get_agent_with_read_through_recovers_agent_created_on_sibling_rep
assert agent is not None
assert agent.agent_id == agent_id
+ prisma_client.db.litellm_agentstable.find_unique.assert_awaited_once_with(
+ where={"agent_id": agent_id},
+ include={"object_permission": True},
+ )
+
+
+async def test_get_agent_with_read_through_recovers_agent_by_name(clean_agent_registry, monkeypatch):
+ from unittest.mock import AsyncMock, MagicMock
+
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.common_utils.registry_read_through import get_agent_with_read_through
+
+ agent_name: Final = "read-through-db-agent-by-name"
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_agentstable.find_unique = AsyncMock(
+ side_effect=[None, FakeAgentRow("read-through-name-lookup-id", agent_name)]
+ )
+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)
+
+ agent: Final = await get_agent_with_read_through(agent_name)
+
+ assert agent is not None
+ assert agent.agent_name == agent_name
+ prisma_client.db.litellm_agentstable.find_unique.assert_awaited_with(
+ where={"agent_name": agent_name},
+ include={"object_permission": True},
+ )
@pytest.mark.asyncio
@@ -159,11 +214,33 @@ async def test_get_agent_with_read_through_returns_none_for_unknown_agent(clean_
from litellm.proxy.common_utils.registry_read_through import get_agent_with_read_through
prisma_client: Final = MagicMock()
- prisma_client.db.litellm_agentstable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_agentstable.find_unique = AsyncMock(return_value=None)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
assert await get_agent_with_read_through("agent-nobody-created") is None
+ assert prisma_client.db.litellm_agentstable.find_unique.await_count == 2
+
+
+async def test_resync_agents_already_registered_skips_db(clean_agent_registry, monkeypatch):
+ from unittest.mock import AsyncMock, MagicMock
+
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.common_utils.registry_read_through import _resync_agents
+
+ agent_id: Final = "read-through-dedup-agent-id"
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_agentstable.find_unique = AsyncMock(
+ return_value=FakeAgentRow(agent_id, "read-through-dedup-agent")
+ )
+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)
+
+ assert await _resync_agents(agent_id) is True
+ assert await _resync_agents(agent_id) is True
+ assert prisma_client.db.litellm_agentstable.find_unique.await_count == 1
+ assert len(clean_agent_registry.agent_list) == 1
class FakeGuardrailRow:
@@ -200,8 +277,11 @@ async def test_get_guardrail_with_read_through_recovers_guardrail_created_on_sib
guardrail_id: Final = "read-through-db-guardrail-id"
guardrail_name: Final = "read-through-db-guardrail"
prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_guardrailstable.find_unique = AsyncMock(
+ return_value=FakeGuardrailRow(guardrail_id, guardrail_name)
+ )
prisma_client.db.litellm_guardrailstable.find_many = AsyncMock(
- return_value=[FakeGuardrailRow(guardrail_id, guardrail_name)]
+ side_effect=AssertionError("full-table guardrail scan on read-through miss")
)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
@@ -210,6 +290,9 @@ async def test_get_guardrail_with_read_through_recovers_guardrail_created_on_sib
guardrail: Final = await get_initialized_guardrail_with_read_through(guardrail_name=guardrail_name)
assert guardrail is not None
assert guardrail.guardrail_name == guardrail_name
+ prisma_client.db.litellm_guardrailstable.find_unique.assert_awaited_once_with(
+ where={"guardrail_name": guardrail_name}
+ )
finally:
IN_MEMORY_GUARDRAIL_HANDLER.delete_in_memory_guardrail(guardrail_id)
@@ -224,7 +307,7 @@ async def test_get_guardrail_with_read_through_returns_none_for_unknown_guardrai
)
prisma_client: Final = MagicMock()
- prisma_client.db.litellm_guardrailstable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_guardrailstable.find_unique = AsyncMock(return_value=None)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
diff --git a/tests/test_litellm/proxy/management_endpoints/test_access_group_management.py b/tests/test_litellm/proxy/management_endpoints/test_access_group_management.py
index 1722d8c377b..c973c6a8346 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_access_group_management.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_access_group_management.py
@@ -13,6 +13,9 @@ sys.path.insert(
) # Adds the parent directory to the system path
from litellm import Router
+from litellm.proxy.management_endpoints.model_management_endpoints import (
+ ReconcileOutcome,
+)
@pytest.mark.asyncio
@@ -121,7 +124,7 @@ async def test_create_access_group_with_model_ids_tags_only_specific_deployments
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new_callable=AsyncMock,
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
response = await create_model_group(
@@ -186,7 +189,7 @@ async def test_create_access_group_with_model_names_tags_all_deployments():
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new_callable=AsyncMock,
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
response = await create_model_group(
@@ -236,7 +239,7 @@ async def test_create_access_group_model_ids_takes_priority_over_model_names():
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new_callable=AsyncMock,
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
response = await create_model_group(
@@ -313,7 +316,7 @@ async def test_create_access_group_invalid_model_id_returns_400():
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new_callable=AsyncMock,
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
with pytest.raises(HTTPException) as exc_info:
@@ -352,7 +355,7 @@ async def test_create_access_group_surfaces_dropped_models():
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new=AsyncMock(return_value=None),
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
with pytest.raises(HTTPException) as exc_info:
@@ -365,6 +368,50 @@ async def test_create_access_group_surfaces_dropped_models():
assert "deploy-A" in str(exc_info.value.detail)
+
+async def test_create_access_group_trusts_reload_snapshot_over_post_lock_fresh_read():
+ """A concurrent reconcile sampled after the lock is released must not make this
+ write's reload look like it dropped the tagged model: the verdict has to judge from
+ the ReconcileOutcome the reload captured under the lock, not a fresh router read."""
+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
+ from litellm.proxy.management_endpoints.model_access_group_management_endpoints import (
+ create_model_group,
+ )
+ from litellm.types.proxy.management_endpoints.model_management_endpoints import (
+ NewModelGroupRequest,
+ )
+
+ deploy_a = MagicMock(model_id="deploy-A", model_name="gpt-4o", model_info={})
+
+ mock_prisma = MagicMock()
+ mock_prisma.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ mock_prisma.db.litellm_proxymodeltable.find_unique = AsyncMock(return_value=deploy_a)
+ mock_prisma.db.litellm_proxymodeltable.update = AsyncMock()
+
+ concurrently_wiped_router = MagicMock()
+ concurrently_wiped_router.get_model_ids.side_effect = [["deploy-A"], []]
+ with (
+ patch("litellm.proxy.proxy_server.llm_router", concurrently_wiped_router),
+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
+ patch(
+ "litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
+ new=AsyncMock(
+ return_value=ReconcileOutcome(
+ still_desired=frozenset({"deploy-A"}), live_after=frozenset({"deploy-A"})
+ )
+ ),
+ ),
+ ):
+ response = await create_model_group(
+ data=NewModelGroupRequest(access_group="production-models", model_ids=["deploy-A"]),
+ user_api_key_dict=UserAPIKeyAuth(user_id="test_admin", user_role=LitellmUserRoles.PROXY_ADMIN),
+ )
+
+ assert response.models_updated == 1
+ assert concurrently_wiped_router.get_model_ids.call_count == 1
+
+
@pytest.mark.asyncio
async def test_tag_deployment_parses_string_model_info_and_refuses_corrupt():
"""The model_info column can arrive as its JSON string; tagging must parse it rather
@@ -420,7 +467,7 @@ async def test_delete_access_group_ignores_models_that_were_already_dead():
patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new=AsyncMock(return_value=None),
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
response = await delete_access_group(
@@ -474,7 +521,7 @@ async def test_create_access_group_read_through_recovers_model_created_on_siblin
patch("litellm.proxy.proxy_server.store_model_in_db", True),
patch(
"litellm.proxy.management_endpoints.model_access_group_management_endpoints.clear_cache",
- new=AsyncMock(return_value=None),
+ new=AsyncMock(return_value=ReconcileOutcome(still_desired=None, live_after=None)),
),
):
response = await create_model_group(
@@ -485,7 +532,7 @@ async def test_create_access_group_read_through_recovers_model_created_on_siblin
assert response.models_updated == 1
assert response.model_names == [model_name]
assert mock_prisma.db.litellm_proxymodeltable.find_many.await_args_list[0].kwargs["where"] == {
- "OR": [{"model_name": model_name}, {"model_id": model_name}]
+ "model_name": model_name
}
diff --git a/tests/test_litellm/proxy/test_route_a2a_models.py b/tests/test_litellm/proxy/test_route_a2a_models.py
index 770f7857265..0523e796543 100644
--- a/tests/test_litellm/proxy/test_route_a2a_models.py
+++ b/tests/test_litellm/proxy/test_route_a2a_models.py
@@ -116,15 +116,15 @@ class _DbAgentRow:
self.object_permission = None
self.spend = 0.0
- def __iter__(self):
- return iter(
- {
- "agent_id": self.agent_id,
- "agent_name": self.agent_name,
- "agent_card_params": {"name": self.agent_name, "url": "http://sibling-db-agent.example.com"},
- "litellm_params": {},
- }.items()
- )
+ def model_dump(self):
+ return {
+ "agent_id": self.agent_id,
+ "agent_name": self.agent_name,
+ "agent_card_params": {"name": self.agent_name, "url": "http://sibling-db-agent.example.com"},
+ "litellm_params": {},
+ "object_permission": None,
+ "spend": self.spend,
+ }
def _router_without_models():
@@ -149,8 +149,8 @@ async def test_route_a2a_model_read_through_recovers_agent_created_on_sibling_re
agent_name = "a2a-sibling-replica-agent"
prisma_client = Mock()
- prisma_client.db.litellm_agentstable.find_many = AsyncMock(
- return_value=[_DbAgentRow("a2a-sibling-replica-agent-id", agent_name)]
+ prisma_client.db.litellm_agentstable.find_unique = AsyncMock(
+ side_effect=[None, _DbAgentRow("a2a-sibling-replica-agent-id", agent_name)]
)
monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
monkeypatch.setattr(proxy_server, "store_model_in_db", True)
@@ -182,4 +182,4 @@ async def test_route_a2a_model_read_through_recovers_agent_created_on_sibling_re
call_kwargs = mock_acompletion.call_args.kwargs
assert call_kwargs["model"] == f"a2a/{agent_name}"
assert call_kwargs["api_base"] == "http://sibling-db-agent.example.com"
- prisma_client.db.litellm_agentstable.find_many.assert_awaited()
+ prisma_client.db.litellm_agentstable.find_unique.assert_awaited()
diff --git a/tests/test_litellm/proxy/test_route_llm_request.py b/tests/test_litellm/proxy/test_route_llm_request.py
index 8f52fa179fe..15b4f09822a 100644
--- a/tests/test_litellm/proxy/test_route_llm_request.py
+++ b/tests/test_litellm/proxy/test_route_llm_request.py
@@ -1179,7 +1179,7 @@ async def test_route_request_read_through_recovers_model_created_on_sibling_repl
assert response.choices[0].message.content == "hello-from-db"
assert len(table.find_many_wheres) == 1
- assert table.find_many_wheres[0] == {"OR": [{"model_name": model_name}, {"model_id": model_name}]}
+ assert table.find_many_wheres[0] == {"model_name": model_name}
@pytest.mark.asyncio
@@ -1207,7 +1207,7 @@ async def test_route_request_unknown_model_raises_and_hits_db_once_within_ttl(mo
with pytest.raises(ProxyModelNotFoundError):
await route_request(data=data, llm_router=router, user_model=None, route_type="acompletion")
- assert len(table.find_many_wheres) == 1
+ assert table.find_many_wheres == [{"model_name": model_name}, {"model_id": model_name}]
@pytest.mark.asyncio
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index fb8438ccb01..68ad911e792 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -7595,6 +7595,62 @@ def test_pre_call_checks_keeps_deployment_when_provider_is_unresolvable(monkeypa
assert len(result) == 1
+class TestUpsertDeploymentRollback:
+ """
+ Regression tests: `upsert_deployment` pops the previous deployment before
+ re-adding the edited one. When the re-add raises under
+ `ignore_invalid_deployments=True`, the pop must be rolled back so this pod
+ keeps serving the previous configuration instead of silently dropping a live
+ deployment (the "Error upserting deployment" drop behind the access-group
+ reload 500 in the 2-replica e2e suite).
+ """
+
+ def test_failed_upsert_keeps_previous_deployment_serving(self):
+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "prod-model",
+ "litellm_params": {"model": "gpt-4o", "api_key": "sk-old"},
+ "model_info": {"id": "prod-1", "db_model": True},
+ }
+ ],
+ ignore_invalid_deployments=True,
+ )
+
+ result = router.upsert_deployment(
+ deployment=Deployment(
+ model_name="prod-model",
+ litellm_params=LiteLLM_Params(model="auto_router/broken"),
+ model_info=ModelInfo(id="prod-1", db_model=True),
+ )
+ )
+
+ assert result is None
+ restored = router.get_deployment(model_id="prod-1")
+ assert restored is not None
+ assert restored.litellm_params.model == "gpt-4o"
+ assert [model["model_name"] for model in router.model_list] == ["prod-model"]
+
+ def test_failed_fresh_add_returns_none_without_restore(self):
+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
+
+ router = litellm.Router(model_list=[], ignore_invalid_deployments=True)
+
+ result = router.upsert_deployment(
+ deployment=Deployment(
+ model_name="fresh-router",
+ litellm_params=LiteLLM_Params(model="auto_router/broken"),
+ model_info=ModelInfo(id="fresh-1", db_model=True),
+ )
+ )
+
+ assert result is None
+ assert router.get_deployment(model_id="fresh-1") is None
+ assert router.model_list == []
+
+
class TestConsumedRequestTagsStamp:
"""Issue #36621: when a request's tags select a tagged pre-routing strategy, those
tags are consumed by the selection; the hook must stamp the rewritten model group so
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index f8e481dc142..e7cfff93aa4 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -1,9 +1,9 @@
{
"LIT001": {
- "limit": 22894
+ "limit": 22892
},
"LIT002": {
- "limit": 26888
+ "limit": 26886
},
"LIT003": {
"limit": 269
@@ -27,7 +27,7 @@
"limit": 0
},
"LIT010": {
- "limit": 16700
+ "limit": 16699
},
"LIT011": {
"limit": 5590