:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(migrations): lock parents first when dropping a foreign key (#100773)
posthog[bot]495441262de5
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex faa0c14781f6..43a9d0117841 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -28,7 +28,7 @@ To retire a model/table:**If the model has a `ForeignKey` to `posthog_team`, `posthog_user`, `posthog_organization` or `posthog_project`, drop that constraint with `DropForeignKey` in `database_operations` in this same migration.** This is required, not a cleanup. Django stops cascading into a table it can no longer see, so the child rows survive a parent delete. Those constraints are `DEFERRABLE INITIALLY DEFERRED`, so the parent delete runs its whole cascade and then fails at `COMMIT`, and team and organization deletion stay broken until someone drops the table.2. Deploy, wait at least one full deploy cycle.3. `SafeDropTable` later in a NEW migration — never by deleting old files. Treat this as owed work rather than an option whenever step 1 left a foreign key to a hot parent in place.- `DROP TABLE` takes `ACCESS EXCLUSIVE` on every table its foreign keys reference, one relation at a time, so its lock order crosses that of any live multi-table read and the two deadlock. `lock_timeout` does not stop that, because the deadlock detector resolves the cycle first and it kills the read, not the migration. `SafeDropTable` takes every lock up front under a budget derived from `deadlock_timeout`, so the migration loses the race instead. Never hand-write the `RunSQL`. See [hot table hazard](#hot-table-hazard).+ `DROP TABLE` takes `ACCESS EXCLUSIVE` on every table its foreign keys reference, one relation at a time, so its lock order crosses that of any live multi-table read and the two deadlock. `lock_timeout` does not stop that, because the deadlock detector resolves the cycle first, and it kills whichever session waited longest: a live read (a 500) or the migration (a blocked deploy). `SafeDropTable` takes every lock up front under a budget derived from `deadlock_timeout`, so the migration loses the race instead. Never hand-write the `RunSQL`. See [hot table hazard](#hot-table-hazard).`python manage.py audit_orphan_hot_table_fks` lists tables already in this state. Run it against a long-lived database: a squashed history has no `CreateModel` for a table that left Django's state before the squash, so a fresh database never creates it and the migration files hold no trace of it.Full guide: `safe-django-migrations.md` (`## Dropping Tables`, `### Removing a whole product or app`). Deleting a migration your branch added but never merged to master is allowed (regenerating).@@ -101,8 +101,8 @@ Two things a callable does not do for you:- **Add a ForeignKey to a [hot table](#hot-table-hazard)** → declare the FK with `db_constraint=False` on the model (so `CreateModel` / `AddField` emit no parent lock), then add the DB constraint back with `AddForeignKeyNotValid` and follow up with `ValidateForeignKey` in a later migration. See [foreign keys to hot tables](#foreign-keys-to-hot-tables).- **Index expressed only as raw SQL** (no Django `Index`) → `CreateIndexConcurrently` / `DropIndexConcurrently` wrapped in `SeparateDatabaseAndState`.- **Retire a column** → `deprecate_field` on the model, or `untrack_field` in place of the generated `RemoveField`. See [retire a column](#retire-a-column).-- **Drop a retired table** → `SafeDropTable("posthog_oldfeature")`. It locks the referenced parents up front so a live read is never the deadlock victim, and it is idempotent under a retry. It refuses a partitioned or inherited table, because its lock list does not cover the members of a hierarchy.-- **Drop a foreign key left behind by a retirement** → `DropForeignKey(table, column=...)` or `DropForeignKey(table, to_table=...)`. It reads the name from `pg_constraint`, so nothing is hardcoded and a retry is a no-op.+- **Drop a retired table** → `SafeDropTable("posthog_oldfeature")`. It locks the referenced parents up front under a budget below `deadlock_timeout`, so a lock cycle tends to end with the migration retried rather than a live read killed, and it is idempotent under a retry. It refuses a partitioned or inherited table, because its lock list does not cover the members of a hierarchy.+- **Drop a foreign key left behind by a retirement** → `DropForeignKey(table, column=...)` or `DropForeignKey(table, to_table=...)`. It reads the name from `pg_constraint`, so nothing is hardcoded and a retry is a no-op. It locks every parent and then the child in one bounded phase, the same as `SafeDropTable`. The transaction holds those locks until `COMMIT`, so give one op every key on the table (`column=["a_id", "b_id"]`) and keep it alone in its migration, next to state-only operations at most. The risk analyzer blocks two drops, or a drop beside other database operations, in one atomic migration. For keys into several busy parents, use `atomic = False` with one op per key instead, so each drop commits alone, and acknowledge the migration in `atomic_false_acknowledged_migrations.txt`.All concurrent-index ops require `atomic = False`.diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.mdindex ffb362e02bdc..0d105ffc4be8 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -169,11 +169,13 @@ class Migration(migrations.Migration):### DROP TABLE lock order-`DROP TABLE` takes `ACCESS EXCLUSIVE` on the dropped table and on every table its own foreign keys reference, one relation at a time while the statement runs. An application query takes `AccessShare` on the tables it reads, also one at a time, in whatever order its plan picks. When the retired table holds keys into `posthog_team`, `posthog_organization` or `posthog_user`, the two orders cross and the two sessions form a real deadlock cycle.+`DROP TABLE` takes `ACCESS EXCLUSIVE` on the dropped table and on every table its own foreign keys reference, one relation at a time while the statement runs. `ALTER TABLE ... DROP CONSTRAINT` on a foreign key does the same: the child first, then the parent. An application query takes `AccessShare` on the tables it reads, also one at a time, and a query that joins a parent to the child locks the parent first. When the child holds keys into `posthog_team`, `posthog_organization`, `posthog_user` or any other busy table, the two orders cross and the two sessions form a real deadlock cycle.-A short `lock_timeout` does not save the application query, because a cycle is resolved by the deadlock detector rather than by the lock timeout. Each waiting backend runs the detector after it has waited for `deadlock_timeout`, and the backend that finds the cycle aborts itself. The application query enters the wait first, so it is the one Postgres kills, and the user sees a 500 on a screen unrelated to the deploy.+A short `lock_timeout` does not break the cycle, because a cycle is resolved by the deadlock detector rather than by the lock timeout. Each waiting backend runs the detector after it has waited for `deadlock_timeout`, and the backend that finds the cycle aborts itself. When the application query entered the wait first, Postgres kills the read and the user sees a 500 on a screen unrelated to the deploy. When the migration entered first, Postgres kills the migration on every `bin/migrate` retry and the deploy stays blocked.-`SafeDropTable` removes the cycle from the migration side. It reads the referenced parents out of `pg_constraint`, takes `ACCESS EXCLUSIVE` on every one of them in a single `LOCK TABLE`, and only then runs the drop, so the drop needs no new lock. The lock phase runs under a `lock_timeout` and a `statement_timeout` derived from the server's `deadlock_timeout`, so the migration always abandons its wait before any peer has waited long enough to run the detector. The migration loses the race, `bin/migrate` retries it, and no application query is ever the victim.+`SafeDropTable` and `DropForeignKey` take the locks from the migration side first. Each reads the referenced parents out of `pg_constraint`, takes `ACCESS EXCLUSIVE` on every parent and then the child in a single `LOCK TABLE`, and only then runs the drop, so the drop needs no new lock. The lock phase runs under a `lock_timeout` and a `statement_timeout` of half the server's `deadlock_timeout`, capped at one second, so the migration abandons its own wait before its own detector runs and `bin/migrate` retries it. That biases a cycle toward the migration. It does not settle every cycle: each backend arms its detector when its own wait starts, so a query that began to wait more than the budget earlier reaches its detector first.++The transaction holds those locks until `COMMIT`. A second drop in the same transaction then waits for new parents while the first drop's parents stay locked, which rebuilds the crossed order. Keep a `DropForeignKey` or `SafeDropTable` alone in its migration, next to state-only operations at most, and give it every key or table of the retirement at once. The migration risk analyzer blocks a migration that does otherwise.```pythonfrom posthog.migration_helpers import SafeDropTable@@ -311,7 +313,11 @@ operations = []```-`DropForeignKey` reads the constraint name out of `pg_constraint`, so there is nothing to hardcode. Never hand-write `ALTER TABLE ... DROP CONSTRAINT IF EXISTS <name>`: Django names foreign keys with a hash suffix, and `IF EXISTS` turns a wrong guess into a migration that succeeds and drops nothing.+`DropForeignKey` reads the constraint name out of `pg_constraint`, so there is nothing to hardcode. Never hand-write `ALTER TABLE ... DROP CONSTRAINT IF EXISTS <name>`: Django names foreign keys with a hash suffix, and `IF EXISTS` turns a wrong guess into a migration that succeeds and drops nothing. The drop is a catalog change, but it locks the child and the parent until `COMMIT`, so it takes its locks parent first in a bounded phase of its own. See [the lock order hazard](#drop-table-lock-order).++Several keys on one table go in one operation, `DropForeignKey("posthog_mymodel", column=["owner_id", "team_id"])`, so they share one lock phase. Keep that operation alone in its migration, next to the state-only `untrack_field` at most. Keys on other tables, and any other schema change to the same table, go in migrations of their own. The migration risk analyzer blocks a migration that runs two `DropForeignKey` operations, or one beside other database operations.++When the keys point at several busy parents, one lock phase has to win every parent at once, which can fail on every retry under load. Set `atomic = False` on the migration instead and give each key its own `DropForeignKey`. Each one then locks one parent and the child in a transaction of its own, and a retry skips the keys already dropped. List the migration in `atomic_false_acknowledged_migrations.txt`, because `AtomicFalsePolicy` asks for that.**`deprecate_field()` is not an option for a foreign key.** It writes no migration, so there is nowhere for the constraint drop to live, and the hidden column leaves exactly the orphan described above. Use `untrack_field()` with `DropForeignKey`.diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex 5436c594ac41..d076bb36f363 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -988,9 +988,11 @@ class SafeRemoveIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):class DropForeignKeyAnalyzer(OperationAnalyzer):"""The constraint drop that rides along with a state-only removal of a column or table.- Dropping a foreign key is a catalog change. It holds ACCESS EXCLUSIVE on the referenced- parent for microseconds and scans nothing, so it scores with `ADD CONSTRAINT ... NOT- VALID` rather than with the operations that rewrite a table.+ Dropping a foreign key is a catalog change and scans nothing, so it scores with `ADD+ CONSTRAINT ... NOT VALID` rather than with the operations that rewrite a table. Its locks+ are the risk, and the op takes them in a bounded, parent-first phase of its own. What the+ op cannot control is the rest of its transaction, so LockPhaseTransactionPolicy+ checks that at migration level."""operation_type = "DropForeignKey"@@ -1000,14 +1002,16 @@ class DropForeignKeyAnalyzer(OperationAnalyzer):return OperationRisk(type=self.operation_type,score=1,- reason="DROP CONSTRAINT on a foreign key is a catalog change (brief lock on the parent, no table scan)",+ reason="DROP CONSTRAINT on a foreign key is a catalog change (parent-first bounded lock phase, no table scan)",details={"table": getattr(op, "table", None),- "column": getattr(op, "column", None),+ "columns": getattr(op, "columns", None),"to_table": getattr(op, "to_table", None),},guidance=f"""Required beside a state-only removal of the column or table this foreign key sits on. Django stops cascading into a relation it cannot see, and the deferred constraint then fails the parent delete at COMMIT.+The transaction holds the parent locks until COMMIT. Keep this op alone in its migration, next to state-only operations at most, and pass every key on the table to one op with `column=[...]`.+Irreversible. Add the constraint back with `AddForeignKeyNotValid` in a new migration rather than by unapplying this one.[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-columns)""",diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.pyindex ea9c92d41399..e00743fbb5e6 100644--- a/posthog/management/migration_analysis/policies.py+++ b/posthog/management/migration_analysis/policies.py@@ -11,7 +11,7 @@ from pathlib import Pathfrom typing import Any, Optionalfrom django.conf import settings-from django.db import models+from django.db import migrations, modelsfrom django.db.migrations.loader import MigrationLoaderfrom posthog.dataclasses import frozen@@ -52,6 +52,35 @@ class _ConstrainedForeignKey:target_table: str+def _descend(ops) -> Iterator[Any]:+ """Yield operations that emit SQL, descending into SeparateDatabaseAndState.database_operations.++ SeparateDatabaseAndState can nest, so the descent is recursive. state_operations never+ touch the database, so they are not descended.+ """+ for op in ops or []:+ if op.__class__.__name__ == "SeparateDatabaseAndState":+ yield from _descend(getattr(op, "database_operations", []) or [])+ else:+ yield op+++# Django operations whose database_forwards does nothing.+_STATE_ONLY_OPERATIONS = {"AlterModelOptions", "AlterModelManagers"}+++def _runs_sql(op) -> bool:+ """False for an operation that only changes Django state and runs nothing."""+ name = op.__class__.__name__+ if name in _STATE_ONLY_OPERATIONS:+ return False+ if name == "RunSQL":+ return bool(getattr(op, "sql", None))+ if name == "RunPython":+ return getattr(op, "code", None) is not migrations.RunPython.noop+ return True++# Apps owned by PostHog where policies are enforcedPOSTHOG_OWNED_APPS = ["posthog", "ee"]@@ -405,14 +434,7 @@ class ConcurrentIndexIdempotencyPolicy(MigrationPolicy):the inner ops and reopen the incident class. state_operations nevertouch the database, so they are not descended."""- yield from self._descend(migration.operations)-- def _descend(self, ops):- for op in ops or []:- if op.__class__.__name__ == "SeparateDatabaseAndState":- yield from self._descend(getattr(op, "database_operations", []) or [])- else:- yield op+ yield from _descend(migration.operations)def _check_single_operation(self, op) -> list[str]:op_type = op.__class__.__name__@@ -562,7 +584,7 @@ class HotTableAlterPolicy(MigrationPolicy):return []violations = []- for op in self._descend(migration.operations):+ for op in _descend(migration.operations):# Unmanaged models (managed=False) map external tables - Django emits no DDL and# no FK constraint, so they can't take the hot-table lock this policy gates.if is_unmanaged_model(op, migration):@@ -582,17 +604,6 @@ class HotTableAlterPolicy(MigrationPolicy):lines = self.ACKNOWLEDGMENTS_FILE.read_text().splitlines()return {line.strip() for line in lines if line.strip() and not line.strip().startswith("#")}- def _descend(self, ops):- """Yield operations that emit SQL, descending into SeparateDatabaseAndState.database_operations.-- state_operations never touch the database, so they are not descended.- """- for op in ops or []:- if op.__class__.__name__ == "SeparateDatabaseAndState":- yield from self._descend(getattr(op, "database_operations", []) or [])- else:- yield op-def _hot_table_target(self, op, app_label: str) -> str | None:"""Return the hot table an operation alters directly, or None.@@ -814,11 +825,10 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):def _dropped_columns(self, migration) -> set[_TableColumn]:"""Columns a DropForeignKey in this migration removes a constraint from."""dropped = set()- for db_op in self._database_operations(migration):+ for db_op in _descend(migration.operations):if db_op.__class__.__name__ != "DropForeignKey":continue- column = getattr(db_op, "column", None)- if column is not None:+ for column in getattr(db_op, "columns", None) or []:dropped.add(_TableColumn(table=getattr(db_op, "table", ""), column=column))return dropped@@ -830,23 +840,14 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):or a table-wide drop reaches is guesswork, and a false block on a correct migrationcosts more than a missed second constraint."""- for db_op in self._database_operations(migration):- if db_op.__class__.__name__ == "DropForeignKey" and getattr(db_op, "column", None) is None:+ for db_op in _descend(migration.operations):+ if db_op.__class__.__name__ == "DropForeignKey" and not getattr(db_op, "columns", None):return Truesql = _without_sql_comments(str(getattr(db_op, "sql", "") or ""))if "DROP CONSTRAINT" in sql.upper():return Truereturn False- def _database_operations(self, migration) -> list[Any]:- ops: list[Any] = []- for op in migration.operations or []:- if op.__class__.__name__ == "SeparateDatabaseAndState":- ops.extend(getattr(op, "database_operations", []) or [])- else:- ops.append(op)- return ops-def _state_before(self, migration) -> Any:loader = _disk_loader()if loader is None:@@ -948,14 +949,63 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):f"see, and the constraint is DEFERRABLE INITIALLY DEFERRED, so a {fk.target_table} delete "f"runs its whole cascade and then fails at COMMIT, permanently. Add "f'DropForeignKey("{table}", column="{fk.column}") to this migration\'s database_operations '- f"(posthog.migration_helpers)."+ f"(posthog.migration_helpers), or add the column to the DropForeignKey already there.")+_LOCK_PHASE_OPERATIONS = {"DropForeignKey", "SafeDropTable"}+++class LockPhaseTransactionPolicy(MigrationPolicy):+ """Keep a DropForeignKey or SafeDropTable alone in its transaction.++ Both take their locks in a bounded, parent-first phase (posthog/migration_helpers/lock_phase.py),+ but the transaction holds the locks until COMMIT. A second lock phase then waits for new+ parents while the first one's parents stay locked. Another operation that runs first holds+ its table while the lock phase waits for the parents, and one that runs after waits for new+ locks while the lock phase holds the parents. Each shape rebuilds the crossed lock order+ that deadlocks against live reads. With atomic = False nothing accumulates, because each+ operation commits on its own.+ """++ def check_operation(self, op) -> list[str]:+ return [] # The hazard is the shared transaction, so it runs at migration level.++ def check_migration(self, migration) -> list[str]:+ if not is_posthog_app(migration.app_label, migration):+ return []+ if not getattr(migration, "atomic", True):+ return []++ names = [op.__class__.__name__ for op in _descend(migration.operations) if _runs_sql(op)]+ lock_phases = [name for name in names if name in _LOCK_PHASE_OPERATIONS]+ if not lock_phases:+ return []++ violations = []+ if len(lock_phases) > 1:+ violations.append(+ f"❌ BLOCKED: {len(lock_phases)} lock-phase operations ({', '.join(sorted(set(lock_phases)))}) share "+ "one transaction, which holds every lock until COMMIT. Pass every key on a table to one "+ "DropForeignKey with column=[...], every table of one retirement to one SafeDropTable, and give "+ "the rest migrations of their own. For keys into several busy parents, set atomic = False "+ "instead, so each DropForeignKey commits alone."+ )+ others = sorted({name for name in names if name not in _LOCK_PHASE_OPERATIONS})+ if others:+ violations.append(+ f"❌ BLOCKED: {', '.join(sorted(set(lock_phases)))} shares its transaction with {', '.join(others)}, "+ "which holds every lock until COMMIT. Move it to a migration of its own. State-only operations "+ "can stay with it."+ )+ return violations++POSTHOG_POLICIES = [UUIDPrimaryKeyPolicy(),AtomicFalsePolicy(),ConcurrentIndexIdempotencyPolicy(),HotTableAlterPolicy(),OrphanedForeignKeyPolicy(),+ LockPhaseTransactionPolicy(),]diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex ae2bf45a4d26..04ffec1e7cdd 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -13,6 +13,7 @@ from posthog.management.migration_analysis.policies import (AtomicFalsePolicy,ConcurrentIndexIdempotencyPolicy,HotTableAlterPolicy,+ LockPhaseTransactionPolicy,OrphanedForeignKeyPolicy,)from posthog.management.migration_analysis.utils import _model_name_for_table@@ -2924,10 +2925,11 @@ class TestOrphanedForeignKeyPolicy:assert len(violations) == 1assert violations[0].startswith("⚠️ WARNING")- def test_a_matching_drop_clears_it(self, monkeypatch):+ @pytest.mark.parametrize("column", ["owner_id", ["other_id", "owner_id"]])+ def test_a_matching_drop_clears_it(self, monkeypatch, column):state = self._state(owner=models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True))- violations = self._check(state, [DropForeignKey("posthog_child", column="owner_id")], monkeypatch)+ violations = self._check(state, [DropForeignKey("posthog_child", column=column)], monkeypatch)assert violations == []@@ -2972,3 +2974,49 @@ class TestOrphanedForeignKeyPolicy:violations = self._check(state, [migrations.RunSQL(sql=sql)], monkeypatch)assert len(violations) == expected+++class TestLockPhaseTransactionPolicy:+ def _untrack(self, *drops):+ return migrations.SeparateDatabaseAndState(+ state_operations=[migrations.RemoveField(model_name="child", name="owner")],+ database_operations=list(drops),+ )++ @parameterized.expand(+ [+ ("alone_beside_state_operations", True, ["untrack_one"], []),+ ("two_drops_in_one_transaction", True, ["untrack_two"], ["column=[...]"]),+ ("another_operation_first", True, ["remove_constraint", "untrack_one"], ["RemoveConstraint"]),+ ("both_shapes_at_once", True, ["remove_constraint", "untrack_two"], ["column=[...]", "RemoveConstraint"]),+ ("a_table_drop_beside_a_key_drop", True, ["untrack_one", "safe_drop"], ["SafeDropTable"]),+ ("a_no_op_beside_the_drop", True, ["no_op_sql", "untrack_one"], []),+ ("a_state_only_django_op_beside_the_drop", True, ["alter_options", "untrack_one"], []),+ ("two_drops_nested_one_level_down", True, ["nested_two"], ["column=[...]"]),+ ("atomic_false_commits_each_drop_alone", False, ["remove_constraint", "untrack_two"], []),+ ]+ )+ def test_a_lock_phase_must_own_its_transaction(self, _name, atomic, shape, expected):+ owner = DropForeignKey("posthog_child", column="owner_id")+ other = DropForeignKey("posthog_child", column="other_id")+ operations = {+ "untrack_one": self._untrack(owner),+ "untrack_two": self._untrack(owner, other),+ "remove_constraint": migrations.RemoveConstraint(model_name="child", name="exactly_one_owner"),+ "safe_drop": SafeDropTable("posthog_retired"),+ "no_op_sql": migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop),+ "alter_options": migrations.AlterModelOptions(name="child", options={"ordering": ["id"]}),+ "nested_two": migrations.SeparateDatabaseAndState(database_operations=[self._untrack(owner, other)]),+ }+ migration = MagicMock()+ migration.app_label = "posthog"+ migration.name = "0001_test"+ migration.atomic = atomic+ migration.operations = [operations[key] for key in shape]++ violations = LockPhaseTransactionPolicy().check_migration(migration)++ assert len(violations) == len(expected)+ for violation, fragment in zip(violations, expected):+ assert violation.startswith("❌ BLOCKED")+ assert fragment in violationdiff --git a/posthog/migration_helpers/drop_foreign_key.py b/posthog/migration_helpers/drop_foreign_key.pyindex cb3c609677b4..ab3919aeae1e 100644--- a/posthog/migration_helpers/drop_foreign_key.py+++ b/posthog/migration_helpers/drop_foreign_key.py@@ -22,6 +22,10 @@ Django's state:),]+Several keys on one table go in one op, so they share one lock phase:++ DropForeignKey("posthog_mymodel", column=["owner_id", "team_id"])+For a whole table leaving state, name the parent instead of the column:migrations.SeparateDatabaseAndState(@@ -38,19 +42,25 @@ a bin/migrate retry.The op is irreversible. Add the constraint back with `AddForeignKeyNotValid` in a newmigration rather than by unapplying this one.-The op deliberately does not touch lock_timeout, exactly like `AddForeignKeyNotValid`.-Dropping a foreign key takes ACCESS EXCLUSIVE on the referenced parent for a metadata-only-change held for microseconds, so it should fail fast on contention under whatever-lock_timeout the connection carries, rather than queue that lock and stall the parent.-Never disable the timeout here: on a hot parent an unbounded wait blocks every query that-arrives behind it. A bin/migrate retry re-attempts once the lock is free.+The drop is a catalog change and scans nothing, but a bare `DROP CONSTRAINT` locks the child+before the parent and deadlocks against live reads. This op locks every parent, then the+child, with `lock_tables`, and only then drops. `lock_phase.py` has the reasoning.++The locks last until COMMIT, so keep the op alone in its migration, next to state-only+operations at most, and give it every key on the table at once. The migration risk analyzer+blocks a migration that does otherwise."""-from django.db import router+from collections.abc import Sequence++from django.db import router, transactionfrom django.db.migrations.operations.base import Operation-_CONSTRAINT_NAMES_SQL = """- SELECT con.conname+from posthog.dataclasses import frozen+from posthog.migration_helpers.lock_phase import lock_tables++_CONSTRAINTS_SQL = """+ SELECT DISTINCT con.conname, tgt.relnameFROM pg_constraint conJOIN pg_class src ON src.oid = con.conrelidJOIN pg_class tgt ON tgt.oid = con.confrelid@@ -59,10 +69,16 @@ _CONSTRAINT_NAMES_SQL = """AND src.relname = %(table)sAND pg_table_is_visible(src.oid)AND (%(to_table)s IS NULL OR tgt.relname = %(to_table)s)- AND (%(column)s IS NULL OR att.attname = %(column)s)+ AND (%(columns)s::name[] IS NULL OR att.attname = ANY(%(columns)s::name[]))"""+@frozen+class _ForeignKeyConstraint:+ name: str+ parent: str++class DropForeignKey(Operation):"""Drop every FOREIGN KEY on `table` that matches the given filter.@@ -73,8 +89,8 @@ class DropForeignKey(Operation):table: the child table holding the constraint, e.g. `"posthog_mymodel"`. A rawtable name rather than a model name, because the model or field is leavingDjango's state in this same migration and may no longer resolve.- column: the child column, e.g. `"owner_id"`. Note the `_id` suffix Django gives- foreign key columns.+ column: the child column, e.g. `"owner_id"`, or a list of them. Note the `_id`+ suffix Django gives foreign key columns.to_table: the referenced parent table, e.g. `"posthog_team"`.Pass `column`, `to_table`, or both. Passing neither would drop every foreign key on the@@ -89,38 +105,49 @@ class DropForeignKey(Operation):reversible = Falsereduces_to_sql = True- def __init__(self, table: str, column: str | None = None, to_table: str | None = None) -> None:- if column is None and to_table is None:+ def __init__(self, table: str, column: str | Sequence[str] | None = None, to_table: str | None = None) -> None:+ columns = [column] if isinstance(column, str) else list(column or [])+ if not columns and to_table is None:raise ValueError("DropForeignKey needs a column, a to_table, or both")self.table = table- self.column = column+ self.columns = columnsself.to_table = to_tabledef state_forwards(self, app_label, state) -> None:pass+ def _constraints(self, schema_editor) -> list[_ForeignKeyConstraint]:+ """Every key that matches the filter, sorted by constraint name."""+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(+ _CONSTRAINTS_SQL,+ {"table": self.table, "to_table": self.to_table, "columns": self.columns or None},+ )+ return [_ForeignKeyConstraint(name=name, parent=parent) for name, parent in sorted(cursor.fetchall())]+def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:# A product app in products/db_routing.yaml migrates on its own database. Django still# traverses this migration on the other aliases, and a raw catalog query cannot tell# them apart, so a same-named table elsewhere would lose its foreign key.if not router.allow_migrate(schema_editor.connection.alias, app_label):return- for name in self._constraint_names(schema_editor):- schema_editor.execute(- f"ALTER TABLE {schema_editor.quote_name(self.table)} DROP CONSTRAINT {schema_editor.quote_name(name)}"- )+ constraints = self._constraints(schema_editor)+ if not constraints:+ return+ # A key that references its own table names the child as its parent, and the child+ # goes last in the lock list.+ parents = sorted({constraint.parent for constraint in constraints} - {self.table})+ drops = ", ".join(f"DROP CONSTRAINT {schema_editor.quote_name(constraint.name)}" for constraint in constraints)+ # LOCK TABLE needs a transaction. Inside an atomic migration this is a savepoint.+ # Under atomic = False it is a transaction of its own, which lets go of the parents+ # as soon as the drops finish.+ with transaction.atomic(using=schema_editor.connection.alias):+ lock_tables(schema_editor, [*parents, self.table])+ schema_editor.execute(f"ALTER TABLE {schema_editor.quote_name(self.table)} {drops}")def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:raise NotImplementedError("DropForeignKey is irreversible; add the constraint back with AddForeignKeyNotValid")def describe(self) -> str:- target = self.column or f"-> {self.to_table}"+ target = ", ".join(self.columns) or f"-> {self.to_table}"return f"Drop foreign key on {self.table} ({target})"-- def _constraint_names(self, schema_editor) -> list[str]:- with schema_editor.connection.cursor() as cursor:- cursor.execute(- _CONSTRAINT_NAMES_SQL,- {"table": self.table, "to_table": self.to_table, "column": self.column},- )- return sorted({row[0] for row in cursor.fetchall()})diff --git a/posthog/migration_helpers/lock_phase.py b/posthog/migration_helpers/lock_phase.pynew file mode 100644index 000000000000..642515594fb3--- /dev/null+++ b/posthog/migration_helpers/lock_phase.py@@ -0,0 +1,56 @@+"""Take every lock a drop needs before the drop runs.++`DROP TABLE` and `ALTER TABLE ... DROP CONSTRAINT` on a foreign key take ACCESS EXCLUSIVE+on the child and then on each referenced parent, one relation at a time while the statement+runs, and the transaction holds every lock until COMMIT. An application query that joins a+parent to the child takes AccessShare on the parent first. The two orders cross, and the two+sessions form a deadlock cycle.++A short `lock_timeout` alone does not stop that. The deadlock detector resolves a cycle,+not the lock timeout, and the backend that runs the detector is the one that aborts. The+application query enters the wait first, so Postgres usually kills the read.++`lock_tables` takes ACCESS EXCLUSIVE on every table in one `LOCK TABLE`, in the order the+caller gives, so the drop after it needs no new lock. Callers pass the parents first,+because that is the order a query that joins parent to child takes its locks. The wait runs+under a budget below the server's `deadlock_timeout`, so the migration abandons its own wait+before its own detector runs, and bin/migrate retries it. That biases a lock cycle toward the+migration. It does not settle every cycle: each backend arms its detector when its own wait+starts, so a query that began to wait more than the budget earlier reaches its detector first.+"""++from collections.abc import Sequence++# deadlock_timeout is a server setting this repository does not own. Half of a raised value+# is a wait long enough to queue the site behind it, so the budget has a ceiling of its own.+MAX_LOCK_BUDGET_MS = 1000+++def quote_tables(schema_editor, tables: Sequence[str]) -> str:+ return ", ".join(schema_editor.quote_name(table) for table in tables)+++def lock_tables(schema_editor, tables: Sequence[str]) -> None:+ """Take ACCESS EXCLUSIVE on `tables`, in order, under the deadlock budget.++ Needs an open transaction. Outside one, `SET LOCAL` only warns, and `LOCK TABLE` raises.+ """+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(+ "SELECT (SELECT setting::int FROM pg_settings WHERE name = 'deadlock_timeout'),"+ " current_setting('lock_timeout'), current_setting('statement_timeout')"+ )+ deadlock_ms, previous_lock, previous_statement = cursor.fetchone()+ budget_ms = max(1, min(MAX_LOCK_BUDGET_MS, deadlock_ms // 2))+ # lock_timeout bounds the wait for one table and statement_timeout bounds the whole LOCK,+ # so several contended tables cannot add up past the budget between them.+ schema_editor.execute(f"SET LOCAL lock_timeout = '{budget_ms}ms'")+ schema_editor.execute(f"SET LOCAL statement_timeout = '{budget_ms}ms'")+ schema_editor.execute(f"LOCK TABLE {quote_tables(schema_editor, tables)} IN ACCESS EXCLUSIVE MODE")+ # The drop needs no new lock, so put back what the transaction came in with. Not+ # DEFAULT: an earlier operation in the same migration can hold a value of its own,+ # and ValidateConstraint disables both timeouts for exactly that reason.+ schema_editor.execute(+ "SELECT set_config('lock_timeout', %s, true), set_config('statement_timeout', %s, true)",+ [previous_lock, previous_statement],+ )diff --git a/posthog/migration_helpers/safe_drop_table.py b/posthog/migration_helpers/safe_drop_table.pyindex 0da66b1e8c24..988f1372cd75 100644--- a/posthog/migration_helpers/safe_drop_table.py+++ b/posthog/migration_helpers/safe_drop_table.py@@ -1,17 +1,12 @@"""Drop retired tables without making a live query the deadlock victim.`DROP TABLE` takes ACCESS EXCLUSIVE on the dropped table and on every table its own-foreign keys reference, one relation at a time while the statement runs. An application-query takes AccessShare on the tables it reads, also one at a time, in whatever order its-plan picks. When the retired table holds keys into posthog_team, posthog_organization or-posthog_user, the two orders cross and the two sessions form a real deadlock cycle.+foreign keys reference, one relation at a time while the statement runs. When the retired+table holds keys into posthog_team, posthog_organization or posthog_user, that order crosses+the order of a live query that reads both, and the two sessions deadlock. `lock_phase.py`+has the full reasoning.-A short `lock_timeout` does not save the application query. A cycle is resolved by the-deadlock detector rather than by the lock timeout, and the backend that finds the cycle is-the one that aborts. The application query enters the wait first, so Postgres kills the-read and the user sees a 500 on a screen unrelated to the deploy.--This operation removes the cycle from the migration side:+This operation takes the locks from the migration side first:from posthog.migration_helpers import SafeDropTable@@ -19,12 +14,8 @@ This operation removes the cycle from the migration side:SafeDropTable(["posthog_oldfeature", "posthog_oldfeaturerun"]),]-It reads the referenced parents out of pg_constraint, takes ACCESS EXCLUSIVE on every one-of them in a single `LOCK TABLE`, and only then runs the drop, so the drop needs no new-lock. The lock phase runs under a budget derived from the server's own `deadlock_timeout`,-so the migration always abandons its wait before any peer has waited long enough to run-the detector. The migration loses the race, bin/migrate retries it, and no application-query is ever the victim.+It reads the referenced parents out of pg_constraint and locks every parent, then the+dropped tables, with `lock_tables`, so the drop needs no new lock.The operation is idempotent, so a bin/migrate retry is free. It tracks no Django state, sothe model still has to leave state a full deploy cycle earlier with@@ -37,6 +28,8 @@ from collections.abc import Sequencefrom django.db import routerfrom django.db.migrations.operations.base import Operation+from posthog.migration_helpers.lock_phase import lock_tables, quote_tables+_EXISTING_TABLES_SQL = """SELECT relnameFROM pg_class@@ -125,9 +118,10 @@ class SafeDropTable(Operation):if not present:returnreferenced = self._query(schema_editor, _REFERENCED_TABLES_SQL, present)+ parents = sorted(set(referenced) - set(present))- self._lock(schema_editor, sorted(set(present) | set(referenced)))- schema_editor.execute(f"DROP TABLE IF EXISTS {self._quote(schema_editor, present)}")+ lock_tables(schema_editor, [*parents, *present])+ schema_editor.execute(f"DROP TABLE IF EXISTS {quote_tables(schema_editor, present)}")def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:raise NotImplementedError("SafeDropTable is irreversible; recreate the table in a new migration")@@ -135,31 +129,6 @@ class SafeDropTable(Operation):def describe(self) -> str:return f"Drop table {', '.join(sorted(self.tables))} under a deterministic lock order"- def _lock(self, schema_editor, tables: list[str]) -> None:- with schema_editor.connection.cursor() as cursor:- cursor.execute(- "SELECT (SELECT setting::int FROM pg_settings WHERE name = 'deadlock_timeout'),"- " current_setting('lock_timeout'), current_setting('statement_timeout')"- )- deadlock_ms, previous_lock, previous_statement = cursor.fetchone()- # Half, so the migration abandons its wait before any peer waiting on the- # migration can run the detector and be killed for it.- budget_ms = max(1, deadlock_ms // 2)- # lock_timeout bounds one attempt and statement_timeout bounds the sequence, so- # several contended tables cannot add up past the budget between them.- schema_editor.execute(f"SET LOCAL lock_timeout = '{budget_ms}ms'")- schema_editor.execute(f"SET LOCAL statement_timeout = '{budget_ms}ms'")- schema_editor.execute(f"LOCK TABLE {self._quote(schema_editor, tables)} IN ACCESS EXCLUSIVE MODE")- # The drop needs no new lock, so put back what the transaction came in with. Not- # DEFAULT: an earlier operation in the same migration can hold a value of its own,- # and ValidateConstraint disables both timeouts for exactly that reason.- schema_editor.execute("SELECT set_config('lock_timeout', %s, true)", [previous_lock])- schema_editor.execute("SELECT set_config('statement_timeout', %s, true)", [previous_statement])-- @staticmethod- def _quote(schema_editor, tables: list[str]) -> str:- return ", ".join(schema_editor.quote_name(table) for table in tables)-@staticmethoddef _query(schema_editor, sql: str, tables: list[str]) -> list[str]:with schema_editor.connection.cursor() as cursor:diff --git a/posthog/migration_helpers/test_drop_foreign_key.py b/posthog/migration_helpers/test_drop_foreign_key.pyindex bb9144e37934..cc62d291462e 100644--- a/posthog/migration_helpers/test_drop_foreign_key.py+++ b/posthog/migration_helpers/test_drop_foreign_key.py@@ -4,13 +4,16 @@ Each test builds a real parent/child pair with real Django-shaped foreign keys,catalog lookup runs against the same pg_constraint rows a migration would see."""+import timeimport uuidimport pytest-from django.db import connection+from django.db import connection, connections+from django.db.utils import OperationalErrorfrom posthog.migration_helpers import DropForeignKey+from posthog.migration_helpers.lock_phase import MAX_LOCK_BUDGET_MS@pytest.fixture@@ -42,13 +45,14 @@ def temp_tables():cursor.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')-def _apply(op):- schema_editor = connection.schema_editor(atomic=False)+def _apply(op, collect=False):+ schema_editor = connection.schema_editor(atomic=False, collect_sql=collect)schema_editor.__enter__()try:op.database_forwards("posthog", schema_editor, from_state=None, to_state=None)finally:schema_editor.__exit__(None, None, None)+ return schema_editor.collected_sql if collect else Nonedef _fk_columns(child):@@ -66,13 +70,35 @@ def _fk_columns(child):return {row[0] for row in cursor.fetchall()}+ "column, remaining",+ [+ ("owner_id", {"other_id"}),+ (["owner_id", "other_id"], set()),+ ],+)@pytest.mark.django_db-def test_drops_only_the_named_column(temp_tables):+def test_drops_only_the_named_columns(temp_tables, column, remaining):child, _, _ = temp_tables- _apply(DropForeignKey(child, column="owner_id"))+ _apply(DropForeignKey(child, column=column))- assert _fk_columns(child) == {"other_id"}+ assert _fk_columns(child) == remaining+++def test_locks_every_parent_before_the_child_and_before_any_drop(temp_tables):+ # DROP CONSTRAINT on its own locks the child first and each parent after it, which is+ # the order that crosses a live read joining parent to child and deadlocks.+ child, parent_a, parent_b = temp_tables++ collected = _apply(collect=True, op=DropForeignKey(child, column=["owner_id", "other_id"]))++ lock = next(statement for statement in collected if "LOCK TABLE" in statement)+ first_drop = next(statement for statement in collected if "DROP CONSTRAINT" in statement)+ assert collected.index(lock) < collected.index(first_drop)+ assert lock.index(parent_a) < lock.index(child)+ assert lock.index(parent_b) < lock.index(child)@pytest.mark.django_db@@ -108,3 +134,45 @@ def test_the_drop_cannot_be_reversed():def test_needs_a_column_or_a_parent():with pytest.raises(ValueError, match="column, a to_table"):DropForeignKey("test_dropfk_child")+++# The raised value is the one an operator sets on a loaded server. Half of it is a ten second+# wait, which the op's own ceiling has to cut back.[email protected]("server_deadlock_timeout", [None, "20s"])[email protected]_db(transaction=True)+def test_a_contended_parent_fails_fast(temp_tables, server_deadlock_timeout):+ child, parent_a, _ = temp_tables+ blocker = connections.create_connection("default")+ blocker.set_autocommit(False)+ with connection.cursor() as cursor:+ if server_deadlock_timeout is not None:+ cursor.execute(f"SET deadlock_timeout = '{server_deadlock_timeout}'")+ cursor.execute("SELECT setting::int FROM pg_settings WHERE name = 'deadlock_timeout'")+ deadlock_seconds = cursor.fetchone()[0] / 1000+ # Far longer than the op allows itself, so an unbounded drop stalls this test the way+ # it stalls a deploy instead of failing it.+ cursor.execute("SET lock_timeout = '10s'")+ try:+ with blocker.cursor() as cursor:+ # An open read holds ACCESS SHARE on the parent, which the drop's ACCESS+ # EXCLUSIVE has to wait for.+ cursor.execute(f'SELECT count(*) FROM "{parent_a}"')++ started = time.monotonic()+ # The lock phase arms lock_timeout and statement_timeout with the same budget, so+ # either one can be the one that fires.+ with pytest.raises(OperationalError, match="lock timeout|statement timeout"):+ _apply(DropForeignKey(child, column="owner_id"))+ waited = time.monotonic() - started+ finally:+ blocker.rollback()+ blocker.close()+ with connection.cursor() as cursor:+ cursor.execute("RESET lock_timeout")+ cursor.execute("RESET deadlock_timeout")++ # Under deadlock_timeout, so the op abandons the wait before its own deadlock detector+ # runs. Under the ceiling too, so a server that allows a longer wait does not get one.+ assert waited < deadlock_seconds+ assert waited < MAX_LOCK_BUDGET_MS / 1000 + 1+ assert _fk_columns(child) == {"owner_id", "other_id"}