Skip to content

: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.

chore(migrations): require dropping hot-parent FKs when retiring a model (#97955)

Eli Reisman4f14b278a23e
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index a1e3c40ea57b..0eced4616c34 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -25,8 +25,11 @@ Adding migrations is fine. **Deleting a historical one — any `*/migrations/NNN
To retire a model/table:
1. Remove all usage and the model class. `makemigrations`, then wrap the generated `DeleteModel` in `migrations.SeparateDatabaseAndState(state_operations=[...])` (state only, no DB change). KEEP this file. Keep the app in `INSTALLED_APPS`.
+ **If the model has a `ForeignKey` to `posthog_team`, `posthog_user`, `posthog_organization` or `posthog_project`, drop that constraint 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. Optionally `DROP TABLE` later in a NEW `RunSQL` migration — never by deleting old files.
+3. `DROP TABLE` later in a NEW `RunSQL` 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, so a drop that still points at a hot parent must `SET LOCAL lock_timeout` to bound the wait. 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).
diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.md
index d29c5b89dc90..e876940e4083 100644
--- a/docs/published/handbook/engineering/safe-django-migrations.md
+++ b/docs/published/handbook/engineering/safe-django-migrations.md
@@ -130,11 +130,34 @@ class Migration(migrations.Migration):
migrations.DeleteModel(name='OldFeature'),
],
database_operations=[
- # If table has FKs to frequently-truncated tables (User, Team, Organization),
- # drop those FK constraints to avoid blocking TransactionTestCase teardown.
- # migrations.RunSQL(
- # sql="ALTER TABLE posthog_oldfeature DROP CONSTRAINT IF EXISTS posthog_oldfeature_team_id_fkey",
- # ),
+ # Required when the table has an FK to a hot parent (Team, User, Organization,
+ # Project). Django stops cascading into a table it cannot see, so the child rows
+ # outlive a parent delete. The constraint is DEFERRABLE INITIALLY DEFERRED, so the
+ # parent delete completes its cascade and then fails at COMMIT.
+ # Django names foreign keys with a hash suffix, so never hardcode the name with
+ # IF EXISTS: a wrong guess drops nothing and the migration still succeeds. Read the
+ # name from the catalog. The loop drops nothing on a re-run, so bin/migrate can
+ # retry the migration safely.
+ migrations.RunSQL(
+ sql="""
+ DO $$
+ DECLARE fk record;
+ BEGIN
+ FOR fk IN
+ SELECT con.conname
+ FROM pg_constraint con
+ JOIN pg_class src ON src.oid = con.conrelid
+ JOIN pg_class tgt ON tgt.oid = con.confrelid
+ WHERE con.contype = 'f'
+ AND src.relname = 'posthog_oldfeature'
+ AND tgt.relname = 'posthog_team'
+ LOOP
+ EXECUTE format('ALTER TABLE posthog_oldfeature DROP CONSTRAINT %I', fk.conname);
+ END LOOP;
+ END $$;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
],
),
]
@@ -142,12 +165,14 @@ class Migration(migrations.Migration):
5. Deploy this PR and verify no errors in production
+**Deleting a parent becomes impossible if you skip that constraint drop.** Once the model leaves Django's state, a `Team.objects.delete()` cascade no longer reaches the table, so its rows keep referencing the team. Because the constraint is deferred, Postgres raises the violation at `COMMIT`, after the whole cascade has run, and the delete can never succeed. Team and organization deletion stay broken for every tenant with rows in that table until someone drops it. Run `python manage.py audit_orphan_hot_table_fks` against a long-lived database to list tables already in this state; a squashed history leaves no trace of them in the migration files.
+
**Test infrastructure note:** If your table has foreign keys pointing TO frequently-truncated tables like `User`, `Team`, or `Organization`, you may see test failures like `cannot truncate a table referenced in a foreign key constraint`. This happens because:
- Django's `TransactionTestCase` uses `TRUNCATE` to clean up between tests
- PostgreSQL won't truncate a table that has FKs pointing to it
- Since the model is removed from Django's state, Django doesn't know to include it in the truncate list
-- Fix: Drop the FK constraints in `database_operations` (see commented example above) - you're dropping the table soon anyway
+- Fix: Drop the FK constraints in `database_operations` (see the example above) - required anyway, because leaving them breaks parent deletion
**Step 2: Wait for safety window**
@@ -159,6 +184,7 @@ class Migration(migrations.Migration):
- Safe to leave unused tables temporarily, but long-term they can clutter schema introspection and slow migrations
- Ensure no other models reference this table via foreign keys before dropping (Django won't cascade automatically)
+- `DROP TABLE` takes `ACCESS EXCLUSIVE` on every table its own foreign keys reference. If one of those is a hot parent, add `SET LOCAL lock_timeout` to bound the wait, because queries arriving while the lock request queues wait behind it
- If you must drop it, use `RunSQL` with raw SQL (see example below)
- In the PR description, reference the model removal PR (e.g., "Model removed in #12345, deployed X days ago") so reviewers can verify the safety window