: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): stop table drops killing live reads (#100779)
posthog[bot]facffe8a1300
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex 801b5ab77b5d..faa0c14781f6 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -27,8 +27,8 @@ 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 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. `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. Leave `lock_timeout` alone, and never set it to 0 here: migrations already run with one, and the drop should fail fast and let `bin/migrate` retry rather than queue that lock. See [hot table hazard](#hot-table-hazard).+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).`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,6 +101,7 @@ 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.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 52175b5531ab..ffb362e02bdc 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -164,14 +164,36 @@ 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. Never `SET lock_timeout = 0` on a drop that reaches a hot parent: the point is to fail fast and let `bin/migrate` retry rather than queue that lock, because queries arriving while the request queues wait behind it. Migrations already run under `MIGRATE_LOCK_TIMEOUT` (`posthog/settings/data_stores.py`), which is 20 seconds by default. That is long enough that a drop reaching a hot parent still queues a 20-second `ACCESS EXCLUSIVE` request, so set a shorter `SET LOCAL lock_timeout` for that case-- If you must drop it, use `RunSQL` with raw SQL (see example below)+- Drop it with `SafeDropTable` from `posthog.migration_helpers`, not with a hand-written `RunSQL`. See [the lock order hazard](#drop-table-lock-order) below for what it protects against- 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+### 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.++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.++`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.++```python+from posthog.migration_helpers import SafeDropTable+++class Migration(migrations.Migration):+ operations = [+ SafeDropTable(["posthog_oldfeature", "posthog_oldfeaturerun"]),+ ]+```++Pass every table of one retirement to a single operation. They are locked and dropped together, so a key between two of them needs no ordering at the call site. The operation is idempotent, so a `bin/migrate` retry is free, and it tracks no Django state, so step 1 above is still required.++Never `SET lock_timeout = 0` on a drop that reaches a hot parent. Migrations already run under `MIGRATE_LOCK_TIMEOUT` (`posthog/settings/data_stores.py`), which is 20 seconds by default, and that is long enough that a raw drop still queues a 20-second `ACCESS EXCLUSIVE` request with every later query behind it.+**Important notes:**- Drop operations are irreversible - once data is deleted, it's gone and any rollback will fail without the table-- Use `RunSQL(DROP TABLE IF EXISTS)` for explicit control and idempotency+- A retry after a lost lock race runs the drop again, because the lock phase failed before the drop. `DROP TABLE IF EXISTS` makes a retry a no-op only after the drop completed+- A partitioned table, or a table in an inheritance hierarchy, is refused with an error rather than dropped. The lock list covers the named tables and their foreign-key parents, and the members of the hierarchy never enter it. Retire one of those with a migration that locks the hierarchy itself### Example@@ -207,10 +229,7 @@ class Migration(migrations.Migration):dependencies = []operations = [- migrations.RunSQL(- sql="DROP TABLE IF EXISTS posthog_oldfeature",- reverse_sql=migrations.RunSQL.noop,- ),+ SafeDropTable("posthog_oldfeature"),]```@@ -227,7 +246,7 @@ Removing a product (`products/<name>/`) is the phased table drop above — onceSafe order:-1. Strip all usage and the model classes, and drop the tables via the [phased approach](#dropping-tables) (state-only `DeleteModel`, wait a deploy cycle, then `DROP TABLE`). Keep the app in `INSTALLED_APPS` so its migrations still run.+1. Strip all usage and the model classes, and drop the tables via the [phased approach](#dropping-tables) (state-only `DeleteModel`, wait a deploy cycle, then `SafeDropTable`). Keep the app in `INSTALLED_APPS` so its migrations still run.2. Only after the drop migration has deployed everywhere, remove the app from `INSTALLED_APPS` and delete the `products/<name>/` folder.3. Optionally `DELETE FROM django_migrations WHERE app = '<app_label>'` to clear the orphan rows.diff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.pyindex 527605144a0e..797ab9914699 100644--- a/posthog/management/migration_analysis/analyzer.py+++ b/posthog/management/migration_analysis/analyzer.py@@ -27,6 +27,7 @@ from posthog.management.migration_analysis.operations import (RunPythonAnalyzer,RunSQLAnalyzer,SafeAddIndexConcurrentlyAnalyzer,+ SafeDropTableAnalyzer,SafeRemoveIndexConcurrentlyAnalyzer,SeparateDatabaseAndStateAnalyzer,ValidateConstraintAnalyzer,@@ -107,6 +108,7 @@ class RiskAnalyzer:"AddConstraintNotValid": AddConstraintNotValidAnalyzer(),"ValidateConstraint": ValidateConstraintAnalyzer(),"DropForeignKey": DropForeignKeyAnalyzer(),+ "SafeDropTable": SafeDropTableAnalyzer(),"SeparateDatabaseAndState": SeparateDatabaseAndStateAnalyzer(),# Postgres extension installs are safe under live load. Sharing one# ExtensionAnalyzer instance across the named operations keeps the@@ -280,8 +282,8 @@ class RiskAnalyzer:analyzer = self.ANALYZERS.get(op_type)if analyzer:- # Pass migration context to RunSQLAnalyzer for DROP TABLE validation- if op_type == "RunSQL" and hasattr(self, "migration") and hasattr(self, "loader"):+ # Pass migration context to the drop analyzers so they can check the staging+ if op_type in ("RunSQL", "SafeDropTable") and hasattr(self, "migration") and hasattr(self, "loader"):return analyzer.analyze(op, migration=self.migration, loader=self.loader) # type: ignore[call-arg]# Pass migration context to RenameModelAnalyzer for db_table checkif op_type == "RenameModel" and hasattr(self, "migration"):diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex d8e37e32ab57..5436c594ac41 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -713,14 +713,16 @@ Safe pattern requires:score=2,reason="DROP TABLE IF EXISTS - properly staged (prior state removal found)",details={"sql": sql, "table": table_name},- guidance=f"""✅ **Validated staged drop:** Found prior SeparateDatabaseAndState that removed model from state.+ guidance=f"""⚠️ **Staged, but hand-written:** Found prior SeparateDatabaseAndState that removed model from state, so the staging is valid. Drop the table with `SafeDropTable` from posthog.migration_helpers instead of this raw DROP.++A raw `DROP TABLE` takes ACCESS EXCLUSIVE on the dropped table and on every table its foreign keys reference, one relation at a time. That order crosses the order of a live multi-table read, and the deadlock detector kills the read rather than the migration. A short `lock_timeout` does not change which session Postgres picks. `SafeDropTable` takes all of the locks up front under a budget derived from `deadlock_timeout`, so the migration loses the race instead.Remaining checklist:- Ensure all code references removed (API, models, imports)- Waited at least one full deployment cycle since state removal- No other models reference this table via foreign keys-[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-tables)""",+[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#drop-table-lock-order)""",)# Not properly staged or can't validate@@ -1078,3 +1080,46 @@ class SeparateDatabaseAndStateAnalyzer(OperationAnalyzer):reason=f"Wrapper operation - see nested operations for risk: {', '.join(db_op_types)}",details={"database_operations": ", ".join(db_op_types)},)+++class SafeDropTableAnalyzer(OperationAnalyzer):+ """The drop-table helper that takes its locks up front (posthog/migration_helpers/safe_drop_table.py).++ Scores with the staged `DROP TABLE IF EXISTS` the RunSQL analyzer already recognizes,+ because it is the same drop. What it adds is lock ordering, so a live read is never+ the deadlock victim, not a weaker guarantee about the rows.+ """++ operation_type = "SafeDropTable"++ def analyze(self, op, migration=None, loader=None) -> OperationRisk:+ tables = [table.lower() for table in op.tables]+ staged = (+ migration+ and loader+ and all(check_drop_properly_staged("table", table, migration, loader) for table in tables)+ )+ if staged:+ return OperationRisk(+ type=self.operation_type,+ score=2,+ reason="SafeDropTable - properly staged (prior state removal found)",+ details={"tables": tables},+ guidance=f"""✅ **Validated staged drop:** Found prior SeparateDatabaseAndState that removed each model from state.++Remaining checklist is the one for any staged drop: all code references removed, one full deployment cycle waited since the state removal, and no other table referencing these.++[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-tables)""",+ )++ return OperationRisk(+ type=self.operation_type,+ score=5,+ reason="SafeDropTable - no prior state removal found",+ details={"tables": tables},+ guidance=f"""❌ **Missing state removal:** Could not find prior SeparateDatabaseAndState that removed this model.++SafeDropTable handles the lock order, not the staging. The model still has to leave Django state a full deployment cycle earlier, with a DropForeignKey for each key into a hot parent.++[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-tables)""",+ )diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex ed41763a8322..ae2bf45a4d26 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -21,6 +21,7 @@ from posthog.migration_helpers import (AddForeignKeyNotValid,DropForeignKey,SafeAddIndexConcurrently,+ SafeDropTable,SafeRemoveIndexConcurrently,ValidateConstraint,)@@ -563,6 +564,16 @@ class TestRunSQLOperations:assert risk.level == RiskLevel.SAFEassert "Unknown operation" not in risk.reason+ def test_safe_drop_table_helper_is_scored_like_the_raw_drop(self):+ # Without migration context the helper stays blocked, like a raw DROP TABLE.+ op = SafeDropTable("posthog_mymodel")++ risk = self.analyzer.analyze_operation(op)++ assert risk.score == 5+ assert risk.level == RiskLevel.BLOCKED+ assert "Unknown operation" not in risk.reason+def test_run_sql_drop_constraint(self):"""Test DROP CONSTRAINT - fast but needs deployment safety review (score 2)."""op = create_mock_operation(@@ -831,6 +842,9 @@ class TestDropTableValidation:# Should be NEEDS_REVIEW (score 2) since properly stagedassert migration_risk.level == RiskLevel.NEEDS_REVIEWassert migration_risk.max_score == 2+ # Staging is not the whole story: the raw form keeps the deadlock-prone lock order.+ guidance = migration_risk.operations[0].guidance+ assert guidance and "SafeDropTable" in guidancedef test_drop_table_resolves_deleted_model_with_custom_db_table(self):"""diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.pyindex d4a3a1f7ee78..b7190571bcad 100644--- a/posthog/migration_helpers/__init__.py+++ b/posthog/migration_helpers/__init__.py@@ -8,6 +8,7 @@ from posthog.migration_helpers.deprecate_field import deprecate_fieldfrom posthog.migration_helpers.drop_foreign_key import DropForeignKeyfrom posthog.migration_helpers.not_valid_constraint import AddConstraintNotValid, ValidateConstraintfrom posthog.migration_helpers.not_valid_foreign_key import AddForeignKeyNotValid, ValidateForeignKey+from posthog.migration_helpers.safe_drop_table import SafeDropTablefrom posthog.migration_helpers.untrack_field import untrack_field__all__ = [@@ -17,6 +18,7 @@ __all__ = ["DropForeignKey","DropIndexConcurrently","SafeAddIndexConcurrently",+ "SafeDropTable","SafeRemoveIndexConcurrently","ValidateConstraint","ValidateForeignKey",diff --git a/posthog/migration_helpers/safe_drop_table.py b/posthog/migration_helpers/safe_drop_table.pynew file mode 100644index 000000000000..0da66b1e8c24--- /dev/null+++ b/posthog/migration_helpers/safe_drop_table.py@@ -0,0 +1,167 @@+"""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.++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:++ from posthog.migration_helpers import SafeDropTable++ operations = [+ 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.++The operation is idempotent, so a bin/migrate retry is free. It tracks no Django state, so+the model still has to leave state a full deploy cycle earlier with+`SeparateDatabaseAndState` plus a `DropForeignKey` for each key into a hot parent.+`safe-django-migrations.md` ("Dropping Tables") has the phases and the full reasoning.+"""++from collections.abc import Sequence++from django.db import router+from django.db.migrations.operations.base import Operation++_EXISTING_TABLES_SQL = """+ SELECT relname+ FROM pg_class+ WHERE relname = ANY(%(tables)s)+ AND relkind = 'r'+ AND pg_table_is_visible(oid)+"""++_REFERENCED_TABLES_SQL = """+ SELECT DISTINCT tgt.relname+ 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 = ANY(%(tables)s)+ AND pg_table_is_visible(src.oid)+"""++_PARTITIONED_TABLES_SQL = """+ SELECT c.relname+ FROM pg_class c+ WHERE c.relname = ANY(%(tables)s)+ AND c.relkind IN ('r', 'p')+ AND pg_table_is_visible(c.oid)+ AND (+ c.relkind = 'p'+ OR EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = c.oid OR inhparent = c.oid)+ )+"""+++class SafeDropTable(Operation):+ """Drop one or more retired tables under a deterministic, time-boxed lock phase.++ Arguments:+ tables: one raw table name, or a list of them. Raw names rather than model names,+ because the models left Django's state in an earlier migration and no longer+ resolve. A single name rather than a list is accepted because one table is the+ common case. Django's migration writer maps a captured argument onto the+ parameter name, so this stays a named parameter and never becomes `*tables`.++ Pass every table of one retirement in a single operation. They are locked and dropped+ together, so a key between two of them needs no ordering at the call site.++ A partitioned table, and any table in an inheritance hierarchy, is refused rather than+ dropped. The lock list covers the named tables and their foreign-key parents, and a+ hierarchy needs its own members in the list as well.+ """++ # A no-op reverse would report success and leave the table gone.+ reversible = False+ reduces_to_sql = True++ def __init__(self, tables: str | Sequence[str]) -> None:+ names = [tables] if isinstance(tables, str) else list(tables)+ if not names:+ raise ValueError("SafeDropTable needs at least one table")+ self.tables = names++ def state_forwards(self, app_label, state) -> None:+ pass++ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:+ # Django traverses this migration on every alias, and a raw catalog query cannot+ # tell a routed product database from the main one.+ if not router.allow_migrate(schema_editor.connection.alias, app_label):+ return+ # SET LOCAL outside a transaction only warns, leaving the lock phase unbounded.+ if not schema_editor.connection.in_atomic_block:+ raise RuntimeError("SafeDropTable needs an atomic migration; remove `atomic = False`")++ # A partitioned root carries relkind 'p', so the existence query cannot see it and+ # the absent-table return below would report success for a table that is still+ # there. A partition's inheritance parent is not a foreign-key target either, so it+ # never enters the lock list and the drop takes ACCESS EXCLUSIVE on it while the+ # statement runs.+ hierarchies = sorted(self._query(schema_editor, _PARTITIONED_TABLES_SQL, self.tables))+ if hierarchies:+ raise RuntimeError(+ f"SafeDropTable cannot drop {', '.join(hierarchies)}: a partitioned or inherited table needs its"+ " whole hierarchy in the lock list, and this operation collects only the named tables and their"+ ' foreign-key parents. See safe-django-migrations.md ("Dropping Tables").'+ )++ present = sorted(self._query(schema_editor, _EXISTING_TABLES_SQL, self.tables))+ if not present:+ return+ referenced = self._query(schema_editor, _REFERENCED_TABLES_SQL, present)++ self._lock(schema_editor, sorted(set(present) | set(referenced)))+ schema_editor.execute(f"DROP TABLE IF EXISTS {self._quote(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")++ 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)++ @staticmethod+ def _query(schema_editor, sql: str, tables: list[str]) -> list[str]:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(sql, {"tables": tables})+ return [row[0] for row in cursor.fetchall()]diff --git a/posthog/migration_helpers/test_safe_drop_table.py b/posthog/migration_helpers/test_safe_drop_table.pynew file mode 100644index 000000000000..170b7538811b--- /dev/null+++ b/posthog/migration_helpers/test_safe_drop_table.py@@ -0,0 +1,187 @@+"""Functional tests for SafeDropTable.++Each test builds real tables with real Django-shaped foreign keys, so the catalog lookups+that decide the lock list run against the same pg_constraint and pg_inherits rows a+migration would see.+"""++import re+import uuid++import pytest++from django.db import connection+from django.db.migrations.writer import OperationWriter++from posthog.migration_helpers import SafeDropTable+++def temp_tables():+ suffix = uuid.uuid4().hex[:8]+ parent = f"test_safedrop_parent_{suffix}"+ child_a = f"test_safedrop_child_a_{suffix}"+ child_b = f"test_safedrop_child_b_{suffix}"+ with connection.cursor() as cursor:+ cursor.execute(f'CREATE TABLE "{parent}" (id serial primary key)')+ for child in (child_a, child_b):+ cursor.execute(+ f"""+ CREATE TABLE "{child}" (+ id serial primary key,+ owner_id int REFERENCES "{parent}"(id) DEFERRABLE INITIALLY DEFERRED+ )+ """+ )+ try:+ yield child_a, child_b, parent+ finally:+ with connection.cursor() as cursor:+ for table in (child_a, child_b, parent):+ cursor.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')+++def partitioned_tables():+ suffix = uuid.uuid4().hex[:8]+ root = f"test_safedrop_partitioned_{suffix}"+ leaf = f"{root}_default"+ with connection.cursor() as cursor:+ cursor.execute(+ f"""+ CREATE TABLE "{root}" (+ id serial,+ created_at timestamptz NOT NULL,+ PRIMARY KEY (id, created_at)+ ) PARTITION BY RANGE (created_at)+ """+ )+ cursor.execute(f'CREATE TABLE "{leaf}" PARTITION OF "{root}" DEFAULT')+ try:+ yield root, leaf+ finally:+ with connection.cursor() as cursor:+ cursor.execute(f'DROP TABLE IF EXISTS "{root}" CASCADE')+++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 None+++def _tables_exist(*tables):+ with connection.cursor() as cursor:+ cursor.execute("SELECT relname FROM pg_class WHERE relname = ANY(%s) AND relkind IN ('r', 'p')", [list(tables)])+ return {row[0] for row in cursor.fetchall()}+++def test_locks_the_referenced_parent_before_dropping(temp_tables):+ child_a, child_b, parent = temp_tables++ collected = _apply(collect=True, op=SafeDropTable([child_a, child_b]))++ lock = next(statement for statement in collected if "LOCK TABLE" in statement)+ drop = next(statement for statement in collected if "DROP TABLE" in statement)+ assert collected.index(lock) < collected.index(drop)+ for table in (child_a, child_b, parent):+ assert table in lock+++def test_the_lock_phase_gives_up_before_any_deadlock_detector_runs(temp_tables):+ child_a, _, _ = temp_tables+ with connection.cursor() as cursor:+ cursor.execute("SELECT setting::int FROM pg_settings WHERE name = 'deadlock_timeout'")+ deadlock_ms = cursor.fetchone()[0]++ collected = _apply(collect=True, op=SafeDropTable(child_a))++ budgets = [int(match) for match in re.findall(r"SET LOCAL \w+_timeout = '(\d+)ms'", "\n".join(collected))]+ assert len(budgets) == 2 # lock_timeout bounds one attempt, statement_timeout bounds them all+ assert all(0 < budget < deadlock_ms for budget in budgets)+++def test_restores_the_timeouts_the_transaction_came_in_with(temp_tables):+ # ValidateConstraint disables both timeouts for the rest of its transaction. Restoring+ # to DEFAULT rather than to the captured value would silently re-arm them.+ child_a, _, _ = temp_tables+ with connection.cursor() as cursor:+ cursor.execute("SELECT set_config('statement_timeout', '0', true)")+ cursor.execute("SELECT set_config('lock_timeout', '17s', true)")++ _apply(SafeDropTable(child_a))++ with connection.cursor() as cursor:+ cursor.execute("SELECT current_setting('lock_timeout'), current_setting('statement_timeout')")+ assert cursor.fetchone() == ("17s", "0")+++def test_drops_every_named_table(temp_tables):+ child_a, child_b, parent = temp_tables++ _apply(SafeDropTable([child_a, child_b]))++ assert _tables_exist(child_a, child_b, parent) == {parent}+++def test_a_second_run_is_a_no_op(temp_tables):+ child_a, child_b, _ = temp_tables+ op = SafeDropTable([child_a, child_b])++ _apply(op)+ _apply(op)++ assert _tables_exist(child_a, child_b) == set()++[email protected]("target", ["root", "leaf"])+def test_refuses_a_table_whose_hierarchy_the_lock_list_misses(partitioned_tables, target):+ # The root carries relkind 'p', so the existence query cannot see it and a silent return+ # would record the migration with the table still there. The leaf is an ordinary table,+ # but its inheritance parent is no foreign-key target, so nothing puts that parent in the+ # lock list and the drop takes ACCESS EXCLUSIVE on it while the statement runs.+ root, leaf = partitioned_tables++ with pytest.raises(RuntimeError, match="whole hierarchy in the lock list"):+ _apply(SafeDropTable(root if target == "root" else leaf))++ assert _tables_exist(root, leaf) == {root, leaf}+++def test_the_drop_cannot_be_reversed():+ op = SafeDropTable("test_safedrop_child")++ # Migration.unapply checks the flag and never reaches database_backwards.+ assert op.reversible is False+ with pytest.raises(NotImplementedError, match="irreversible"):+ op.database_backwards("posthog", None, None, None)+++def test_needs_a_table():+ with pytest.raises(ValueError, match="at least one table"):+ SafeDropTable([])++[email protected]("tables", ["test_safedrop_child", ["test_safedrop_child_a", "test_safedrop_child_b"]])+def test_the_migration_writer_can_rebuild_the_operation(tables):+ # squashmigrations renders every operation through this writer, and the writer maps each+ # captured argument onto a constructor parameter name. A `*tables` signature offers no+ # name, so it raises IndexError, and a deconstruct that only emits kwargs renders+ # SafeDropTable() with the tables silently gone.+ op = SafeDropTable(tables)++ rendered, _ = OperationWriter(op, indentation=0).serialize()++ assert f"tables={tables!r}" in rendered+ _, args, kwargs = op.deconstruct()+ assert SafeDropTable(*args, **kwargs).tables == op.tablesdiff --git a/posthog/migrations/1353_drop_retired_ducklake_tables.py b/posthog/migrations/1353_drop_retired_ducklake_tables.pyindex 37c18d9581e0..b22ac53aa3f8 100644--- a/posthog/migrations/1353_drop_retired_ducklake_tables.py+++ b/posthog/migrations/1353_drop_retired_ducklake_tables.py@@ -1,5 +1,7 @@from django.db import migrations+from posthog.migration_helpers import SafeDropTable+class Migration(migrations.Migration):"""Drop the ducklake tables 1242 left behind.@@ -18,9 +20,9 @@ class Migration(migrations.Migration):them. The tables have to go with the keys.DROP TABLE takes ACCESS EXCLUSIVE on every table these foreign keys reference, and two of- those are hot. The statement runs under a short lock_timeout so it fails fast and bin/migrate- retries, rather than queueing that lock for the whole MIGRATE_LOCK_TIMEOUT window while every- query arriving behind it waits.+ those are hot. SafeDropTable takes those locks up front in a fixed order, under a budget+ derived from the server's deadlock_timeout, so the migration gives up and bin/migrate retries+ rather than an application read being chosen as the deadlock victim."""dependencies = [@@ -28,11 +30,5 @@ class Migration(migrations.Migration):]operations = [- migrations.RunSQL(- sql="""- SET LOCAL lock_timeout = '2s';- DROP TABLE IF EXISTS posthog_ducklakecatalog, posthog_ducklakebackfill;- """,- reverse_sql=migrations.RunSQL.noop,- ),+ SafeDropTable(["posthog_ducklakecatalog", "posthog_ducklakebackfill"]),]diff --git a/products/tasks/backend/migrations/0124_drop_retired_code_home_tables.py b/products/tasks/backend/migrations/0124_drop_retired_code_home_tables.pyindex 922be00ff4ad..b7ce2eb2b872 100644--- a/products/tasks/backend/migrations/0124_drop_retired_code_home_tables.py+++ b/products/tasks/backend/migrations/0124_drop_retired_code_home_tables.py@@ -1,5 +1,7 @@from django.db import migrations+from posthog.migration_helpers import SafeDropTable+class Migration(migrations.Migration):"""Drop the Code Home tables 0069 left behind.@@ -18,9 +20,9 @@ class Migration(migrations.Migration):posthog/models/team/util.py is keyed on team_id and would never reach them.DROP TABLE takes ACCESS EXCLUSIVE on every table these foreign keys reference, and two of- those are hot. The statement runs under a short lock_timeout so it fails fast and bin/migrate- retries, rather than queueing that lock for the whole MIGRATE_LOCK_TIMEOUT window while every- query arriving behind it waits.+ those are hot. SafeDropTable takes those locks up front in a fixed order, under a budget+ derived from the server's deadlock_timeout, so the migration gives up and bin/migrate retries+ rather than an application read being chosen as the deadlock victim."""dependencies = [@@ -28,11 +30,5 @@ class Migration(migrations.Migration):]operations = [- migrations.RunSQL(- sql="""- SET LOCAL lock_timeout = '2s';- DROP TABLE IF EXISTS posthog_code_workstream, posthog_code_pr_snapshot, posthog_code_workflow_config;- """,- reverse_sql=migrations.RunSQL.noop,- ),+ SafeDropTable(["posthog_code_workstream", "posthog_code_pr_snapshot", "posthog_code_workflow_config"]),]