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): only treat a recoverable database outage as grounds to serve without one (#35864)
Yassin Kortamc3a8962c0033
diff --git a/litellm/proxy/db/exception_handler.py b/litellm/proxy/db/exception_handler.pyindex 3965f5b2979..8991c3e0125 100644--- a/litellm/proxy/db/exception_handler.py+++ b/litellm/proxy/db/exception_handler.py@@ -35,21 +35,52 @@ class PrismaDBExceptionHandler:@staticmethoddef is_database_connection_error(e: Exception) -> bool:- """True iff the exception is (or could be) a DB-connectivity- failure, i.e. something that justifies the- ``allow_requests_on_db_unavailable`` HA fallback.+ """True only for a database that is temporarily unreachable and is+ expected to come back on its own.++ This is the gate for ``allow_requests_on_db_unavailable``, which lets+ the proxy keep serving, and issue fallback identities, without a+ verified database. Only a transient outage justifies that. A fault that+ will never resolve by itself, such as a query engine that is missing or+ version-skewed, a malformed query the client library built, or a+ transaction used incorrectly, must surface rather than be absorbed into+ an indefinite degraded mode.++ Membership is an allowlist, so an unrecognized failure is treated as+ permanent. A genuine outage reaches the caller as one of+ ``DB_CONNECTION_ERROR_TYPES``: the engine is a local HTTP server, and an+ unreachable database surfaces as a transport error against it rather+ than as a prisma type.++ Reporting decisions want the opposite breadth; use+ ``is_database_infrastructure_error`` for those.+ """+ import prisma.engine.errors++ if isinstance(e, DB_CONNECTION_ERROR_TYPES):+ return True+ if isinstance(e, prisma.engine.errors.EngineConnectionError):+ return True+ return isinstance(e, ProxyException) and e.type == ProxyErrorTypes.no_db_connection++ @staticmethod+ def is_database_infrastructure_error(e: Exception) -> bool:+ """True when the failure came from the database or its query engine+ rather than from the caller's request.++ This answers a reporting question, not a serving one: should the caller+ be told the service is at fault, or that their request was. It stays+ deliberately broad, because a permanently faulted engine is still a+ service problem, and reporting one as a credential failure sends an+ operator looking in the wrong place. Widening it can only change which+ error a caller sees; it never grants access.Known data-layer PrismaError subclasses (``UniqueViolationError``,- ``RecordNotFoundError``, etc.) are explicitly excluded — the DB IS- reachable, so a fallback that grants an anonymous token would be- an auth bypass. Unknown / bare ``PrismaError`` instances default- to True so genuine outages that don't match a specific subclass- still trigger the fallback.+ ``RecordNotFoundError``, etc.) are excluded — the DB IS reachable and+ the request itself is what failed."""import prisma- # Explicit data-layer exclusion: DB IS reachable, fallback must- # NOT fire.data_layer_errors: Final = (prisma.errors.DataError,prisma.errors.UniqueViolationError,@@ -194,7 +225,7 @@ class PrismaDBExceptionHandler:"""import asyncio- if PrismaDBExceptionHandler.is_database_connection_error(e):+ if PrismaDBExceptionHandler.is_database_infrastructure_error(e):return Trueif PrismaDBExceptionHandler.is_database_transport_error(e):return Truediff --git a/litellm/proxy/management_endpoints/access_group_endpoints.py b/litellm/proxy/management_endpoints/access_group_endpoints.pyindex d242145b37c..c00c2a5ba4c 100644--- a/litellm/proxy/management_endpoints/access_group_endpoints.py+++ b/litellm/proxy/management_endpoints/access_group_endpoints.py@@ -611,7 +611,7 @@ async def delete_access_group(access_group_id,e,)- if PrismaDBExceptionHandler.is_database_connection_error(e):+ if PrismaDBExceptionHandler.is_database_infrastructure_error(e):raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail=CommonProxyErrors.db_not_connected_error.value,diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 46bb6e14a40..cdd41d2ed42 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -4962,7 +4962,7 @@ class PrismaClient:except asyncio.CancelledError:breakexcept Exception as e:- if isinstance(e, asyncio.TimeoutError) or PrismaDBExceptionHandler.is_database_connection_error(e):+ if isinstance(e, asyncio.TimeoutError) or PrismaDBExceptionHandler.is_database_infrastructure_error(e):await self.attempt_db_reconnect(reason="db_health_watchdog_connection_error",timeout_seconds=self._db_watchdog_reconnect_timeout_seconds,diff --git a/tests/test_litellm/proxy/auth/test_auth_exception_handler.py b/tests/test_litellm/proxy/auth/test_auth_exception_handler.pyindex 11e6f483e35..27798ec0bff 100644--- a/tests/test_litellm/proxy/auth/test_auth_exception_handler.py+++ b/tests/test_litellm/proxy/auth/test_auth_exception_handler.py@@ -4,9 +4,15 @@ import osimport sysfrom unittest.mock import AsyncMock, MagicMock, patch+import httpximport pytestfrom fastapi import HTTPException, Request, statusfrom prisma import errors as prisma_errors+from prisma.engine.errors import (+ BinaryNotFoundError,+ EngineConnectionError,+ MismatchedVersionsError,+)from prisma.errors import (ClientNotConnectedError,DataError,@@ -31,19 +37,20 @@ from litellm.proxy.auth.auth_exception_handler import UserAPIKeyAuthExceptionHan@pytest.mark.asyncio@pytest.mark.parametrize(- "prisma_error",+ "db_error",[- # Specific connectivity subclasses.- HTTPClientClosedError(),- ClientNotConnectedError(),- # Bare / generic PrismaError defaults to connectivity — we can't- # tell what it is, so err on the safe side for genuine outages.- PrismaError(),+ pytest.param(httpx.ConnectError("All connection attempts failed"), id="ConnectError"),+ pytest.param(httpx.ReadError("read failed"), id="ReadError"),+ pytest.param(httpx.ReadTimeout("timed out"), id="ReadTimeout"),+ pytest.param(EngineConnectionError(), id="EngineConnectionError"),],)-async def test_handle_authentication_error_db_unavailable_connectivity(prisma_error):- """Transport-level / connectivity failures (and generic PrismaError)- trigger the HA fallback."""+async def test_handle_authentication_error_db_unavailable_connectivity(db_error):+ """A database that is temporarily unreachable triggers the HA fallback.++ These are the failures a real outage actually produces: the query engine is+ a local HTTP server, so an unreachable database surfaces as a transport+ error against it."""handler = UserAPIKeyAuthExceptionHandler()mock_request = MagicMock()@@ -52,7 +59,7 @@ async def test_handle_authentication_error_db_unavailable_connectivity(prisma_er{"allow_requests_on_db_unavailable": True},):result = await handler._handle_authentication_error(- prisma_error,+ db_error,mock_request,{},"/test",@@ -63,6 +70,52 @@ async def test_handle_authentication_error_db_unavailable_connectivity(prisma_erassert result.token == "failed-to-connect-to-db"+ "prisma_error",+ [+ pytest.param(BinaryNotFoundError("query engine binary not found"), id="BinaryNotFoundError"),+ pytest.param(MismatchedVersionsError(expected="1", got="2"), id="MismatchedVersionsError"),+ pytest.param(HTTPClientClosedError(), id="HTTPClientClosedError"),+ pytest.param(ClientNotConnectedError(), id="ClientNotConnectedError"),+ pytest.param(PrismaError(), id="bare_PrismaError"),+ ],+)+async def test_handle_authentication_error_permanent_fault_gets_no_fallback_identity(+ prisma_error,+):+ """A fault that cannot resolve on its own must not mint a fallback identity,+ even with ``allow_requests_on_db_unavailable`` enabled.++ That setting trades verification for availability on the assumption the+ database returns. When it never will, the trade buys nothing and the proxy+ would keep admitting callers it cannot verify for as long as it runs, so the+ fault has to reach the caller instead.++ It must still reach them as a service failure. Denying the fallback is not+ licence to report a database fault as a rejected credential, which would+ send an operator hunting a key problem that does not exist."""+ handler = UserAPIKeyAuthExceptionHandler()++ mock_request = MagicMock()+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {"allow_requests_on_db_unavailable": True},+ ):+ with pytest.raises(ProxyException) as exc_info:+ await handler._handle_authentication_error(+ prisma_error,+ mock_request,+ {},+ "/test",+ None,+ "test-key",+ )++ assert exc_info.value.type == ProxyErrorTypes.no_db_connection+ assert exc_info.value.code == str(status.HTTP_503_SERVICE_UNAVAILABLE)++@pytest.mark.asyncio@pytest.mark.parametrize("prisma_error",diff --git a/tests/test_litellm/proxy/db/test_exception_handler.py b/tests/test_litellm/proxy/db/test_exception_handler.pyindex 23099177812..a188289bfce 100644--- a/tests/test_litellm/proxy/db/test_exception_handler.py+++ b/tests/test_litellm/proxy/db/test_exception_handler.py@@ -4,6 +4,7 @@ import osimport sysfrom unittest.mock import MagicMock, patch+import httpximport pytestfrom fastapi import HTTPException, Request, statusfrom prisma import errors as prisma_errors@@ -41,11 +42,13 @@ from litellm.proxy.db.exception_handler import PrismaDBExceptionHandlerPrismaError("timed out while connecting"),],)-def test_is_database_connection_error_prisma_connection_errors(prisma_error):+def test_is_database_infrastructure_error_prisma_connection_errors(prisma_error):"""- Test that only Prisma connection-related errors are considered DB connection errors.+ Test that Prisma failures originating below the request are reported as+ infrastructure faults, so a caller is told the service failed rather than+ that its credentials did."""- assert PrismaDBExceptionHandler.is_database_connection_error(prisma_error) == True+ assert PrismaDBExceptionHandler.is_database_infrastructure_error(prisma_error) == True@pytest.mark.parametrize(@@ -398,7 +401,7 @@ def test_handle_db_exception_with_connection_error():"""Test that DB connection errors are handled gracefully when allow_requests_on_db_unavailable is True"""- db_error = ClientNotConnectedError()+ db_error = httpx.ConnectError("All connection attempts failed")result = PrismaDBExceptionHandler.handle_db_exception(db_error)assert result is None@@ -411,8 +414,8 @@ def test_handle_db_exception_raises_error():"""Test that DB connection errors are raised when allow_requests_on_db_unavailable is False"""- db_error = ClientNotConnectedError()- with pytest.raises(ClientNotConnectedError):+ db_error = httpx.ConnectError("All connection attempts failed")+ with pytest.raises(httpx.ConnectError):PrismaDBExceptionHandler.handle_db_exception(db_error)@@ -426,3 +429,123 @@ def test_handle_db_exception_with_non_db_error():)with pytest.raises(litellm.BudgetExceededError):PrismaDBExceptionHandler.handle_db_exception(regular_error)+++def _permanent_prisma_faults():+ """Every prisma error class that is not a transient outage and not a+ data-layer error, built by enumeration so the list cannot drift out of sync+ with the installed prisma version."""+ import inspect++ from prisma import engine as prisma_engine++ payload = {"user_facing_error": {"meta": {"target": ["x"]}}, "error_message": "boom"}++ class _Response:+ status = 422++ def build(cls):+ attempts = (+ ((), {}),+ ((payload,), {}),+ (("x",), {}),+ (("x", "y"), {}),+ ((_Response(),), {}),+ ((_Response(), "body"), {}),+ ((), {"expected": "1", "got": "2"}),+ )+ for args, kwargs in attempts:+ try:+ return cls(*args, **kwargs)+ except Exception:+ continue+ return None++ discovered = {}+ for module in (prisma_errors, prisma_engine.errors):+ for name, obj in vars(module).items():+ if inspect.isclass(obj) and issubclass(obj, BaseException) and obj.__module__.startswith("prisma"):+ discovered[name] = obj++ faults = []+ for name, cls in sorted(discovered.items()):+ if issubclass(cls, prisma_engine.errors.EngineConnectionError):+ continue+ instance = build(cls)+ if instance is None or not PrismaDBExceptionHandler.is_database_infrastructure_error(instance):+ continue+ faults.append(pytest.param(instance, id=name))+ return faults+++PERMANENT_PRISMA_FAULTS = _permanent_prisma_faults()+++def test_permanent_fault_enumeration_is_not_empty():+ """Guards the parametrized tests below: if the enumeration silently found+ nothing, those tests would pass without asserting anything."""+ assert len(PERMANENT_PRISMA_FAULTS) >= 15++[email protected]("prisma_error", PERMANENT_PRISMA_FAULTS)+def test_permanent_prisma_faults_are_not_transient(prisma_error):+ """A fault that cannot resolve on its own must not qualify a request to be+ served without a verified database.++ ``allow_requests_on_db_unavailable`` trades verification for availability on+ the assumption the database returns. A missing or version-skewed query+ engine, a malformed generated query, or a misused transaction never returns,+ so absorbing one turns a bounded degraded window into a permanent one."""+ assert PrismaDBExceptionHandler.is_database_connection_error(prisma_error) is False++[email protected]("prisma_error", PERMANENT_PRISMA_FAULTS)+def test_permanent_prisma_faults_are_still_reported_as_service_problems(prisma_error):+ """Narrowing what may be served without a database must not change what the+ caller is told.++ A permanently faulted engine is still the service's fault, so it has to keep+ reaching the reporting predicate that renders it as unavailable rather than+ as a rejected credential."""+ assert PrismaDBExceptionHandler.is_database_infrastructure_error(prisma_error) is True+ assert PrismaDBExceptionHandler.is_database_service_unavailable_error(prisma_error) is True+++ "transient_error",+ [+ pytest.param(httpx.ConnectError("All connection attempts failed"), id="ConnectError"),+ pytest.param(httpx.ReadError("read failed"), id="ReadError"),+ pytest.param(httpx.ReadTimeout("timed out"), id="ReadTimeout"),+ pytest.param(prisma_errors.HTTPClientClosedError(), id="HTTPClientClosedError_is_not_transient"),+ ],+)+def test_genuine_outage_still_qualifies_for_the_fallback(transient_error):+ """The httpx transport errors are how a real outage actually reaches the+ caller: the query engine is a local HTTP server, so an unreachable database+ surfaces as a transport failure against it rather than as a prisma type.+ Narrowing the classifier must leave that path intact."""+ expected = not isinstance(transient_error, prisma_errors.HTTPClientClosedError)+ assert PrismaDBExceptionHandler.is_database_connection_error(transient_error) is expected+++def test_engine_connection_error_is_the_transient_prisma_type():+ """``EngineConnectionError`` is the one prisma class that means the engine+ could not reach the database and may succeed later."""+ from prisma.engine.errors import EngineConnectionError++ assert PrismaDBExceptionHandler.is_database_connection_error(EngineConnectionError()) is True+++@patch(+ "litellm.proxy.proxy_server.general_settings",+ {"allow_requests_on_db_unavailable": True},+)+def test_handle_db_exception_surfaces_a_permanent_fault_even_when_degraded_mode_is_enabled():+ """The startup gate must not boot a proxy whose engine is permanently+ faulted. Absorbing it produces a process that reports healthy and persists+ nothing, indefinitely, with no error for an operator to find."""+ from prisma.engine.errors import BinaryNotFoundError++ with pytest.raises(BinaryNotFoundError):+ PrismaDBExceptionHandler.handle_db_exception(BinaryNotFoundError("query engine binary not found"))diff --git a/tests/test_litellm/proxy/db/test_prisma_self_heal.py b/tests/test_litellm/proxy/db/test_prisma_self_heal.pyindex 7f723fa3ae0..e8e7568d6d8 100644--- a/tests/test_litellm/proxy/db/test_prisma_self_heal.py+++ b/tests/test_litellm/proxy/db/test_prisma_self_heal.py@@ -290,7 +290,7 @@ async def test_db_health_watchdog_should_trigger_reconnect_on_db_error(AsyncMock(side_effect=[None, asyncio.CancelledError()]),),patch(- "litellm.proxy.db.exception_handler.PrismaDBExceptionHandler.is_database_connection_error",+ "litellm.proxy.db.exception_handler.PrismaDBExceptionHandler.is_database_infrastructure_error",return_value=True,),):@@ -321,7 +321,7 @@ async def test_db_health_watchdog_should_trigger_reconnect_on_probe_timeout(AsyncMock(side_effect=[None, asyncio.CancelledError()]),),patch(- "litellm.proxy.db.exception_handler.PrismaDBExceptionHandler.is_database_connection_error",+ "litellm.proxy.db.exception_handler.PrismaDBExceptionHandler.is_database_infrastructure_error",return_value=False,),):