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]

fix(proxy-extras): bound migration lock waits with SET LOCAL lock_timeout in the migration SQL (#46329)

Yassin Kortamae9c208b8d0a
diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml
index 95dc73998d7..b31f5a6d4e5 100644
--- a/.github/workflows/test-linting.yml
+++ b/.github/workflows/test-linting.yml
@@ -618,6 +618,9 @@ jobs:
- name: check_migrations_no_data_rewrites
run: uv run --no-sync python ./tests/code_coverage_tests/check_migrations_no_data_rewrites.py
+ - name: check_migrations_lock_timeout
+ run: uv run --no-sync python ./tests/code_coverage_tests/check_migrations_lock_timeout.py
+
- name: check_no_publicly_known_master_key
run: uv run --no-sync python ./tests/code_coverage_tests/check_no_publicly_known_master_key.py
diff --git a/ci_cd/run_migration.py b/ci_cd/run_migration.py
index c737050f3a8..84d529d2a99 100644
--- a/ci_cd/run_migration.py
+++ b/ci_cd/run_migration.py
@@ -322,7 +322,12 @@ def create_migration(
# Write the SQL to migration.sql
migration_file = migration_dir / "migration.sql"
- migration_file.write_text(diff_sql)
+ migration_sql: Final = (
+ diff_sql
+ if "CONCURRENTLY" in diff_sql.upper()
+ else "SET LOCAL lock_timeout = '10s';\n\n" + diff_sql
+ )
+ migration_file.write_text(migration_sql)
print(f"Created migration in {migration_dir}")
return True
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migration_lock.py b/litellm-proxy-extras/litellm_proxy_extras/migration_lock.py
index 3df82d8c81e..671ce0f5c3e 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/migration_lock.py
+++ b/litellm-proxy-extras/litellm_proxy_extras/migration_lock.py
@@ -1,5 +1,4 @@
import random
-import re
import time
from collections.abc import Generator, Mapping
from contextlib import contextmanager
@@ -10,12 +9,10 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from litellm_proxy_extras._logging import logger
from litellm_proxy_extras.prisma_toolchain import (
MIGRATION_LOCK_TIMEOUT_ENV_VAR,
- migration_ddl_lock_timeout,
migration_lock_timeout,
)
MIGRATION_LOCK_KEY: Final = int.from_bytes(b"llm_mig2", "big")
-_LOCK_TIMEOUT_PINNED_RE: Final = re.compile(r"(?:-c\s*|--)lock_timeout=")
if TYPE_CHECKING:
import psycopg
@@ -30,29 +27,12 @@ def _migration_url(database_url: str, direct_url: "str | None") -> str:
return urlunsplit(direct._replace(query=urlencode((*parameters, ("schema", schema)))))
-def _with_ddl_lock_timeout(url: str) -> str:
- split: Final = urlsplit(url)
- pairs: Final = tuple(parse_qsl(split.query))
- if any(key == "pgbouncer" and value == "true" for key, value in pairs):
- return url
- existing: Final = next((value for key, value in pairs if key == "options"), "")
- if _LOCK_TIMEOUT_PINNED_RE.search(existing):
- return url
- timeout_ms: Final = max(1, int(migration_ddl_lock_timeout() * 1000))
- options: Final = f"{existing} -c lock_timeout={timeout_ms}".strip()
- rewritten: Final = tuple((key, value) for key, value in pairs if key != "options") + (("options", options),)
- return urlunsplit(split._replace(query=urlencode(rewritten)))
-
-
def migration_environment(environment: Mapping[str, str]) -> Mapping[str, str]:
database_url: Final = environment.get("DATABASE_URL")
if not database_url:
return environment
migration_url: Final = _migration_url(database_url, environment.get("DIRECT_URL"))
- return {
- **environment,
- "DATABASE_URL": _with_ddl_lock_timeout(migration_url),
- }
+ return {**environment, "DATABASE_URL": migration_url}
@dataclass(frozen=True, slots=True)
diff --git a/litellm-proxy-extras/litellm_proxy_extras/prisma_toolchain.py b/litellm-proxy-extras/litellm_proxy_extras/prisma_toolchain.py
index 11b58284f41..07f83f76d2b 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/prisma_toolchain.py
+++ b/litellm-proxy-extras/litellm_proxy_extras/prisma_toolchain.py
@@ -60,13 +60,11 @@ PRISMA_COMMAND_TIMEOUT_ENV_VAR = "LITELLM_PRISMA_COMMAND_TIMEOUT"
PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR = "LITELLM_PRISMA_BOOTSTRAP_TIMEOUT"
PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR = "LITELLM_PRISMA_MIGRATE_DEPLOY_TIMEOUT"
MIGRATION_LOCK_TIMEOUT_ENV_VAR = "LITELLM_MIGRATION_LOCK_TIMEOUT"
-MIGRATION_DDL_LOCK_TIMEOUT_ENV_VAR = "LITELLM_MIGRATION_DDL_LOCK_TIMEOUT"
NODEENV_CACHE_DIR_ENV_VAR = "PRISMA_NODEENV_CACHE_DIR"
DEFAULT_PRISMA_COMMAND_TIMEOUT = 60.0
DEFAULT_PRISMA_BOOTSTRAP_TIMEOUT = 600.0
DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT = 600.0
-DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT = 10.0
BOOTSTRAP_ARG = "--version"
PRISMA_CONSOLE_SCRIPT = "prisma"
@@ -113,11 +111,6 @@ def migration_lock_timeout() -> float:
return _timeout_from_env(MIGRATION_LOCK_TIMEOUT_ENV_VAR, 600.0)
-def migration_ddl_lock_timeout() -> float:
- """Seconds one migration statement may wait on a table lock before Postgres cancels it."""
- return _timeout_from_env(MIGRATION_DDL_LOCK_TIMEOUT_ENV_VAR, DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT)
-
-
def prisma_bootstrap_timeout() -> float:
"""Seconds the one-time Node toolchain install may run for."""
return _timeout_from_env(
diff --git a/litellm-proxy-extras/litellm_proxy_extras/utils.py b/litellm-proxy-extras/litellm_proxy_extras/utils.py
index 061fb627c65..2a109130ff8 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/utils.py
+++ b/litellm-proxy-extras/litellm_proxy_extras/utils.py
@@ -18,7 +18,6 @@ from litellm_proxy_extras import prisma_toolchain
from litellm_proxy_extras._logging import logger
from litellm_proxy_extras.migration_lock import held_migration_lock
from litellm_proxy_extras.prisma_toolchain import (
- MIGRATION_DDL_LOCK_TIMEOUT_ENV_VAR,
PRISMA_COMMAND_TIMEOUT_ENV_VAR,
PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR,
ensure_prisma_toolchain,
@@ -1165,10 +1164,9 @@ class ProxyExtrasDBManager:
raise RuntimeError(
f"Database migration failed after {MAX_MIGRATE_DEPLOY_ATTEMPTS} "
"attempts that made no progress (timeouts, lock timeouts or deadlock retries). "
- "Check database connectivity, load, long-running transactions on the migrated tables, "
- "and _prisma_migrations ledger state. Raise "
- f"{PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR} if the attempts timed out, or "
- f"{MIGRATION_DDL_LOCK_TIMEOUT_ENV_VAR} if they timed out waiting for a table lock."
+ "Check database connectivity, load and _prisma_migrations ledger state. "
+ "If a migration hit SET LOCAL lock_timeout, check for long-running transactions on the migrated tables. "
+ f"Raise {PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR} if the attempts timed out."
)
finally:
os.chdir(original_dir)
@@ -1284,8 +1282,8 @@ class ProxyExtrasDBManager:
if migration_name and _MIGRATION_LOCK_TIMEOUT_MARKER in stderr:
ProxyExtrasDBManager._log_migration_lock_holders(migration_name)
logger.warning(
- "Migration %s timed out waiting for a table lock, rolling its ledger row back and retrying. "
- f"Raise {MIGRATION_DDL_LOCK_TIMEOUT_ENV_VAR} if the database needs longer.",
+ "Migration %s timed out waiting for a table lock after hitting SET LOCAL lock_timeout, rolling "
+ "its ledger row back and retrying. Check for long-running transactions on the migrated tables.",
migration_name,
)
ProxyExtrasDBManager._v2_roll_back_migration_best_effort(migration_name)
diff --git a/tests/code_coverage_tests/check_migrations_lock_timeout.py b/tests/code_coverage_tests/check_migrations_lock_timeout.py
new file mode 100644
index 00000000000..22190f5fb77
--- /dev/null
+++ b/tests/code_coverage_tests/check_migrations_lock_timeout.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+
+import re
+import sys
+from itertools import chain
+from pathlib import Path
+from typing import Final
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+MIGRATIONS_DIR = REPO_ROOT / "litellm-proxy-extras" / "litellm_proxy_extras" / "migrations"
+GRANDFATHERED_THROUGH: Final = "20261009000000_add_credential_display_name"
+LOCK_TIMEOUT_LINE: Final = "SET LOCAL lock_timeout = '10s';"
+LOCK_TIMEOUT_RE: Final = re.compile(
+ r"SET\s+LOCAL\s+lock_timeout\s*=\s*'\d+(?:ms|s)';",
+ re.IGNORECASE,
+)
+
+
+def first_statement(sql: str) -> str:
+ executable_sql: Final = "\n".join(
+ line for line in sql.splitlines() if line.strip() and not line.lstrip().startswith("--")
+ )
+ match: Final = re.search(r"(?s).*?;", executable_sql)
+ return match.group().strip() if match is not None else executable_sql.strip()
+
+
+def scan_migration(directory: Path) -> tuple[str, ...]:
+ if directory.name <= GRANDFATHERED_THROUGH:
+ return ()
+
+ sql: Final = (directory / "migration.sql").read_text(encoding="utf-8")
+ if "CONCURRENTLY" in sql.upper():
+ return ()
+
+ if LOCK_TIMEOUT_RE.fullmatch(first_statement(sql)):
+ return ()
+
+ return (
+ f"{directory.name}/migration.sql: first SQL statement must be SET LOCAL lock_timeout; "
+ f"add this exact line: {LOCK_TIMEOUT_LINE}",
+ )
+
+
+def scan_migrations(migrations_dir: Path) -> tuple[str, ...]:
+ directories: Final = tuple(sorted(path for path in migrations_dir.iterdir() if (path / "migration.sql").is_file()))
+ return tuple(chain.from_iterable(scan_migration(directory) for directory in directories))
+
+
+def main() -> int:
+ if not MIGRATIONS_DIR.is_dir():
+ sys.stderr.write(f"migrations directory not found: {MIGRATIONS_DIR}\n")
+ return 2
+
+ violations: Final = scan_migrations(MIGRATIONS_DIR)
+ for violation in violations:
+ sys.stdout.write(f"{violation}\n")
+
+ if violations:
+ return 1
+
+ sys.stdout.write("All new migrations start with SET LOCAL lock_timeout.\n")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/e2e/migrations/checks.py b/tests/e2e/migrations/checks.py
index a1748ec34e6..11a711e6611 100644
--- a/tests/e2e/migrations/checks.py
+++ b/tests/e2e/migrations/checks.py
@@ -17,9 +17,11 @@ NEXT: Final = Migration(
"CREATE TABLE migration_next (id int PRIMARY KEY); INSERT INTO migration_next VALUES (2);",
)
FATAL: Final = Migration(COMPLETE.name, "DO $$ BEGIN RAISE EXCEPTION 'MIGRATION_TEST_FATAL'; END $$;")
-GATED: Final = Migration(
- COMPLETE.name, f"SELECT pg_advisory_lock({GATE_KEY}); {COMPLETE.script} SELECT pg_advisory_unlock({GATE_KEY});"
+_GATED_SQL: Final = (
+ f"SELECT pg_advisory_lock({GATE_KEY}); {COMPLETE.script} SELECT pg_advisory_unlock({GATE_KEY});"
)
+GATED: Final = Migration(COMPLETE.name, f"SET LOCAL lock_timeout = '10s';\n{_GATED_SQL}")
+GATED_WITH_SHORT_LOCK_TIMEOUT: Final = Migration(COMPLETE.name, f"SET LOCAL lock_timeout = '2s';\n{_GATED_SQL}")
@step("Start {count} proxy containers on the test database")
diff --git a/tests/e2e/migrations/test_startup.py b/tests/e2e/migrations/test_startup.py
index 856192937e2..4a43ed4c0e3 100644
--- a/tests/e2e/migrations/test_startup.py
+++ b/tests/e2e/migrations/test_startup.py
@@ -8,6 +8,7 @@ from .checks import (
COMPLETE,
FATAL,
GATED,
+ GATED_WITH_SHORT_LOCK_TIMEOUT,
assert_completed,
assert_completed_after_lock_timeouts,
start_replicas,
@@ -111,19 +112,17 @@ class TestMigrationStartup:
)
def test_lock_timeout_exhaustion_then_restart(self, containers: Containers, database: Database) -> None:
with database.lock():
- with containers.start(
- database, (GATED,), environment={"LITELLM_MIGRATION_DDL_LOCK_TIMEOUT": "2"}
- ) as replica:
+ with containers.start(database, (GATED_WITH_SHORT_LOCK_TIMEOUT,)) as replica:
until("owner blocked in migration SQL", lambda: bool(database.blocked()))
failed((replica,), "attempts that made no progress")
assert not database.exists("migration_effect")
assert database.query(
"SELECT count(*) FROM _prisma_migrations WHERE migration_name = %s AND finished_at IS NOT NULL",
- (GATED.name,),
+ (GATED_WITH_SHORT_LOCK_TIMEOUT.name,),
) == ((0,),)
- with containers.start(database, (GATED,)) as restarted:
+ with containers.start(database, (GATED_WITH_SHORT_LOCK_TIMEOUT,)) as restarted:
ready((restarted,), database)
- assert_completed_after_lock_timeouts(database, GATED)
+ assert_completed_after_lock_timeouts(database, GATED_WITH_SHORT_LOCK_TIMEOUT)
@meta(
Subject(
diff --git a/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py b/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
index 697c5a828bb..e60f049a8ed 100644
--- a/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
+++ b/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
@@ -884,19 +884,18 @@ class _FakeLedger:
(
"postgresql://pool/db?pgbouncer=true",
"postgresql://writer/db",
- "postgresql://writer/db?schema=public&options=-c+lock_timeout%3D10000",
+ "postgresql://writer/db?schema=public",
),
(
"postgresql://pool/db?schema=tenant%20one&pgbouncer=true",
"postgresql://writer/db?sslmode=require&schema=wrong",
- "postgresql://writer/db?sslmode=require&schema=tenant+one&options=-c+lock_timeout%3D10000",
+ "postgresql://writer/db?sslmode=require&schema=tenant+one",
),
),
)
-def test_v2_migrations_use_the_direct_connection_with_the_runtime_schema(monkeypatch, pooled, direct, expected):
+def test_v2_migrations_use_the_direct_connection_with_the_runtime_schema(pooled, direct, expected):
from litellm_proxy_extras.migration_lock import migration_environment
- monkeypatch.delenv("LITELLM_MIGRATION_DDL_LOCK_TIMEOUT", raising=False)
environment = {"DATABASE_URL": pooled, "PRISMA_OFFLINE_MODE": "true"}
configured = {**environment, **({"DIRECT_URL": direct} if direct else {})}
migrated = migration_environment(configured)
@@ -906,106 +905,6 @@ def test_v2_migrations_use_the_direct_connection_with_the_runtime_schema(monkeyp
assert configured["DATABASE_URL"] == pooled
- "database_url,direct_url,ddl_timeout,expected_pairs",
- (
- (
- "postgresql://writer/db",
- None,
- None,
- [("options", "-c lock_timeout=10000")],
- ),
- (
- "postgresql://pool/db?schema=tenant&pgbouncer=true",
- "postgresql://writer/db?options=-c%20statement_timeout%3D0&schema=wrong",
- None,
- [("schema", "tenant"), ("options", "-c statement_timeout=0 -c lock_timeout=10000")],
- ),
- (
- "postgresql://pool/db",
- "postgresql://writer/db?options=-c%20lock_timeout%3D2500",
- None,
- [("options", "-c lock_timeout=2500"), ("schema", "public")],
- ),
- (
- "postgresql://pool/db",
- "postgresql://writer/db?options=-clock_timeout%3D2500",
- None,
- [("options", "-clock_timeout=2500"), ("schema", "public")],
- ),
- (
- "postgresql://pool/db",
- "postgresql://writer/db?options=--lock_timeout%3D0",
- None,
- [("options", "--lock_timeout=0"), ("schema", "public")],
- ),
- (
- "postgresql://pool/db",
- "postgresql://writer/db?options=-c%20deadlock_timeout%3D1000",
- None,
- [("schema", "public"), ("options", "-c deadlock_timeout=1000 -c lock_timeout=10000")],
- ),
- (
- "postgresql://pool/db",
- "postgresql://writer/db?pgbouncer=true",
- None,
- [("pgbouncer", "true"), ("schema", "public")],
- ),
- (
- "postgresql://writer/db",
- None,
- "2.5",
- [("options", "-c lock_timeout=2500")],
- ),
- (
- "postgresql://writer/db",
- None,
- "abc",
- [("options", "-c lock_timeout=10000")],
- ),
- ),
- ids=(
- "plain-database-url",
- "direct-url-with-an-existing-options-value",
- "pinned-dash-c-lock-timeout",
- "pinned-dash-clock-timeout",
- "pinned-double-dash-lock-timeout-zero-disables",
- "unrelated-deadlock-timeout-is-not-a-pin",
- "pooled-direct-url",
- "timeout-override",
- "invalid-override-falls-back",
- ),
-)
-def test_migration_environment_pins_a_ddl_lock_timeout(
- monkeypatch, database_url, direct_url, ddl_timeout, expected_pairs
-):
- from urllib.parse import parse_qsl, urlsplit
-
- from litellm_proxy_extras.migration_lock import migration_environment
-
- if ddl_timeout is None:
- monkeypatch.delenv("LITELLM_MIGRATION_DDL_LOCK_TIMEOUT", raising=False)
- else:
- monkeypatch.setenv("LITELLM_MIGRATION_DDL_LOCK_TIMEOUT", ddl_timeout)
- environment = {"DATABASE_URL": database_url, **({"DIRECT_URL": direct_url} if direct_url else {})}
- snapshot = dict(environment)
-
- migrated = migration_environment(environment)
-
- assert parse_qsl(urlsplit(migrated["DATABASE_URL"]).query) == expected_pairs
- assert environment == snapshot
-
-
-def test_migration_environment_lock_timeout_encodes_the_options_value(monkeypatch):
- from litellm_proxy_extras.migration_lock import migration_environment
-
- monkeypatch.delenv("LITELLM_MIGRATION_DDL_LOCK_TIMEOUT", raising=False)
-
- migrated = migration_environment({"DATABASE_URL": "postgresql://writer/db"})
-
- assert migrated["DATABASE_URL"] == "postgresql://writer/db?options=-c+lock_timeout%3D10000"
-
-
class _MigrateDeployHarness:
"""Drives _setup_database_v2 with a scripted sequence of
`prisma migrate deploy` outcomes, with every recovery command faked out so
@@ -1019,12 +918,15 @@ class _MigrateDeployHarness:
repeat_last=False,
confirmed_migrations=(),
ledger: "_FakeLedger | None" = None,
+ database_url: str = "postgresql://u:p@localhost:9/x",
+ prisma_env: dict[str, str] | None = None,
):
import subprocess as subprocess_module
import litellm_proxy_extras.utils as utils_module
self.deploy_calls = []
+ self.deploy_environments = []
self.resolved = []
self.rolled_back = []
self.sleeps = []
@@ -1036,12 +938,14 @@ class _MigrateDeployHarness:
if ledger is None:
monkeypatch.delenv("DATABASE_URL", raising=False)
+ monkeypatch.delenv("DIRECT_URL", raising=False)
else:
- monkeypatch.setenv("DATABASE_URL", "postgresql://u:p@localhost:9/x")
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ monkeypatch.delenv("DIRECT_URL", raising=False)
monkeypatch.setattr("psycopg.connect", ledger.connect)
monkeypatch.setenv("LITELLM_MIGRATION_DIR", str(tmp_path))
monkeypatch.setattr(utils_module.prisma_toolchain, "run_prisma", self._fake_run)
- monkeypatch.setattr(utils_module, "_get_prisma_env", lambda: {})
+ monkeypatch.setattr(utils_module, "_get_prisma_env", lambda: prisma_env or {})
monkeypatch.setattr(utils_module.time, "sleep", self.sleeps.append)
self.baseline_succeeds = True
@@ -1061,6 +965,7 @@ class _MigrateDeployHarness:
def _fake_run(self, cmd, **kwargs):
if cmd[1:] == ["migrate", "deploy"]:
self.deploy_calls.append(cmd)
+ self.deploy_environments.append(kwargs["env"].get("DATABASE_URL", ""))
outcome = self._next_outcome()
if outcome == "ok":
return _FakeCompleted()
@@ -1168,6 +1073,26 @@ class TestConcurrentP3009Recovery:
class TestMigrateDeployAttemptAccounting:
+ def test_migrate_deploy_does_not_add_startup_options_to_a_pooled_url(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ from urllib.parse import parse_qsl, urlsplit
+
+ pooled_url: Final = "postgresql://pool/db?schema=tenant&connection_limit=5"
+ harness: Final = _MigrateDeployHarness(
+ monkeypatch,
+ tmp_path,
+ ["ok"],
+ ledger=_FakeLedger(at_error=(), after_peer=()),
+ database_url=pooled_url,
+ prisma_env={"DATABASE_URL": pooled_url},
+ )
+
+ assert harness.run() is True
+ received_url: Final = harness.deploy_environments[0]
+ assert received_url == pooled_url
+ assert all(key != "options" for key, _ in parse_qsl(urlsplit(received_url).query))
+
def test_a_push_created_database_finishes_bootstrapping(self, monkeypatch, tmp_path):
harness = _MigrateDeployHarness(
monkeypatch,
@@ -1282,7 +1207,7 @@ class TestMigrateDeployAttemptAccounting:
class TestMigrationLockTimeoutRecovery:
"""A migration whose DDL wait Postgres cancelled (55P03, from the lock_timeout the
- migration URL now pins) is retryable: the half-written ledger row is rolled back and
+ migration SQL sets locally) is retryable: the half-written ledger row is rolled back and
the next attempt reruns the migration, priced like a deadlock retry."""
def test_a_lock_timed_out_migration_rolls_back_and_retries(self, monkeypatch, tmp_path):
@@ -1305,7 +1230,7 @@ class TestMigrationLockTimeoutRecovery:
repeat_last=True,
)
- with pytest.raises(RuntimeError, match="LITELLM_MIGRATION_DDL_LOCK_TIMEOUT"):
+ with pytest.raises(RuntimeError, match="SET LOCAL lock_timeout"):
harness.run()
assert len(harness.deploy_calls) == _ATTEMPT_BUDGET
assert harness.rolled_back == [_LOCK_TIMEOUT_MIGRATION] * _ATTEMPT_BUDGET
@@ -2158,4 +2083,3 @@ def test_repair_survives_an_unreachable_database(monkeypatch: pytest.MonkeyPatch
assert ProxyExtrasDBManager.repair_invalid_indexes() is False
-
diff --git a/tests/unit/test_check_migrations_lock_timeout.py b/tests/unit/test_check_migrations_lock_timeout.py
new file mode 100644
index 00000000000..b9c2f723fba
--- /dev/null
+++ b/tests/unit/test_check_migrations_lock_timeout.py
@@ -0,0 +1,62 @@
+import importlib.util
+import sys
+from pathlib import Path
+
+_CHECKER_PATH = Path(__file__).resolve().parents[1] / "code_coverage_tests" / "check_migrations_lock_timeout.py"
+_SPEC = importlib.util.spec_from_file_location("check_migrations_lock_timeout", _CHECKER_PATH)
+assert _SPEC is not None and _SPEC.loader is not None
+checker = importlib.util.module_from_spec(_SPEC)
+sys.modules[_SPEC.name] = checker
+_SPEC.loader.exec_module(checker)
+
+
+def _scan(tmp_path: Path, sql: str, name: str = "20261010000000_fixture") -> tuple[str, ...]:
+ directory = tmp_path / name
+ directory.mkdir()
+ (directory / "migration.sql").write_text(sql, encoding="utf-8")
+ return checker.scan_migration(directory)
+
+
+def test_missing_lock_timeout_line_fails(tmp_path: Path) -> None:
+ violations = _scan(tmp_path, 'ALTER TABLE "Foo" ADD COLUMN "bar" TEXT;')
+
+ assert len(violations) == 1
+ assert "SET LOCAL lock_timeout = '10s';" in violations[0]
+
+
+def test_lock_timeout_line_first_passes(tmp_path: Path) -> None:
+ assert _scan(tmp_path, "SET LOCAL lock_timeout = '10s';\nALTER TABLE foo ADD bar int;") == ()
+
+
+def test_multiline_lock_timeout_statement_first_passes(tmp_path: Path) -> None:
+ sql = "SET LOCAL\nlock_timeout = '10s';\nALTER TABLE foo ADD bar int;"
+
+ assert _scan(tmp_path, sql) == ()
+
+
+def test_comments_before_lock_timeout_line_pass(tmp_path: Path) -> None:
+ sql = "-- migration setup\n\n -- lock bound\nset local LOCK_TIMEOUT = '2s';\nALTER TABLE foo ADD bar int;"
+
+ assert _scan(tmp_path, sql) == ()
+
+
+def test_lock_timeout_line_after_another_statement_fails(tmp_path: Path) -> None:
+ sql = "ALTER TABLE foo ADD bar int;\nSET LOCAL lock_timeout = '10s';"
+
+ assert _scan(tmp_path, sql)
+
+
+def test_session_lock_timeout_without_local_fails(tmp_path: Path) -> None:
+ assert _scan(tmp_path, "SET lock_timeout = '10s';\nALTER TABLE foo ADD bar int;")
+
+
+def test_grandfathered_migration_without_lock_timeout_passes(tmp_path: Path) -> None:
+ name = "20261009000000_add_credential_display_name"
+
+ assert _scan(tmp_path, "ALTER TABLE foo ADD bar int;", name) == ()
+
+
+def test_concurrently_migration_without_lock_timeout_passes(tmp_path: Path) -> None:
+ sql = "create index concurrently foo_bar_idx on foo (bar);"
+
+ assert _scan(tmp_path, sql) == ()