: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(devex): block a foreign key drop that locks two hot parents (#110298)
Julian Bez3299a92c9346
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex 5fe8d6a65b6c..be829019f473 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -103,7 +103,7 @@ Two things a callable does not do for you:- **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 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 the check and unique rules on a retiring column** → `DropColumnConstraints(table, columns=[...])`, before the release that stops writing the column. It finds every check, unique and exclusion constraint and every unique index on those columns in the catalog, including ones an earlier swap left behind that no migration names, and drops them under one bounded lock. Never type a Django-generated name into `DROP CONSTRAINT IF EXISTS`: a wrong name succeeds and drops nothing. The risk analyzer blocks a forward drop of a name with Django's hash suffix.-- **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`.+- **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`. The analyzer blocks one op whose keys reach two hot tables, even under `atomic = False`.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 28eb08d7bd9d..20afc2929027 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -317,7 +317,7 @@ operations = [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.+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. The migration risk analyzer blocks one `DropForeignKey` whose keys reach two or more of `posthog_team`, `posthog_user`, `posthog_organization` and `posthog_project`, with or without `atomic = False`.**`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/policies.py b/posthog/management/migration_analysis/policies.pyindex 8574517387a6..ef7ebbf8fd48 100644--- a/posthog/management/migration_analysis/policies.py+++ b/posthog/management/migration_analysis/policies.py@@ -768,7 +768,82 @@ def _disk_loader() -> Optional[MigrationLoader]:return _loader-class OrphanedForeignKeyPolicy(MigrationPolicy):+class _ForeignKeyStatePolicy(MigrationPolicy):+ """Base for policies that read the foreign keys a table holds in Django state before a migration."""++ def _state_before(self, migration) -> Any:+ loader = _disk_loader()+ if loader is None:+ return None+ node = (migration.app_label, migration.name)+ try:+ # Django resolves swappable and __first__ sentinels while it builds the graph, so+ # asking for the node beats replaying migration.dependencies, which still holds+ # the raw sentinels that project_state cannot take as nodes.+ return loader.project_state(node, at_end=False)+ except Exception:+ pass+ try:+ return loader.project_state([parent.key for parent in loader.graph.node_map[node].parents])+ except Exception:+ # A migration the graph cannot place is not this policy's problem to report.+ return None++ def _table_of(self, model_state, app_label: str, model_name: str) -> str:+ return model_state.options.get("db_table") or f"{app_label}_{model_name}"++ def _constrained_foreign_keys(self, state, model_state, field_name) -> Iterator[_ConstrainedForeignKey]:+ """Yield the foreign keys on this model that the database holds a constraint for."""+ for name, field in model_state.fields.items():+ if field_name is not None and name != field_name:+ continue+ remote = getattr(field, "remote_field", None)+ if remote is None or getattr(field, "many_to_many", False):+ continue+ column = getattr(field, "db_column", None) or f"{name}_id"+ if not getattr(field, "db_constraint", True) and not self._added_by_helper(model_state, column):+ continue+ yield _ConstrainedForeignKey(field=name, column=column, target_table=self._target_table(state, remote))++ def _added_by_helper(self, model_state, column: str) -> bool:+ """True when a migration added a real constraint for a db_constraint=False field.++ AddForeignKeyNotValid is the sanctioned way to give a hot-table foreign key a database+ constraint while the model keeps db_constraint=False, so the state flag alone does not+ prove the database is free of one.+ """+ loader = _disk_loader()+ if loader is None:+ return False+ model_name = model_state.name.lower()+ for migration in loader.disk_migrations.values():+ # AddForeignKeyNotValid resolves model_name in its own app, and model names repeat across apps.+ if migration.app_label != model_state.app_label:+ continue+ for op in migration.operations or []:+ for candidate in (+ list(getattr(op, "database_operations", []) or []) if hasattr(op, "database_operations") else [op]+ ):+ if candidate.__class__.__name__ != "AddForeignKeyNotValid":+ continue+ if str(getattr(candidate, "model_name", "")).lower() != model_name:+ continue+ if getattr(candidate, "column", None) == column:+ return True+ return False++ def _target_table(self, state, remote) -> str:+ target = remote.model+ if not isinstance(target, str):+ target = f"{target._meta.app_label}.{target._meta.model_name}"+ app_label, _, model_name = target.rpartition(".")+ target_state = state.models.get((app_label, model_name.lower()))+ if target_state is not None:+ return self._table_of(target_state, app_label, model_name.lower())+ return f"{app_label}_{model_name.lower()}"+++class OrphanedForeignKeyPolicy(_ForeignKeyStatePolicy):"""Flag a state-only DeleteModel or RemoveField that leaves a foreign key behind."""def check_operation(self, op) -> list[str]:@@ -848,24 +923,6 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):return Truereturn False- def _state_before(self, migration) -> Any:- loader = _disk_loader()- if loader is None:- return None- node = (migration.app_label, migration.name)- try:- # Django resolves swappable and __first__ sentinels while it builds the graph, so- # asking for the node beats replaying migration.dependencies, which still holds- # the raw sentinels that project_state cannot take as nodes.- return loader.project_state(node, at_end=False)- except Exception:- pass- try:- return loader.project_state([parent.key for parent in loader.graph.node_map[node].parents])- except Exception:- # A migration the graph cannot place is not this policy's problem to report.- return None-def _tables_adopted_elsewhere(self, app_label: str) -> set[_TableColumn]:"""Columns that a model in another app still tracks at the graph leaves.@@ -891,56 +948,6 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):adopted.add(_TableColumn(table=table, column=getattr(field, "db_column", None) or f"{name}_id"))return adopted- def _table_of(self, model_state, app_label: str, model_name: str) -> str:- return model_state.options.get("db_table") or f"{app_label}_{model_name}"-- def _constrained_foreign_keys(self, state, model_state, field_name) -> Iterator[_ConstrainedForeignKey]:- """Yield the foreign keys on this model that the database holds a constraint for."""- for name, field in model_state.fields.items():- if field_name is not None and name != field_name:- continue- remote = getattr(field, "remote_field", None)- if remote is None or getattr(field, "many_to_many", False):- continue- column = getattr(field, "db_column", None) or f"{name}_id"- if not getattr(field, "db_constraint", True) and not self._added_by_helper(model_state, column):- continue- yield _ConstrainedForeignKey(field=name, column=column, target_table=self._target_table(state, remote))-- def _added_by_helper(self, model_state, column: str) -> bool:- """True when a migration added a real constraint for a db_constraint=False field.-- AddForeignKeyNotValid is the sanctioned way to give a hot-table foreign key a database- constraint while the model keeps db_constraint=False, so the state flag alone does not- prove the database is free of one.- """- loader = _disk_loader()- if loader is None:- return False- model_name = model_state.name.lower()- for migration in loader.disk_migrations.values():- for op in migration.operations or []:- for candidate in (- list(getattr(op, "database_operations", []) or []) if hasattr(op, "database_operations") else [op]- ):- if candidate.__class__.__name__ != "AddForeignKeyNotValid":- continue- if str(getattr(candidate, "model_name", "")).lower() != model_name:- continue- if getattr(candidate, "column", None) == column:- return True- return False-- def _target_table(self, state, remote) -> str:- target = remote.model- if not isinstance(target, str):- target = f"{target._meta.app_label}.{target._meta.model_name}"- app_label, _, model_name = target.rpartition(".")- target_state = state.models.get((app_label, model_name.lower()))- if target_state is not None:- return self._table_of(target_state, app_label, model_name.lower())- return f"{app_label}_{model_name.lower()}"-def _violation(self, model_name: str, table: str, fk: _ConstrainedForeignKey) -> str:severity = "❌ BLOCKED" if fk.target_table in _HOT_TABLES else "⚠️ WARNING"return (@@ -956,7 +963,7 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):_LOCK_PHASE_OPERATIONS = {"DropColumnConstraints", "DropForeignKey", "SafeDropTable"}-class LockPhaseTransactionPolicy(MigrationPolicy):+class LockPhaseTransactionPolicy(_ForeignKeyStatePolicy):"""Keep a DropForeignKey, DropColumnConstraints or SafeDropTable alone in its transaction.Each takes its locks in a bounded, parent-first phase (posthog/migration_helpers/lock_phase.py),@@ -966,23 +973,65 @@ class LockPhaseTransactionPolicy(MigrationPolicy):locks while the lock phase holds the parents. Each shape rebuilds the crossed lock orderthat deadlocks against live reads. With atomic = False nothing accumulates, because eachoperation commits on its own.++ One DropForeignKey whose keys reach two hot parents has the same problem inside a single+ lock phase: it must win every hot parent in one budget, and under load each bin/migrate+ retry can lose the same way. atomic = False does not help it, because DropForeignKey runs+ in a transaction of its own and locks all of its parents there."""def check_operation(self, op) -> list[str]:return [] # The hazard is the shared transaction, so it runs at migration level.+ def _hot_parents(self, migration, op) -> list[str]:+ """Hot tables that the keys of one DropForeignKey reference, read from state before the migration.++ A table that already left Django's state has no fields to read, so its keys are not+ checked. A false block on a correct migration costs more than a missed check.+ """+ columns = getattr(op, "columns", None) or []+ # A drop by to_table, or of one column, reaches one parent at most.+ if len(columns) < 2 or getattr(op, "to_table", None):+ return []+ state = self._state_before(migration)+ if state is None:+ return []+ parents = set()+ for (app_label, model_name), model_state in state.models.items():+ if self._table_of(model_state, app_label, model_name) != op.table:+ continue+ for fk in self._constrained_foreign_keys(state, model_state, None):+ if fk.column in columns and fk.target_table in _HOT_TABLES:+ parents.add(fk.target_table)+ return sorted(parents)++ def _hot_parent_violations(self, migration) -> list[str]:+ violations = []+ for op in _descend(migration.operations):+ if op.__class__.__name__ != "DropForeignKey":+ continue+ hot_parents = self._hot_parents(migration, op)+ if len(hot_parents) > 1:+ violations.append(+ f"❌ BLOCKED: DropForeignKey on {op.table} locks {len(hot_parents)} hot parents "+ f"({', '.join(hot_parents)}) in one lock phase, which must win all of them in one short "+ "budget, so under load every bin/migrate retry can fail. Set atomic = False, give each key "+ "its own DropForeignKey, and list the migration in atomic_false_acknowledged_migrations.txt."+ )+ return violations+def check_migration(self, migration) -> list[str]:if not is_posthog_app(migration.app_label, migration):return []+ violations = self._hot_parent_violations(migration)if not getattr(migration, "atomic", True):- return []+ return violationsnames = [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 []+ return violations- violations = []if len(lock_phases) > 1:violations.append(f"❌ BLOCKED: {len(lock_phases)} lock-phase operations ({', '.join(sorted(set(lock_phases)))}) share "diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 8b0371cab4e1..88099e49a692 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -3025,6 +3025,58 @@ class TestLockPhaseTransactionPolicy:assert violation.startswith("❌ BLOCKED")assert fragment in violation+ @pytest.mark.parametrize(+ "atomic,drops,blocked",+ [+ (True, [["created_by_id", "team_id"]], True),+ (False, [["created_by_id", "team_id"]], True),+ (True, [["team_id", "widget_id"]], False),+ (False, ["created_by_id", "team_id"], False),+ ],+ )+ def test_one_drop_must_not_lock_two_hot_parents(self, monkeypatch, atomic, drops, blocked):+ state = ProjectState()+ state.add_model(+ ModelState(+ app_label="posthog",+ name="Child",+ fields=[+ ("id", models.AutoField(primary_key=True)),+ ("team", models.ForeignKey("posthog.Team", on_delete=models.CASCADE)),+ ("created_by", models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)),+ ("widget", models.ForeignKey("posthog.Widget", on_delete=models.CASCADE)),+ ],+ options={"db_table": "posthog_child"},+ )+ )+ for name, table in [("Team", "posthog_team"), ("User", "posthog_user"), ("Widget", "posthog_widget")]:+ state.add_model(+ ModelState(+ app_label="posthog",+ name=name,+ fields=[("id", models.AutoField(primary_key=True))],+ options={"db_table": table},+ )+ )+ monkeypatch.setattr(LockPhaseTransactionPolicy, "_state_before", lambda _s, _m: state)+ migration = MagicMock()+ migration.app_label = "posthog"+ migration.name = "0001_test"+ migration.atomic = atomic+ migration.operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[migrations.DeleteModel(name="Child")],+ database_operations=[DropForeignKey("posthog_child", column=column) for column in drops],+ )+ ]++ violations = LockPhaseTransactionPolicy().check_migration(migration)++ assert len(violations) == (1 if blocked else 0)+ if blocked:+ assert violations[0].startswith("❌ BLOCKED")+ assert "posthog_team, posthog_user" in violations[0]+class TestGeneratedNameDropPolicy:@parameterized.expand(