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): read through to the DB on registry misses so just-created models, guardrails, and agents resolve on sibling replicas
mateo-berri292161f766ca
diff --git a/litellm/proxy/agent_endpoints/a2a_endpoints.py b/litellm/proxy/agent_endpoints/a2a_endpoints.pyindex 27780aeb994..a4e1ac126d9 100644--- a/litellm/proxy/agent_endpoints/a2a_endpoints.py+++ b/litellm/proxy/agent_endpoints/a2a_endpoints.py@@ -152,14 +152,13 @@ def _jsonrpc_error()-def _get_agent(agent_id: str):+async def _get_agent(agent_id: str) -> "AgentResponse | None":"""Look up an agent by ID or name. Returns None if not found."""- from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry+ from litellm.proxy.common_utils.registry_read_through import (+ get_agent_with_read_through,+ )- agent = global_agent_registry.get_agent_by_id(agent_id=agent_id)- if agent is None:- agent = global_agent_registry.get_agent_by_name(agent_name=agent_id)- return agent+ return await get_agent_with_read_through(agent_id)def _enforce_inbound_trace_id(agent: Any, request: Request) -> None:@@ -531,7 +530,7 @@ async def get_agent_card()try:- agent: Final = _get_agent(agent_id)+ agent: Final = await _get_agent(agent_id)if agent is None:raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")@@ -645,7 +644,7 @@ async def invoke_agent_a2a(params.pop(key)# Find the agent- agent: Final = _get_agent(agent_id)+ agent: Final = await _get_agent(agent_id)if agent is None:return _jsonrpc_error(request_id, -32000, f"Agent '{agent_id}' not found", 404)diff --git a/litellm/proxy/agent_endpoints/a2a_routing.py b/litellm/proxy/agent_endpoints/a2a_routing.pyindex 038b6b4a840..2228735d805 100644--- a/litellm/proxy/agent_endpoints/a2a_routing.py+++ b/litellm/proxy/agent_endpoints/a2a_routing.py@@ -25,10 +25,12 @@ async def route_a2a_agent_request(Returns None if not an A2A request (allows normal routing to continue)."""# Import here to avoid circular imports- from litellm.proxy.agent_endpoints.agent_registry import global_agent_registryfrom litellm.proxy.agent_endpoints.auth.agent_permission_handler import (AgentRequestHandler,)+ from litellm.proxy.common_utils.registry_read_through import (+ get_agent_with_read_through,+ )from litellm.proxy.route_llm_request import (ROUTE_ENDPOINT_MAPPING,ProxyModelNotFoundError,@@ -44,7 +46,7 @@ async def route_a2a_agent_request(agent_name: Final = model_name[4:]# Look up agent in registry- agent: Final = global_agent_registry.get_agent_by_name(agent_name)+ agent: Final = await get_agent_with_read_through(agent_name)if agent is None:verbose_proxy_logger.error("[A2A] Agent '%s' not found in registry", agent_name)route_name = ROUTE_ENDPOINT_MAPPING.get(route_type, route_type)diff --git a/litellm/proxy/common_utils/registry_read_through.py b/litellm/proxy/common_utils/registry_read_through.pynew file mode 100644index 00000000000..b78106205d4--- /dev/null+++ b/litellm/proxy/common_utils/registry_read_through.py@@ -0,0 +1,143 @@+"""Read-through recovery for in-memory registries in multi-replica deployments.++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.+"""++import asyncio+from collections.abc import Awaitable, Callable+from typing import TYPE_CHECKING, Final++from litellm._logging import verbose_proxy_logger+from litellm.caching.in_memory_cache import InMemoryCache++if TYPE_CHECKING:+ from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.types.agents import AgentResponse++READ_THROUGH_MISS_TTL_SECONDS: Final = 2.0+++class RegistryReadThrough:+ __slots__ = ("_lock", "_miss_ttl_seconds", "_recent_misses", "_resync")++ def __init__(+ self,+ resync: Callable[[str], Awaitable[bool]],+ miss_ttl_seconds: float = READ_THROUGH_MISS_TTL_SECONDS,+ ) -> None:+ self._resync = resync+ self._miss_ttl_seconds = miss_ttl_seconds+ self._lock = asyncio.Lock()+ self._recent_misses = InMemoryCache(max_size_in_memory=1000)++ async def attempt(self, key: str) -> bool:+ if self._recent_misses.get_cache(key) is not None:+ return False+ async with self._lock:+ if self._recent_misses.get_cache(key) is not None:+ 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+ verbose_proxy_logger.warning("registry read-through for %r failed: %s", key, e)+ return False+ if not found:+ self._recent_misses.set_cache(key, True, ttl=self._miss_ttl_seconds)+ return found+++def _db_backed_registries_enabled() -> bool:+ from litellm.proxy import proxy_server++ return proxy_server.prisma_client is not None and proxy_server.store_model_in_db is True+++async def _resync_model_deployments(model_name: str) -> bool:+ from litellm.proxy import proxy_server+ from litellm.repositories.model_repository import ModelRepository++ if not _db_backed_registries_enabled():+ 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}]}+ )+ if not rows:+ return False+ if proxy_server.llm_router is None:+ await proxy_server.proxy_config.add_deployment(+ prisma_client=prisma_client, proxy_logging_obj=proxy_server.proxy_logging_obj+ )+ return proxy_server.llm_router is not None+ proxy_server.proxy_config._add_deployment(db_models=rows)+ proxy_server.llm_model_list = proxy_server.llm_router.get_model_list()+ return True+++async def _resync_guardrails(guardrail_name: str) -> bool:+ from litellm.proxy import proxy_server++ 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)+ return _initialized_guardrail(guardrail_name) is not None+++async def _resync_agents(agent_id_or_name: str) -> bool:+ from litellm.proxy import proxy_server++ 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_agents_in_db(prisma_client=prisma_client)+ return _agent_from_registry(agent_id_or_name) is not None+++model_registry_read_through: Final = RegistryReadThrough(resync=_resync_model_deployments)+guardrail_registry_read_through: Final = RegistryReadThrough(resync=_resync_guardrails)+agent_registry_read_through: Final = RegistryReadThrough(resync=_resync_agents)+++def _agent_from_registry(agent_id_or_name: str) -> "AgentResponse | None":+ from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry++ by_id: Final = global_agent_registry.get_agent_by_id(agent_id=agent_id_or_name)+ if by_id is not None:+ return by_id+ return global_agent_registry.get_agent_by_name(agent_name=agent_id_or_name)+++async def get_agent_with_read_through(agent_id_or_name: str) -> "AgentResponse | None":+ agent: Final = _agent_from_registry(agent_id_or_name)+ if agent is not None:+ return agent+ if not await agent_registry_read_through.attempt(agent_id_or_name):+ return None+ return _agent_from_registry(agent_id_or_name)+++def _initialized_guardrail(guardrail_name: str) -> "CustomGuardrail | None":+ from litellm.proxy.guardrails import guardrail_endpoints++ return guardrail_endpoints.GUARDRAIL_REGISTRY.get_initialized_guardrail_callback(guardrail_name=guardrail_name)+++async def get_initialized_guardrail_with_read_through(guardrail_name: str) -> "CustomGuardrail | None":+ active: Final = _initialized_guardrail(guardrail_name)+ if active is not None:+ return active+ if not await guardrail_registry_read_through.attempt(guardrail_name):+ return None+ return _initialized_guardrail(guardrail_name)diff --git a/litellm/proxy/guardrails/guardrail_endpoints.py b/litellm/proxy/guardrails/guardrail_endpoints.pyindex 761d8aabc8a..dff70ccf68d 100644--- a/litellm/proxy/guardrails/guardrail_endpoints.py+++ b/litellm/proxy/guardrails/guardrail_endpoints.py@@ -2244,8 +2244,12 @@ async def apply_guardrail(litellm_logging_obj = Nonestart_time: Final = datetime.now(timezone.utc)+ from litellm.proxy.common_utils.registry_read_through import (+ get_initialized_guardrail_with_read_through,+ )+try:- active_guardrail: Final[CustomGuardrail | None] = GUARDRAIL_REGISTRY.get_initialized_guardrail_callback(+ active_guardrail: Final[CustomGuardrail | None] = await get_initialized_guardrail_with_read_through(guardrail_name=request.guardrail_name)if active_guardrail is None:diff --git a/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py b/litellm/proxy/management_endpoints/model_access_group_management_endpoints.pyindex 7051f705a03..75d33c6c40a 100644--- a/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py+++ b/litellm/proxy/management_endpoints/model_access_group_management_endpoints.py@@ -7,7 +7,10 @@ Endpoints here:import jsonfrom collections.abc import Mapping, Sequence-from typing import Any, Final+from typing import TYPE_CHECKING, Any, Final++if TYPE_CHECKING:+ from litellm.router import Routerfrom fastapi import APIRouter, Depends, HTTPException@@ -52,6 +55,23 @@ def validate_models_exist(model_names: list[str], llm_router) -> tuple[bool, lisreturn (len(missing) == 0, missing)+async def _missing_models_after_read_through(+ model_names: Sequence[str], llm_router: "Router | None"+) -> tuple[str, ...]:+ from litellm.proxy import proxy_server+ from litellm.proxy.common_utils.registry_read_through import (+ model_registry_read_through,+ )++ _, missing = validate_models_exist(model_names=list(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)+ return tuple(still_missing)++def add_access_group_to_deployment(model_info: dict[str, Any], access_group: str) -> tuple[dict[str, Any], bool]:"""Add an access group to a deployment's model_info.@@ -369,12 +389,12 @@ async def create_model_group(# Validate model_names exist in router (only if using model_names path)if not use_model_ids and has_model_names:assert data.model_names is not None- all_valid, missing_models = validate_models_exist(+ missing_models: Final = await _missing_models_after_read_through(model_names=data.model_names,llm_router=llm_router,)- if not all_valid:+ if missing_models:raise HTTPException(status_code=400,detail={"error": f"Model(s) not found: {', '.join(missing_models)}"},@@ -633,12 +653,12 @@ async def update_access_group(# Validation: Check if all new models exist (only if using model_names path)if not use_model_ids and has_model_names:assert data.model_names is not None- all_valid, missing_models = validate_models_exist(+ missing_models: Final = await _missing_models_after_read_through(model_names=data.model_names,llm_router=llm_router,)- if not all_valid:+ if missing_models:raise HTTPException(status_code=400,detail={"error": f"Model(s) not found: {', '.join(missing_models)}"},diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex dd8deed57f1..657e0cbcafa 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -313,112 +313,150 @@ async def add_shared_session_to_data(data: dict) -> None:pass+RouteType = Literal[+ "acompletion",+ "atext_completion",+ "aembedding",+ "aimage_generation",+ "aspeech",+ "atranscription",+ "amoderation",+ "arerank",+ "aresponses",+ "aget_responses",+ "adelete_responses",+ "acancel_responses",+ "acompact_responses",+ "acreate_response_reply",+ "alist_input_items",+ "_arealtime", # private function for realtime API+ "acreate_realtime_client_secret",+ "arealtime_calls",+ "acreate_realtime_transcription_session",+ "_aresponses_websocket", # private function for responses WebSocket mode+ "aimage_edit",+ "agenerate_content",+ "agenerate_content_stream",+ "allm_passthrough_route",+ "acreate_batch",+ "aretrieve_batch",+ "alist_batches",+ "afile_content",+ "afile_retrieve",+ "acreate_fine_tuning_job",+ "acancel_fine_tuning_job",+ "alist_fine_tuning_jobs",+ "aretrieve_fine_tuning_job",+ "avector_store_search",+ "avector_store_create",+ "avector_store_retrieve",+ "avector_store_list",+ "avector_store_update",+ "avector_store_delete",+ "avector_store_file_create",+ "avector_store_file_list",+ "avector_store_file_retrieve",+ "avector_store_file_content",+ "avector_store_file_update",+ "avector_store_file_delete",+ "aocr",+ "asearch",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",+ "avideo_create_character",+ "avideo_get_character",+ "avideo_edit",+ "avideo_extension",+ "acreate_container",+ "alist_containers",+ "aretrieve_container",+ "adelete_container",+ "aupload_container_file",+ "alist_container_files",+ "aretrieve_container_file",+ "adelete_container_file",+ "aretrieve_container_file_content",+ "acreate_skill",+ "alist_skills",+ "aget_skill",+ "adelete_skill",+ "aingest",+ "anthropic_messages",+ "acreate_interaction",+ "aget_interaction",+ "adelete_interaction",+ "acancel_interaction",+ "acreate_agent",+ "alist_agents",+ "aget_agent",+ "adelete_agent",+ "alist_agent_versions",+ "asend_message",+ "call_mcp_tool",+ "acancel_batch",+ "afile_delete",+ "acreate_eval",+ "alist_evals",+ "aget_eval",+ "aupdate_eval",+ "adelete_eval",+ "acancel_eval",+ "acreate_run",+ "alist_runs",+ "aget_run",+ "acancel_run",+ "adelete_run",+]++async def route_request(data: dict,llm_router: LitellmRouter | None,user_model: str | None,- route_type: Literal[- "acompletion",- "atext_completion",- "aembedding",- "aimage_generation",- "aspeech",- "atranscription",- "amoderation",- "arerank",- "aresponses",- "aget_responses",- "adelete_responses",- "acancel_responses",- "acompact_responses",- "acreate_response_reply",- "alist_input_items",- "_arealtime", # private function for realtime API- "acreate_realtime_client_secret",- "arealtime_calls",- "acreate_realtime_transcription_session",- "_aresponses_websocket", # private function for responses WebSocket mode- "aimage_edit",- "agenerate_content",- "agenerate_content_stream",- "allm_passthrough_route",- "acreate_batch",- "aretrieve_batch",- "alist_batches",- "afile_content",- "afile_retrieve",- "acreate_fine_tuning_job",- "acancel_fine_tuning_job",- "alist_fine_tuning_jobs",- "aretrieve_fine_tuning_job",- "avector_store_search",- "avector_store_create",- "avector_store_retrieve",- "avector_store_list",- "avector_store_update",- "avector_store_delete",- "avector_store_file_create",- "avector_store_file_list",- "avector_store_file_retrieve",- "avector_store_file_content",- "avector_store_file_update",- "avector_store_file_delete",- "aocr",- "asearch",- "avideo_generation",- "avideo_list",- "avideo_status",- "avideo_content",- "avideo_remix",- "avideo_create_character",- "avideo_get_character",- "avideo_edit",- "avideo_extension",- "acreate_container",- "alist_containers",- "aretrieve_container",- "adelete_container",- "aupload_container_file",- "alist_container_files",- "aretrieve_container_file",- "adelete_container_file",- "aretrieve_container_file_content",- "acreate_skill",- "alist_skills",- "aget_skill",- "adelete_skill",- "aingest",- "anthropic_messages",- "acreate_interaction",- "aget_interaction",- "adelete_interaction",- "acancel_interaction",- "acreate_agent",- "alist_agents",- "aget_agent",- "adelete_agent",- "alist_agent_versions",- "asend_message",- "call_mcp_tool",- "acancel_batch",- "afile_delete",- "acreate_eval",- "alist_evals",- "aget_eval",- "aupdate_eval",- "adelete_eval",- "acancel_eval",- "acreate_run",- "alist_runs",- "aget_run",- "acancel_run",- "adelete_run",- ],+ route_type: RouteType,user_api_key_dict: UserAPIKeyAuth | None = None,):"""Common helper to route the request"""+ try:+ return await _route_request_single_attempt(+ data=data,+ llm_router=llm_router,+ user_model=user_model,+ route_type=route_type,+ user_api_key_dict=user_api_key_dict,+ )+ except ProxyModelNotFoundError:+ requested_model: Final = data.get("model", "")+ if not isinstance(requested_model, str) or not requested_model:+ raise+ from litellm.proxy import proxy_server+ from litellm.proxy.common_utils.registry_read_through import (+ model_registry_read_through,+ )++ if not await model_registry_read_through.attempt(requested_model):+ raise+ return await _route_request_single_attempt(+ data=data,+ llm_router=proxy_server.llm_router,+ user_model=user_model,+ route_type=route_type,+ user_api_key_dict=user_api_key_dict,+ )+++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+ llm_router: LitellmRouter | None,+ user_model: str | None,+ route_type: RouteType,+ user_api_key_dict: UserAPIKeyAuth | None = None,+):raise_if_required_body_param_missing(route_type=route_type, data=data)await add_shared_session_to_data(data)diff --git a/ruff.toml b/ruff.tomlindex 095e3e24c52..bd3f8334e94 100644--- a/ruff.toml+++ b/ruff.toml@@ -6,7 +6,7 @@ lint.extend-select = ["T20", "PGH004", "RUF008", "RUF009", "RUF100"]# litellm's own ruff config both rely on suppressions this config can't see.lint.external = [# Enforced by the strict-rule gate (scripts/ruff_strict_gate.py + ruff-strict.toml)- "C901", "TID251",+ "ANN202", "C901", "TID251",# Enforced by upstream litellm's ruff config, but not run in this repo's CI"PLC0415", "E402", "BLE001", "ARG002", "S102", "S324", "S606", "D401", "F403", "F405",]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.pynew file mode 100644index 00000000000..e1c8f031579--- /dev/null+++ b/tests/test_litellm/proxy/common_utils/test_registry_read_through.py@@ -0,0 +1,231 @@+import asyncio+from typing import Final++import pytest++from litellm.proxy.common_utils.registry_read_through import RegistryReadThrough+++class ResyncSpy:+ def __init__(self, found: bool = True, error: Exception | None = None) -> None:+ self.found = found+ self.error = error+ self.calls: list[str] = []++ async def __call__(self, key: str) -> bool:+ self.calls.append(key)+ if self.error is not None:+ raise self.error+ return self.found+++async def test_attempt_returns_true_when_resync_finds_object():+ spy: Final = ResyncSpy(found=True)+ read_through: Final = RegistryReadThrough(resync=spy)++ assert await read_through.attempt("new-model") is True+ assert spy.calls == ["new-model"]+++async def test_attempt_found_key_is_not_negative_cached():+ spy: Final = ResyncSpy(found=True)+ read_through: Final = RegistryReadThrough(resync=spy)++ assert await read_through.attempt("new-model") is True+ assert await read_through.attempt("new-model") is True+ assert spy.calls == ["new-model", "new-model"]+++async def test_missing_key_is_negative_cached_within_ttl():+ spy: Final = ResyncSpy(found=False)+ read_through: Final = RegistryReadThrough(resync=spy, miss_ttl_seconds=60.0)++ assert await read_through.attempt("ghost-model") is False+ assert await read_through.attempt("ghost-model") is False+ assert spy.calls == ["ghost-model"]+++async def test_negative_cache_expires_and_resync_runs_again():+ spy: Final = ResyncSpy(found=False)+ read_through: Final = RegistryReadThrough(resync=spy, miss_ttl_seconds=0.05)++ assert await read_through.attempt("ghost-model") is False+ await asyncio.sleep(0.1)+ assert await read_through.attempt("ghost-model") is False+ assert spy.calls == ["ghost-model", "ghost-model"]+++async def test_resync_exception_returns_false_without_negative_caching():+ spy: Final = ResyncSpy(error=RuntimeError("db down"))+ read_through: Final = RegistryReadThrough(resync=spy)++ assert await read_through.attempt("new-model") is False+ assert await read_through.attempt("new-model") is False+ assert spy.calls == ["new-model", "new-model"]+++async def test_concurrent_attempts_for_missing_key_resync_once():+ class SlowResyncSpy(ResyncSpy):+ async def __call__(self, key: str) -> bool:+ await asyncio.sleep(0.05)+ return await super().__call__(key)++ spy: Final = SlowResyncSpy(found=False)+ read_through: Final = RegistryReadThrough(resync=spy, miss_ttl_seconds=60.0)++ results: Final = await asyncio.gather(*(read_through.attempt("ghost-model") for _ in range(5)))+ assert results == [False] * 5+ assert spy.calls == ["ghost-model"]+++async def test_distinct_keys_do_not_share_negative_cache():+ spy: Final = ResyncSpy(found=False)+ read_through: Final = RegistryReadThrough(resync=spy, miss_ttl_seconds=60.0)++ assert await read_through.attempt("ghost-a") is False+ assert await read_through.attempt("ghost-b") is False+ assert spy.calls == ["ghost-a", "ghost-b"]+++class FakeAgentRow:+ def __init__(self, agent_id: str, agent_name: str) -> None:+ self.agent_id = agent_id+ self.agent_name = agent_name+ 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 clean_agent_registry():+ from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry++ original_agents: Final = list(global_agent_registry.agent_list)+ original_config_agents: Final = getattr(global_agent_registry, "config_agents", ())+ global_agent_registry.agent_list = []+ global_agent_registry.config_agents = ()+ try:+ yield global_agent_registry+ finally:+ global_agent_registry.agent_list = original_agents+ global_agent_registry.config_agents = original_config_agents+++async def test_get_agent_with_read_through_recovers_agent_created_on_sibling_replica(+ 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_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")]+ )+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)++ assert clean_agent_registry.get_agent_by_id(agent_id=agent_id) is None+ agent: Final = await get_agent_with_read_through(agent_id)++ assert agent is not None+ assert agent.agent_id == agent_id+++async def test_get_agent_with_read_through_returns_none_for_unknown_agent(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++ prisma_client: Final = MagicMock()+ prisma_client.db.litellm_agentstable.find_many = AsyncMock(return_value=[])+ 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+++class FakeGuardrailRow:+ def __init__(self, guardrail_id: str, guardrail_name: str) -> None:+ self.guardrail_id = guardrail_id+ self.guardrail_name = guardrail_name++ def __iter__(self):+ return iter(+ {+ "guardrail_id": self.guardrail_id,+ "guardrail_name": self.guardrail_name,+ "litellm_params": {+ "guardrail": "litellm_content_filter",+ "mode": "pre_call",+ "default_on": True,+ "blocked_words": [{"keyword": "secret", "action": "BLOCK"}],+ },+ "guardrail_info": {},+ }.items()+ )+++async def test_get_guardrail_with_read_through_recovers_guardrail_created_on_sibling_replica(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_initialized_guardrail_with_read_through,+ )+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLER++ 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_many = AsyncMock(+ return_value=[FakeGuardrailRow(guardrail_id, guardrail_name)]+ )+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)++ try:+ guardrail: Final = await get_initialized_guardrail_with_read_through(guardrail_name=guardrail_name)+ assert guardrail is not None+ assert guardrail.guardrail_name == guardrail_name+ finally:+ IN_MEMORY_GUARDRAIL_HANDLER.delete_in_memory_guardrail(guardrail_id)+++async def test_get_guardrail_with_read_through_returns_none_for_unknown_guardrail(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_initialized_guardrail_with_read_through,+ )++ prisma_client: Final = MagicMock()+ prisma_client.db.litellm_guardrailstable.find_many = AsyncMock(return_value=[])+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)++ assert await get_initialized_guardrail_with_read_through(guardrail_name="guardrail-nobody-created") is Nonediff --git a/tests/test_litellm/proxy/management_endpoints/test_access_group_management.py b/tests/test_litellm/proxy/management_endpoints/test_access_group_management.pyindex 3240ad20edb..1722d8c377b 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@@ -430,3 +430,99 @@ async def test_delete_access_group_ignores_models_that_were_already_dead():assert response.models_updated == 1mock_prisma.db.litellm_proxymodeltable.update.assert_awaited_once()+++async def test_create_access_group_read_through_recovers_model_created_on_sibling_replica():+ """Regression: an access group referencing a model that another replica just wrote+ to the DB must be created instead of 400ing until the periodic config reload."""+ 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,+ )++ from types import SimpleNamespace++ model_name = "e2e-ag-sibling-replica-model"+ db_row = SimpleNamespace(+ model_id=f"{model_name}-id",+ model_name=model_name,+ litellm_params={"model": "openai/gpt-4o", "api_key": "fake", "mock_response": "hi"},+ model_info={},+ blocked=False,+ )++ mock_router = Router(+ model_list=[+ {+ "model_name": "some-other-model",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"},+ }+ ]+ )++ mock_prisma = MagicMock()+ mock_prisma.db.litellm_proxymodeltable.find_many = AsyncMock(side_effect=[[db_row], [], [db_row]])+ mock_prisma.db.litellm_proxymodeltable.update = AsyncMock()++ with (+ patch("litellm.proxy.proxy_server.llm_router", mock_router),+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),+ 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),+ ),+ ):+ response = await create_model_group(+ data=NewModelGroupRequest(access_group="replica-lag-group", model_names=[model_name]),+ user_api_key_dict=UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN),+ )++ 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}]+ }+++async def test_create_access_group_model_missing_everywhere_still_400s():+ from fastapi import HTTPException++ 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,+ )++ model_name = "e2e-ag-model-nobody-created"+ mock_router = Router(+ model_list=[+ {+ "model_name": "some-other-model",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"},+ }+ ]+ )+ mock_prisma = MagicMock()+ mock_prisma.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])++ with (+ patch("litellm.proxy.proxy_server.llm_router", mock_router),+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),+ patch("litellm.proxy.proxy_server.store_model_in_db", True),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await create_model_group(+ data=NewModelGroupRequest(access_group="ghost-group", model_names=[model_name]),+ user_api_key_dict=UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN),+ )++ assert exc_info.value.status_code == 400+ assert model_name in str(exc_info.value.detail)diff --git a/tests/test_litellm/proxy/test_route_a2a_models.py b/tests/test_litellm/proxy/test_route_a2a_models.pyindex 616fa62cda5..22f99d03d21 100644--- a/tests/test_litellm/proxy/test_route_a2a_models.py+++ b/tests/test_litellm/proxy/test_route_a2a_models.py@@ -49,6 +49,7 @@ async def test_route_a2a_model_bypasses_router():)mock_registry = Mock()+ mock_registry.get_agent_by_id = Mock(return_value=None)mock_registry.get_agent_by_name = Mock(return_value=mock_agent)# Mock litellm.acompletion to verify it's called@@ -104,3 +105,77 @@ async def test_route_non_a2a_model_raises_error_if_not_in_router():user_model=None,route_type="acompletion",)+++class _DbAgentRow:+ def __init__(self, agent_id: str, agent_name: str) -> None:+ self.agent_id = agent_id+ self.agent_name = agent_name+ 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 _router_without_models():+ mock_router = Mock()+ mock_router.model_names = []+ mock_router.deployment_names = []+ mock_router.has_model_id = Mock(return_value=False)+ mock_router.model_group_alias = None+ mock_router.router_general_settings = Mock(pass_through_all_models=False)+ mock_router.default_deployment = None+ mock_router.pattern_router = Mock(patterns=[])+ mock_router.map_team_model = Mock(return_value=None)+ return mock_router+++async def test_route_a2a_model_read_through_recovers_agent_created_on_sibling_replica(monkeypatch):+ import litellm.proxy.proxy_server as proxy_server+ from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry++ 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)]+ )+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)++ original_agents = list(global_agent_registry.agent_list)+ original_config_agents = getattr(global_agent_registry, "config_agents", ())+ global_agent_registry.agent_list = []+ global_agent_registry.config_agents = ()++ data = {+ "model": f"a2a/{agent_name}",+ "messages": [{"role": "user", "content": "Hello"}],+ }+ mock_acompletion = AsyncMock(return_value={"id": "read-through-response"})++ try:+ with patch("litellm.acompletion", mock_acompletion):+ await route_request(+ data=data,+ llm_router=_router_without_models(),+ user_model=None,+ route_type="acompletion",+ )+ finally:+ global_agent_registry.agent_list = original_agents+ global_agent_registry.config_agents = original_config_agents++ mock_acompletion.assert_called_once()+ 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()diff --git a/tests/test_litellm/proxy/test_route_llm_request.py b/tests/test_litellm/proxy/test_route_llm_request.pyindex 3ae0e1e7d18..ebd52c448bc 100644--- a/tests/test_litellm/proxy/test_route_llm_request.py+++ b/tests/test_litellm/proxy/test_route_llm_request.py@@ -1091,3 +1091,124 @@ async def test_route_request_rejects_chat_completion_without_messages():assert exc_info.value.status_code == 400assert exc_info.value.param == "messages"llm_router.acompletion.assert_not_called()+++class FakeProxyModelTable:+ def __init__(self, rows):+ self.rows = rows+ self.find_many_wheres = []++ async def find_many(self, where=None, **kwargs):+ self.find_many_wheres.append(where)+ return list(self.rows)+++def _fake_prisma_client_with_models(rows):+ from types import SimpleNamespace++ table = FakeProxyModelTable(rows)+ return SimpleNamespace(db=SimpleNamespace(litellm_proxymodeltable=table)), table+++def _db_model_row(model_name: str, mock_response: str):+ from types import SimpleNamespace++ return SimpleNamespace(+ model_id=f"{model_name}-id",+ model_name=model_name,+ litellm_params={"model": "openai/gpt-4o", "api_key": "fake", "mock_response": mock_response},+ model_info={},+ blocked=False,+ )+++async def test_route_request_read_through_recovers_model_created_on_sibling_replica(monkeypatch):+ """Regression: a model written to the DB by another replica must be served on+ first request instead of 400ing until the periodic config reload."""+ import litellm+ import litellm.proxy.proxy_server as proxy_server++ model_name = "e2e-sibling-replica-model"+ router = litellm.Router(+ model_list=[+ {+ "model_name": "some-other-model",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"},+ }+ ]+ )+ fake_prisma, table = _fake_prisma_client_with_models([_db_model_row(model_name, "hello-from-db")])+ monkeypatch.setattr(proxy_server, "prisma_client", fake_prisma)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)+ monkeypatch.setattr(proxy_server, "llm_router", router)++ llm_call = await route_request(+ data={"model": model_name, "messages": [{"role": "user", "content": "hi"}]},+ llm_router=router,+ user_model=None,+ route_type="acompletion",+ )+ response = await llm_call++ 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}]}+++async def test_route_request_unknown_model_raises_and_hits_db_once_within_ttl(monkeypatch):+ import litellm+ import litellm.proxy.proxy_server as proxy_server++ model_name = "e2e-model-nobody-created"+ router = litellm.Router(+ model_list=[+ {+ "model_name": "some-other-model",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"},+ }+ ]+ )+ fake_prisma, table = _fake_prisma_client_with_models([])+ monkeypatch.setattr(proxy_server, "prisma_client", fake_prisma)+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)+ monkeypatch.setattr(proxy_server, "llm_router", router)++ data = {"model": model_name, "messages": [{"role": "user", "content": "hi"}]}+ with pytest.raises(ProxyModelNotFoundError):+ await route_request(data=data, llm_router=router, user_model=None, route_type="acompletion")+ 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+++async def test_route_request_read_through_disabled_without_store_model_in_db(monkeypatch):+ import litellm+ import litellm.proxy.proxy_server as proxy_server++ model_name = "e2e-config-only-proxy-model"+ router = litellm.Router(+ model_list=[+ {+ "model_name": "some-other-model",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"},+ }+ ]+ )+ fake_prisma, table = _fake_prisma_client_with_models([_db_model_row(model_name, "should-not-load")])+ monkeypatch.setattr(proxy_server, "prisma_client", fake_prisma)+ monkeypatch.setattr(proxy_server, "store_model_in_db", False)+ monkeypatch.setattr(proxy_server, "llm_router", router)++ with pytest.raises(ProxyModelNotFoundError):+ await route_request(+ data={"model": model_name, "messages": [{"role": "user", "content": "hi"}]},+ llm_router=router,+ user_model=None,+ route_type="acompletion",+ )++ assert table.find_many_wheres == []