Skip to content

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]

[Feature] Proxy: opt-in v2 migration resolver (--use_v2_migration_resolver)

Yuneng Jianga16c00e22c51
diff --git a/litellm-proxy-extras/litellm_proxy_extras/utils.py b/litellm-proxy-extras/litellm_proxy_extras/utils.py
index c24188cba1d..04005ce2548 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/utils.py
+++ b/litellm-proxy-extras/litellm_proxy_extras/utils.py
@@ -30,6 +30,26 @@ def _get_prisma_env() -> dict:
return prisma_env
+_MIGRATION_TS_RE = re.compile(r"^(\d{14})_")
+
+
+def _migration_timestamp(name: str) -> int:
+ """Extract the leading `YYYYMMDDHHMMSS` timestamp from a migration name.
+
+ Returns 0 if the name doesn't match the Prisma pattern — unexpected-format
+ entries sort as "oldest" and are treated as historical.
+ """
+ m = _MIGRATION_TS_RE.match(name)
+ return int(m.group(1)) if m else 0
+
+
+def _max_migration_timestamp(names) -> int:
+ """Max timestamp in a set/list of migration names (0 if empty)."""
+ if not names:
+ return 0
+ return max(_migration_timestamp(n) for n in names)
+
+
def _get_prisma_command() -> str:
"""Get the Prisma command to use, bypassing Python wrapper in offline mode."""
if str_to_bool(os.getenv("PRISMA_OFFLINE_MODE")):
@@ -383,18 +403,255 @@ class ProxyExtrasDBManager:
)
@staticmethod
- def setup_database(use_migrate: bool = False) -> bool:
+ def _strip_prisma_query_params(url: str) -> str:
+ """Remove Prisma-specific query params (connection_limit, pool_timeout,
+ schema, etc.) from DATABASE_URL so psycopg can parse it."""
+ from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
+
+ parsed = urlparse(url)
+ if not parsed.query:
+ return url
+ libpq_params = {
+ "sslmode",
+ "sslcert",
+ "sslkey",
+ "sslrootcert",
+ "sslpassword",
+ "application_name",
+ "connect_timeout",
+ "client_encoding",
+ "options",
+ "service",
+ "gssencmode",
+ "krbsrvname",
+ "target_session_attrs",
+ }
+ kept = [(k, v) for k, v in parse_qsl(parsed.query) if k in libpq_params]
+ return urlunparse(parsed._replace(query=urlencode(kept)))
+
+ @staticmethod
+ def _warn_if_db_ahead_of_head(migrations_dir: str) -> None:
+ """
+ Log a warning if _prisma_migrations contains applied migrations with
+ timestamps newer than every migration this build ships.
+
+ This is informational only for the v2 resolver — it tells the operator
+ the DB was likely migrated by a newer deployment, which is usually a
+ signal that this (older) version shouldn't run against it. We do NOT
+ block startup: many users have weird _prisma_migrations state from
+ prior thrashing bugs, and blocking them would be a breaking change.
+
+ Safe no-op if psycopg isn't installed or DB isn't reachable.
+ """
+ database_url = os.getenv("DATABASE_URL")
+ if not database_url:
+ return
+
+ try:
+ import psycopg
+ except ImportError:
+ return
+
+ cleaned_url = ProxyExtrasDBManager._strip_prisma_query_params(database_url)
+ known = set(ProxyExtrasDBManager._get_migration_names(migrations_dir))
+
+ try:
+ with psycopg.connect(cleaned_url, connect_timeout=10) as conn:
+ try:
+ rows = conn.execute(
+ "SELECT migration_name FROM _prisma_migrations "
+ "WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL"
+ ).fetchall()
+ except psycopg.errors.UndefinedTable:
+ return
+ except psycopg.OperationalError:
+ return
+
+ applied = {r[0] for r in rows}
+ unknown = applied - known
+ if not unknown:
+ return
+
+ head_newest_ts = _max_migration_timestamp(known)
+ hostile = {
+ name for name in unknown if _migration_timestamp(name) > head_newest_ts
+ }
+ if not hostile:
+ return
+
+ sorted_hostile = sorted(hostile)
+ logger.warning(
+ "Database has %d migration(s) applied that are NEWER than any "
+ "migration this LiteLLM version ships. This usually means the "
+ "database was migrated by a newer LiteLLM deployment. Some API "
+ "endpoints may fail because this proxy's Prisma client does not "
+ "know about those schema changes. Consider upgrading this "
+ "deployment. Unknown: %s",
+ len(hostile),
+ ", ".join(sorted_hostile[:5]) + (" ..." if len(sorted_hostile) > 5 else ""),
+ )
+
+ @staticmethod
+ def _setup_database_v2(use_migrate: bool) -> bool:
+ """
+ v2 migration resolver (opt-in via --use_v2_migration_resolver).
+
+ Runs `prisma migrate deploy` and handles standard recovery paths
+ (P3005 baseline, P3009/P3018 idempotent errors). Critically, it does
+ NOT call `_resolve_all_migrations` — the diff-and-force recovery that
+ caused schema thrashing when two LiteLLM versions contended for the
+ same DB during rolling deploys.
+
+ Ahead-of-HEAD state (DB has migrations newer than this build ships)
+ is logged as a warning, not a fatal error — users whose DBs got into
+ weird shapes from the old thrashing should still be able to start.
+ """
+ schema_path = ProxyExtrasDBManager._get_prisma_dir() + "/schema.prisma"
+ migrations_dir = ProxyExtrasDBManager._get_prisma_dir()
+
+ if not use_migrate:
+ # Preserve `prisma db push` path unchanged.
+ original_dir = os.getcwd()
+ os.chdir(migrations_dir)
+ try:
+ subprocess.run(
+ [_get_prisma_command(), "db", "push", "--accept-data-loss"],
+ timeout=60,
+ check=True,
+ env=_get_prisma_env(),
+ )
+ return True
+ finally:
+ os.chdir(original_dir)
+
+ # Informational — never blocks.
+ ProxyExtrasDBManager._warn_if_db_ahead_of_head(migrations_dir)
+
+ original_dir = os.getcwd()
+ os.chdir(migrations_dir)
+ try:
+ for attempt in range(4):
+ try:
+ result = subprocess.run(
+ [_get_prisma_command(), "migrate", "deploy"],
+ timeout=60,
+ check=True,
+ capture_output=True,
+ text=True,
+ env=_get_prisma_env(),
+ )
+ logger.info(f"prisma migrate deploy stdout: {result.stdout}")
+ return True
+
+ except subprocess.TimeoutExpired:
+ logger.info(
+ f"prisma migrate deploy attempt {attempt + 1} timed out, retrying"
+ )
+ time.sleep(random.randrange(5, 15))
+ continue
+
+ except subprocess.CalledProcessError as e:
+ stderr = e.stderr or ""
+
+ if "P3005" in stderr and "database schema is not empty" in stderr:
+ logger.info(
+ "Schema exists but no migrations ledger — creating baseline"
+ )
+ ProxyExtrasDBManager._create_baseline_migration(schema_path)
+ continue
+
+ if "P3009" in stderr:
+ migration_match = re.search(r"`(\d+_\S+?)`", stderr)
+ if (
+ migration_match
+ and ProxyExtrasDBManager._is_idempotent_error(stderr)
+ ):
+ name = migration_match.group(1)
+ logger.info(
+ f"Migration {name} failed idempotently — marking applied and retrying"
+ )
+ try:
+ ProxyExtrasDBManager._roll_back_migration(name)
+ except (
+ subprocess.CalledProcessError,
+ subprocess.TimeoutExpired,
+ ):
+ pass
+ ProxyExtrasDBManager._resolve_specific_migration(name)
+ continue
+ raise RuntimeError(
+ "Database migration failed and cannot be auto-recovered. "
+ f"Manual intervention required.\n\nPrisma error:\n{stderr}"
+ ) from e
+
+ if "P3018" in stderr:
+ if ProxyExtrasDBManager._is_permission_error(stderr):
+ raise RuntimeError(
+ "Database migration failed due to insufficient "
+ "permissions. Please grant the required privileges "
+ f"and retry.\n\nPrisma error:\n{stderr}"
+ ) from e
+
+ migration_match = re.search(
+ r"Migration name: (\d+_\S+)", stderr
+ )
+ if (
+ migration_match
+ and ProxyExtrasDBManager._is_idempotent_error(stderr)
+ ):
+ name = migration_match.group(1)
+ logger.info(
+ f"Migration {name} SQL hit idempotent error — marking applied and retrying"
+ )
+ try:
+ ProxyExtrasDBManager._roll_back_migration(name)
+ except (
+ subprocess.CalledProcessError,
+ subprocess.TimeoutExpired,
+ ):
+ pass
+ ProxyExtrasDBManager._resolve_specific_migration(name)
+ continue
+
+ raise RuntimeError(
+ "Database migration failed and cannot be auto-recovered. "
+ f"Manual intervention required.\n\nPrisma error:\n{stderr}"
+ ) from e
+
+ raise RuntimeError(
+ "Database migration failed and cannot be auto-recovered. "
+ f"Manual intervention required.\n\nPrisma error:\n{stderr}"
+ ) from e
+
+ raise RuntimeError(
+ "Database migration failed after 4 attempts (persistent timeouts). "
+ "Check database connectivity and load."
+ )
+ finally:
+ os.chdir(original_dir)
+
+ @staticmethod
+ def setup_database(
+ use_migrate: bool = False, use_v2_resolver: bool = False
+ ) -> bool:
"""
Set up the database using either prisma migrate or prisma db push
Uses migrations from litellm-proxy-extras package
Args:
- schema_path (str): Path to the Prisma schema file
- use_migrate (bool): Whether to use prisma migrate instead of db push
+ use_migrate: Whether to use prisma migrate instead of db push
+ use_v2_resolver: Opt into the v2 migration resolver (safer during
+ rolling deploys; does not run the diff-and-force recovery
+ that causes schema thrashing). Defaults to False for
+ backwards compatibility.
Returns:
bool: True if setup was successful, False otherwise
"""
+ if use_v2_resolver:
+ logger.info("Using v2 migration resolver (--use_v2_migration_resolver)")
+ return ProxyExtrasDBManager._setup_database_v2(use_migrate=use_migrate)
+
schema_path = ProxyExtrasDBManager._get_prisma_dir() + "/schema.prisma"
for attempt in range(4):
original_dir = os.getcwd()
diff --git a/litellm-proxy-extras/tests/test_setup_database_fail_fast.py b/litellm-proxy-extras/tests/test_setup_database_fail_fast.py
new file mode 100644
index 00000000000..38df390a42d
--- /dev/null
+++ b/litellm-proxy-extras/tests/test_setup_database_fail_fast.py
@@ -0,0 +1,158 @@
+"""Regression tests for ProxyExtrasDBManager v2 migration resolver.
+
+The v2 resolver is opt-in via `--use_v2_migration_resolver` / the
+`use_v2_resolver=True` kwarg. These tests exercise the v2 path; the v1
+(default) behavior is unchanged from pre-fix.
+"""
+
+import subprocess
+from unittest.mock import patch
+
+import pytest
+
+from litellm_proxy_extras.utils import (
+ ProxyExtrasDBManager,
+ _max_migration_timestamp,
+ _migration_timestamp,
+)
+
+
+def _fake_migrate_deploy_failure(returncode: int, stderr: str):
+ def _run(*args, **kwargs):
+ raise subprocess.CalledProcessError(
+ returncode=returncode,
+ cmd=args[0],
+ stderr=stderr,
+ output="",
+ )
+
+ return _run
+
+
+def test_v2_p3018_permission_error_raises_runtime_error(monkeypatch, tmp_path):
+ """v2: a permission failure during migrate deploy raises RuntimeError."""
+ monkeypatch.setenv("DATABASE_URL", "postgresql://u:p@localhost:9/x")
+ monkeypatch.setattr(
+ ProxyExtrasDBManager, "_warn_if_db_ahead_of_head", lambda _: None
+ )
+ monkeypatch.setattr(ProxyExtrasDBManager, "_get_prisma_dir", lambda: str(tmp_path))
+ (tmp_path / "schema.prisma").write_text("// stub")
+
+ stderr = (
+ "Error: P3018\nMigration name: 20250326162113_baseline\n"
+ "Database error code: 42501\npermission denied for schema public"
+ )
+ with patch("subprocess.run", side_effect=_fake_migrate_deploy_failure(1, stderr)):
+ with pytest.raises(RuntimeError, match="permission"):
+ ProxyExtrasDBManager.setup_database(use_migrate=True, use_v2_resolver=True)
+
+
+def test_v2_non_idempotent_p3009_raises_runtime_error(monkeypatch, tmp_path):
+ """v2: a non-idempotent migration failure raises (no silent recovery)."""
+ monkeypatch.setenv("DATABASE_URL", "postgresql://u:p@localhost:9/x")
+ monkeypatch.setattr(
+ ProxyExtrasDBManager, "_warn_if_db_ahead_of_head", lambda _: None
+ )
+ monkeypatch.setattr(ProxyExtrasDBManager, "_get_prisma_dir", lambda: str(tmp_path))
+ (tmp_path / "schema.prisma").write_text("// stub")
+
+ stderr = (
+ "Error: P3009\nMigration `20260101000000_genuinely_broken` failed\n"
+ 'Reason: syntax error at or near "BRKN" LINE 42'
+ )
+ with patch("subprocess.run", side_effect=_fake_migrate_deploy_failure(1, stderr)):
+ with pytest.raises(RuntimeError, match="cannot be auto-recovered"):
+ ProxyExtrasDBManager.setup_database(use_migrate=True, use_v2_resolver=True)
+
+
+def test_strip_prisma_query_params_removes_connection_limit():
+ """DATABASE_URLs with Prisma-specific params should be parseable by psycopg."""
+ url = "postgresql://u:p@h:5432/db?connection_limit=100&pool_timeout=60&sslmode=require"
+ stripped = ProxyExtrasDBManager._strip_prisma_query_params(url)
+ assert "connection_limit" not in stripped
+ assert "pool_timeout" not in stripped
+ assert "sslmode=require" in stripped
+
+
+def test_strip_prisma_query_params_passthrough_no_query():
+ """URLs without query strings are returned unchanged."""
+ url = "postgresql://u:p@h:5432/db"
+ assert ProxyExtrasDBManager._strip_prisma_query_params(url) == url
+
+
+def test_migration_timestamp_extracts_leading_digits():
+ assert _migration_timestamp("20260101000000_add_foo") == 20260101000000
+ assert _migration_timestamp("20250326162113_baseline") == 20250326162113
+
+
+def test_migration_timestamp_returns_zero_on_malformed():
+ assert _migration_timestamp("0_init") == 0
+ assert _migration_timestamp("not_a_migration") == 0
+
+
+def test_max_migration_timestamp():
+ names = {"20250326000000_a", "20260415000000_b", "20251115000000_c"}
+ assert _max_migration_timestamp(names) == 20260415000000
+
+
+def test_max_migration_timestamp_empty_set():
+ assert _max_migration_timestamp(set()) == 0
+
+
+def test_v1_default_still_calls_resolve_all_migrations(monkeypatch, tmp_path):
+ """v1 (default) continues to call _resolve_all_migrations on the happy path.
+
+ This is the existing buggy behavior — we're not fixing it in v1, only
+ offering v2 as opt-in. This test pins the default so that a future
+ inadvertent default flip is caught.
+ """
+ monkeypatch.setattr(ProxyExtrasDBManager, "_get_prisma_dir", lambda: str(tmp_path))
+ (tmp_path / "schema.prisma").write_text("// stub")
+
+ # Stub `prisma migrate deploy` to claim success with pending migrations
+ # applied, which is the code path that triggers the legacy post-migration
+ # sanity check (a call to _resolve_all_migrations).
+ class FakeResult:
+ stdout = "Applied migration.\n"
+ stderr = ""
+
+ def fake_run(cmd, *args, **kwargs):
+ return FakeResult()
+
+ resolve_called = {"n": 0}
+
+ def fake_resolve(*args, **kwargs):
+ resolve_called["n"] += 1
+
+ monkeypatch.setattr("subprocess.run", fake_run)
+ monkeypatch.setattr(ProxyExtrasDBManager, "_resolve_all_migrations", fake_resolve)
+
+ ok = ProxyExtrasDBManager.setup_database(use_migrate=True) # v2 flag NOT set
+ assert ok is True
+ assert resolve_called["n"] == 1, "v1 default should still invoke the legacy path"
+
+
+def test_v2_does_not_call_resolve_all_migrations(monkeypatch, tmp_path):
+ """v2 must never call _resolve_all_migrations — that's the bug it fixes."""
+ monkeypatch.setattr(
+ ProxyExtrasDBManager, "_warn_if_db_ahead_of_head", lambda _: None
+ )
+ monkeypatch.setattr(ProxyExtrasDBManager, "_get_prisma_dir", lambda: str(tmp_path))
+ (tmp_path / "schema.prisma").write_text("// stub")
+
+ class FakeResult:
+ stdout = "Applied migration.\n"
+ stderr = ""
+
+ monkeypatch.setattr("subprocess.run", lambda *a, **kw: FakeResult())
+
+ resolve_called = {"n": 0}
+ monkeypatch.setattr(
+ ProxyExtrasDBManager,
+ "_resolve_all_migrations",
+ lambda *a, **kw: resolve_called.__setitem__("n", resolve_called["n"] + 1),
+ )
+
+ ok = ProxyExtrasDBManager.setup_database(use_migrate=True, use_v2_resolver=True)
+ assert ok is True
+ assert resolve_called["n"] == 0, "v2 must not invoke the diff-and-force recovery"
diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.py
index 114103508ea..73735796eb3 100644
--- a/litellm/proxy/db/prisma_client.py
+++ b/litellm/proxy/db/prisma_client.py
@@ -403,10 +403,18 @@ class PrismaManager:
return dname
@staticmethod
- def setup_database(use_migrate: bool = False) -> bool:
+ def setup_database(
+ use_migrate: bool = False, use_v2_resolver: bool = False
+ ) -> bool:
"""
Set up the database using either prisma migrate or prisma db push
+ Args:
+ use_migrate: Use `prisma migrate deploy` instead of `db push`.
+ use_v2_resolver: Opt into the v2 migration resolver that avoids
+ the diff-and-force recovery behavior (which caused schema
+ thrashing during rolling deploys). Defaults to False.
+
Returns:
bool: True if setup was successful, False otherwise
"""
@@ -427,7 +435,10 @@ class PrismaManager:
prisma_dir = PrismaManager._get_prisma_dir()
- return ProxyExtrasDBManager.setup_database(use_migrate=use_migrate)
+ return ProxyExtrasDBManager.setup_database(
+ use_migrate=use_migrate,
+ use_v2_resolver=use_v2_resolver,
+ )
else:
# Use prisma db push with increased timeout
subprocess.run(
diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py
index f1e5938c1f4..3845203bb9d 100644
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@ -577,6 +577,16 @@ class ProxyInitializationHelpers:
help="Exit with error if database migration fails on startup.",
envvar="ENFORCE_PRISMA_MIGRATION_CHECK",
)
+ "--use_v2_migration_resolver",
+ is_flag=True,
+ default=False,
+ help=(
+ "Opt into the v2 migration resolver. Avoids the diff-and-force recovery "
+ "path that can cause schema thrashing during rolling deploys where two "
+ "LiteLLM versions contend for the same DB. Default is the v1 resolver."
+ ),
+)
@click.option(
"--reload",
is_flag=True,
@@ -624,6 +634,7 @@ def run_server( # noqa: PLR0915
keepalive_timeout,
max_requests_before_restart,
enforce_prisma_migration_check: bool,
+ use_v2_migration_resolver: bool,
reload: bool,
):
if setup:
@@ -893,9 +904,31 @@ def run_server( # noqa: PLR0915
):
check_prisma_schema_diff(db_url=None)
else:
- if not PrismaManager.setup_database(
- use_migrate=not use_prisma_db_push
- ):
+ if not use_v2_migration_resolver:
+ print( # noqa
+ "\033[1;33mLiteLLM Proxy: Using default (v1) migration resolver. "
+ "If your deployment has seen schema thrashing during rolling "
+ "deploys, try --use_v2_migration_resolver (safer: avoids the "
+ "diff-and-force recovery that caused the thrash).\033[0m"
+ )
+ try:
+ setup_ok = PrismaManager.setup_database(
+ use_migrate=not use_prisma_db_push,
+ use_v2_resolver=use_v2_migration_resolver,
+ )
+ except RuntimeError as e:
+ # v2 resolver raises on unrecoverable migration errors
+ # (e.g. non-idempotent failures, permission issues).
+ # v1 never raises here, so this only fires when the
+ # operator opted into v2.
+ print( # noqa
+ "\033[1;31mLiteLLM Proxy: Database migration cannot proceed. "
+ f"{e}\033[0m",
+ file=sys.stderr,
+ flush=True,
+ )
+ sys.exit(2)
+ if not setup_ok:
if enforce_prisma_migration_check:
print( # noqa
"\033[1;31mLiteLLM Proxy: Database setup failed after multiple retries. "