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): force prisma recreate on postgres cached-plan error (#36428)
devin-ai-integration[bot]865ed9676579
diff --git a/litellm/proxy/db/routing_prisma_wrapper.py b/litellm/proxy/db/routing_prisma_wrapper.pyindex 8287ef1addf..5aeb52be535 100644--- a/litellm/proxy/db/routing_prisma_wrapper.py+++ b/litellm/proxy/db/routing_prisma_wrapper.py@@ -103,6 +103,17 @@ class RoutingPrismaWrapper:def reader(self) -> PrismaWrapper:return self._reader+ @property+ def read_target(self) -> PrismaWrapper:+ """The wrapper `_TOP_LEVEL_READ_METHODS` dispatch to right now.++ Callers that need to reason about the engine a read actually ran on+ (e.g. recovering from prepared statements that went stale on it) must+ consult this rather than `writer`, and `__getattr__` routes through it+ so the two cannot drift apart.+ """+ return self._writer if self._reader_unavailable else self._reader+@propertydef reader_unavailable(self) -> bool:return self._reader_unavailable@@ -254,8 +265,7 @@ class RoutingPrismaWrapper:def __getattr__(self, name: str) -> Any:if name in _TOP_LEVEL_READ_METHODS:- target: Final = self._writer if self._reader_unavailable else self._reader- return getattr(target, name)+ return getattr(self.read_target, name)writer_attr: Final = getattr(self._writer, name)# Per-model action accessors are non-callable instances that expose# both `find_many` and `create`. Methods like execute_raw / batch_ /diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex d3ca2fa64ed..ec1aa262736 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -16,6 +16,7 @@ from dataclasses import dataclass, fieldfrom datetime import date, datetime, timedelta, timezonefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, Optional, TypeVar, Union, cast, overloadfrom litellm import _custom_logger_compatible_callbacks_literal@@ -3006,6 +3007,62 @@ async def prefetch_config_params(prisma_client: "PrismaClient | None", param_nam)+class _ForcedRecreateDeclined(Exception):+ """A forced recreate was declined by the engine-generation guard.++ Distinct from a reconnect *failure*: the machinery worked, it just found+ that another path had already replaced the writer, so it left the engines+ alone. The caller's engine may still be poisoned, so the cycle must not+ report success, but it must not count as a failure either, or the record+ of what could not be repaired would gate the retry that recovers.+ """+++@dataclass(frozen=True, slots=True)+class _StaleReadEngine:+ """The read engine a query observed, identified rather than only counted.++ `PrismaClient.read_db` resolves to the reader while it is available and to+ the writer once it is not, and the two carry independent generation+ counters that both start at zero and advance on the same reconnect+ cadence. A bare generation compared across that switch would silently pit+ one engine's counter against another's, so the wrapper is carried with the+ number and a switch counts as the engine having moved.++ Holding the wrapper itself rather than its `id()` is load-bearing, not+ incidental: the strong reference keeps the wrapper alive, so its address+ cannot be recycled under a stored observation and match an unrelated+ engine later. It is only free because writer and reader both live as long+ as the client does; a replaceable reader would make this a retention leak.+ """++ wrapper: PrismaWrapper+ generation: int++ @classmethod+ def observe(cls, wrapper: PrismaWrapper) -> "_StaleReadEngine":+ return cls(wrapper=wrapper, generation=wrapper.engine_generation)++ def is_still_live(self, current: PrismaWrapper) -> bool:+ """Whether this exact engine is still serving reads, unreplaced.++ A True answer must never be the only thing standing between a poisoned+ engine and its repair. The generation moves only after a replacement+ connects, and a recreate whose connect raises leaves it unmoved until+ some later recreate succeeds, so this can report an engine as live+ after it has stopped working. What bounds that is the failed-repair+ record in `_cooldown_applies`, written by a repair attempt that fails+ rather than by whatever broke the engine: the two need not be the same+ recreate, since the synchronous token-refresh fallback in+ `PrismaWrapper.__getattr__` recreates outside the reconnect machinery+ and records nothing. The record is written only for callers that named+ an engine, and it collapses the rest of the burst for up to one+ cooldown window rather than guaranteeing a repair, since the cooldown+ conjunct underneath it still expires and lets a later caller retry.+ """+ return self.wrapper is current and self.generation == current.engine_generation++class PrismaClient:spend_log_transactions: list = []_spend_log_transactions_lock = asyncio.Lock()@@ -3153,6 +3210,14 @@ class PrismaClient:float(os.getenv("PRISMA_AUTH_RECONNECT_LOCK_TIMEOUT_SECONDS", "0.1")),)self._consecutive_reconnect_failures: int = 0+ # Last generation of each read engine whose repair was attempted and+ # failed. Scoped to the engine rather than counted globally so an+ # unrelated reconnect failure cannot suppress a stale reader's+ # recovery, and keyed per wrapper rather than held in one slot so a+ # writer failure cannot evict the reader's record and hand the waiver+ # back to a caller whose engine is still unrepaired. Bounded at two+ # entries: a client has one writer and at most one reader.+ self._failed_recreate_generations: Mapping[PrismaWrapper, int] = MappingProxyType({})self._reconnect_escalation_threshold: int = max(1, int(os.getenv("PRISMA_RECONNECT_ESCALATION_THRESHOLD", "3")))self._engine_pidfd: int = -1self._engine_pid: int = 0@@ -3168,6 +3233,19 @@ class PrismaClient:return self.db.writerreturn self.db+ @property+ def read_db(self) -> PrismaWrapper:+ """Underlying wrapper that top-level reads are dispatched to.++ Identical to `writer_db` without a read replica. With one configured+ it is the reader, which is the engine `query_first` actually runs on,+ so anything reasoning about the state of the connection that served a+ read has to consult this rather than the writer.+ """+ if isinstance(self.db, RoutingPrismaWrapper):+ return self.db.read_target+ return self.db+def tx(self) -> "TransactionManager":"""Open an interactive transaction on the writer.@@ -3391,18 +3469,30 @@ class PrismaClient:`attempt_db_reconnect`, which is singleflight: when a schema changepoisons every pooled connection at once, the first cached-plan errorrecreates the client and the concurrent waiters reuse that single- recreate instead of racing to kill each other's fresh engine. We then- retry the identical query exactly once.+ recreate instead of racing to kill each other's fresh engine. We pass+ `force_recreate` so the reconnect skips its `SELECT 1` liveness probe:+ the connection is healthy here, it is the prepared statements on it+ that are stale, so a passing probe would otherwise skip the recreate+ and leave the retry to hit the same error. We then retry the identical+ query exactly once.The retry reuses the original query byte-for-byte. Mutating the SQL(e.g. injecting a unique comment) would defeat PostgreSQL's plan cache,forcing a fresh plan on every request and pegging the database CPU.- If the reconnect is skipped because a recent reconnect is still within- its cooldown, the retry runs against the same connection and may fail- again; the get_data backoff decorator re-runs the lookup and a later- attempt reconnects once the cooldown elapses.+ The reconnect cooldown must not gate the engine this query itself saw+ as stale, or a migration landing within the cooldown of an earlier+ reconnect leaves auth failing until it elapses. The engine observed+ before the query names it, so the reconnect bypasses the cooldown only+ while that same engine is still the live one.++ It is observed from `read_db`, not `writer_db`: `query_first` is a+ top-level read, so with a read replica configured it runs on the reader+ and it is the reader's prepared statements that went stale. Naming the+ writer here would let an unrelated writer reconnect re-arm the cooldown+ while the reader stayed poisoned."""+ stale_read_engine: Final = _StaleReadEngine.observe(self.read_db)try:return await self.db.query_first(sql_query, *args)except Exception as e:@@ -3414,7 +3504,11 @@ class PrismaClient:"query. This may occur during rolling deployments when schema ""changes are applied.")- await self.attempt_db_reconnect(reason="postgres_cached_plan_error")+ await self.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=stale_read_engine,+ )return await self.db.query_first(sql_query, *args)@backoff.on_exception(@@ -4697,7 +4791,11 @@ class PrismaClient:self._cleanup_engine_watcher()asyncio.create_task(self._start_engine_watcher())- async def _run_reconnect_cycle(self, timeout_seconds: float | None = None) -> None:+ async def _run_reconnect_cycle(+ self,+ timeout_seconds: float | None = None,+ force_recreate: bool = False,+ ) -> None:"""Run a reconnect cycle with a single overall timeout budget.@@ -4708,6 +4806,11 @@ class PrismaClient:the client via the non-blocking kill-then-construct flow rather thancalling disconnect(), which blocks the event loop on the synchronoussubprocess.Popen.wait() inside prisma-client-py (see issue #26191).++ `force_recreate` skips the direct path's liveness probe, for callers+ whose failure lives in the session state rather than the connection+ (stale prepared statements after a schema change): a reachable writer+ proves nothing about those, so the probe must not veto the recreate."""effective_timeout: Final = (timeout_seconds if timeout_seconds is not None else self._db_watchdog_reconnect_timeout_seconds@@ -4747,8 +4850,29 @@ class PrismaClient:# direct path there is no SELECT 1 probe here, so the generation# guard is the only thing standing between a crash-reconnect and# a refresh that raced it.- await self.db.recreate_prisma_client(db_url, expected_generation=expected_generation)+ recreated: Final = await self.db.recreate_prisma_client(db_url, expected_generation=expected_generation)await self._start_engine_watcher()+ # Same contract as the direct path below: a forced caller asked+ # for its engine to be replaced, so a decline is not a success.+ # Reachable here because the escalation threshold flips+ # `_engine_confirmed_dead`, which routes the next cycle, forced+ # callers included, down this branch.+ if force_recreate is True and recreated is False:+ # Clear the dead-engine flag first, restoring the policy the+ # non-forced path already has: a decline does not raise for+ # it, so it falls through to the clear below. Only the+ # forced branch would strand the flag, and stranding it+ # routes the next cycle back down this probe-free branch,+ # where the refreshed generation now matches and the+ # recreate kills the healthy engine a refresh just spawned+ # (#29176). This has to stay AFTER `_start_engine_watcher`+ # above: clearing the flag while the watcher is still torn+ # down would be worse than either alone.+ self._engine_confirmed_dead = False+ raise _ForcedRecreateDeclined(+ "Forced Prisma recreate declined by the generation guard; "+ "the engine that failed was not replaced"+ )await asyncio.wait_for(_do_heavy_reconnect(), timeout=effective_timeout)# Only clear the "dead engine" flag after the heavy reconnect@@ -4773,44 +4897,106 @@ class PrismaClient:# detect a refresh that landed since cycle entry and skip the# redundant restart.writer: Final = self.writer_db- try:- await writer.query_raw("SELECT 1")- verbose_proxy_logger.info(- "Writer healthy on probe; skipping recreate (engine "- "likely already replaced by a token refresh)."- )- if isinstance(self.db, RoutingPrismaWrapper):- self.db.mark_writer_recovered()- await self._start_engine_watcher()- return- except Exception as probe_err:- verbose_proxy_logger.warning(- "Writer probe failed (%s); recreating Prisma client.",- probe_err,- )+ if force_recreate is False:+ try:+ await writer.query_raw("SELECT 1")+ verbose_proxy_logger.info(+ "Writer healthy on probe; skipping recreate (engine "+ "likely already replaced by a token refresh)."+ )+ if isinstance(self.db, RoutingPrismaWrapper):+ self.db.mark_writer_recovered()+ await self._start_engine_watcher()+ return+ except Exception as probe_err:+ verbose_proxy_logger.warning(+ "Writer probe failed (%s); recreating Prisma client.",+ probe_err,+ )# Fresh Prisma client + new engine subprocess. The previous# "lightweight" path called `disconnect()` which blocks the# event loop on `subprocess.Popen.wait()`; since that call# ends up killing the engine anyway, we do it non-blockingly# via `_kill_engine_process` inside `recreate_prisma_client`.self._cleanup_engine_watcher()- await self.db.recreate_prisma_client(db_url, expected_generation=expected_generation)+ recreated: Final = await self.db.recreate_prisma_client(db_url, expected_generation=expected_generation)await self._start_engine_watcher()# Smoke-test the writer specifically; query_raw on the routing# wrapper sends to the reader, which would not validate the- # newly-recreated writer engine.+ # newly-recreated writer engine. The reader is left to the+ # caller's own retried query, a stronger check than SELECT 1,+ # and a reader that fails to come back sets `_reader_unavailable`+ # so reads fall through to the writer just recreated here.await self.writer_db.query_raw("SELECT 1")+ # A recreate can decline: the optimistic-lock guard no-ops when+ # the writer generation moved since cycle entry, and the routing+ # wrapper then leaves the reader untouched as well. Callers that+ # merely suspect a transport blip are happy either way, but a+ # forced caller asked for this engine to be replaced because its+ # session state is poisoned, and it was not. Do not report that+ # as a success: it would reset the consecutive-failure count and+ # log a repair that never happened.+ if force_recreate is True and recreated is False:+ raise _ForcedRecreateDeclined(+ "Forced Prisma recreate declined by the generation guard; "+ "the engine that failed was not replaced"+ )await asyncio.wait_for(_do_direct_reconnect(), timeout=effective_timeout)+ def _cooldown_applies(self, stale_read_engine: "_StaleReadEngine | None") -> bool:+ """+ Whether the reconnect cooldown should still gate this caller.++ The cooldown collapses a burst of callers onto one recreate, so it+ keeps gating a caller whose named engine has already been replaced:+ that recreate is the one it was waiting for. While that engine is still+ the live one the damage is still being served, so deferring to an+ unrelated reconnect's cooldown would leave it broken until the cooldown+ elapses.++ A named engine always describes the one that served the failing read+ (see `_query_first_with_cached_plan_fallback`), so it is compared+ against `read_db`, identity included: `read_db` can resolve to a+ different wrapper than it did at observation time.++ The waiver is withdrawn once a repair of this same engine has been+ tried and failed. A failed recreate leaves the generation where it was,+ so without this every queued caller would still see its own engine live+ and run its own full recreate serially instead of collapsing onto one+ attempt, which is what the cooldown is for. The record is scoped to the+ engine rather than to a global failure count: an unrelated reconnect+ failing somewhere else says nothing about whether this engine can be+ repaired, and gating on it would suppress the recovery this method+ exists to allow.++ The record is never cleared, and does not need to be. Generations are+ monotonic per wrapper, so once the engine is repaired every later+ caller names a higher one and the entry can never match again. And this+ method is only ever the first half of the gate: the cooldown window+ itself still expires, so an engine that can never be repaired degrades+ to the plain cooldown rather than being suppressed forever.+ """+ if stale_read_engine is None:+ return True+ if self._failed_recreate_generations.get(stale_read_engine.wrapper) == stale_read_engine.generation:+ return True+ return not stale_read_engine.is_still_live(self.read_db)+async def _attempt_reconnect_inside_lock(self,force: bool,reason: str,timeout_seconds: float | None,+ force_recreate: bool = False,+ stale_read_engine: "_StaleReadEngine | None" = None,) -> bool:now: Final = time.time()- if force is False and now - self._db_last_reconnect_attempt_ts < self._db_reconnect_cooldown_seconds:+ if (+ force is False+ and self._cooldown_applies(stale_read_engine)+ and now - self._db_last_reconnect_attempt_ts < self._db_reconnect_cooldown_seconds+ ):verbose_proxy_logger.debug("Skipping DB reconnect attempt inside lock due to cooldown. reason=%s",reason,@@ -4834,12 +5020,43 @@ class PrismaClient:reconnect_succeeded = Falsetry:- await self._run_reconnect_cycle(timeout_seconds=timeout_seconds)+ await self._run_reconnect_cycle(timeout_seconds=timeout_seconds, force_recreate=force_recreate)reconnect_succeeded = Trueself._consecutive_reconnect_failures = 0verbose_proxy_logger.info("Prisma DB reconnect succeeded. reason=%s", reason)+ except _ForcedRecreateDeclined as declined:+ # A decline is raised only when the recreate returns False, which+ # happens only at the generation guard, and the generation moves+ # only after a replacement has connected. So a decline is proof+ # that a replacement SUCCEEDED, and zeroing a consecutive-failure+ # count on that proof is right by definition rather than by+ # analogy to what a reported success used to do. Note what it+ # proves is that the WRITER was replaced, not that this caller's+ # engine was repaired: on a read replica the reader can still be+ # poisoned, since the wrapper returns before touching it. Leaving+ # the count at the threshold would let the escalation check above+ # re-arm the dead-engine flag on the very next attempt and send a+ # healthy replacement back down the probe-free heavy path.+ self._consecutive_reconnect_failures = 0+ verbose_proxy_logger.warning("Prisma DB reconnect declined. reason=%s detail=%s", reason, declined)except Exception as reconnect_err:self._consecutive_reconnect_failures += 1+ # Remember WHICH engine could not be repaired, so the rest of this+ # caller's burst collapses onto the cooldown instead of each+ # retrying the recreate that just failed. Recorded only for a+ # caller that named a generation: a watchdog or transport-error+ # reconnect failing here is unrelated to any stale read engine and+ # must not suppress its waiver.+ if stale_read_engine is not None:+ # Key off the wrapper the CALLER named, never a freshly resolved+ # `read_db`. A failed reader recreate is itself what marks the+ # reader unavailable, so re-resolving here would file the+ # reader's failure under the writer: the poisoned reader would+ # lose its record and the healthy writer would gain a spurious+ # one, wrong in both directions at once.+ self._failed_recreate_generations = MappingProxyType(+ {**self._failed_recreate_generations, stale_read_engine.wrapper: stale_read_engine.generation}+ )verbose_proxy_logger.error("Prisma DB reconnect failed (%d consecutive). reason=%s error=%s",self._consecutive_reconnect_failures,@@ -4857,15 +5074,35 @@ class PrismaClient:force: bool = False,timeout_seconds: float | None = None,lock_timeout_seconds: float | None = None,+ force_recreate: bool = False,+ stale_read_engine: "_StaleReadEngine | None" = None,) -> bool:"""Attempt to reconnect the Prisma client in a singleflight manner.+ `force` bypasses the cooldown unconditionally; `force_recreate`+ bypasses the liveness probe that would otherwise skip recreating a+ reachable engine; `stale_read_engine` bypasses the cooldown only while+ the engine that produced the caller's failure is still the live one+ (see `_cooldown_applies`).++ A `force_recreate` caller can also get False for a third reason: the+ generation guard declined because another path had already replaced+ the engine, which is a successful outcome reported as False. Callers+ that branch on the return value (`exception_handler` raises on False,+ `auth_checks` retries only on True) would misread that as a dead end,+ and are safe today only because neither passes `force_recreate`. Do+ not add it to one of them without revisiting how it reads the result.+Returns:bool: True if reconnection succeeded, else False."""now: Final = time.time()- if force is False and now - self._db_last_reconnect_attempt_ts < self._db_reconnect_cooldown_seconds:+ if (+ force is False+ and self._cooldown_applies(stale_read_engine)+ and now - self._db_last_reconnect_attempt_ts < self._db_reconnect_cooldown_seconds+ ):verbose_proxy_logger.debug("Skipping DB reconnect attempt due to cooldown. reason=%s",reason,@@ -4874,7 +5111,9 @@ class PrismaClient:if lock_timeout_seconds is None:async with self._db_reconnect_lock:- return await self._attempt_reconnect_inside_lock(force, reason, timeout_seconds)+ return await self._attempt_reconnect_inside_lock(+ force, reason, timeout_seconds, force_recreate, stale_read_engine+ )lock_acquired_by_timeout_task = False@@ -4923,7 +5162,9 @@ class PrismaClient:return Falsetry:- return await self._attempt_reconnect_inside_lock(force, reason, timeout_seconds)+ return await self._attempt_reconnect_inside_lock(+ force, reason, timeout_seconds, force_recreate, stale_read_engine+ )finally:self._db_reconnect_lock.release()diff --git a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.py b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.pyindex 87063bdf00b..ed1317e647d 100644--- a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.py+++ b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.py@@ -17,13 +17,14 @@ import hashlibimport jsonfrom datetime import datetime, timedelta, timezonefrom types import SimpleNamespace-from typing import Any+from typing import Any, Finalfrom unittest.mock import AsyncMock, MagicMockimport pytestfrom fastapi import HTTPExceptionfrom litellm.proxy._types import LiteLLM_VerificationTokenView+from litellm.proxy.db.routing_prisma_wrapper import RoutingPrismaWrapperfrom litellm.proxy.utils import PrismaClient@@ -270,6 +271,9 @@ async def test_query_first_with_cached_plan_fallback_reconnects_then_retries_ideassert retry_call.args == first_call.args == (original_query, "abc")reconnect.assert_awaited_once()assert reconnect.await_args.kwargs.get("force", False) is False+ # https://github.com/BerriAI/litellm/issues/36418: without this the healthy+ # writer probe skips the recreate and the stale plans survive the retry+ assert reconnect.await_args.kwargs.get("force_recreate") is Trueassert [name for name, *_ in manager.mock_calls] == ["query_first","attempt_db_reconnect",@@ -564,3 +568,68 @@ async def test_get_data_team_keys_forward_limit_as_take("where": {"team_id": "team-1"},"include": {"litellm_budget_table": True},}+++async def test_query_first_with_cached_plan_fallback_reports_pre_query_engine_generation(+ prisma_client: PrismaClient,+) -> None:+ """The generation is snapshotted before the query, not after it fails: it+ names the engine that prepared the stale statement, which is what lets the+ reconnect bypass an unrelated cooldown while that engine is still live+ (https://github.com/BerriAI/litellm/issues/36418). Reading it after the+ failure would miss a recreate that landed in between and force a+ needless second one."""+ prisma_client.db.engine_generation = 3++ async def _fail_then_bump(*args: Any, **kwargs: Any) -> dict[str, str]:+ if prisma_client.db.engine_generation == 3:+ prisma_client.db.engine_generation = 4+ raise RuntimeError("cached plan must not change result type")+ return {"token": "abc"}++ prisma_client.db.query_first = AsyncMock(side_effect=_fail_then_bump)+ prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)++ await prisma_client._query_first_with_cached_plan_fallback("SELECT 1")++ kwargs = prisma_client.attempt_db_reconnect.await_args.kwargs+ assert kwargs.get("stale_read_engine").generation == 3+++async def test_query_first_with_cached_plan_fallback_reports_the_reader_generation(+ prisma_client: PrismaClient,+) -> None:+ """With a read replica configured the query runs on the READER, so the+ reader's generation is the one that names the engine holding the stale+ prepared statement. Snapshotting the writer's instead would let an+ unrelated writer reconnect re-arm the cooldown while the reader stayed+ poisoned (https://github.com/BerriAI/litellm/issues/36418). The two+ generations are deliberately far apart so only the right one matches."""+ writer = MagicMock(name="writer")+ writer.engine_generation = 99+ writer.query_first = AsyncMock(return_value={"token": "wrong-engine"})+ reader = MagicMock(name="reader")+ reader.engine_generation = 3+ reader.query_first = AsyncMock(+ side_effect=[RuntimeError("cached plan must not change result type"), {"token": "abc"}]+ )+ prisma_client.db = RoutingPrismaWrapper(writer=writer, reader=reader)+ prisma_client.attempt_db_reconnect = AsyncMock(return_value=True)++ await prisma_client._query_first_with_cached_plan_fallback("SELECT 1")++ reported: Final = prisma_client.attempt_db_reconnect.await_args.kwargs.get("stale_read_engine")+ pinned = {+ "reported_generation": reported.generation,+ "reported_the_reader_itself": reported.wrapper is reader,+ "reader_served_the_query": reader.query_first.await_count,+ "writer_served_the_query": writer.query_first.await_count,+ }+ assert pinned == {+ "reported_generation": 3,+ "reported_the_reader_itself": True,+ "reader_served_the_query": 2,+ "writer_served_the_query": 0,+ }diff --git a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_reconnect.py b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_reconnect.pyindex 867554157fd..719d7cc73f5 100644--- a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_reconnect.py+++ b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_reconnect.py@@ -7,17 +7,34 @@ Symbols pinned here:- ``PrismaClient.start_db_health_watchdog_task``- ``PrismaClient.stop_db_health_watchdog_task``- ``PrismaClient._db_health_watchdog_loop``++Note on fixtures for the routing tests: the reader and the writer carry+independent generation counters, so a fixture that gives them far-apart values+reads clearly and proves nothing about identity, because comparing the numbers+alone already yields the right answer. Pick values so that ONLY the mechanism+under test can produce the expected result, which for identity means two+engines whose generations deliberately coincide.++Note on what to assert: pin the requirement, not the mechanism. An assertion+that restates what the implementation currently does can only ever agree with+it, including when it is wrong, so it ends up defending the defect from being+corrected. One here did exactly that, asserting that a declined heavy-path+recreate leaves the dead-engine flag set, which read as a faithful description+and was a reintroduction of #29176. "A later cycle must not kill a healthy+engine" would have failed against it whatever mechanism produced it."""from __future__ import annotationsimport asyncio-from typing import Any+import time+from typing import Any, Finalfrom unittest.mock import AsyncMock, MagicMockimport pytest-from litellm.proxy.utils import PrismaClient+from litellm.proxy.db.routing_prisma_wrapper import RoutingPrismaWrapper+from litellm.proxy.utils import PrismaClient, _StaleReadEngine@pytest.mark.asyncio@@ -96,6 +113,48 @@ async def test_run_reconnect_cycle_direct_path_recreates_when_probe_fails(}+async def test_run_reconnect_cycle_force_recreate_skips_probe_and_recreates(+ prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A healthy writer must not veto the recreate when the caller already+ knows the session state is poisoned (stale prepared statements after a+ schema change). Regression for+ https://github.com/BerriAI/litellm/issues/36418."""+ monkeypatch.setenv("DATABASE_URL", "postgres://x:y@h:5432/db")+ prisma_client._engine_confirmed_dead = False+ prisma_client._engine_pid = 0+ prisma_client._start_engine_watcher = AsyncMock()+ prisma_client._cleanup_engine_watcher = MagicMock()++ writer = prisma_client.db+ writer.recreate_prisma_client = AsyncMock()+ writer.query_raw = AsyncMock(return_value=[{"?column?": 1}])++ await prisma_client._run_reconnect_cycle(timeout_seconds=5, force_recreate=True)+ pinned = {+ "recreate_called": writer.recreate_prisma_client.await_count,+ "writer_query_raw_calls": writer.query_raw.await_count,+ }+ assert pinned == {"recreate_called": 1, "writer_query_raw_calls": 1}+++async def test_attempt_db_reconnect_forwards_force_recreate_to_cycle(+ prisma_client: PrismaClient,+) -> None:+ """Regression for https://github.com/BerriAI/litellm/issues/36418: the flag+ has to survive both hops (attempt_db_reconnect -> inside-lock -> cycle),+ otherwise the cached-plan caller silently gets a probe-gated reconnect."""+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(reason="explicit", force_recreate=True)++ assert ok is True+ assert prisma_client._run_reconnect_cycle.await_args.kwargs.get("force_recreate") is True++@pytest.mark.asyncioasync def test_run_reconnect_cycle_passes_writer_generation_to_recreate(prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch@@ -584,3 +643,456 @@ async def test_run_reconnect_cycle_heavy_path_forwards_entry_generation_to_recrekwargs = prisma_client.db.recreate_prisma_client.await_args.kwargsassert kwargs.get("expected_generation") == 4+++async def test_attempt_db_reconnect_bypasses_cooldown_for_still_live_stale_engine(+ prisma_client: PrismaClient,+) -> None:+ """A schema change landing inside the cooldown of an earlier reconnect used+ to leave auth failing until the cooldown elapsed. While the engine the+ caller's failure came from is still the live one, the cooldown must not+ gate the recreate. Regression for+ https://github.com/BerriAI/litellm/issues/36418."""+ prisma_client.db.engine_generation = 7+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ assert ok is True+ assert prisma_client._run_reconnect_cycle.await_count == 1+++async def test_attempt_db_reconnect_honors_cooldown_once_stale_engine_replaced(+ prisma_client: PrismaClient,+) -> None:+ """The bypass is scoped to the damaged engine: once a concurrent recreate+ has replaced it, the cooldown must still collapse the rest of the burst+ onto that recreate instead of killing the fresh engine."""+ prisma_client.db.engine_generation = 8+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ assert ok is False+ prisma_client._run_reconnect_cycle.assert_not_awaited()+++async def test_attempt_db_reconnect_keeps_cooldown_for_callers_without_generation(+ prisma_client: PrismaClient,+) -> None:+ """Watchdog and transport-error callers name no generation, so they keep+ the plain cooldown behaviour."""+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(reason="watchdog_probe_failed")++ assert ok is False+ prisma_client._run_reconnect_cycle.assert_not_awaited()+++def _routing_client(prisma_client: PrismaClient, reader_generation: int, writer_generation: int) -> tuple[Any, Any]:+ """Wire ``prisma_client.db`` to a routing wrapper with distinct engines.++ Returns the (writer, reader) mocks so a test can move either generation+ independently, which is the only way to tell the two counters apart.+ """+ writer = MagicMock(name="writer")+ writer.engine_generation = writer_generation+ reader = MagicMock(name="reader")+ reader.engine_generation = reader_generation+ prisma_client.db = RoutingPrismaWrapper(writer=writer, reader=reader)+ return writer, reader+++async def test_attempt_db_reconnect_reads_generation_from_the_reader_that_served_the_query(+ prisma_client: PrismaClient,+) -> None:+ """``query_first`` is a top-level read, so with a replica configured the+ stale prepared statements are on the READER. A writer reconnect that moved+ the writer generation must not re-arm the cooldown while the reader the+ query actually failed on is still the live, poisoned one. Regression for+ https://github.com/BerriAI/litellm/issues/36418."""+ _routing_client(prisma_client, reader_generation=7, writer_generation=99)+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ assert ok is True+ assert prisma_client._run_reconnect_cycle.await_count == 1+++async def test_attempt_db_reconnect_honors_cooldown_once_the_reader_itself_was_replaced(+ prisma_client: PrismaClient,+) -> None:+ """The mirror of the above: once the reader has been replaced, the recreate+ the caller needed has already happened, so the cooldown collapses the rest+ of the burst even though the writer generation never moved."""+ _routing_client(prisma_client, reader_generation=8, writer_generation=99)+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ assert ok is False+ prisma_client._run_reconnect_cycle.assert_not_awaited()+++async def test_attempt_db_reconnect_gates_when_reads_moved_to_an_engine_of_the_same_generation(+ prisma_client: PrismaClient,+) -> None:+ """The counters are per engine, so the reader and the writer can sit on the+ same number at the same time. Once the reader goes unavailable reads move to+ the writer, and the caller's poisoned reader is no longer serving anything,+ so the cooldown should gate it. Comparing generations alone cannot tell the+ two apart and would hand out the waiver here: the generations are equal on+ purpose, which is what makes this the case identity has to decide."""+ writer, reader = _routing_client(prisma_client, reader_generation=5, writer_generation=5)+ stale: Final = _StaleReadEngine(wrapper=reader, generation=5)+ prisma_client.db._reader_unavailable = True+ prisma_client._db_last_reconnect_attempt_ts = time.time()+ prisma_client._run_reconnect_cycle = AsyncMock()++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=stale,+ )++ pinned = {+ "reads_now_served_by_the_writer": prisma_client.read_db is writer,+ "generations_coincide": reader.engine_generation == writer.engine_generation,+ # `_cooldown_applies` gates on the failed-repair record OR on liveness,+ # and either alone produces this result. Pin that the record is empty,+ # or a stray entry would make this pass while testing the other gate.+ "no_failed_repair_recorded": dict(prisma_client._failed_recreate_generations) == {},+ "recovered": ok,+ "cycles_run": prisma_client._run_reconnect_cycle.await_count,+ }+ assert pinned == {+ "reads_now_served_by_the_writer": True,+ "generations_coincide": True,+ "no_failed_repair_recorded": True,+ "recovered": False,+ "cycles_run": 0,+ }+++async def test_failed_repair_of_one_engine_is_not_evicted_by_a_failure_on_the_other(+ prisma_client: PrismaClient,+) -> None:+ """The record is kept per engine. Held in a single slot, a failed writer+ repair would evict the reader's record, and the next caller naming the+ reader's still-unrepaired generation would get the waiver back and run its+ own redundant cycle, which is the burst the record exists to collapse."""+ writer, reader = _routing_client(prisma_client, reader_generation=5, writer_generation=3)+ stale_reader: Final = _StaleReadEngine(wrapper=reader, generation=5)+ stale_writer: Final = _StaleReadEngine(wrapper=writer, generation=3)+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._run_reconnect_cycle = AsyncMock(side_effect=RuntimeError("engine spawn failed"))++ await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error", force_recreate=True, stale_read_engine=stale_reader+ )+ prisma_client.db._reader_unavailable = True+ await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error", force_recreate=True, stale_read_engine=stale_writer+ )+ prisma_client.db._reader_unavailable = False+ cycles_before_the_reader_returns: Final = prisma_client._run_reconnect_cycle.await_count++ await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error", force_recreate=True, stale_read_engine=stale_reader+ )++ pinned = {+ "cycles_before": cycles_before_the_reader_returns,+ "cycles_after": prisma_client._run_reconnect_cycle.await_count,+ }+ assert pinned == {"cycles_before": 2, "cycles_after": 2}+++async def test_attempt_db_reconnect_withdraws_the_waiver_after_this_generation_failed_to_repair(+ prisma_client: PrismaClient,+) -> None:+ """A failed recreate leaves the generation where it was, so without a record+ of the failure every queued caller of the same burst would still see its own+ generation live and run its own full recreate serially instead of collapsing+ onto one attempt. Drives two callers rather than presetting the record, so+ the record has to actually be written by the failure."""+ prisma_client.db.engine_generation = 7+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._run_reconnect_cycle = AsyncMock(side_effect=RuntimeError("engine spawn failed"))++ first = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )+ second = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ pinned = {+ "first": first,+ "second": second,+ "cycles_run": prisma_client._run_reconnect_cycle.await_count,+ }+ assert pinned == {"first": False, "second": False, "cycles_run": 1}+++async def test_attempt_db_reconnect_keeps_the_waiver_after_an_unrelated_reconnect_failure(+ prisma_client: PrismaClient,+) -> None:+ """The failure record is scoped to the generation it was trying to repair.+ A watchdog or transport-error reconnect names no generation, so its failure+ says nothing about whether a stale read engine can be repaired and must not+ gate it: gating on a global failure count would 503 authentication for the+ length of the cooldown."""+ prisma_client.db.engine_generation = 7+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._run_reconnect_cycle = AsyncMock(side_effect=RuntimeError("watchdog reconnect failed"))++ unrelated = await prisma_client.attempt_db_reconnect(reason="watchdog_probe_failed")+ # Read before the second call: a global failure gate would be armed here,+ # and the recovering reconnect below resets the counter either way.+ failures_left_by_the_unrelated_reconnect: Final = prisma_client._consecutive_reconnect_failures++ prisma_client._run_reconnect_cycle = AsyncMock()+ cached_plan = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=_StaleReadEngine(wrapper=prisma_client.read_db, generation=7),+ )++ pinned = {+ "unrelated_failed": unrelated,+ "failures_left_by_the_unrelated_reconnect": failures_left_by_the_unrelated_reconnect,+ "cached_plan_recovered": cached_plan,+ "cycles_run_for_cached_plan": prisma_client._run_reconnect_cycle.await_count,+ }+ assert pinned == {+ "unrelated_failed": False,+ "failures_left_by_the_unrelated_reconnect": 1,+ "cached_plan_recovered": True,+ "cycles_run_for_cached_plan": 1,+ }+++async def test_forced_recreate_declined_by_the_generation_guard_is_not_reported_as_success(+ prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """``recreate_prisma_client`` declines when the writer generation moved+ since cycle entry, and the routing wrapper then leaves the reader untouched+ too. A forced caller asked for its engine to be replaced and it was not, so+ reporting success would reset the consecutive-failure count and log a repair+ that never happened. The declined attempt must equally not count as a+ failure, or the caller's own backoff would be gated on its next try."""+ monkeypatch.setenv("DATABASE_URL", "postgres://x:y@h:5432/db")+ prisma_client._engine_confirmed_dead = False+ prisma_client._engine_pid = 0+ prisma_client._start_engine_watcher = AsyncMock()+ prisma_client._cleanup_engine_watcher = MagicMock()+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._consecutive_reconnect_failures = 0++ writer = prisma_client.db+ writer.recreate_prisma_client = AsyncMock(return_value=False)+ writer.query_raw = AsyncMock(return_value=[{"?column?": 1}])++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ )++ pinned = {+ "reported_success": ok,+ "recreate_attempted": writer.recreate_prisma_client.await_count,+ "consecutive_failures": prisma_client._consecutive_reconnect_failures,+ }+ assert pinned == {+ "reported_success": False,+ "recreate_attempted": 1,+ "consecutive_failures": 0,+ }+++async def test_unforced_recreate_declined_by_the_generation_guard_still_succeeds(+ prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The decline is only an error for a caller that forced the recreate. A+ transport-blip caller is happy to learn another path already replaced the+ engine, so its reconnect still reports success."""+ monkeypatch.setenv("DATABASE_URL", "postgres://x:y@h:5432/db")+ prisma_client._engine_confirmed_dead = False+ prisma_client._engine_pid = 0+ prisma_client._start_engine_watcher = AsyncMock()+ prisma_client._cleanup_engine_watcher = MagicMock()+ prisma_client._db_last_reconnect_attempt_ts = 0.0++ writer = prisma_client.db+ writer.recreate_prisma_client = AsyncMock(return_value=False)+ # First call is the liveness probe, which must fail so the recreate is+ # reached at all; the second is the post-recreate smoke test.+ writer.query_raw = AsyncMock(side_effect=[Exception("probe fails"), [{"?column?": 1}]])++ ok = await prisma_client.attempt_db_reconnect(reason="transport_blip")++ pinned = {"reported_success": ok, "recreate_attempted": writer.recreate_prisma_client.await_count}+ assert pinned == {"reported_success": True, "recreate_attempted": 1}+++async def test_heavy_path_forced_recreate_declined_is_not_reported_as_success(+ prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A forced caller reaches the heavy branch too: the escalation threshold+ flips ``_engine_confirmed_dead`` after repeated failures, and every cycle+ after that takes the dead-engine path. A decline there has to be treated+ exactly as it is on the direct path, or the escalation itself reintroduces+ the success that never happened."""+ monkeypatch.setenv("DATABASE_URL", "postgres://x:y@h:5432/db")+ prisma_client._engine_confirmed_dead = True+ prisma_client._engine_pid = 1234+ prisma_client._start_engine_watcher = AsyncMock()+ prisma_client._cleanup_engine_watcher = MagicMock()+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ prisma_client._consecutive_reconnect_failures = 0+ monkeypatch.setattr(PrismaClient, "_reap_all_zombies", staticmethod(lambda: set()))++ prisma_client.db.recreate_prisma_client = AsyncMock(return_value=False)++ ok = await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ )++ pinned = {+ "reported_success": ok,+ "recreate_attempted": prisma_client.db.recreate_prisma_client.await_count,+ "consecutive_failures": prisma_client._consecutive_reconnect_failures,+ # The dead-engine flag must be CLEARED. A raise normally skips the+ # clear, which is right for a failure and wrong here: the guard+ # declined because another path had already replaced the engine, so it+ # is alive. Leaving it set routes the next cycle back down this+ # probe-free branch, where the recreate would kill that healthy engine.+ "engine_still_confirmed_dead": prisma_client._engine_confirmed_dead,+ }+ assert pinned == {+ "reported_success": False,+ "recreate_attempted": 1,+ "consecutive_failures": 0,+ "engine_still_confirmed_dead": False,+ }+++async def test_declined_heavy_recreate_disarms_escalation_for_the_next_attempt(+ prisma_client: PrismaClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Clearing the dead-engine flag on a decline is not enough on its own. The+ escalation check re-arms that flag whenever the consecutive-failure count is+ still at the threshold, so a decline that left the count alone would send+ the very next attempt back down the probe-free heavy path and recreate over+ the healthy engine another path had just installed. Drives the SECOND+ attempt, because the first one alone cannot show this."""+ monkeypatch.setenv("DATABASE_URL", "postgres://x:y@h:5432/db")+ prisma_client._engine_pid = 1234+ prisma_client._start_engine_watcher = AsyncMock()+ prisma_client._cleanup_engine_watcher = MagicMock()+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ monkeypatch.setattr(PrismaClient, "_reap_all_zombies", staticmethod(lambda: set()))+ # Escalation already armed by earlier genuine failures.+ prisma_client._consecutive_reconnect_failures = prisma_client._reconnect_escalation_threshold+ prisma_client.db.recreate_prisma_client = AsyncMock(return_value=False)+ prisma_client.db.query_raw = AsyncMock(return_value=[{"?column?": 1}])++ armed: Final = prisma_client._engine_confirmed_dead is False and prisma_client._consecutive_reconnect_failures > 0++ await prisma_client.attempt_db_reconnect(reason="postgres_cached_plan_error", force_recreate=True)++ # Kept as its own assert, not folded into the judgement below. These are two+ # claims about two moments, the first being a precondition for the second+ # meaning anything, and a single combined comparison would hide which one+ # failed from both the traceback and a mutation report.+ assert {+ "escalation_was_armed_by_the_count": armed,+ "failures": prisma_client._consecutive_reconnect_failures,+ "engine_confirmed_dead": prisma_client._engine_confirmed_dead,+ } == {"escalation_was_armed_by_the_count": True, "failures": 0, "engine_confirmed_dead": False}++ prisma_client._db_last_reconnect_attempt_ts = 0.0+ await prisma_client.attempt_db_reconnect(reason="postgres_cached_plan_error", force_recreate=True)++ # The requirement: a later cycle must not reclassify the healthy replacement+ # as dead and restart it through the probe-free path.+ assert prisma_client._engine_confirmed_dead is False+++async def test_unrelated_reconnect_failure_does_not_erase_the_burst_record(+ prisma_client: PrismaClient,+) -> None:+ """The failure record names one engine, so a caller that names none must+ not overwrite it. Otherwise a watchdog failure landing between two callers+ of the same burst clears the record and the second caller runs its own full+ recreate against the engine the first one just failed to repair."""+ prisma_client.db.engine_generation = 7+ prisma_client._db_last_reconnect_attempt_ts = 0.0+ stale: Final = _StaleReadEngine(wrapper=prisma_client.read_db, generation=7)+ prisma_client._run_reconnect_cycle = AsyncMock(side_effect=RuntimeError("engine spawn failed"))++ await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=stale,+ )+ # force=True the way the engine-death callers do, so this one actually+ # reaches the failure branch instead of being skipped by the cooldown the+ # first caller just stamped.+ await prisma_client.attempt_db_reconnect(reason="engine_process_death", force=True)+ cycles_before_the_second_burst_caller: Final = prisma_client._run_reconnect_cycle.await_count++ await prisma_client.attempt_db_reconnect(+ reason="postgres_cached_plan_error",+ force_recreate=True,+ stale_read_engine=stale,+ )++ pinned = {+ "cycles_before": cycles_before_the_second_burst_caller,+ "cycles_after": prisma_client._run_reconnect_cycle.await_count,+ }+ assert pinned == {"cycles_before": 2, "cycles_after": 2}