Repository navigation
fix(proxy): self-heal Prisma connection for auth and runtime #21706
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 20 commits
e6f894d
d1b2805
ffe8637
4dee7dc
b560164
cb19ec1
e89c5b7
14f529a
5e0fbf0
67809b8
edcb6bd
1144b7f
1921bad
2083f39
2c02d1e
c0a395a
4844f76
3bb2423
f288319
b53c342
aa71695
8b8c58a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -102,6 +102,7 @@ | |
| should_create_missing_views, | ||
| ) | ||
| from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter | ||
| from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler | ||
| from litellm.proxy.db.log_db_metrics import log_db_metrics | ||
| from litellm.proxy.db.prisma_client import PrismaWrapper | ||
| from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import ( | ||
|
|
@@ -2266,6 +2267,32 @@ def __init__( | |
| else False | ||
| ), | ||
| ) # Client to connect to Prisma db | ||
| self._db_reconnect_lock = asyncio.Lock() | ||
| self._db_health_watchdog_task: Optional[asyncio.Task] = None | ||
| self._db_last_reconnect_attempt_ts: float = 0.0 | ||
| self._db_reconnect_cooldown_seconds: int = max( | ||
| 1, int(os.getenv("PRISMA_RECONNECT_COOLDOWN_SECONDS", "15")) | ||
| ) | ||
| self._db_health_watchdog_interval_seconds: int = max( | ||
| 5, int(os.getenv("PRISMA_HEALTH_WATCHDOG_INTERVAL_SECONDS", "30")) | ||
| ) | ||
| self._db_health_watchdog_enabled: bool = ( | ||
| str_to_bool(os.getenv("PRISMA_HEALTH_WATCHDOG_ENABLED", "true")) is True | ||
| ) | ||
| self._db_health_watchdog_probe_timeout_seconds: float = max( | ||
| 0.5, | ||
| float(os.getenv("PRISMA_HEALTH_WATCHDOG_PROBE_TIMEOUT_SECONDS", "5.0")), | ||
| ) | ||
| self._db_watchdog_reconnect_timeout_seconds: float = max( | ||
| 1.0, float(os.getenv("PRISMA_WATCHDOG_RECONNECT_TIMEOUT_SECONDS", "30.0")) | ||
| ) | ||
| self._db_auth_reconnect_timeout_seconds: float = max( | ||
| 0.5, float(os.getenv("PRISMA_AUTH_RECONNECT_TIMEOUT_SECONDS", "2.0")) | ||
| ) | ||
| self._db_auth_reconnect_lock_timeout_seconds: float = max( | ||
| 0.0, | ||
| float(os.getenv("PRISMA_AUTH_RECONNECT_LOCK_TIMEOUT_SECONDS", "0.1")), | ||
| ) | ||
| verbose_proxy_logger.debug("Success - Created Prisma Client") | ||
|
|
||
| def get_request_status( | ||
|
|
@@ -3533,6 +3560,174 @@ async def disconnect(self): | |
| ) | ||
| raise e | ||
|
|
||
| async def _run_reconnect_cycle( | ||
| self, timeout_seconds: Optional[float] = None | ||
| ) -> None: | ||
| """ | ||
| Run a reconnect cycle with direct db operations and a single overall timeout | ||
| budget to avoid long retries on hot paths (e.g. auth). | ||
| """ | ||
| async def _do_direct_reconnect() -> None: | ||
| try: | ||
| await self.db.disconnect() | ||
| except Exception as disconnect_err: | ||
| verbose_proxy_logger.debug( | ||
| "Prisma DB disconnect before reconnect failed (ignored): %s", | ||
| disconnect_err, | ||
| ) | ||
|
|
||
| await self.db.connect() | ||
| await self.db.query_raw("SELECT 1") | ||
|
|
||
| effective_timeout = ( | ||
| timeout_seconds | ||
| if timeout_seconds is not None | ||
| else self._db_watchdog_reconnect_timeout_seconds | ||
| ) | ||
| await asyncio.wait_for(_do_direct_reconnect(), timeout=effective_timeout) | ||
|
|
||
| async def attempt_db_reconnect( | ||
| self, | ||
| reason: str, | ||
| force: bool = False, | ||
| timeout_seconds: Optional[float] = None, | ||
| lock_timeout_seconds: Optional[float] = None, | ||
| ) -> bool: | ||
| """ | ||
| Attempt to reconnect the Prisma client in a singleflight manner. | ||
|
|
||
| Returns: | ||
| bool: True if reconnection succeeded, else False. | ||
| """ | ||
| now = time.time() | ||
| if ( | ||
| force is False | ||
| 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, | ||
| ) | ||
| return False | ||
|
|
||
| async def _attempt_reconnect_inside_lock() -> bool: | ||
| now = time.time() | ||
| if ( | ||
| force is False | ||
| 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, | ||
| ) | ||
| return False | ||
|
|
||
| verbose_proxy_logger.warning( | ||
| "Attempting Prisma DB reconnect. reason=%s", reason | ||
| ) | ||
|
|
||
| reconnect_succeeded = False | ||
| try: | ||
| await self._run_reconnect_cycle(timeout_seconds=timeout_seconds) | ||
| reconnect_succeeded = True | ||
| verbose_proxy_logger.info( | ||
| "Prisma DB reconnect succeeded. reason=%s", reason | ||
| ) | ||
| except Exception as reconnect_err: | ||
| verbose_proxy_logger.error( | ||
| "Prisma DB reconnect failed. reason=%s error=%s", | ||
| reason, | ||
| reconnect_err, | ||
| ) | ||
| finally: | ||
| # Start cooldown after reconnect attempt has completed. | ||
| self._db_last_reconnect_attempt_ts = time.time() | ||
|
|
||
| return reconnect_succeeded | ||
|
|
||
| if lock_timeout_seconds is None: | ||
| async with self._db_reconnect_lock: | ||
| return await _attempt_reconnect_inside_lock() | ||
|
|
||
| try: | ||
| await asyncio.wait_for( | ||
| self._db_reconnect_lock.acquire(), | ||
| timeout=lock_timeout_seconds, | ||
| ) | ||
| except asyncio.TimeoutError: | ||
| verbose_proxy_logger.debug( | ||
| "Skipping DB reconnect attempt due to lock acquisition timeout. reason=%s timeout=%ss", | ||
| reason, | ||
| lock_timeout_seconds, | ||
| ) | ||
| return False | ||
|
|
||
| try: | ||
| return await _attempt_reconnect_inside_lock() | ||
| finally: | ||
| self._db_reconnect_lock.release() | ||
|
|
||
| async def start_db_health_watchdog_task(self) -> None: | ||
| """ | ||
| Start a background task that probes DB health and attempts reconnect on failure. | ||
| """ | ||
| if self._db_health_watchdog_enabled is not True: | ||
| verbose_proxy_logger.debug( | ||
| "Prisma DB health watchdog disabled via PRISMA_HEALTH_WATCHDOG_ENABLED" | ||
| ) | ||
| return | ||
| if self._db_health_watchdog_task is not None: | ||
| return | ||
| self._db_health_watchdog_task = asyncio.create_task( | ||
| self._db_health_watchdog_loop() | ||
| ) | ||
| verbose_proxy_logger.info( | ||
| "Started Prisma DB health watchdog (interval=%ss, reconnect_cooldown=%ss, probe_timeout=%ss, reconnect_timeout=%ss)", | ||
| self._db_health_watchdog_interval_seconds, | ||
| self._db_reconnect_cooldown_seconds, | ||
| self._db_health_watchdog_probe_timeout_seconds, | ||
| self._db_watchdog_reconnect_timeout_seconds, | ||
| ) | ||
|
|
||
| async def stop_db_health_watchdog_task(self) -> None: | ||
| """ | ||
| Stop DB health watchdog task gracefully. | ||
| """ | ||
| if self._db_health_watchdog_task is None: | ||
| return | ||
| self._db_health_watchdog_task.cancel() | ||
| try: | ||
| await self._db_health_watchdog_task | ||
| except asyncio.CancelledError: | ||
| pass | ||
| self._db_health_watchdog_task = None | ||
| verbose_proxy_logger.info("Stopped Prisma DB health watchdog") | ||
|
|
||
| async def _db_health_watchdog_loop(self) -> None: | ||
| while True: | ||
| try: | ||
| await asyncio.sleep(self._db_health_watchdog_interval_seconds) | ||
| await asyncio.wait_for( | ||
| self.db.query_raw("SELECT 1"), | ||
| timeout=self._db_health_watchdog_probe_timeout_seconds, | ||
| ) | ||
| except asyncio.CancelledError: | ||
| break | ||
| except Exception as e: | ||
| if isinstance( | ||
| e, asyncio.TimeoutError | ||
| ) or PrismaDBExceptionHandler.is_database_connection_error(e): | ||
| await self.attempt_db_reconnect( | ||
| reason="db_health_watchdog_connection_error", | ||
| timeout_seconds=self._db_watchdog_reconnect_timeout_seconds, | ||
| ) | ||
| else: | ||
| verbose_proxy_logger.debug( | ||
| "Prisma DB health watchdog observed non-DB error: %s", e | ||
| ) | ||
|
Comment on lines
+3741
to
+3762
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Watchdog health_check uses backoff retries before reaching reconnect
Consider calling |
||
|
|
||
| @backoff.on_exception( | ||
| backoff.expo, | ||
| Exception, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wait_for(lock.acquire())can leak the lock on timeoutOn Python 3.9–3.11,
asyncio.wait_for(lock.acquire(), timeout=...)has a known race condition: if the lock becomes available at the exact moment the timeout fires, the lock is acquired butTimeoutErroris still raised. Since the lock is never released, all subsequent callers will deadlock on it permanently.This was fixed in CPython 3.12 (bpo-98048), but since litellm supports Python ≥3.9, this path is vulnerable.
A safer pattern is to use
asyncio.wait_forwith a wrapper that releases on cancellation, or use a manual approach:Alternatively, a simpler approach: use a
asyncio.wait_foronly on Python 3.12+ and fall back to a manual timer on older versions, or just useasyncio.timeout()(3.11+).Context Used: Rule from
dashboard- What: Avoid creating new database requests or Router objects in the critical request path.Why: Cre... (source)