: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
feat(migrations): add FK-to-hot-table helper and analyzer check (#65597)
Julian Bez6aae7ac66022
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex c79b17e382b3..84e091517fd9 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -28,10 +28,13 @@ If the task is a ClickHouse migration, use `clickhouse-migrations` instead.- **Add/drop an index** → `SafeAddIndexConcurrently` / `SafeRemoveIndexConcurrently` (`model_name` + `models.Index`). Never use Django's `AddIndexConcurrently` — CI blocks it.- **Add a CHECK constraint** → `AddConstraintNotValid` then `ValidateConstraint` in a later migration (or same migration with `atomic = False`).+- **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`.All concurrent-index ops require `atomic = False`.+Meta-principle when you hit a risky-but-common pattern with no helper: don't hand-roll the safe DDL from docs — ship a drop-in helper in `posthog/migration_helpers` and point the CI policy at it. A one-import helper beats a wall of caveated `RunSQL` every time.+## Hot table hazard`posthog_team`, `posthog_user`, `posthog_organization`, and `posthog_project` are read on virtually every request. Any `ALTER TABLE` on them — including a plain nullable `AddField`, which is "safe" everywhere else — needs an `ACCESS EXCLUSIVE` lock, and while that lock request waits behind in-flight queries, every later query on the table queues behind it. Even a metadata-only `ADD COLUMN` can stall site-wide traffic in waves (one per `bin/migrate` retry) until the ALTER wins the lock race. This has caused production 5xx incidents.@@ -42,6 +45,13 @@ Before writing a migration that touches one of these models:- `CREATE INDEX CONCURRENTLY` (via `SafeAddIndexConcurrently`) is fine — `SHARE UPDATE EXCLUSIVE` doesn't block reads or writes.- If the field genuinely belongs on the hot table (core identity, cross-product settings, SDK config), the `HotTableAlterPolicy` analyzer blocks the migration in CI until `<app_label>.<migration_name>` is added to `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt`. That acknowledgment also means coordinating the deploy with infra for a low-traffic window.+### Foreign keys to hot tables++A `ForeignKey` _targeting_ a hot table is the same hazard from the other side, and it bites from **any** app — a plain product-app `CreateModel` or `AddField` with `to="posthog.team"` (or `settings.AUTH_USER_MODEL`, which is `posthog_user`). Creating the FK constraint takes a `SHARE ROW EXCLUSIVE` lock on the referenced parent, which conflicts with the `ROW EXCLUSIVE` every `INSERT`/`UPDATE`/`DELETE` on the parent holds; under write traffic the lock queues and `lock_timeout` cancels it on each `bin/migrate` retry. `HotTableAlterPolicy` now flags this case. Two ways out:++- **`db_constraint=False` on the `ForeignKey`** — emits no FK constraint and takes **no** lock on the parent at all (app-level enforcement only). This is the only truly lock-free path.+- **A real DB constraint, two-phase** — declare the FK `db_constraint=False`, then add it back as a DB constraint with `AddForeignKeyNotValid`, and `ValidateForeignKey` in a later migration. Be honest: `ADD CONSTRAINT ... NOT VALID` still takes a _brief_ `SHARE ROW EXCLUSIVE` lock on the parent for the metadata add — it skips the row scan, so it shrinks the lock window but does not eliminate it. `VALIDATE` then runs lock-free on the parent.+## Cross-language `NOT NULL` hazard`posthog_user`, `posthog_team`, and other core tables in the main Postgres database are written by Django **and** by `nodejs/` (plugin-server tests via `insertRow`), `rust/` services, and Temporal workers. Those non-Django writers issue raw `INSERT`s that only list the columns they care about, so any new `NOT NULL` column without a Postgres-level `DEFAULT` will break them with `null value in column "<col>" violates not-null constraint`.diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.mdindex 1a7ce9c9364b..074c74b10ad2 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -44,6 +44,52 @@ The migration analyzer (`HotTableAlterPolicy`) blocks any DDL on these tables in2. Add `<app_label>.<migration_name>` to `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt` — this is the explicit "I accept the risk" act, and it's visible in review.3. Coordinate the deploy with #team-infrastructure for a low-traffic window.+### Foreign Keys to Hot Tables++**Problem:** The hazard above also fires from the _referencing_ side, and from **any** app — a plain `CreateModel` or `AddField` in a product app with a `ForeignKey(to="posthog.team", ...)` (or `to=settings.AUTH_USER_MODEL`, which resolves to `posthog_user`). Creating the FK constraint takes a `SHARE ROW EXCLUSIVE` lock on the _referenced parent_ table, even though the child table is brand new. That lock conflicts with the `ROW EXCLUSIVE` lock every `INSERT`/`UPDATE`/`DELETE` on the parent holds, so under write traffic the lock request queues behind in-flight writes, `lock_timeout` cancels it, and each `bin/migrate` retry repeats the stall. A `CreateModel` with an FK to `posthog_team` has blocked a deploy this way.++`HotTableAlterPolicy` flags `CreateModel` / `AddField` whose FK target resolves to a hot table (it skips FKs declared `db_constraint=False`). Two options:++**Option A — `db_constraint=False` (the only truly lock-free path):**++```python+# CreateModel / AddField then emit no FK constraint and take NO lock on the parent.+# Referential integrity is enforced in application code only.+team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+```++This is the option that avoids the parent lock entirely — reach for it when you can live without database-level enforcement.++**Option B — a real DB constraint, two-phase via the helper:**++Declare the FK `db_constraint=False` (so `CreateModel` / `AddField` take no lock), then add the constraint back in a later migration with `AddForeignKeyNotValid`, and `ValidateForeignKey` after that:++```python+# 00xx_add_fk_not_valid.py (brief SHARE ROW EXCLUSIVE on the parent — see caveat below)+from posthog.migration_helpers import AddForeignKeyNotValid++operations = [+ AddForeignKeyNotValid(+ model_name="mymodel",+ name="mymodel_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+]++# 00yy_validate_fk.py (SHARE UPDATE EXCLUSIVE on the child, no parent lock)+from posthog.migration_helpers import ValidateForeignKey++operations = [+ ValidateForeignKey(model_name="mymodel", name="mymodel_team_id_fk"),+]+```++Be honest about the lock: `ADD CONSTRAINT ... NOT VALID` still takes a **brief** `SHARE ROW EXCLUSIVE` lock on the parent for the catalog metadata add. It skips the row-validation scan, so it shrinks the lock window to metadata-only — but it does **not** eliminate the parent lock. Only `db_constraint=False` (Option A) is truly lock-free. The follow-up `VALIDATE CONSTRAINT` scans child rows under `SHARE UPDATE EXCLUSIVE` and takes no lock on the parent.++If the FK genuinely must lock the hot table on add, acknowledge it the same way as any other hot-table DDL (add the migration to `hot_table_acknowledged_migrations.txt` and coordinate the deploy).+## Dropping Tables**Problem:** `DeleteModel` operations drop tables immediately. This breaks backwards compatibility during deployment and **cannot be rolled back** - once data is deleted, any rollback deployment will fail because the table no longer exists.@@ -487,7 +533,7 @@ class Migration(migrations.Migration):Keep the two phases in **separate migrations** (so the add's brief `ACCESS EXCLUSIVE` lock isn't held through the validate scan), or in the same migration with `atomic = False`.If validation fails, Django marks the migration unapplied — clean the offending rows and re-run.-**Note:** The same NOT VALID / VALIDATE pattern applies to `FOREIGN KEY` constraints on existing columns; there's no helper for that yet, so hand-write the `RunSQL` (`ADD CONSTRAINT ... FOREIGN KEY ... NOT VALID` then `VALIDATE CONSTRAINT`). New nullable FK columns don't need it — the column starts empty, so there's nothing to validate.+**Note:** The same NOT VALID / VALIDATE pattern applies to `FOREIGN KEY` constraints via `AddForeignKeyNotValid` / `ValidateForeignKey` — don't hand-write the `RunSQL`. This matters most when the FK points at a hot table; see [Foreign Keys to Hot Tables](#foreign-keys-to-hot-tables). New nullable FK columns to non-hot tables don't need it — the column starts empty, so there's nothing to validate.### Key Points@@ -497,6 +543,8 @@ If validation fails, Django marks the migration unapplied — clean the offendin- If validation fails, Django marks the migration as unapplied - clean the offending rows and re-run the validation migration- Can fix data issues and retry validation without blocking production+The same two-phase pattern exists for **foreign keys** via `AddForeignKeyNotValid` / `ValidateForeignKey` — but note that an FK to a hot table needs extra care, since `ADD CONSTRAINT ... NOT VALID` still briefly locks the _referenced parent_. See [Foreign Keys to Hot Tables](#foreign-keys-to-hot-tables).+## Running Data Migrations**Problem:** `RunSQL` with `UPDATE` or `DELETE` operations can lock rows for extended periods, especially on large tables. `RunPython` operations can be slow and hold locks.diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.pyindex b19ba64ec105..66fb02a99305 100644--- a/posthog/management/migration_analysis/policies.py+++ b/posthog/management/migration_analysis/policies.py@@ -8,6 +8,11 @@ import refrom abc import ABC, abstractmethodfrom pathlib import Path+from django.conf import settings+from django.db import models++from posthog.management.migration_analysis.operations import is_unmanaged_model+# Apps owned by PostHog where policies are enforcedPOSTHOG_OWNED_APPS = ["posthog", "ee"]@@ -445,6 +450,12 @@ class HotTableAlterPolicy(MigrationPolicy):# so the helper is gated like a plain AddConstraint. (ValidateConstraint# is not listed - VALIDATE takes only SHARE UPDATE EXCLUSIVE.)"AddConstraintNotValid",+ # AddForeignKeyNotValid(model_name=<hot table>) emits ALTER TABLE posthog_*+ # ADD CONSTRAINT against the hot *child* itself - same lock hazard. Gating on+ # model_name catches that; the helper's sanctioned use (a FK *pointing at* a+ # hot parent) carries the parent in to_table, not model_name, so it stays+ # unflagged here.+ "AddForeignKeyNotValid",}# Op types that carry the target model in `name`MODEL_LEVEL_OPS = {@@ -482,6 +493,14 @@ class HotTableAlterPolicy(MigrationPolicy):violations = []for op in self._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):+ continue+ fk_table = self._fk_target_hot_table(op)+ if fk_table:+ violations.append(self._fk_violation(op, fk_table, label))+ continuetable = self._hot_table_target(op, migration.app_label)if table:violations.append(self._violation(op, table, label))@@ -505,7 +524,11 @@ class HotTableAlterPolicy(MigrationPolicy):yield opdef _hot_table_target(self, op, app_label: str) -> str | None:- """Return the hot table an operation alters, or None."""+ """Return the hot table an operation alters directly, or None.++ FK *targets* (a CreateModel/AddField pointing at a hot table) are handled+ upstream in check_migration via _fk_target_hot_table, not here.+ """op_type = op.__class__.__name__# The hot models all live in the posthog app; same-named models in@@ -528,6 +551,63 @@ class HotTableAlterPolicy(MigrationPolicy):return None+ def _fk_target_hot_table(self, op) -> str | None:+ """Return the hot table a CreateModel/AddField FK points at, or None.++ Skips FKs declared with db_constraint=False - those emit no FK constraint+ and take NO lock on the parent, so they're the sanctioned escape hatch.++ AlterField that turns a column into a hot-table FK is the same hazard class+ but a rarer shape; it's intentionally out of scope here.+ """+ op_type = op.__class__.__name__+ if op_type == "CreateModel":+ fields = getattr(op, "fields", None) or []+ for _name, field in fields:+ table = self._fk_field_hot_table(field)+ if table:+ return table+ elif op_type == "AddField":+ table = self._fk_field_hot_table(getattr(op, "field", None))+ if table:+ return table+ return None++ def _fk_field_hot_table(self, field) -> str | None:+ # A ManyToManyField with an auto-created through table emits FK constraints to the+ # target, taking the same SHARE ROW EXCLUSIVE lock on the parent. An explicit+ # `through=` model defines its own FK fields, which get analyzed when that model's+ # CreateModel runs - skip it here so it isn't double-counted. db_constraint=False on+ # the M2M propagates to the through FKs, so it's the same escape hatch as a plain FK.+ if isinstance(field, models.ManyToManyField):+ if getattr(field.remote_field, "through", None) is not None:+ return None+ if getattr(field.remote_field, "db_constraint", True) is False:+ return None+ return self._resolve_fk_target_table(field.remote_field.model)+ if not isinstance(field, models.ForeignKey):+ return None+ if getattr(field, "db_constraint", True) is False:+ return None # db_constraint=False takes no lock on the parent; the escape hatch+ return self._resolve_fk_target_table(field.remote_field.model)++ def _resolve_fk_target_table(self, target) -> str | None:+ """Resolve a FK target to a hot posthog_* table name, or None.++ `field.remote_field.model` is a string label like "posthog.team" in+ migration state. settings.AUTH_USER_MODEL (the swappable user FK) desugars+ to that same "posthog.user" string at serialization time, so both the+ explicit and swappable forms land here as strings.+ """+ if target == settings.AUTH_USER_MODEL:+ target = "posthog.user"+ if not isinstance(target, str) or "." not in target:+ return None+ app, _, model_name = target.rpartition(".")+ if app.lower() == "posthog" and model_name.lower() in self.HOT_MODELS:+ return f"posthog_{model_name.lower()}"+ return None+def _hot_table_in_sql(self, sql) -> str | None:sql = str(sql)# Strip /* */, -- and # comments so table names inside comments don't match@@ -559,6 +639,35 @@ class HotTableAlterPolicy(MigrationPolicy):"See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#altering-hot-tables")+ def _fk_violation(self, op, table: str, label: str) -> str:+ return (+ f'❌ BLOCKED: {op.__class__.__name__} adds a ForeignKey to "{table}" - this table is read on '+ "virtually every request. Creating the FK constraint takes a SHARE ROW EXCLUSIVE lock on the "+ f"referenced parent ({table}), which conflicts with the ROW EXCLUSIVE lock every "+ "INSERT/UPDATE/DELETE on it holds. Under write traffic the lock request queues, lock_timeout "+ "cancels it, and each bin/migrate retry repeats the stall. This has blocked deploys.\n"+ "Two options:\n"+ "(a) db_constraint=False on the ForeignKey - emits no FK constraint and takes NO lock on the "+ "parent at all (app-level enforcement only). This is the only truly lock-free path.\n"+ "(b) For a real database constraint, declare the FK with db_constraint=False, then add it back "+ "as a DB constraint via posthog.migration_helpers.AddForeignKeyNotValid in a later migration and "+ "ValidateForeignKey after that. NOT VALID still takes a *brief* SHARE ROW EXCLUSIVE lock on the "+ "parent for the metadata add (it skips the row scan), so it shrinks the lock window but does not "+ "eliminate it; VALIDATE then runs lock-free on the parent.\n"+ f'If this FK genuinely must lock {table} on add, add "{label}" to '+ "posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt to accept the "+ "risk, and coordinate the deploy with #team-infrastructure for a low-traffic window.\n"+ "See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#foreign-keys-to-hot-tables"+ )+++# DevEx meta-principle for anyone adding a policy here: when a pattern is risky but+# common, the goal is not to document a clever safe workaround and trust authors to+# hand-roll it - it's to ship a drop-in helper in posthog/migration_helpers that bakes+# in the safe behavior, then point this policy's violation message at that helper. A+# blocked migration with a "use SafeAddIndexConcurrently" / "use AddForeignKeyNotValid"+# message reaches for one import; a wall of hand-written RunSQL with caveats reopens the+# incident class. Prefer the helper-plus-pointer over documenting complexity.# Registry of all PostHog policiesPOSTHOG_POLICIES = [diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 53a4befc16c7..568063f3064a 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -1,5 +1,6 @@from unittest.mock import MagicMock+from django.conf import settingsfrom django.db import migrations, modelsfrom parameterized import parameterized@@ -9,6 +10,7 @@ from posthog.management.migration_analysis.models import RiskLevelfrom posthog.management.migration_analysis.policies import ConcurrentIndexIdempotencyPolicy, HotTableAlterPolicyfrom posthog.migration_helpers import (AddConstraintNotValid,+ AddForeignKeyNotValid,SafeAddIndexConcurrently,SafeRemoveIndexConcurrently,ValidateConstraint,@@ -2302,3 +2304,152 @@ class TestHotTableAlterPolicy:mock_migration.__module__ = "products.some_product.backend.migrations.0001_test"risk = self.analyzer.analyze_migration(mock_migration, "products/some_product/backend/migrations/0001_test.py")assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)++ def _analyze_product(self, operations, app_label="some_product", name="0001_test"):+ mock_migration = MagicMock()+ mock_migration.atomic = True+ mock_migration.app_label = app_label+ mock_migration.name = name+ mock_migration.operations = operations+ mock_migration.__module__ = f"products.{app_label}.backend.migrations.{name}"+ return self.analyzer.analyze_migration(mock_migration, f"products/{app_label}/backend/migrations/{name}.py")++ def test_create_model_with_fk_to_hot_table_blocked(self):+ """The warehouse_sources.0034 case: a product CreateModel with a FK to posthog.team."""+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("team", models.ForeignKey("posthog.team", on_delete=models.CASCADE)),+ ],+ )+ risk = self._analyze_product([op])+ assert any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)+ assert any("db_constraint=False" in v for v in risk.policy_violations)+ assert any("AddForeignKeyNotValid" in v for v in risk.policy_violations)++ def test_create_model_with_fk_to_hot_table_db_constraint_false_not_flagged(self):+ """db_constraint=False emits no FK constraint and takes no parent lock - the escape hatch."""+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("team", models.ForeignKey("posthog.team", on_delete=models.CASCADE, db_constraint=False)),+ ],+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_field_fk_to_hot_table_blocked(self):+ op = create_mock_operation(+ migrations.AddField,+ model_name="datawarehousetable",+ name="team",+ field=models.ForeignKey("posthog.team", on_delete=models.CASCADE),+ )+ risk = self._analyze_product([op])+ assert any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_create_model_with_fk_to_non_hot_table_not_flagged(self):+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("table", models.ForeignKey("warehouse_sources.datawarehousetable", on_delete=models.CASCADE)),+ ],+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_create_model_unmanaged_with_fk_to_hot_table_not_flagged(self):+ """managed=False maps an external table - Django emits no DDL or FK, so no parent lock."""+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("team", models.ForeignKey("posthog.team", on_delete=models.CASCADE)),+ ],+ options={"managed": False},+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_field_m2m_to_hot_table_blocked(self):+ """A M2M to a hot table auto-creates a through table with FK constraints to the parent."""+ op = create_mock_operation(+ migrations.AddField,+ model_name="datawarehousetable",+ name="teams",+ field=models.ManyToManyField("posthog.team"),+ )+ risk = self._analyze_product([op])+ assert any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_field_m2m_to_hot_table_db_constraint_false_not_flagged(self):+ """db_constraint=False propagates to the through FKs - the same escape hatch as a plain FK."""+ op = create_mock_operation(+ migrations.AddField,+ model_name="datawarehousetable",+ name="teams",+ field=models.ManyToManyField("posthog.team", db_constraint=False),+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_field_m2m_with_explicit_through_not_flagged(self):+ """An explicit through model defines its own FKs, analyzed when its CreateModel runs."""+ op = create_mock_operation(+ migrations.AddField,+ model_name="datawarehousetable",+ name="teams",+ field=models.ManyToManyField("posthog.team", through="some_product.TableTeam"),+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_create_model_with_swappable_user_fk_blocked(self):+ """settings.AUTH_USER_MODEL desugars to posthog.user, a hot table."""+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("created_by", models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)),+ ],+ )+ risk = self._analyze_product([op])+ assert any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_fk_to_hot_table_acknowledged_not_flagged(self, tmp_path, monkeypatch):+ ack_file = tmp_path / "acks.txt"+ ack_file.write_text("some_product.0001_test\n")+ monkeypatch.setattr(HotTableAlterPolicy, "ACKNOWLEDGMENTS_FILE", ack_file)+ op = create_mock_operation(+ migrations.CreateModel,+ name="WarehouseColumnAnnotation",+ fields=[+ ("id", models.UUIDField(primary_key=True)),+ ("team", models.ForeignKey("posthog.team", on_delete=models.CASCADE)),+ ],+ )+ risk = self._analyze_product([op])+ assert not any("SHARE ROW EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_foreign_key_not_valid_on_hot_child_blocked(self):+ """The helper run against a hot child still ALTERs posthog_team itself - gate it."""+ op = AddForeignKeyNotValid(model_name="team", name="team_owner_fk", column="owner_id", to_table="some_table")+ risk = self._analyze([op])+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)++ def test_add_foreign_key_not_valid_pointing_at_hot_parent_not_flagged(self):+ """The sanctioned use: a non-hot child's FK pointing at a hot parent carries the+ parent in to_table, not model_name, so it isn't gated as a direct hot-table alter."""+ op = AddForeignKeyNotValid(+ model_name="mymodel", name="mymodel_team_fk", column="team_id", to_table="posthog_team"+ )+ risk = self._analyze([op])+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.pyindex 8d9cbda05d2d..20ea5e9de26b 100644--- a/posthog/migration_helpers/__init__.py+++ b/posthog/migration_helpers/__init__.py@@ -5,12 +5,15 @@ from posthog.migration_helpers.concurrent_index import (SafeRemoveIndexConcurrently,)from posthog.migration_helpers.not_valid_constraint import AddConstraintNotValid, ValidateConstraint+from posthog.migration_helpers.not_valid_foreign_key import AddForeignKeyNotValid, ValidateForeignKey__all__ = ["AddConstraintNotValid",+ "AddForeignKeyNotValid","CreateIndexConcurrently","DropIndexConcurrently","SafeAddIndexConcurrently","SafeRemoveIndexConcurrently","ValidateConstraint",+ "ValidateForeignKey",]diff --git a/posthog/migration_helpers/not_valid_foreign_key.py b/posthog/migration_helpers/not_valid_foreign_key.pynew file mode 100644index 000000000000..9c17752ca855--- /dev/null+++ b/posthog/migration_helpers/not_valid_foreign_key.py@@ -0,0 +1,186 @@+"""Two-phase FOREIGN KEY helper: add the FK as NOT VALID, then VALIDATE separately.++Adding a foreign key the normal way (a plain `ForeignKey` in a model, which Django+emits inline in `CREATE TABLE` or as `ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY`)+takes a SHARE ROW EXCLUSIVE lock on the *referenced parent* table while the constraint+is added, and then validates every existing child row under that lock. On a hot parent+table (posthog_team, posthog_user, ...) that SHARE ROW EXCLUSIVE conflicts with the+ROW EXCLUSIVE lock every INSERT/UPDATE/DELETE on the parent holds, so under write+traffic the lock request queues, lock_timeout cancels it, and every bin/migrate retry+repeats the stall. This blocked a prod deploy.++Be honest about the lock nuance - there are two distinct options, and only one is truly+lock-free:++1. `db_constraint=False` on the `ForeignKey` (declared in the model) is the only path+ that takes NO lock on the parent at all. `CREATE TABLE` / `AddField` then emit no FK+ constraint - the relationship is enforced in application code only. Reach for this when+ the FK targets a hot table and you can live without database-level enforcement; it is+ the only option that would have saved the deploy above.+2. This helper splits the constraint into two phases so a real database FK can still be+ added with a much smaller lock window:++ - `AddForeignKeyNotValid` runs `ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ...+ NOT VALID`. This still takes a *brief* SHARE ROW EXCLUSIVE lock on the parent for+ the catalog metadata add - it is NOT lock-free - but it skips the row-validation+ scan, so the lock window is metadata-only rather than scan-length.+ - `ValidateForeignKey` later runs `ALTER TABLE ... VALIDATE CONSTRAINT ...`, which+ scans the child rows under SHARE UPDATE EXCLUSIVE and takes no lock on the parent.++The intended author workflow for a hot-table FK is:++ # model: declare the FK with db_constraint=False so CREATE TABLE / AddField emit+ # no parent lock at all. on_delete stays a Django/Python concern - the collector+ # handles cascades and signals; Django never emits a DB-level ON DELETE action.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)++ # 00xx_add_fk_not_valid.py (brief SHARE ROW EXCLUSIVE on the parent)+ operations = [+ AddForeignKeyNotValid(+ model_name="mymodel",+ name="mymodel_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ ]++ # 00yy_validate_fk.py (SHARE UPDATE EXCLUSIVE on the child, no parent lock)+ operations = [+ ValidateForeignKey(model_name="mymodel", name="mymodel_team_id_fk"),+ ]++Put the two phases in SEPARATE migrations (validate after the add has deployed), or in+the same migration with `atomic = False` - never the same atomic migration, or the ADD's+lock is held through the VALIDATE scan and the split buys nothing.++The ADD phase deliberately does NOT disable lock_timeout / statement_timeout: it's a+brief metadata-only ALTER, so it should fail fast on lock contention (the default+lock_timeout) instead of queuing the SHARE ROW EXCLUSIVE lock behind in-flight writes on+the parent and stalling it further. A bin/migrate retry re-attempts once the lock is+free. The VALIDATE phase reuses `ValidateConstraint`, which disables the timeouts so a+deploy-time statement_timeout can't kill the scan mid-flight.++Both phases are idempotent (bin/migrate re-runs the whole migration on failure): the add+skips if the constraint already exists, the validate skips if it is already validated.++`ValidateConstraint` from `not_valid_constraint` works unchanged for FK constraints -+`VALIDATE CONSTRAINT` and the `pg_constraint.convalidated` probe are constraint-type+agnostic. `ValidateForeignKey` is a thin subclass of it so the two FK phases read as a+pair at the call site and the validate op deconstructs under its own name.+"""++from django.db.migrations.operations.base import Operation++from posthog.migration_helpers.not_valid_constraint import ValidateConstraint, _constraint_validity+++class ValidateForeignKey(ValidateConstraint):+ """Phase 2 for a FOREIGN KEY: VALIDATE an FK previously added with NOT VALID.++ `VALIDATE CONSTRAINT` and the `pg_constraint.convalidated` probe don't care whether+ the constraint is a CHECK or a FOREIGN KEY, so the behaviour is entirely inherited from+ `ValidateConstraint`. This exists as a real subclass (not an alias) so it deconstructs+ under its own name - a squash that touches an FK validate op round-trips as+ `ValidateForeignKey`, matching the name the docs tell authors to use, and the migration+ analyzer can tell FK validation apart from CHECK validation.+ """++ pass+++class AddForeignKeyNotValid(Operation):+ """Phase 1: add a FOREIGN KEY constraint with NOT VALID (no child-row scan).++ Emits the same FK DDL Django would, minus the row scan: `ALTER TABLE ... ADD+ CONSTRAINT ... FOREIGN KEY (column) REFERENCES to_table (to_column) DEFERRABLE+ INITIALLY DEFERRED NOT VALID`. This takes a brief SHARE ROW EXCLUSIVE lock on the+ *referenced parent* table for the catalog metadata add - it is NOT lock-free, but it+ skips validating existing child rows under that lock. Follow up with+ `ValidateForeignKey` in a separate migration.++ The constraint is DEFERRABLE INITIALLY DEFERRED to match Django's Postgres FKs (so+ child-before-parent inserts inside one transaction still pass), and carries no ON+ DELETE action - exactly like a Django FK, whose cascades are handled by the Python+ collector, not the database. This keeps it a true drop-in for the model's FK.++ This op tracks no Django model state: the relationship is expected to already be in+ state from a `ForeignKey(..., db_constraint=False)` on the model (whose CreateModel /+ AddField emitted no parent lock). The migration class needs `atomic = False` if this+ op shares a migration with `ValidateForeignKey`.++ Arguments:+ model_name: the child model (used to resolve its db_table and for state checks).+ name: the constraint name. Must match what you pass to `ValidateForeignKey`.+ column: the child FK column, e.g. `"team_id"`.+ to_table: the referenced parent table, e.g. `"posthog_team"`.+ to_column: the referenced parent column. Defaults to `"id"`.+ """++ reversible = True++ def __init__(+ self,+ model_name: str,+ name: str,+ column: str,+ to_table: str,+ to_column: str = "id",+ ) -> None:+ self.model_name = model_name+ self.name = name+ self.column = column+ self.to_table = to_table+ self.to_column = to_column++ def state_forwards(self, app_label, state) -> None:+ pass # the relationship is already tracked by the model's db_constraint=False FK++ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:+ model = to_state.apps.get_model(app_label, self.model_name)+ if not self.allow_migrate_model(schema_editor.connection.alias, model):+ return+ # No timeout disabling here: ADD CONSTRAINT ... NOT VALID is a brief metadata-only+ # ALTER (no child-row scan), so it should keep the default lock_timeout and fail+ # fast on contention rather than queue the SHARE ROW EXCLUSIVE lock behind in-flight+ # writes on the parent. A bin/migrate retry re-attempts once the lock is free.+ if _constraint_validity(schema_editor, model._meta.db_table, self.name) is not None:+ return # already added; a bin/migrate retry is a no-op+ table = schema_editor.quote_name(model._meta.db_table)+ name = schema_editor.quote_name(self.name)+ column = schema_editor.quote_name(self.column)+ to_table = schema_editor.quote_name(self.to_table)+ to_column = schema_editor.quote_name(self.to_column)+ # DEFERRABLE INITIALLY DEFERRED on Postgres - matches what Django emits for a FK,+ # so this stays a drop-in (deferred constraint checks survive child-before-parent+ # inserts within a transaction).+ deferrable = schema_editor.connection.ops.deferrable_sql()+ schema_editor.execute(+ f"ALTER TABLE {table} ADD CONSTRAINT {name} "+ f"FOREIGN KEY ({column}) REFERENCES {to_table} ({to_column}){deferrable} NOT VALID"+ )++ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:+ model = from_state.apps.get_model(app_label, self.model_name)+ if not self.allow_migrate_model(schema_editor.connection.alias, model):+ return+ table = schema_editor.quote_name(model._meta.db_table)+ name = schema_editor.quote_name(self.name)+ schema_editor.execute(f"ALTER TABLE {table} DROP CONSTRAINT IF EXISTS {name}")++ def deconstruct(self) -> tuple[str, list[object], dict[str, str]]:+ kwargs = {+ "model_name": self.model_name,+ "name": self.name,+ "column": self.column,+ "to_table": self.to_table,+ "to_column": self.to_column,+ }+ return (self.__class__.__qualname__, [], kwargs)++ def describe(self) -> str:+ return f"Add FOREIGN KEY constraint {self.name} on {self.model_name} (NOT VALID)"++ @property+ def migration_name_fragment(self) -> str:+ return f"add_fk_{self.name}"diff --git a/posthog/migration_helpers/test_not_valid_foreign_key.py b/posthog/migration_helpers/test_not_valid_foreign_key.pynew file mode 100644index 000000000000..a9171a830921--- /dev/null+++ b/posthog/migration_helpers/test_not_valid_foreign_key.py@@ -0,0 +1,250 @@+import uuid++import pytest++from django.db import connection, models, transaction+from django.db.migrations.state import ModelState, ProjectState+from django.db.utils import IntegrityError++from posthog.migration_helpers import AddForeignKeyNotValid, ValidateForeignKey++MODEL_NAME = "TmpFkModel"+++def temp_tables():+ # A one-off child + parent table plus a ProjectState model pointing at the child.+ suffix = uuid.uuid4().hex[:8]+ parent = f"test_fk_parent_{suffix}"+ child = f"test_fk_child_{suffix}"+ with connection.cursor() as cursor:+ cursor.execute(f'CREATE TABLE "{parent}" (id serial primary key)')+ cursor.execute(f'CREATE TABLE "{child}" (id serial primary key, parent_id int)')+ state = ProjectState()+ state.add_model(+ ModelState(+ app_label="posthog",+ name=MODEL_NAME,+ fields=[+ ("id", models.AutoField(primary_key=True)),+ ("parent_id", models.IntegerField(null=True)),+ ],+ options={"db_table": child},+ )+ )+ try:+ yield child, parent, state+ finally:+ with connection.cursor() as cursor:+ cursor.execute(f'DROP TABLE IF EXISTS "{child}"')+ cursor.execute(f'DROP TABLE IF EXISTS "{parent}"')+++def _add_op(name, parent):+ return AddForeignKeyNotValid(+ model_name=MODEL_NAME,+ name=name,+ column="parent_id",+ to_table=parent,+ to_column="id",+ )+++def _apply_forwards(op, state):+ schema_editor = connection.schema_editor(atomic=False)+ schema_editor.__enter__()+ try:+ op.database_forwards("posthog", schema_editor, from_state=state, to_state=state)+ finally:+ schema_editor.__exit__(None, None, None)+++def _apply_backwards(op, state):+ schema_editor = connection.schema_editor(atomic=False)+ schema_editor.__enter__()+ try:+ op.database_backwards("posthog", schema_editor, from_state=state, to_state=state)+ finally:+ schema_editor.__exit__(None, None, None)+++def _convalidated(constraint_name):+ # None if the constraint is absent, else its convalidated flag.+ with connection.cursor() as cursor:+ cursor.execute("SELECT convalidated FROM pg_constraint WHERE conname = %s", [constraint_name])+ row = cursor.fetchone()+ return None if row is None else bool(row[0])+++def _insert_parent(parent):+ with connection.cursor() as cursor:+ cursor.execute(f'INSERT INTO "{parent}" DEFAULT VALUES RETURNING id')+ return cursor.fetchone()[0]+++def _insert_child(child, parent_id):+ with connection.cursor() as cursor:+ cursor.execute(f'INSERT INTO "{child}" (parent_id) VALUES (%s)', [parent_id])++[email protected]_db(transaction=True)+def test_add_foreign_key_not_valid_creates_unvalidated_constraint(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"++ _apply_forwards(_add_op(name, parent), state)++ assert _convalidated(name) is False # present but not validated++[email protected]_db(transaction=True)+def test_add_foreign_key_not_valid_skips_existing_rows_but_enforces_new_rows(temp_tables):+ # The point of NOT VALID: a pre-existing orphan child row is tolerated, new ones aren't.+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ _insert_child(child, 999) # pre-existing orphan (no matching parent)++ _apply_forwards(_add_op(name, parent), state) # succeeds despite the orphan (no scan)++ with pytest.raises(IntegrityError):+ _insert_child(child, 888) # new orphan is rejected++[email protected]_db(transaction=True)+def test_add_foreign_key_not_valid_is_deferrable(temp_tables):+ # DEFERRABLE INITIALLY DEFERRED: a child can be inserted before its parent within one+ # transaction, with the FK checked at commit - matching Django's FK semantics. Without+ # deferrability the child insert would raise immediately.+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ _apply_forwards(_add_op(name, parent), state)++ with transaction.atomic(), connection.cursor() as cursor:+ cursor.execute(f'INSERT INTO "{child}" (parent_id) VALUES (4242)') # parent 4242 not inserted yet+ cursor.execute(f'INSERT INTO "{parent}" (id) VALUES (4242)') # added before commit++ assert _convalidated(name) is False # commit succeeded; the deferred check passed++[email protected]_db(transaction=True)+def test_add_foreign_key_not_valid_is_idempotent(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ op = _add_op(name, parent)++ _apply_forwards(op, state)+ _apply_forwards(op, state)++ assert _convalidated(name) is False++[email protected]_db(transaction=True)+def test_add_foreign_key_not_valid_reverse_drops(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ op = _add_op(name, parent)++ _apply_forwards(op, state)+ assert _convalidated(name) is False++ _apply_backwards(op, state)+ assert _convalidated(name) is None++ _apply_backwards(op, state) # idempotent: DROP CONSTRAINT IF EXISTS+ assert _convalidated(name) is None++[email protected]_db(transaction=True)+def test_validate_foreign_key_marks_constraint_valid(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ pid = _insert_parent(parent)+ _insert_child(child, pid) # clean data+ _apply_forwards(_add_op(name, parent), state)+ assert _convalidated(name) is False++ _apply_forwards(ValidateForeignKey(model_name=MODEL_NAME, name=name), state)++ assert _convalidated(name) is True++[email protected]_db(transaction=True)+def test_validate_foreign_key_is_idempotent(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ _apply_forwards(_add_op(name, parent), state)+ validate = ValidateForeignKey(model_name=MODEL_NAME, name=name)++ _apply_forwards(validate, state)+ _apply_forwards(validate, state) # already validated -> skipped++ assert _convalidated(name) is True++[email protected]_db(transaction=True)+def test_validate_foreign_key_fails_on_existing_violation(temp_tables):+ child, parent, state = temp_tables+ name = f"{child}_parent_fk"+ _insert_child(child, 999) # existing orphan+ _apply_forwards(_add_op(name, parent), state)++ with pytest.raises(IntegrityError):+ _apply_forwards(ValidateForeignKey(model_name=MODEL_NAME, name=name), state)++ assert _convalidated(name) is False # stays unvalidated, can retry after cleanup+++def _collected_forward_sql(op, child):+ # collect_sql records statements instead of running them; the constraint is+ # absent, so the validity probe returns None and the op proceeds to emit DDL.+ state = ProjectState()+ state.add_model(+ ModelState(+ app_label="posthog",+ name=MODEL_NAME,+ fields=[("id", models.AutoField(primary_key=True)), ("parent_id", models.IntegerField(null=True))],+ options={"db_table": child},+ )+ )+ schema_editor = connection.schema_editor(atomic=False, collect_sql=True)+ schema_editor.__enter__()+ try:+ op.database_forwards("posthog", schema_editor, from_state=state, to_state=state)+ finally:+ schema_editor.__exit__(None, None, None)+ return "\n".join(schema_editor.collected_sql)+++def test_add_foreign_key_not_valid_keeps_lock_timeout():+ # ADD CONSTRAINT ... NOT VALID takes a brief SHARE ROW EXCLUSIVE lock on the parent, so it+ # must keep the default lock_timeout and fail fast on contention rather than queue the lock+ # behind in-flight writes on the parent.+ op = AddForeignKeyNotValid(model_name=MODEL_NAME, name="tfk", column="parent_id", to_table="some_parent")+ collected = _collected_forward_sql(op, "test_fk_child_collect")++ assert "SET lock_timeout = 0" not in collected+ assert "SET statement_timeout = 0" not in collected+ assert "ADD CONSTRAINT" in collected.upper()+ assert "NOT VALID" in collected.upper()+ assert "DEFERRABLE INITIALLY DEFERRED" in collected.upper() # matches Django's FK DDL+ assert "ON DELETE" not in collected.upper() # Django handles cascade in Python, not the DB+++def test_deconstruct_round_trips():+ op = AddForeignKeyNotValid(model_name=MODEL_NAME, name="tfk", column="parent_id", to_table="some_parent")+ name, args, kwargs = op.deconstruct()++ assert name == "AddForeignKeyNotValid"+ assert args == []+ rebuilt = AddForeignKeyNotValid(**kwargs)+ assert rebuilt.deconstruct() == op.deconstruct()+++def test_validate_foreign_key_deconstructs_under_own_name():+ # A subclass, not an alias - so a squash round-trips it as ValidateForeignKey.+ op = ValidateForeignKey(model_name=MODEL_NAME, name="tfk")+ name, args, kwargs = op.deconstruct()++ assert name == "ValidateForeignKey"+ assert ValidateForeignKey(**kwargs).deconstruct() == op.deconstruct()diff --git a/products/README.md b/products/README.mdindex f739b39bbbb1..6f52339c8cfb 100644--- a/products/README.md+++ b/products/README.md@@ -192,6 +192,7 @@ The lint command validates:- Create or move your backend models under the product's `backend/` folder.- Use direct imports from the product location (e.g., `from products.experiments.backend.models import Experiment`)- Use string-based foreign key references to avoid circular imports (e.g., `models.ForeignKey("posthog.Team", on_delete=models.CASCADE)`)+ - A `ForeignKey` **targeting a hot table** (`posthog.Team`, `posthog.User`, `posthog.Organization`, `posthog.Project`, including `settings.AUTH_USER_MODEL`) is unsafe even within the same database, and even for a brand-new `CreateModel`: building the FK constraint takes a `SHARE ROW EXCLUSIVE` lock on the _referenced parent_ table, which can stall a deploy under write traffic. `HotTableAlterPolicy` blocks this in CI. Either declare the FK with `db_constraint=False` (no parent lock at all, app-level enforcement only) or add it as a real constraint with the two-phase `AddForeignKeyNotValid` / `ValidateForeignKey` helpers. See [Foreign Keys to Hot Tables](https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#foreign-keys-to-hot-tables). (This is a different problem from the cross-database FK limitation below — that one is about FKs _across separate product databases_.)- Create a `products/your_product_name/backend/migrations` folder.- Run `python manage.py makemigrations your_product_name -n initial_migration`- If this is a brand-new model, you're done.