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): avoid DB outage during planned RDS IAM rotation (#34749)
mubashir1osmani7cd009caf746
diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.pyindex fbccb8a726c..cc608d6e82c 100644--- a/litellm/proxy/db/prisma_client.py+++ b/litellm/proxy/db/prisma_client.py@@ -12,7 +12,7 @@ import urllibimport urllib.parsefrom dataclasses import dataclassfrom datetime import datetime, timedelta-from typing import Any, Callable, Union+from typing import Any, Callable, Protocol, Unionfrom litellm._logging import verbose_proxy_loggerfrom litellm.secret_managers.main import str_to_bool@@ -40,6 +40,106 @@ class IAMEndpoint:return url+class _PrismaProcess(Protocol):+ pid: object+++class _PrismaEngine(Protocol):+ @property+ def process(self) -> _PrismaProcess: ...++ async def query(self, content: str, *, tx_id: str | None) -> object: ...++ async def start_transaction(self, *, content: str) -> str: ...++ async def commit_transaction(self, tx_id: str) -> None: ...++ async def rollback_transaction(self, tx_id: str) -> None: ...+++class _PrismaClient(Protocol):+ _Prisma__engine: _PrismaEngine++ @property+ def _engine(self) -> _PrismaEngine: ...+++class _PrismaDrainTracker:+ def __init__(self) -> None:+ self._active_operations = 0+ self._transactions: frozenset[str] = frozenset()+ self._drained = asyncio.Event()+ self._drained.set()++ def begin_operation(self) -> None:+ if self._active_operations == 0:+ self._drained.clear()+ self._active_operations += 1++ def end_operation(self) -> None:+ self._active_operations -= 1+ if self._active_operations == 0:+ self._drained.set()++ def transaction_started(self, transaction_id: str) -> None:+ self._transactions = self._transactions.union((transaction_id,))++ def transaction_finished(self, transaction_id: str) -> None:+ if transaction_id not in self._transactions:+ return+ self._transactions = self._transactions.difference((transaction_id,))+ self.end_operation()++ async def wait_until_drained(self) -> None:+ await self._drained.wait()+++class _TrackedPrismaEngine:+ def __init__(self, engine: _PrismaEngine, tracker: _PrismaDrainTracker) -> None:+ self._engine = engine+ self.tracker = tracker++ @property+ def process(self) -> _PrismaProcess:+ return self._engine.process++ def __getattr__(self, name: str) -> object:+ return getattr(self._engine, name)++ async def query(self, content: str, *, tx_id: str | None) -> object:+ self.tracker.begin_operation()+ try:+ return await self._engine.query(content, tx_id=tx_id)+ finally:+ self.tracker.end_operation()++ async def start_transaction(self, *, content: str) -> str:+ self.tracker.begin_operation()+ try:+ transaction_id = await self._engine.start_transaction(content=content)+ except (Exception, asyncio.CancelledError):+ self.tracker.end_operation()+ raise+ self.tracker.transaction_started(transaction_id)+ return transaction_id++ async def commit_transaction(self, tx_id: str) -> None:+ self.tracker.begin_operation()+ try:+ await self._engine.commit_transaction(tx_id)+ finally:+ self.tracker.end_operation()+ self.tracker.transaction_finished(tx_id)++ async def rollback_transaction(self, tx_id: str) -> None:+ self.tracker.begin_operation()+ try:+ await self._engine.rollback_transaction(tx_id)+ finally:+ self.tracker.end_operation()+ self.tracker.transaction_finished(tx_id)++def parse_iam_endpoint_from_url(url: str) -> IAMEndpoint:"""Parse an IAMEndpoint from a Postgres URL.@@ -88,6 +188,8 @@ class PrismaWrapper:# Fallback refresh interval if token parsing fails (10 minutes)FALLBACK_REFRESH_INTERVAL_SECONDS = 600+ ENGINE_RETIREMENT_DRAIN_TIMEOUT_SECONDS = 90+def __init__(self,original_prisma: Any,@@ -119,6 +221,8 @@ class PrismaWrapper:self._token_refresh_task: asyncio.Task | None = Noneself._reconnection_lock = asyncio.Lock()self._last_refresh_time: datetime | None = None+ self._active_drain_tracker = self._instrument_prisma_client(original_prisma)+ self._retirement_tasks: frozenset[asyncio.Task[None]] = frozenset()# Coordination for planned engine restarts (issue #29176). Every# `recreate_prisma_client` SIGTERMs the running query-engine on@@ -136,7 +240,28 @@ class PrismaWrapper:self._engine_generation: int = 0self.on_engine_replaced: Callable[[], None] | None = None- def _get_engine_pid(self) -> int:+ @staticmethod+ def _read_engine(prisma_client: _PrismaClient) -> _PrismaEngine:+ return prisma_client._engine++ @staticmethod+ def _write_engine(prisma_client: _PrismaClient, engine: _PrismaEngine) -> None:+ prisma_client._Prisma__engine = engine++ def _instrument_prisma_client(self, prisma_client: _PrismaClient) -> _PrismaDrainTracker | None:+ from prisma.errors import ClientNotConnectedError++ try:+ engine = self._read_engine(prisma_client)+ except (AttributeError, ClientNotConnectedError):+ return None+ if isinstance(engine, _TrackedPrismaEngine):+ return engine.tracker+ tracker = _PrismaDrainTracker()+ self._write_engine(prisma_client, _TrackedPrismaEngine(engine, tracker))+ return tracker++ def _get_engine_pid(self, prisma_client: _PrismaClient | None = None) -> int:"""Get the PID of the current Prisma engine subprocess, or 0 if unavailable.Must never raise: it runs inside the reconnect path, where the client@@ -145,19 +270,50 @@ class PrismaWrapper:escaped here, ``recreate_prisma_client`` would fail before it couldbuild a replacement client and the reconnect loop could never recover."""+ from prisma.errors import ClientNotConnectedError+try:- if self._original_prisma.is_connected() is not True:- return 0- engine = self._original_prisma._engine- process = getattr(engine, "process", None) if engine is not None else None- if process is not None:- pid = process.pid- if isinstance(pid, int):- return pid- except (AttributeError, TypeError):+ target_prisma = self._original_prisma if prisma_client is None else prisma_client+ pid = self._read_engine(target_prisma).process.pid+ if isinstance(pid, int):+ return pid+ except (AttributeError, ClientNotConnectedError, TypeError):passreturn 0+ async def _retire_engine_when_drained(self, pid: int, tracker: _PrismaDrainTracker | None) -> None:+ if tracker is not None:+ try:+ await asyncio.wait_for(+ tracker.wait_until_drained(),+ timeout=self.ENGINE_RETIREMENT_DRAIN_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ verbose_proxy_logger.warning(+ "%sReplaced prisma engine PID %s did not drain within %ss; killing it with work still in flight.",+ self._log_prefix,+ pid,+ self.ENGINE_RETIREMENT_DRAIN_TIMEOUT_SECONDS,+ )+ await self._kill_engine_process(pid)++ def _schedule_engine_retirement(self, pid: int, tracker: _PrismaDrainTracker | None) -> None:+ if pid <= 0:+ return+ retirement_task = asyncio.create_task(self._retire_engine_when_drained(pid, tracker))+ self._retirement_tasks = self._retirement_tasks.union((retirement_task,))+ retirement_task.add_done_callback(self._retirement_finished)++ def _retirement_finished(self, retirement_task: asyncio.Task[None]) -> None:+ self._retirement_tasks = self._retirement_tasks.difference((retirement_task,))++ async def connect(self, timeout: int | timedelta | None = None) -> None:+ if timeout is None:+ await self._original_prisma.connect()+ else:+ await self._original_prisma.connect(timeout)+ self._active_drain_tracker = self._instrument_prisma_client(self._original_prisma)+@staticmethodasync def _kill_engine_process(pid: int) -> None:"""Force-kill the engine subprocess to prevent DB connection pool leaks.@@ -415,6 +571,7 @@ class PrismaWrapper:self._original_prisma = Prisma(**kwargs)await self._original_prisma.connect()+ self._active_drain_tracker = self._instrument_prisma_client(self._original_prisma)self._engine_generation += 1# Let the owner (PrismaClient) re-arm its engine-death watcher on the@@ -425,6 +582,45 @@ class PrismaWrapper:return True+ async def _replace_prisma_client_for_token_refresh_locked(+ self,+ new_db_url: str,+ ) -> None:+ from prisma import Prisma+ from prisma.types import DatasourceOverride++ if self._recreate_uses_datasource:+ datasource = DatasourceOverride(url=new_db_url)+ replacement_prisma = Prisma(datasource=datasource)+ else:+ replacement_prisma = Prisma()++ old_prisma = self._original_prisma+ old_engine_pid = self._get_engine_pid(old_prisma)+ old_drain_tracker = self._active_drain_tracker+ if old_drain_tracker is None:+ old_drain_tracker = self._instrument_prisma_client(old_prisma)+ try:+ await replacement_prisma.connect()+ except (Exception, asyncio.CancelledError):+ self._schedule_engine_retirement(self._get_engine_pid(replacement_prisma), None)+ raise+ replacement_drain_tracker = self._instrument_prisma_client(replacement_prisma)++ if old_engine_pid > 0:+ if len(self._expected_engine_deaths) >= 64:+ self._expected_engine_deaths.clear()+ self._expected_engine_deaths.add(old_engine_pid)++ self._original_prisma = replacement_prisma+ self._active_drain_tracker = replacement_drain_tracker+ self._engine_generation += 1++ if self.on_engine_replaced is not None:+ self.on_engine_replaced()++ self._schedule_engine_retirement(old_engine_pid, old_drain_tracker)+async def start_token_refresh_task(self) -> None:"""Start the background token refresh task.@@ -527,11 +723,17 @@ class PrismaWrapper:)return+ previous_db_url = os.getenv(self._db_url_env_var)new_db_url = self.get_rds_iam_token()if new_db_url:- # We already hold `_reconnection_lock`; call the locked core- # directly (the public method would re-acquire and deadlock).- await self._recreate_prisma_client_locked(new_db_url)+ try:+ await self._replace_prisma_client_for_token_refresh_locked(new_db_url)+ except (Exception, asyncio.CancelledError):+ if previous_db_url is None:+ os.environ.pop(self._db_url_env_var, None)+ else:+ os.environ[self._db_url_env_var] = previous_db_url+ raiseself._last_refresh_time = datetime.utcnow()verbose_proxy_logger.info("%sRDS IAM token refreshed successfully. New token valid for ~15 minutes.",diff --git a/tests/test_litellm/proxy/conftest.py b/tests/test_litellm/proxy/conftest.pyindex 1d71035b67f..230ccaf5fd4 100644--- a/tests/test_litellm/proxy/conftest.py+++ b/tests/test_litellm/proxy/conftest.py@@ -13,6 +13,7 @@ from typing import Dict, Optionalimport pytestimport yamlfrom fastapi.testclient import TestClient+from prisma.errors import ClientNotConnectedError_PROXY_MODULE_GLOBALS_TO_ISOLATE = ("master_key",@@ -20,7 +21,7 @@ _PROXY_MODULE_GLOBALS_TO_ISOLATE = ()-class StubClientNotConnectedError(Exception):+class StubClientNotConnectedError(ClientNotConnectedError):pass@@ -33,10 +34,7 @@ class DisconnectedPrisma:@propertydef _engine(self) -> None:- raise StubClientNotConnectedError(- "Client is not connected to the query engine, you must call `connect()` "- "before attempting to query data."- )+ raise StubClientNotConnectedError()@pytest.fixturediff --git a/tests/test_litellm/proxy/db/test_prisma_planned_engine_restart.py b/tests/test_litellm/proxy/db/test_prisma_planned_engine_restart.pyindex 9b382a41964..18a238b7545 100644--- a/tests/test_litellm/proxy/db/test_prisma_planned_engine_restart.py+++ b/tests/test_litellm/proxy/db/test_prisma_planned_engine_restart.py@@ -17,12 +17,14 @@ Symbols pinned here:import asyncioimport os+import signalimport sysimport urllib.parsefrom datetime import datetime, timedelta-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, call, patchimport pytest+from prisma import Prisma as GeneratedPrismasys.path.insert(0, os.path.abspath("../../../..")@@ -40,12 +42,11 @@ def mock_prisma_binary():def _make_wrapper(engine_pid: int = 111, iam: bool = False) -> PrismaWrapper:- mock_prisma = MagicMock()- mock_prisma.connect = AsyncMock()- mock_prisma.is_connected = MagicMock(return_value=True)- mock_prisma._engine = MagicMock()- mock_prisma._engine.process.pid = engine_pid- return PrismaWrapper(original_prisma=mock_prisma, iam_token_db_auth=iam)+ prisma = GeneratedPrisma(use_dotenv=False)+ engine = MagicMock()+ engine.process.pid = engine_pid+ setattr(prisma, "_Prisma__engine", engine)+ return PrismaWrapper(original_prisma=prisma, iam_token_db_auth=iam)def _token_db_url(created: datetime, expires_in: int = 900) -> str:@@ -58,6 +59,21 @@ def _token_db_url(created: datetime, expires_in: int = 900) -> str:return f"postgresql://user:{quoted}@host:5432/db"+def test_wrapper_instruments_generated_prisma_engine() -> None:+ prisma = GeneratedPrisma(use_dotenv=False)+ engine = MagicMock()+ setattr(prisma, "_Prisma__engine", engine)++ wrapper = PrismaWrapper(original_prisma=prisma, iam_token_db_auth=False)++ assert wrapper._active_drain_tracker is not None+ assert prisma._engine._engine is engine+++async def _wait_for_retirements(wrapper: PrismaWrapper) -> None:+ await asyncio.gather(*tuple(wrapper._retirement_tasks))++@pytest.mark.asyncioasync def test_recreate_marks_old_engine_pid_as_expected_death(mock_prisma_binary):"""The watcher must be able to tell a planned kill from a crash."""@@ -236,6 +252,7 @@ async def test_safe_refresh_token_refreshes_when_token_expired(patch("asyncio.sleep", new_callable=AsyncMock),):await wrapper._safe_refresh_token()+ await _wait_for_retirements(wrapper)pinned = {"token_minted": wrapper.get_rds_iam_token.call_count,@@ -244,6 +261,251 @@ async def test_safe_refresh_token_refreshes_when_token_expired(assert pinned == {"token_minted": 1, "prisma_constructed": 1}+async def test_safe_refresh_connects_replacement_before_swapping_and_killing(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ old_prisma = wrapper._original_prisma+ expired = datetime.utcnow() - timedelta(seconds=1200)+ monkeypatch.setenv("DATABASE_URL", _token_db_url(created=expired, expires_in=900))+ wrapper.get_rds_iam_token = MagicMock(return_value="postgresql://fresh")+ replacement_prisma = MagicMock()++ async def connect_replacement() -> None:+ assert wrapper._original_prisma is old_prisma+ assert mock_kill.call_count == 0++ replacement_prisma.connect = AsyncMock(side_effect=connect_replacement)+ replacement_prisma.is_connected = MagicMock(return_value=True)+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = 222+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ def observe_kill(pid: int, sent_signal: int) -> None:+ assert wrapper._original_prisma is replacement_prisma++ with (+ patch("os.kill", side_effect=observe_kill) as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await wrapper._safe_refresh_token()+ await _wait_for_retirements(wrapper)++ assert wrapper._original_prisma is replacement_prisma+ mock_kill.assert_any_call(111, signal.SIGTERM)+ assert wrapper._engine_generation == 1+++async def test_safe_refresh_failure_keeps_old_client_and_token(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ old_prisma = wrapper._original_prisma+ expired = datetime.utcnow() - timedelta(seconds=1200)+ previous_db_url = _token_db_url(created=expired, expires_in=900)+ monkeypatch.setenv("DATABASE_URL", previous_db_url)++ def mint_token() -> str:+ monkeypatch.setenv("DATABASE_URL", "postgresql://fresh")+ return "postgresql://fresh"++ wrapper.get_rds_iam_token = MagicMock(side_effect=mint_token)+ replacement_prisma = MagicMock(connect=AsyncMock(side_effect=RuntimeError("database unavailable")))+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ with patch("os.kill") as mock_kill:+ with pytest.raises(RuntimeError, match="database unavailable"):+ await wrapper._safe_refresh_token()++ assert wrapper._original_prisma is old_prisma+ assert os.environ["DATABASE_URL"] == previous_db_url+ assert wrapper._engine_generation == 0+ mock_kill.assert_not_called()+++async def test_safe_refresh_waits_for_active_query_before_retiring_old_engine(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ old_engine = wrapper._original_prisma._engine+ query_started = asyncio.Event()+ release_query = asyncio.Event()++ async def run_query(content: str, *, tx_id: object | None) -> dict[str, str]:+ query_started.set()+ await release_query.wait()+ return {"status": "complete"}++ old_engine._engine.query = AsyncMock(side_effect=run_query)+ query_task = asyncio.create_task(old_engine.query("query", tx_id=None))+ await query_started.wait()++ expired = datetime.utcnow() - timedelta(seconds=1200)+ monkeypatch.setenv("DATABASE_URL", _token_db_url(created=expired, expires_in=900))+ wrapper.get_rds_iam_token = MagicMock(return_value="postgresql://fresh")+ replacement_prisma = MagicMock(connect=AsyncMock())+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = 222+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ with (+ patch("os.kill") as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await wrapper._safe_refresh_token()+ assert mock_kill.call_count == 0+ assert not query_task.done()+ release_query.set()+ await query_task+ await _wait_for_retirements(wrapper)++ mock_kill.assert_any_call(111, signal.SIGTERM)+++async def test_safe_refresh_waits_for_open_transaction_before_retiring_old_engine(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ old_engine = wrapper._original_prisma._engine+ old_engine._engine.start_transaction = AsyncMock(return_value="transaction-1")+ old_engine._engine.commit_transaction = AsyncMock()+ transaction_id = await old_engine.start_transaction(content="transaction")++ expired = datetime.utcnow() - timedelta(seconds=1200)+ monkeypatch.setenv("DATABASE_URL", _token_db_url(created=expired, expires_in=900))+ wrapper.get_rds_iam_token = MagicMock(return_value="postgresql://fresh")+ replacement_prisma = MagicMock(connect=AsyncMock())+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = 222+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ with (+ patch("os.kill") as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await wrapper._safe_refresh_token()+ assert mock_kill.call_count == 0+ await old_engine.commit_transaction(transaction_id)+ await _wait_for_retirements(wrapper)++ mock_kill.assert_any_call(111, signal.SIGTERM)+++async def test_retirement_kills_old_engine_when_drain_never_completes(+ mock_prisma_binary, monkeypatch+):+ """A leaked drain count (e.g. a transaction whose owner was hard-cancelled+ before commit/rollback) must not keep the replaced engine alive forever."""+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ monkeypatch.setattr(wrapper, "ENGINE_RETIREMENT_DRAIN_TIMEOUT_SECONDS", 0.05)+ old_engine = wrapper._original_prisma._engine+ old_engine._engine.start_transaction = AsyncMock(return_value="transaction-1")+ await old_engine.start_transaction(content="transaction")++ expired = datetime.utcnow() - timedelta(seconds=1200)+ monkeypatch.setenv("DATABASE_URL", _token_db_url(created=expired, expires_in=900))+ wrapper.get_rds_iam_token = MagicMock(return_value="postgresql://fresh")+ replacement_prisma = MagicMock(connect=AsyncMock())+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = 222+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ with (+ patch("os.kill") as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await wrapper._safe_refresh_token()+ await asyncio.wait_for(_wait_for_retirements(wrapper), timeout=2)++ mock_kill.assert_any_call(111, signal.SIGTERM)+++async def test_safe_refresh_cancellation_restores_token_and_cleans_replacement(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ old_prisma = wrapper._original_prisma+ expired = datetime.utcnow() - timedelta(seconds=1200)+ previous_db_url = _token_db_url(created=expired, expires_in=900)+ monkeypatch.setenv("DATABASE_URL", previous_db_url)+ connect_started = asyncio.Event()+ block_connect = asyncio.Event()++ def mint_token() -> str:+ monkeypatch.setenv("DATABASE_URL", "postgresql://fresh")+ return "postgresql://fresh"++ async def connect_replacement() -> None:+ connect_started.set()+ await block_connect.wait()++ wrapper.get_rds_iam_token = MagicMock(side_effect=mint_token)+ replacement_prisma = MagicMock(connect=AsyncMock(side_effect=connect_replacement))+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = 222+ mock_prisma_binary.Prisma.return_value = replacement_prisma++ with (+ patch("os.kill") as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ refresh_task = asyncio.create_task(wrapper._safe_refresh_token())+ await connect_started.wait()+ refresh_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await refresh_task+ await _wait_for_retirements(wrapper)++ assert wrapper._original_prisma is old_prisma+ assert os.environ["DATABASE_URL"] == previous_db_url+ assert wrapper._engine_generation == 0+ assert mock_kill.call_args_list == [+ call(222, signal.SIGTERM),+ call(222, signal.SIGKILL),+ ]+++async def test_repeated_safe_refreshes_retire_each_replaced_engine(+ mock_prisma_binary, monkeypatch+):+ wrapper = _make_wrapper(engine_pid=111, iam=True)+ replacement_clients = []+ for engine_pid in (222, 333):+ replacement_prisma = MagicMock(connect=AsyncMock())+ replacement_prisma.is_connected = MagicMock(return_value=True)+ replacement_prisma._engine = MagicMock()+ replacement_prisma._engine.process.pid = engine_pid+ replacement_clients.append(replacement_prisma)+ mock_prisma_binary.Prisma.side_effect = replacement_clients+ wrapper.get_rds_iam_token = MagicMock(side_effect=("postgresql://first", "postgresql://second"))+ expired = datetime.utcnow() - timedelta(seconds=1200)++ with (+ patch("os.kill") as mock_kill,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ for _ in range(2):+ monkeypatch.setenv("DATABASE_URL", _token_db_url(created=expired, expires_in=900))+ await wrapper._safe_refresh_token()+ await _wait_for_retirements(wrapper)++ assert mock_kill.call_args_list == [+ call(111, signal.SIGTERM),+ call(111, signal.SIGKILL),+ call(222, signal.SIGTERM),+ call(222, signal.SIGKILL),+ ]+ assert wrapper._original_prisma is replacement_clients[-1]+ assert wrapper._engine_generation == 2++@pytest.mark.asyncioasync def test_safe_refresh_token_refreshes_when_token_unparseable(mock_prisma_binary, monkeypatch@@ -260,6 +522,7 @@ async def test_safe_refresh_token_refreshes_when_token_unparseable(patch("asyncio.sleep", new_callable=AsyncMock),):await wrapper._safe_refresh_token()+ await _wait_for_retirements(wrapper)assert wrapper.get_rds_iam_token.call_count == 1