Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions litellm/proxy/db/tool_registry_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import ToolDiscoveryQueueItem
from litellm.proxy.db.exception_handler import call_with_db_reconnect_retry
from litellm.types.tool_management import (
LiteLLM_ToolTableRow,
ToolPolicyOverrideRow,
Expand Down Expand Up @@ -307,7 +308,11 @@ def is_initialized(self) -> bool:
async def sync_tool_policy_from_db(self, prisma_client: "PrismaClient") -> None:
"""Load all tool policies and object-permission blocked_tools from DB."""
try:
tools = await prisma_client.db.litellm_tooltable.find_many()
tools = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_tooltable.find_many(),
reason="sync_tool_policy_from_db_tools_lookup_failure",
)
self._tool_input_policies = {
row.tool_name: getattr(row, "input_policy", "untrusted") or "untrusted"
for row in tools
Expand All @@ -317,7 +322,11 @@ async def sync_tool_policy_from_db(self, prisma_client: "PrismaClient") -> None:
for row in tools
}

perms = await prisma_client.db.litellm_objectpermissiontable.find_many()
perms = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_objectpermissiontable.find_many(),
reason="sync_tool_policy_from_db_perms_lookup_failure",
)
self._blocked_tools_by_op_id = {}
for row in perms:
op_id = getattr(row, "object_permission_id", None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
UserAPIKeyAuth,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.db.exception_handler import call_with_db_reconnect_retry
from litellm.types.management_endpoints import (
CACHE_SETTINGS_FIELDS,
REDIS_TYPE_DESCRIPTIONS,
Expand Down Expand Up @@ -159,8 +160,12 @@ async def init_cache_settings_in_db(prisma_client, proxy_config):
import json

try:
cache_config = await prisma_client.db.litellm_cacheconfig.find_unique(
where={"id": "cache_config"}
cache_config = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_cacheconfig.find_unique(
where={"id": "cache_config"}
),
reason="init_cache_settings_in_db_lookup_failure",
)
if cache_config is not None and cache_config.cache_settings:
# Parse cache settings JSON
Expand Down
21 changes: 16 additions & 5 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,10 @@ def generate_feedback_box():
from litellm.proxy.container_endpoints.endpoints import router as container_router
from litellm.proxy.credential_endpoints.endpoints import router as credential_router
from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import SpendLogCleanup
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.db.exception_handler import (
PrismaDBExceptionHandler,
call_with_db_reconnect_retry,
)
from litellm.proxy.db.spend_counter_reseed import SpendCounterReseed
from litellm.proxy.discovery_endpoints import ui_discovery_endpoints_router
from litellm.proxy.fine_tuning_endpoints.endpoints import router as fine_tuning_router
Expand Down Expand Up @@ -5975,8 +5978,12 @@ async def _init_sso_settings_in_db(self, prisma_client: PrismaClient):
"""

try:
sso_settings = await prisma_client.db.litellm_ssoconfig.find_unique(
where={"id": "sso_config"}
sso_settings = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_ssoconfig.find_unique(
where={"id": "sso_config"}
),
reason="init_sso_settings_in_db_lookup_failure",
)
if sso_settings is not None:
sso_settings.sso_settings.pop("role_mappings", None)
Expand Down Expand Up @@ -6011,8 +6018,12 @@ async def _init_hashicorp_vault_config_override(self, prisma_client: PrismaClien
)

try:
db_record = await prisma_client.db.litellm_configoverrides.find_unique(
where={"config_type": "hashicorp_vault"}
db_record = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_configoverrides.find_unique(
where={"config_type": "hashicorp_vault"}
),
reason="init_hashicorp_vault_config_override_lookup_failure",
)

if db_record is None or db_record.config_value is None:
Expand Down
9 changes: 6 additions & 3 deletions litellm/proxy/search_endpoints/search_tool_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from litellm._logging import verbose_proxy_logger
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy.db.exception_handler import call_with_db_reconnect_retry
from litellm.proxy.utils import PrismaClient
from litellm.types.search import SearchTool

Expand Down Expand Up @@ -179,10 +180,12 @@ async def get_all_search_tools_from_db(
List of search tool configurations
"""
try:
search_tools_from_db = (
await prisma_client.db.litellm_searchtoolstable.find_many(
search_tools_from_db = await call_with_db_reconnect_retry(
prisma_client,
lambda: prisma_client.db.litellm_searchtoolstable.find_many(
order={"created_at": "desc"},
)
),
reason="get_all_search_tools_from_db_lookup_failure",
)

search_tools: List[SearchTool] = []
Expand Down
74 changes: 74 additions & 0 deletions tests/test_litellm/proxy/db/test_tool_registry_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,77 @@ async def test_tool_policy_registry_not_initialized_returns_untrusted():
assert not registry.is_initialized()
result = registry.get_effective_policies(["unknown_tool"])
assert result == {"unknown_tool": "untrusted"}


@pytest.mark.asyncio
async def test_sync_tool_policy_from_db_retries_on_transport_error_first_read():
"""`ToolPolicyRegistry.sync_tool_policy_from_db` self-heals across one
ClientNotConnectedError on the tools read — the perms read still fires
after the recovery and the registry initializes cleanly."""
import prisma as prisma_pkg

registry = ToolPolicyRegistry()
invocations: list = []

async def _flaky_find_many():
invocations.append(None)
if len(invocations) == 1:
raise prisma_pkg.errors.ClientNotConnectedError()
return []

mock_prisma_client = MagicMock()
mock_prisma_client.db.litellm_tooltable.find_many = AsyncMock(
side_effect=_flaky_find_many
)
mock_prisma_client.db.litellm_objectpermissiontable.find_many = AsyncMock(
return_value=[]
)
mock_prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)
mock_prisma_client._db_auth_reconnect_timeout_seconds = 2.0
mock_prisma_client._db_auth_reconnect_lock_timeout_seconds = 0.1

await registry.sync_tool_policy_from_db(mock_prisma_client)

assert len(invocations) == 2
mock_prisma_client.attempt_db_reconnect.assert_awaited_once()
reconnect_kwargs = mock_prisma_client.attempt_db_reconnect.await_args.kwargs
assert (
reconnect_kwargs["reason"]
== "sync_tool_policy_from_db_tools_lookup_failure"
)
assert registry.is_initialized()


@pytest.mark.asyncio
async def test_sync_tool_policy_from_db_retries_on_transport_error_second_read():
"""Same as above but the blip happens on the perms read — distinct reason
tag in telemetry confirms the second wrap is wired separately."""
import prisma as prisma_pkg

registry = ToolPolicyRegistry()
perms_invocations: list = []

async def _flaky_perms_find_many():
perms_invocations.append(None)
if len(perms_invocations) == 1:
raise prisma_pkg.errors.ClientNotConnectedError()
return []

mock_prisma_client = MagicMock()
mock_prisma_client.db.litellm_tooltable.find_many = AsyncMock(return_value=[])
mock_prisma_client.db.litellm_objectpermissiontable.find_many = AsyncMock(
side_effect=_flaky_perms_find_many
)
mock_prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)
mock_prisma_client._db_auth_reconnect_timeout_seconds = 2.0
mock_prisma_client._db_auth_reconnect_lock_timeout_seconds = 0.1

await registry.sync_tool_policy_from_db(mock_prisma_client)

assert len(perms_invocations) == 2
mock_prisma_client.attempt_db_reconnect.assert_awaited_once()
reconnect_kwargs = mock_prisma_client.attempt_db_reconnect.await_args.kwargs
assert (
reconnect_kwargs["reason"]
== "sync_tool_policy_from_db_perms_lookup_failure"
)
Comment on lines +361 to +367

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Missing is_initialized() assertion after self-heal

The first-read counterpart test (test_sync_tool_policy_from_db_retries_on_transport_error_first_read) asserts registry.is_initialized() after the retry succeeds, but this second-read test omits that check. Because _initialized = True is only set after both reads complete, a regression that prevents initialization from completing after the perms-read retry would go undetected here.

Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,45 @@ async def test_list_search_tools_db_masking_sensitive_values(monkeypatch):
app.dependency_overrides.pop(user_api_key_auth, None)


@pytest.mark.asyncio
async def test_get_all_search_tools_from_db_retries_on_transport_error():
"""`SearchToolRegistry.get_all_search_tools_from_db` self-heals across one
ClientNotConnectedError via call_with_db_reconnect_retry."""
import prisma
from litellm.proxy.search_endpoints.search_tool_registry import (
SearchToolRegistry,
)

invocations: list = []

async def _flaky_find_many(**kwargs):
invocations.append(None)
if len(invocations) == 1:
raise prisma.errors.ClientNotConnectedError()
return []

mock_prisma_client = MagicMock()
mock_prisma_client.db.litellm_searchtoolstable.find_many = AsyncMock(
side_effect=_flaky_find_many
)
mock_prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)
mock_prisma_client._db_auth_reconnect_timeout_seconds = 2.0
mock_prisma_client._db_auth_reconnect_lock_timeout_seconds = 0.1

result = await SearchToolRegistry.get_all_search_tools_from_db(
prisma_client=mock_prisma_client
)

assert result == []
assert len(invocations) == 2
mock_prisma_client.attempt_db_reconnect.assert_awaited_once()
reconnect_kwargs = mock_prisma_client.attempt_db_reconnect.await_args.kwargs
assert (
reconnect_kwargs["reason"]
== "get_all_search_tools_from_db_lookup_failure"
)


@contextlib.contextmanager
def _mock_search_tool_backend(db_tools):
"""Patch the DB registry, prisma client, and config so /search_tools/list
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,41 @@ async def test_init_cache_settings_in_db_skips_when_params_unchanged(self):
mock_proxy_config._init_cache.assert_not_called()
mock_proxy_config.switch_on_llm_response_caching.assert_not_called()

@pytest.mark.asyncio
async def test_init_cache_settings_in_db_retries_on_transport_error(self):
"""`CacheSettingsManager.init_cache_settings_in_db` self-heals across one
ClientNotConnectedError via call_with_db_reconnect_retry."""
import prisma

invocations: list = []

async def _flaky_find_unique(**kwargs):
invocations.append(None)
if len(invocations) == 1:
raise prisma.errors.ClientNotConnectedError()
return None # No config → function returns early after retry.

mock_prisma_client = MagicMock()
mock_prisma_client.db.litellm_cacheconfig.find_unique = AsyncMock(
side_effect=_flaky_find_unique
)
mock_prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)
mock_prisma_client._db_auth_reconnect_timeout_seconds = 2.0
mock_prisma_client._db_auth_reconnect_lock_timeout_seconds = 0.1
mock_proxy_config = MagicMock()

await CacheSettingsManager.init_cache_settings_in_db(
prisma_client=mock_prisma_client, proxy_config=mock_proxy_config
)

assert len(invocations) == 2
mock_prisma_client.attempt_db_reconnect.assert_awaited_once()
reconnect_kwargs = mock_prisma_client.attempt_db_reconnect.await_args.kwargs
assert (
reconnect_kwargs["reason"]
== "init_cache_settings_in_db_lookup_failure"
)


# ── Audit-log emission for /cache/settings ────────────────────────────────────

Expand Down
Loading
Loading