: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(devex): fix the column retirement guidance and add DropForeignKey (#98147)
Julian Bezb178bec7be8d
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex 0eced4616c34..801b5ab77b5d 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -25,26 +25,30 @@ Adding migrations is fine. **Deleting a historical one — any `*/migrations/NNNTo 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.+ **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, 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).+ `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).`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).-## Retire a column in two phases+## Retire a column-Deleting the field and running `makemigrations` is not the first phase.-Django generates a plain `RemoveField`, which drops the column in the same deploy that removes the code.-Old pods still write to that column, and a rollback finds it gone.+**Default: don't drop it.** Take the field out of the ORM and leave the column. It keeps its data and needs no deploy coordination.-1. Remove all usage and the field from the model. `makemigrations`, then wrap the generated `RemoveField` in `migrations.SeparateDatabaseAndState(state_operations=[...], database_operations=[])`. The column stays in Postgres. Example: `posthog/migrations/1328_remove_userproductlist_reason_state.py`.-2. Deploy, wait at least one full deploy cycle, and confirm no deployed code reads the column.-3. Drop the column in a NEW `RunSQL` migration with `ALTER TABLE ... DROP COLUMN IF EXISTS`. Example: `posthog/migrations/1340_drop_userproductlist_reason_columns.py`.+Deleting the field and running `makemigrations` is not that. Django names every concrete field in every `SELECT` and `INSERT` it writes, so the generated `RemoveField` drops the column in the same deploy that stops the code asking for it, and every pod still on the old release fails its queries. A `# deprecated` comment does not help, because the field is still on the model.-`RemoveFieldAnalyzer` scores a bare `RemoveField` at 5, the highest risk the "Migration Risk Analysis" CI job reports.-The phase 2 drop scores low only when `check_drop_properly_staged` finds the phase 1 state removal in an ancestor migration, so the two phases must land in that order and never in one migration.+Two helpers in `posthog.migration_helpers` do it properly:++- `deprecate_field(models.IntegerField(null=True))` wraps the field in place. No migration. Reads and writes warn, and the column leaves every query. The field must already be `null=True`, because nothing writes the column once it is hidden. Use `raise_on_access=True` to prove no caller is left.+- `untrack_field("mymodel", "myfield")` replaces the generated `RemoveField` with a state-only migration, so the field leaves the model class and the column stays.++**A foreign key column must use `untrack_field` plus `DropForeignKey` in the same migration.** Once Django cannot see the field, a parent delete stops cascading into it, and the deferred constraint fails the delete at `COMMIT` forever after. `deprecate_field` cannot be used on a foreign key at all, because it writes no migration and so has nowhere to put the constraint drop.++Only drop the column after one of those has been deployed for a full deploy cycle, and drop it with `RunSQL ... DROP COLUMN IF EXISTS` in a migration that follows the state removal. Coming from `deprecate_field`, delete the wrapped line and replace the generated `RemoveField` with `untrack_field` first; both migrations can go in one PR. Never ship the plain `RemoveField` that `makemigrations` writes, because it removes state and drops the column in one operation and the analyzer cannot tell it from an unstaged drop.++Check non-ORM readers first (`nodejs/`, `rust/`, Temporal workers, Metabase). Hiding a field from Django says nothing about them.Full guide: `safe-django-migrations.md` (`## Dropping Columns`).@@ -96,6 +100,8 @@ Two things a callable does not do for you:- **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`.+- **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 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 e876940e4083..52175b5531ab 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -121,6 +121,9 @@ In one PR, remove the model and all code that references it:4. Wrap the generated migration in `SeparateDatabaseAndState` to only affect Django's state, not the database:```python+from posthog.migration_helpers import DropForeignKey++class Migration(migrations.Migration):dependencies = []@@ -134,30 +137,7 @@ class Migration(migrations.Migration):# 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,- ),+ DropForeignKey("posthog_oldfeature", to_table="posthog_team"),],),]@@ -184,7 +164,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+- `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)- 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@@ -257,47 +237,90 @@ Leaving the table in place — code gone, table dropped in a follow-up — is a**Problem:** `RemoveField` operations drop columns immediately. This breaks backwards compatibility during deployment and **cannot be rolled back** - once data is deleted, any rollback deployment will fail because the column no longer exists.-### Safe Approach+### Safe Approach: Retire the field, keep the column++**Strongly recommended:** don't drop the column. Take the field out of the ORM and stop there. An unused column costs almost nothing, keeps its data, and needs no deploy coordination.++Deleting the field and running `makemigrations` is **not** a way to do that. Django names every concrete field in every `SELECT` and `INSERT` it writes, whether or not any code reads it:++```text+SELECT "posthog_mymodel"."id", "posthog_mymodel"."name", "posthog_mymodel"."myfield" FROM ...+```++So `makemigrations` writes a plain `RemoveField`, which drops the column in the same deploy that stops the code asking for it. Marking the field deprecated in a comment does not help either, because the field is still on the model and the ORM still names it.++Two supported ways to actually take the field out of the ORM:++**`deprecate_field()` - keep the field on the model, write no migration.**++```python+from posthog.migration_helpers import deprecate_field++class MyModel(models.Model):+ myfield = deprecate_field(models.BooleanField(null=True, blank=True))+```++Reads and writes log a `DeprecationWarning` and the column leaves every query. Under `makemigrations` and `migrate` the real field comes back, so Django's migration state and the schema stay as they are. Pass `raise_on_access=True` to turn the warning into an error once you believe no caller is left.++The field must already be `null=True`, and the helper refuses it otherwise. Nothing writes the column once the field is hidden, so a `NOT NULL` column would reject every later insert. Make the field nullable in its own migration first, where a reviewer can see the `DROP NOT NULL` it takes.++**`untrack_field()` - take the field off the model now, in a state-only migration.**++```python+from posthog.migration_helpers import untrack_field++operations = [untrack_field("mymodel", "myfield")]+```-Use the same multi-phase pattern as [Dropping Tables](#dropping-tables).-Deleting the field and running `makemigrations` is **not** phase 1 on its own: Django generates a plain `RemoveField`, which drops the column in the same deploy that removes the code.+Delete the field from the model, run `makemigrations`, then replace the generated `RemoveField` operations with this. The column stays in Postgres.-**Phase 1: remove the field from Django state only.**-Delete every reference to the field and the field itself from the model, run `makemigrations`, then wrap the generated `RemoveField` in `SeparateDatabaseAndState`:+The field must already be `null=True` here too, and this helper cannot refuse it the way `deprecate_field()` does, because it takes field names rather than fields. Django stops naming the column in `INSERT`s as soon as the field leaves state, so a `NOT NULL` column with no database default rejects every insert the next release writes. Foreign key columns are usually `NOT NULL`, so check before you untrack one.++Pick `deprecate_field()` when you want no migration and don't mind a dead line on the model. Pick `untrack_field()` when you want the model clean and don't mind a migration file.++**If the column has a foreign key, dropping the constraint in the same migration is required, not optional.** Once the field leaves Django's state, a parent delete stops cascading into it, so the child rows outlive the parent. Django's foreign keys are `DEFERRABLE INITIALLY DEFERRED`, so Postgres checks at `COMMIT`, after the whole cascade has run, and raises. The delete can never succeed. This is the same failure that [Dropping Tables](#dropping-tables) describes, reached through a column instead of a table.```python-# 1328_remove_userproductlist_reason_state.py+from posthog.migration_helpers import DropForeignKey, untrack_field+operations = [- migrations.SeparateDatabaseAndState(- state_operations=[- migrations.RemoveField(model_name="userproductlist", name="reason"),- ],- database_operations=[],+ untrack_field(+ "mymodel",+ "owner",+ database_operations=[DropForeignKey("posthog_mymodel", column="owner_id")],),]```-The column stays in Postgres, so in-flight requests on the old release keep working and a rollback still finds it.-Deploy this, and verify no code references the field (application servers, workers, background jobs).+`DropForeignKey` reads the constraint name out of `pg_constraint`, so there is nothing to hardcode. Never hand-write `ALTER TABLE ... DROP CONSTRAINT IF EXISTS <name>`: Django names foreign keys with a hash suffix, and `IF EXISTS` turns a wrong guess into a migration that succeeds and drops nothing.++**`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`.-**Phase 2: drop the column, at least one full deployment cycle later.**+### If you must drop the column++Only after one of the above has been deployed for at least one full deploy cycle. That deployed release is what makes the drop safe: no running pod names the column any more, so nothing fails while the rollout finishes.++Both paths finish the same way. The column leaves Django's state through `untrack_field()`, then a following migration drops it with `RunSQL`:```python-# 1340_drop_userproductlist_reason_columns.pyoperations = [migrations.RunSQL(- sql='ALTER TABLE "posthog_userproductlist" DROP COLUMN IF EXISTS "reason";',- reverse_sql='ALTER TABLE "posthog_userproductlist" ADD COLUMN IF NOT EXISTS "reason" varchar(32) NULL;',+ sql='ALTER TABLE "posthog_mymodel" DROP COLUMN IF EXISTS "myfield";',+ reverse_sql='ALTER TABLE "posthog_mymodel" ADD COLUMN IF NOT EXISTS "myfield" varchar(32) NULL;',),]```+Coming from `deprecate_field()`, delete the wrapped line, run `makemigrations`, and replace the generated `RemoveField` with `untrack_field()` as above. Both migrations can go in one PR, because the analyzer follows migration dependencies and an ancestor in the same PR counts. Coming from `untrack_field()`, the state removal is already deployed, so only the `RunSQL` is left.++Never let `makemigrations` write the drop for you as a plain `RemoveField`. That operation removes the field from state and drops the column together, which is indistinguishable from dropping a column nobody staged, and the analyzer blocks it for that reason.+**Important notes:**- Dropping a column is irreversible - the data is permanently deleted. `reverse_sql` can re-add an empty column so the migration unapplies, but it cannot restore the values- `DROP COLUMN` takes an `ACCESS EXCLUSIVE` lock (briefly) - on a [hot table](#altering-hot-tables) schedule it for a low-traffic window-- The "Migration Risk Analysis" CI job scores a bare `RemoveField` at 5, its highest risk. Phase 2 scores low only when the analyzer finds the phase 1 state removal in an ancestor migration, so the two phases must land in that order-- Consider leaving unused columns indefinitely to avoid data loss risks+- Check for readers outside Django before dropping. `nodejs/`, `rust/`, Temporal workers, and Metabase queries do not go through the ORM, so hiding the field from Django tells you nothing about them+- The "Migration Risk Analysis" CI job scores a bare `RemoveField` at 5, its highest risk. A `RunSQL` drop scores low once the analyzer finds the state removal in an ancestor migration, which it checks on its own with no allowlist to maintain## Renaming Tablesdiff --git a/posthog/management/commands/analyze_migration_risk.py b/posthog/management/commands/analyze_migration_risk.pyindex c6e307bbc08f..00c7ee88f338 100644--- a/posthog/management/commands/analyze_migration_risk.py+++ b/posthog/management/commands/analyze_migration_risk.py@@ -7,7 +7,6 @@ from django.core.management.base import BaseCommandfrom django.db import migrationsfrom posthog.management.migration_analysis.analyzer import RiskAnalyzer-from posthog.management.migration_analysis.deprecated_field_filter import DeprecatedFieldFilterfrom posthog.management.migration_analysis.formatters import ConsoleTreeFormatter, JsonFormatterfrom posthog.management.migration_analysis.models import MigrationRisk, RiskLevel@@ -172,14 +171,8 @@ class Command(BaseCommand):# Exit code 1 means migrations neededoutput = stdout_capture.getvalue()if output.strip():- # Filter out deprecated field removals- filtered_output = DeprecatedFieldFilter.filter_output(output)-- if not filtered_output.strip():- return ""-# Prepend Summary for CI workflow, wrap Django's output in code block- return f"**Summary:** ⚠️ Missing migrations detected\n\n```\n{filtered_output}\n```\n\nRun `python manage.py makemigrations` to create them.\n"+ return f"**Summary:** ⚠️ Missing migrations detected\n\n```\n{output}\n```\n\nRun `python manage.py makemigrations` to create them.\n"return ""except Exception:# Ignore other errors (e.g., can't connect to DB)diff --git a/posthog/management/commands/test/test_analyze_migration_risk.py b/posthog/management/commands/test/test_analyze_migration_risk.pyindex 4589f61d550f..503cc1da58dc 100644--- a/posthog/management/commands/test/test_analyze_migration_risk.py+++ b/posthog/management/commands/test/test_analyze_migration_risk.py@@ -112,75 +112,3 @@ class TestAnalyzeMigrationRisk(TestCase):output = out.getvalue()assert output == ""-- def test_check_missing_migrations_filters_deprecated_fields(self):- """Should return empty string when only deprecated field removals are detected."""- from posthog.management.commands.analyze_migration_risk import Command-- command = Command()-- def mock_makemigrations(*args, **kwargs):- # Simulate Django detecting deprecated fields needing removal- import sys-- sys.stdout.write("Migrations for 'posthog':\n")- sys.stdout.write(" posthog/migrations/0886_remove_annotation_is_emoji_and_more.py\n")- sys.stdout.write(" - Remove field is_emoji from annotation\n")- sys.stdout.write(" - Remove field recording_id from annotation\n")- raise SystemExit(1)-- with patch("django.core.management.call_command", side_effect=mock_makemigrations):- result = command.check_missing_migrations()-- # Should return empty string because all operations are "Remove field"- assert result == ""-- def test_check_missing_migrations_does_not_filter_mixed_operations(self):- """Should filter out Remove field operations but keep others."""- from posthog.management.commands.analyze_migration_risk import Command-- command = Command()-- def mock_makemigrations(*args, **kwargs):- # Simulate mixed operations (removals + non-removals)- import sys-- sys.stdout.write("Migrations for 'posthog':\n")- sys.stdout.write(" posthog/migrations/0887_test.py\n")- sys.stdout.write(" - Remove field is_emoji from annotation\n")- sys.stdout.write(" - Add field new_field to testmodel\n")- raise SystemExit(1)-- with patch("django.core.management.call_command", side_effect=mock_makemigrations):- result = command.check_missing_migrations()-- # Should return warning with non-removal operations- assert "**Summary:** ⚠️ Missing migrations detected" in result- assert "Add field new_field to testmodel" in result- # Should NOT include the deprecated field removal- assert "Remove field is_emoji from annotation" not in result-- def test_check_missing_migrations_preserves_non_deprecated_removals(self):- """Should NOT filter out Remove field for non-deprecated fields (false negative check)."""- from posthog.management.commands.analyze_migration_risk import Command-- command = Command()-- def mock_makemigrations(*args, **kwargs):- # Simulate removal of a field that is NOT wrapped in deprecate_field()- import sys-- sys.stdout.write("Migrations for 'posthog':\n")- sys.stdout.write(" posthog/migrations/0887_test.py\n")- sys.stdout.write(" - Remove field is_emoji from annotation\n") # deprecated- sys.stdout.write(" - Remove field nonexistent_field from testmodel\n") # NOT deprecated!- raise SystemExit(1)-- with patch("django.core.management.call_command", side_effect=mock_makemigrations):- result = command.check_missing_migrations()-- # Should return warning for non-deprecated field removal- assert "**Summary:** ⚠️ Missing migrations detected" in result- assert "Remove field nonexistent_field from testmodel" in result- # Should NOT include deprecated field removal- assert "Remove field is_emoji from annotation" not in resultdiff --git a/posthog/management/commands/test/test_migrations_are_safe.py b/posthog/management/commands/test/test_migrations_are_safe.pydeleted file mode 100644index 4cfdce70dc56..000000000000--- a/posthog/management/commands/test/test_migrations_are_safe.py+++ /dev/null@@ -1,176 +0,0 @@-import re--from posthog.management.commands.test_migrations_are_safe import validate_migration_sql---def test_new_tables_must_not_have_int_32_ids() -> None:- sql_for_model_with_int32 = """-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" serial NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" serial NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;-"""- should_fail = validate_migration_sql(sql_for_model_with_int32)- assert should_fail is True---def test_new_tables_must_not_have_int64_ids() -> None:- sql_for_model_with_int64 = """-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" bigserial NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" bigserial NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;- """- should_fail = validate_migration_sql(sql_for_model_with_int64)- assert should_fail is True---def test_new_tables_can_have_uuid_ids() -> None:- sql_for_model_with_uuid = """-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" uuid NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;-BEGIN;------ Create model StrawMan----CREATE TABLE "posthog_strawman" ("id" uuid NOT NULL PRIMARY KEY, "name" varchar(400) NULL);-COMMIT;- """- should_fail = validate_migration_sql(sql_for_model_with_uuid)- assert should_fail is False---def test_unique_indexes_can_apply_only_to_not_null_values() -> None:- sql_for_unique_index_with_where = """-BEGIN;-CREATE UNIQUE INDEX CONCURRENTLY team_secret_api_token_unique_idx ON posthog_team (secret_api_token) WHERE secret_api_token IS NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_for_unique_index_with_where)- assert should_fail is False---def test_add_column_with_constant_string_default_is_safe() -> None:- sql_with_constant_string_default = """-BEGIN;------ Add field default_experiment_stats_method to organization----ALTER TABLE "posthog_organization" ADD COLUMN "default_experiment_stats_method" varchar(20) DEFAULT 'bayesian' NOT NULL;-ALTER TABLE "posthog_organization" ALTER COLUMN "default_experiment_stats_method" DROP DEFAULT;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_constant_string_default)- assert should_fail is False---def test_add_column_with_constant_number_default_is_safe() -> None:- sql_with_constant_number_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "max_items" integer DEFAULT 100 NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_constant_number_default)- assert should_fail is False---def test_add_column_with_constant_boolean_default_is_safe() -> None:- sql_with_constant_boolean_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "is_enabled" boolean DEFAULT TRUE NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_constant_boolean_default)- assert should_fail is False---def test_add_column_with_now_function_default_is_safe() -> None:- sql_with_now_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "created_at" timestamp DEFAULT NOW() NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_now_default)- assert should_fail is False---def test_add_column_with_volatile_function_default_is_unsafe() -> None:- sql_with_volatile_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "expires_at" timestamp DEFAULT NOW() + INTERVAL '1 day' NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_volatile_default)- assert should_fail is True---def test_add_column_with_no_default_not_null_is_unsafe() -> None:- sql_with_no_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "required_field" varchar(20) NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_no_default)- assert should_fail is True---def test_add_column_with_nullable_field_is_safe() -> None:- sql_with_nullable_field = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "optional_field" varchar(20) NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_nullable_field)- assert should_fail is False---def test_add_column_with_random_function_default_is_unsafe() -> None:- sql_with_random_default = """-BEGIN;-ALTER TABLE "posthog_organization" ADD COLUMN "random_value" float DEFAULT random() NOT NULL;-COMMIT;- """- should_fail = validate_migration_sql(sql_with_random_default)- assert should_fail is True---def test_migration_path_regex_handles_products_structure() -> None:- products_match = re.findall(- r"products/([a-z_]+)/backend/migrations/([a-zA-Z_0-9]+)\.py",- "products/tasks/backend/migrations/0006_remove_workflowstage_agent.py",- )- assert products_match == [("tasks", "0006_remove_workflowstage_agent")]-- products_match = re.findall(- r"products/([a-z_]+)/backend/migrations/([a-zA-Z_0-9]+)\.py",- "products/early_access_features/backend/migrations/0001_initial.py",- )- assert products_match == [("early_access_features", "0001_initial")]-- products_match = re.findall(- r"products/([a-z_]+)/backend/migrations/([a-zA-Z_0-9]+)\.py", "posthog/migrations/0770_something.py"- )- assert products_match == []-- posthog_match = re.findall(r"([a-z]+)\/migrations\/([a-zA-Z_0-9]+)\.py", "posthog/migrations/0770_something.py")- assert posthog_match == [("posthog", "0770_something")]diff --git a/posthog/management/commands/test_migrations_are_safe.py b/posthog/management/commands/test_migrations_are_safe.pydeleted file mode 100644index 85d4d2037139..000000000000--- a/posthog/management/commands/test_migrations_are_safe.py+++ /dev/null@@ -1,218 +0,0 @@-# ruff: noqa: T201 allow print statements--import os-import re-import sys-import select-from typing import Optional--from django.core.management import call_command-from django.core.management.base import BaseCommand, CommandError---def _get_new_tables(sql: str):- return re.findall(r'CREATE TABLE "([a-zA-Z0-9_]*)"', sql)---def _get_table(search_string: str, operation_sql: str) -> Optional[str]:- match = re.match(r'.*{} "([a-zA-Z0-9_]*)"'.format(search_string), operation_sql)- if match:- return match[1]- return None---def validate_migration_sql(sql) -> bool:- new_tables = _get_new_tables(sql)- operations = sql.split("\n")- tables_created_so_far: list[str] = []- for operation_sql in operations:- # Extract table name from queries of this format: ALTER TABLE "posthog_feature" or ALTER TABLE posthog_feature- table_being_altered: Optional[str] = None- if "ALTER TABLE" in operation_sql:- matches = re.findall(r'ALTER TABLE "?([a-z_]+)"?', operation_sql)- table_being_altered = matches[0] if matches else None- # Extract table name from queries of this format: CREATE TABLE "posthog_feature" or CREATE TABLE posthog_feature- if "CREATE TABLE" in operation_sql:- matches = re.findall(r'CREATE TABLE "?([a-z_]+)"?', operation_sql)- if matches:- table_name = matches[0]- tables_created_so_far.append(table_name)-- if '"id" serial' in operation_sql or '"id" bigserial' in operation_sql:- print(- f"\n\n\033[91mFound a new table with an integer id. Please use UUIDModel instead.\nSource: `{operation_sql}`"- )- return True-- if (- "ALTER TABLE" in operation_sql # Only check ALTER TABLE operations- and re.findall(r"(?<!DROP) (NOT NULL|DEFAULT .* NOT NULL)", operation_sql, re.M & re.I)- and "-- not-null-ignore" not in operation_sql- # Ignore for brand-new tables- and (table_being_altered not in tables_created_so_far or table_being_altered not in new_tables)- ):- # Check if this is adding/altering a column with a constant default (safe in PostgreSQL 11+)- if ("ADD COLUMN" in operation_sql and "DEFAULT" in operation_sql) or (- "ALTER COLUMN" in operation_sql and "SET DEFAULT" in operation_sql- ):- # Extract the default value to check if it's a constant- # Match DEFAULT followed by either a quoted string or unquoted value including typecast until NOT NULL or end of significant tokens- # regexr.com is your friend when trying to understand this regex- default_match = re.search(- r"DEFAULT\s+((?:'[^']*')|(?:[^'\s]+(?:\s+[^'\s]+)*?))(\s+|::\w+\s+)(?:NOT\s+NULL|;|$)",- operation_sql,- re.I,- )- if default_match:- default_value = default_match.group(1).strip()- # Check if it's a constant (string literal, number, boolean, or simple constant like NOW())- if (- (default_value.startswith("'") and default_value.endswith("'")) # String literal- or re.match(r"^-?\d+(\.\d+)?$", default_value) # Number- or default_value.upper() in ["TRUE", "FALSE", "NULL"] # Boolean/NULL- or default_value.upper()- in [- "NOW()",- "CURRENT_TIMESTAMP",- "CURRENT_DATE",- "CURRENT_TIME",- ] # Functions marked as stable in postgres- ):- # This is safe - adding/altering a column with a constant default- # doesn't require table rewrite in PostgreSQL 11+- continue-- print(- f"\n\n\033[91mFound a non-null field or default added to an existing model. This will lock up the table while migrating. Please add 'null=True, blank=True' to the field.\nSource: `{operation_sql}`"- )- return True-- if "RENAME" in operation_sql:- print(- f"\n\n\033[91mFound a RENAME command. This will lock up the table while migrating. Please create a new column and provide alternative method for swapping columns.\nSource: `{operation_sql}`"- )- return True-- if "DROP COLUMN" in operation_sql and "-- drop-column-ignore" not in operation_sql:- print(- f"\n\n\033[91mFound a DROP COLUMN command. This will lead to the app crashing while we roll out, and it will mean we can't roll back beyond this PR. Instead, please use the deprecate_field function: `from django_deprecate_fields import deprecate_field` and `your_field = deprecate_field(models.IntegerField(null=True, blank=True))`\nSource: `{operation_sql}`"- )- return True-- if "DROP TABLE" in operation_sql:- print(- f"\n\n\033[91mFound a DROP TABLE command. This could lead to unsafe states for the app. Please avoid dropping tables.\nSource: `{operation_sql}`"- )- return True- if (- " CONSTRAINT " in operation_sql- # Ignore constraints inside CREATE TABLE (new table is empty, nothing to validate)- and "CREATE TABLE" not in operation_sql- # Ignore for new foreign key columns that are nullable, as their foreign key constraint does not lock- and not re.search(r"ADD COLUMN .+ NULL CONSTRAINT", operation_sql)- and "-- existing-table-constraint-ignore" not in operation_sql- and " NOT VALID" not in operation_sql- # VALIDATE CONSTRAINT is a different, non-locking operation- and " VALIDATE CONSTRAINT " not in operation_sql- and " DROP CONSTRAINT " not in operation_sql- and (- table_being_altered not in tables_created_so_far- or _get_table("ALTER TABLE", operation_sql) not in new_tables # Ignore for brand-new tables- )- ):- print(- f"\n\n\033[91mFound a CONSTRAINT command without NOT VALID. This locks tables which causes downtime. "- "See https://github.com/PostHog/posthog/blob/master/docs/published/safe-django-migrations.md for guidance."- "If adding the constraint by itself, please use `AddConstraintNotValid()` of `django.contrib.postgres.operations` instead. "- "See https://docs.djangoproject.com/en/4.2/ref/contrib/postgres/operations/#adding-constraints-without-enforcing-validation.\n"- f"Source: `{operation_sql}`"- )- return True- if (- "CREATE INDEX" in operation_sql- and "CONCURRENTLY" not in operation_sql- and _get_table(" ON", operation_sql) not in new_tables- ):- print(- f"\n\n\033[91mFound a CREATE INDEX command that isn't run CONCURRENTLY. This locks tables which causes downtime. "- "Use a RunSQL `SET lock_timeout = 0; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...` wrapped in SeparateDatabaseAndState "- "(not AddIndexConcurrently, which is non-idempotent and blocked by ConcurrentIndexIdempotencyPolicy). "- "See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#adding-indexes\n"- f"Source: `{operation_sql}`"- )- return True-- # if it isn't already invalid, then the migration is valid- return False---class Command(BaseCommand):- help = "Automated test to make sure there are no non-null, dropping, renaming, or multiple migrations"-- def handle(self, *args, **options):- def run_and_check_migration(variable):- try:- # Handle both posthog/migrations and products/*/backend/migrations paths- # For products: products/product_name/backend/migrations/0001_initial.py -> (product_name, 0001_initial)- # For posthog: posthog/migrations/0001_initial.py -> (posthog, 0001_initial)- products_match = re.findall(r"products/([a-z_]+)/backend/migrations/([a-zA-Z_0-9]+)\.py", variable)- if products_match:- results = products_match[0]- else:- results = re.findall(r"([a-z]+)\/migrations\/([a-zA-Z_0-9]+)\.py", variable)[0]-- sql = call_command("sqlmigrate", results[0], results[1])- should_fail = validate_migration_sql(sql)- if should_fail:- sys.exit(1)-- except IndexError:- print(f"\n\n\033[93m⚠️ WARNING: Could not parse migration path: {variable.strip()}\033[0m")- print(- "Expected format: posthog/migrations/NNNN_name.py or products/name/backend/migrations/NNNN_name.py"- )- if os.getenv("CI"):- print("\033[91mFailing in CI due to unparseable migration path\033[0m")- sys.exit(1)- except CommandError as e:- print(f"\n\n\033[93m⚠️ WARNING: Failed to run sqlmigrate for {variable.strip()}\033[0m")- print(f"Error: {e}")- if os.getenv("CI"):- print("\033[91mFailing in CI due to sqlmigrate error\033[0m")- sys.exit(1)-- # Wait for stdin with 1 second timeout- if select.select([sys.stdin], [], [], 1)[0]:- migrations = sys.stdin.readlines()- else:- if os.getenv("CI"):- print("\n\n\033[91mNo migrations provided in CI - this is likely a mistake")- sys.exit(1)- print("No stdin detected, using default migrations - only useful for testing purposes.")- migrations = []-- if not migrations:- migrations = ["posthog/migrations/0771_teamrevenueanalyticsconfig_filter_test_accounts_and_more.py"]-- if len(migrations) > 1:- print(- f"\n\n\033[91mFound multiple migrations. Please scope PRs to one migration to promote easy debugging and revertability"- )- sys.exit(1)-- for data in migrations:- data = data.strip()- # Skip empty lines- if not data:- continue- # Validate file extension- if not data.endswith(".py"):- print(f"\033[93m⚠️ Skipping non-Python file: {data}\033[0m")- continue- # Prevent path traversal- if ".." in data or data.startswith("/"):- print(f"\033[91m⚠️ Skipping suspicious path: {data}\033[0m")- if os.getenv("CI"):- sys.exit(1)- continue- run_and_check_migration(data)diff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.pyindex d7e82bcb8b4c..527605144a0e 100644--- a/posthog/management/migration_analysis/analyzer.py+++ b/posthog/management/migration_analysis/analyzer.py@@ -16,6 +16,7 @@ from posthog.management.migration_analysis.operations import (CreateIndexConcurrentlyAnalyzer,CreateModelAnalyzer,DeleteModelAnalyzer,+ DropForeignKeyAnalyzer,DropIndexConcurrentlyAnalyzer,ExtensionAnalyzer,RemoveFieldAnalyzer,@@ -105,6 +106,7 @@ class RiskAnalyzer:"SafeRemoveIndexConcurrently": SafeRemoveIndexConcurrentlyAnalyzer(),"AddConstraintNotValid": AddConstraintNotValidAnalyzer(),"ValidateConstraint": ValidateConstraintAnalyzer(),+ "DropForeignKey": DropForeignKeyAnalyzer(),"SeparateDatabaseAndState": SeparateDatabaseAndStateAnalyzer(),# Postgres extension installs are safe under live load. Sharing one# ExtensionAnalyzer instance across the named operations keeps thediff --git a/posthog/management/migration_analysis/deprecated_field_filter.py b/posthog/management/migration_analysis/deprecated_field_filter.pydeleted file mode 100644index ed5df3cd7803..000000000000--- a/posthog/management/migration_analysis/deprecated_field_filter.py+++ /dev/null@@ -1,184 +0,0 @@-import re---class DeprecatedFieldFilter:- """- Filters 'Remove field' operations for fields wrapped in deprecate_field().-- Django-deprecate-fields hides deprecated fields from model introspection unless- a migration command ('makemigrations', 'migrate', 'showmigrations') is in sys.argv.- This causes false positives where deprecated fields appear as missing operations- in makemigrations output.-- This filter introspects only the models that have field removals, checking if- those specific fields are wrapped in deprecate_field(). Only deprecated field- removals are filtered out - real missing migrations are preserved.-- If django-deprecate-fields is not installed, filtering is skipped entirely.- """-- # Check if django-deprecate-fields is available- _deprecated_field_class = None- try:- from django_deprecate_fields import DeprecatedField-- _deprecated_field_class = DeprecatedField- except ImportError:- pass-- @staticmethod- def _collect_removal_models(lines: list[str]) -> set[str]:- """- Extract model names from 'Remove field' operations.-- Returns set of lowercase model names that have field removals.- """- removal_models = set()- for line in lines:- if match := re.match(r"\s*-\s*Remove field \w+ from (\w+)", line):- removal_models.add(match.group(1).lower())- return removal_models-- @staticmethod- def _get_deprecated_fields_for_models(model_names: set[str]) -> set[tuple[str, str]]:- """- Get deprecated fields for specific models only.-- Returns set of (model_name, field_name) tuples for fields that are instances- of DeprecatedField. Only checks models whose names are in model_names.- """- if DeprecatedFieldFilter._deprecated_field_class is None:- return set()-- from django.apps import apps-- deprecated_fields = set()- DeprecatedField = DeprecatedFieldFilter._deprecated_field_class-- for model in apps.get_models():- object_name = model._meta.object_name- if object_name is None:- continue- model_name = object_name.lower()- if model_name not in model_names:- continue # Skip models we don't care about-- # Check this model for DeprecatedField instances- for field_name, field_value in model.__dict__.items():- if isinstance(field_value, DeprecatedField):- deprecated_fields.add((model_name, field_name))-- return deprecated_fields-- @staticmethod- def _filter_lines(lines: list[str], deprecated_fields: set[tuple[str, str]]) -> str:- """- Filter lines, removing deprecated field removal operations.-- Preserves non-deprecated operations and removes app headers that have no- migrations after filtering.- """- result_lines = []- current_migration_file: str | None = None- current_migration_ops: list[str] = []-- def is_deprecated_removal(line: str) -> bool:- """Check if a 'Remove field' line is for a deprecated field."""- # Match: " - Remove field field_name from ModelName"- match = re.match(r"\s*-\s*Remove field (\w+) from (\w+)", line)- if not match:- return False-- field_name = match.group(1)- model_name = match.group(2).lower()-- # Check if this field is deprecated- return (model_name, field_name) in deprecated_fields-- def finalize_migration():- """Add current migration to results if it has non-deprecated operations."""- nonlocal current_migration_file, current_migration_ops- if current_migration_file is not None and current_migration_ops:- # Filter out operations that are deprecated field removals- kept_ops = [op for op in current_migration_ops if not is_deprecated_removal(op)]-- if kept_ops:- # Has non-deprecated operations - include migration- result_lines.append(current_migration_file)- result_lines.extend(kept_ops)-- current_migration_file = None- current_migration_ops = []-- for line in lines:- # Check if this is an app header (e.g., "Migrations for 'posthog':")- if line.startswith("Migrations for '"):- # Finalize previous migration- finalize_migration()- # Add app header (we'll remove it later if it has no migrations)- result_lines.append(line)-- # Check if this is a migration file line (e.g., " posthog/migrations/...")- elif line.strip() and line.startswith(" ") and "/" in line and ".py" in line:- # Finalize previous migration- finalize_migration()- # Start new migration- current_migration_file = line- current_migration_ops = []-- # Check if this is an operation line (e.g., " - Remove field ...")- elif line.strip().startswith("- "):- current_migration_ops.append(line)-- # Don't forget the last migration- finalize_migration()-- # Remove app headers that have no migrations following them- final_output = []- i = 0- while i < len(result_lines):- line = result_lines[i]- if line.startswith("Migrations for '"):- # Check if the next line is another app header or end of list- if i + 1 < len(result_lines) and not result_lines[i + 1].startswith("Migrations for '"):- # Has content, keep it- final_output.append(line)- # else: skip this app header- else:- final_output.append(line)- i += 1-- return "\n".join(final_output)-- @staticmethod- def filter_output(output: str) -> str:- """- Filter deprecated field removals from makemigrations output.-- Returns filtered output with deprecated field removals hidden, or empty string- if all operations were deprecated field removals.-- If django-deprecate-fields is not installed, returns output unchanged.- """- if DeprecatedFieldFilter._deprecated_field_class is None:- # Library not available, no filtering possible- return output-- lines = output.split("\n")-- # First pass: collect model names that have "Remove field" operations- removal_models = DeprecatedFieldFilter._collect_removal_models(lines)-- if not removal_models:- # No removals to filter, return as-is- return output-- # Only introspect models that have removals (performance optimization)- deprecated_fields = DeprecatedFieldFilter._get_deprecated_fields_for_models(removal_models)-- if not deprecated_fields:- # No deprecated fields found, return as-is- return output-- # Second pass: filter lines using deprecated fields set- return DeprecatedFieldFilter._filter_lines(lines, deprecated_fields)diff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex e9cf7b32567a..d8e37e32ab57 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -170,10 +170,15 @@ class RemoveFieldAnalyzer(OperationAnalyzer):score=5,reason="Dropping column breaks backwards compatibility and can't rollback",details={"model": op.model_name, "field": op.name},- guidance=f"""Use SeparateDatabaseAndState for multi-phase column drops:-1. Remove field from Django state (state_operations only, column stays in DB)-2. Wait at least one full deployment cycle-3. Drop the column with RunSQL: ALTER TABLE ... DROP COLUMN IF EXISTS+ guidance=f"""Django names every model field in every SELECT it writes, so this drops the column in the same deploy that stops the code asking for it. Pods still on the old release fail every query against the table.++Consider leaving the column in place. An unused column costs little and keeps its data.++To retire the field, take it out of the ORM first and leave the column:+- `deprecate_field(...)` from `posthog.migration_helpers` keeps the field on the model and writes no migration. Not for a foreign key: with no migration there is nowhere to drop the constraint+- `untrack_field(...)` from `posthog.migration_helpers` replaces this RemoveField with a state-only migration. A foreign key needs this one, with `DropForeignKey(...)` beside it++To drop the column for real, use `untrack_field(...)` here, then `RunSQL ... DROP COLUMN IF EXISTS` in a following migration. This analyzer validates that shape on its own.[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-columns)""",)@@ -978,6 +983,35 @@ class SafeRemoveIndexConcurrentlyAnalyzer(_SafeConcurrentIndexAnalyzer):operation_type = "SafeRemoveIndexConcurrently"+class DropForeignKeyAnalyzer(OperationAnalyzer):+ """The constraint drop that rides along with a state-only removal of a column or table.++ Dropping a foreign key is a catalog change. It holds ACCESS EXCLUSIVE on the referenced+ parent for microseconds and scans nothing, so it scores with `ADD CONSTRAINT ... NOT+ VALID` rather than with the operations that rewrite a table.+ """++ operation_type = "DropForeignKey"+ default_score = 1++ def analyze(self, op) -> OperationRisk:+ return OperationRisk(+ type=self.operation_type,+ score=1,+ reason="DROP CONSTRAINT on a foreign key is a catalog change (brief lock on the parent, no table scan)",+ details={+ "table": getattr(op, "table", None),+ "column": getattr(op, "column", None),+ "to_table": getattr(op, "to_table", None),+ },+ guidance=f"""Required beside a state-only removal of the column or table this foreign key sits on. Django stops cascading into a relation it cannot see, and the deferred constraint then fails the parent delete at COMMIT.++Irreversible. Add the constraint back with `AddForeignKeyNotValid` in a new migration rather than by unapplying this one.++[See the migration safety guide]({SAFE_MIGRATIONS_DOCS_URL}#dropping-columns)""",+ )++class AddConstraintNotValidAnalyzer(OperationAnalyzer):"""Phase 1 of the NOT VALID pattern - mirrors the score the RunSQL analyzergives a hand-written `ADD CONSTRAINT ... NOT VALID` (safe: brief lock, nodiff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 532113470135..570256fc6d19 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -16,6 +16,7 @@ from posthog.management.migration_analysis.utils import _model_name_for_tablefrom posthog.migration_helpers import (AddConstraintNotValid,AddForeignKeyNotValid,+ DropForeignKey,SafeAddIndexConcurrently,SafeRemoveIndexConcurrently,ValidateConstraint,@@ -550,6 +551,15 @@ class TestRunSQLOperations:assert risk.score == 2assert risk.level == RiskLevel.NEEDS_REVIEW+ def test_drop_foreign_key_helper_scores_safe(self):+ op = DropForeignKey("posthog_mymodel", column="owner_id")++ risk = self.analyzer.analyze_operation(op)++ assert risk.score == 1+ assert risk.level == RiskLevel.SAFE+ 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(@@ -1187,12 +1197,20 @@ class TestDropTableValidation:assert migration_risk.level == RiskLevel.BLOCKEDassert migration_risk.max_score == 5- def test_drop_column_with_prior_state_removal(self):+ @parameterized.expand(+ [+ ("scalar_column", "prompt", "prompt"),+ # A foreign key is where the two names disagree: state calls the field `owner`,+ # and the column Django made for it is `owner_id`.+ ("foreign_key_column", "owner", "owner_id"),+ ]+ )+ def test_drop_column_with_prior_state_removal(self, _name: str, state_field_name: str, column_name: str):"""Valid pattern: Prior migration removes field from state, then drop column.- Migration 0006: SeparateDatabaseAndState removes Evaluation.prompt- Migration 0007: ALTER TABLE ... DROP COLUMN IF EXISTS prompt+ Migration 0006: SeparateDatabaseAndState removes Evaluation.<field>+ Migration 0007: ALTER TABLE ... DROP COLUMN IF EXISTS <column>"""# Create mock migration graph with proper stagingmock_migration = MagicMock()@@ -1203,7 +1221,7 @@ class TestDropTableValidation:# Create the DROP COLUMN operationdrop_op = create_mock_operation(migrations.RunSQL,- sql="ALTER TABLE llm_analytics_evaluation DROP COLUMN IF EXISTS prompt;",+ sql=f"ALTER TABLE llm_analytics_evaluation DROP COLUMN IF EXISTS {column_name};",)mock_migration.operations = [drop_op]@@ -1212,7 +1230,7 @@ class TestDropTableValidation:parent_migration.app_label = "llm_analytics"parent_migration.name = "0006_remove_evaluation_prompt"- remove_field_op = create_mock_operation(migrations.RemoveField, model_name="Evaluation", name="prompt")+ remove_field_op = create_mock_operation(migrations.RemoveField, model_name="Evaluation", name=state_field_name)separate_op = create_mock_operation(migrations.SeparateDatabaseAndState,state_operations=[remove_field_op],diff --git a/posthog/management/migration_analysis/utils.py b/posthog/management/migration_analysis/utils.pyindex f3668f15d537..1d5dcd80abb2 100644--- a/posthog/management/migration_analysis/utils.py+++ b/posthog/management/migration_analysis/utils.py@@ -334,6 +334,17 @@ def _extract_model_name_from_table(table_name: str, app_label: Optional[str] = Nreturn model_name+def _field_owns_column(state_field_name: str, column_name: str) -> bool:+ """True when a field removed from Django state owns the column a later migration drops.++ A foreign key needs the suffix: state calls the field `owner`, and the column it owns is+ `owner_id`. Django refuses a second field named `owner_id` on a model that already has+ `owner`, so the suffix cannot match a different field by accident.+ """+ state_field_name = state_field_name.lower()+ return column_name.lower() in (state_field_name, f"{state_field_name}_id")++def _migration_removed_from_state(migration: Any, target_type: str, model_name: str, field_name: Optional[str] = None) -> bool:@@ -378,7 +389,7 @@ def _migration_removed_from_state(if (removed_model_name.lower() == model_name.lower()and field_name- and removed_field_name.lower() == field_name.lower()+ and _field_owns_column(removed_field_name, field_name)):return Truediff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.pyindex 20ea5e9de26b..d4a3a1f7ee78 100644--- a/posthog/migration_helpers/__init__.py+++ b/posthog/migration_helpers/__init__.py@@ -4,16 +4,22 @@ from posthog.migration_helpers.concurrent_index import (SafeAddIndexConcurrently,SafeRemoveIndexConcurrently,)+from posthog.migration_helpers.deprecate_field import deprecate_field+from 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.untrack_field import untrack_field__all__ = ["AddConstraintNotValid","AddForeignKeyNotValid","CreateIndexConcurrently",+ "DropForeignKey","DropIndexConcurrently","SafeAddIndexConcurrently","SafeRemoveIndexConcurrently","ValidateConstraint","ValidateForeignKey",+ "deprecate_field",+ "untrack_field",]diff --git a/posthog/migration_helpers/deprecate_field.py b/posthog/migration_helpers/deprecate_field.pynew file mode 100644index 000000000000..7a3c75455845--- /dev/null+++ b/posthog/migration_helpers/deprecate_field.py@@ -0,0 +1,108 @@+"""Take a retired field out of the ORM while its column stays in Postgres.++Vendored from django-deprecate-fields 0.2.3, Copyright 3YOURMIND GmbH, Apache License 2.0.+Upstream: https://github.com/3YOURMIND/django-deprecate-fields++Vendored so the list of migration commands below lives in this repo, where our own commands+can be added to it.+"""++import sys+import logging+import warnings++logger = logging.getLogger(__name__)++# Under these the real field must stay on the model, or makemigrations sees a field that is+# missing from model state and offers a RemoveField that would drop the column.+_MIGRATION_COMMANDS = frozenset(+ {+ "makemigrations",+ "migrate",+ "showmigrations",+ "sqlmigrate",+ "squashmigrations",+ "analyze_migration_risk",+ }+)+++class FieldDeprecatedError(Exception):+ pass+++def in_migration_context() -> bool:+ """True when this process runs a command that reads or writes Django migration state.++ Only the subcommand counts, which is sys.argv[1] for both manage.py and django-admin.+ Matching any argv token instead would let "pytest -k migrate" put every deprecated field+ back on its model for the whole run.+ """+ return len(sys.argv) > 1 and sys.argv[1] in _MIGRATION_COMMANDS+++class DeprecatedField:+ """Stands in for a field whose column is still in the database.++ Django names every concrete field in every SELECT and INSERT it writes. A plain+ descriptor is not a concrete field, so the column leaves all generated SQL while the+ column itself stays untouched. Use deprecate_field() instead of this class directly.+ """++ def __init__(self, raise_on_access: bool = False) -> None:+ self.raise_on_access = raise_on_access+ self.name = "<unknown>"++ def __set_name__(self, owner: type, name: str) -> None:+ # Django's ModelBase hands an attribute with no contribute_to_class straight to+ # type.__new__, which is what calls this.+ self.name = name++ def __get__(self, obj: object, objtype: type | None = None) -> object:+ if obj is None:+ return self+ self._report(f"accessing deprecated field {obj.__class__.__name__}.{self.name}")+ return None++ def __set__(self, obj: object, val: object) -> None:+ # The write is dropped on purpose: a descriptor is shared by every instance, so storing+ # the value here would leak it into every other row, and no column is left to hold it.+ self._report(f"writing to deprecated field {obj.__class__.__name__}.{self.name}")++ def _report(self, msg: str) -> None:+ if self.raise_on_access:+ raise FieldDeprecatedError(msg)+ warnings.warn(msg, DeprecationWarning, stacklevel=3)+ logger.warning(msg)+++def deprecate_field(field_instance: object, raise_on_access: bool = False) -> object:+ """Hide a field from the ORM without touching its column.++ This is phase 1 of a column retirement, and on its own it is a complete and safe end+ state: the column keeps its data and any release can be rolled back to. Wrap the field,+ deploy, and stop there unless the column has to go.++ To finish the drop, one full deploy cycle later, delete the wrapped line, run+ makemigrations, and replace the generated RemoveField with untrack_field(). A following+ migration drops the column with RunSQL. The risk analyzer validates that shape on its own,+ by finding the state removal among the drop migration's ancestors.++ The field must already be null=True. Nothing writes the column once the field is hidden,+ so a NOT NULL column would reject every later insert. Declaring the nullability in the+ model keeps the ALTER TABLE it needs visible in review and scored by the risk analyzer.++ Args:+ field_instance: The field to hide, written exactly as it is today, and null=True.+ raise_on_access: Raise FieldDeprecatedError instead of logging a warning. Use it to+ prove no caller is left before the column is dropped.+ """+ if getattr(field_instance, "null", False) is not True:+ raise FieldDeprecatedError(+ "deprecate_field() needs a field that is already null=True, because nothing writes "+ "the column once the field is hidden. Set null=True on the field in the model, let "+ "makemigrations write the AlterField, and wrap it after that lands."+ )+ if in_migration_context():+ return field_instance+ return DeprecatedField(raise_on_access=raise_on_access)diff --git a/posthog/migration_helpers/drop_foreign_key.py b/posthog/migration_helpers/drop_foreign_key.pynew file mode 100644index 000000000000..cb3c609677b4--- /dev/null+++ b/posthog/migration_helpers/drop_foreign_key.py@@ -0,0 +1,126 @@+"""Drop the FOREIGN KEY constraints a retired column or table still holds.++Retiring a model or a field with `SeparateDatabaseAndState` leaves the table or column in+Postgres, which is the point: old releases keep working. What it also leaves is every+foreign key that column carries, and Django can no longer see it. A parent delete stops+cascading into a relation it does not know about, so the child rows outlive the parent.+Django's foreign keys are DEFERRABLE INITIALLY DEFERRED, so Postgres does not complain+during the cascade; it checks at COMMIT, after the whole delete has run, and raises. The+delete can never succeed. Retiring a model whose table pointed at posthog_team this way+made team and organization deletion impossible until the table was dropped.++So the constraint has to go in the same migration that takes the column or table out of+Django's state:++ from posthog.migration_helpers import DropForeignKey, untrack_field++ operations = [+ untrack_field(+ "mymodel",+ "owner",+ database_operations=[DropForeignKey("posthog_mymodel", column="owner_id")],+ ),+ ]++For a whole table leaving state, name the parent instead of the column:++ migrations.SeparateDatabaseAndState(+ state_operations=[migrations.DeleteModel(name="OldFeature")],+ database_operations=[DropForeignKey("posthog_oldfeature", to_table="posthog_team")],+ )++Do not hand-write `ALTER TABLE ... DROP CONSTRAINT IF EXISTS <name>`. Django names foreign+keys with a hash suffix, so the name is not something you can derive at the call site, and+`IF EXISTS` turns a wrong guess into a migration that succeeds and drops nothing. This op+reads the names out of pg_constraint instead, which is also what makes it idempotent under+a bin/migrate retry.++The op is irreversible. Add the constraint back with `AddForeignKeyNotValid` in a new+migration rather than by unapplying this one.++The op deliberately does not touch lock_timeout, exactly like `AddForeignKeyNotValid`.+Dropping a foreign key takes ACCESS EXCLUSIVE on the referenced parent for a metadata-only+change held for microseconds, so it should fail fast on contention under whatever+lock_timeout the connection carries, rather than queue that lock and stall the parent.+Never disable the timeout here: on a hot parent an unbounded wait blocks every query that+arrives behind it. A bin/migrate retry re-attempts once the lock is free.+"""++from django.db import router+from django.db.migrations.operations.base import Operation++_CONSTRAINT_NAMES_SQL = """+ 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+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ANY(con.conkey)+ WHERE con.contype = 'f'+ AND src.relname = %(table)s+ AND pg_table_is_visible(src.oid)+ AND (%(to_table)s IS NULL OR tgt.relname = %(to_table)s)+ AND (%(column)s IS NULL OR att.attname = %(column)s)+"""+++class DropForeignKey(Operation):+ """Drop every FOREIGN KEY on `table` that matches the given filter.++ Tracks no Django state. Use it inside `database_operations` of the same+ `SeparateDatabaseAndState` that removes the field or model from state.++ Arguments:+ table: the child table holding the constraint, e.g. `"posthog_mymodel"`. A raw+ table name rather than a model name, because the model or field is leaving+ Django's state in this same migration and may no longer resolve.+ column: the child column, e.g. `"owner_id"`. Note the `_id` suffix Django gives+ foreign key columns.+ to_table: the referenced parent table, e.g. `"posthog_team"`.++ Pass `column`, `to_table`, or both. Passing neither would drop every foreign key on the+ table, which is never what a retirement means, so it raises instead.+ """++ # A dropped constraint cannot be put back: its definition is recorded nowhere this op can+ # read, and the arguments do not carry the column list or the referenced column. A no-op+ # reverse would report success while Django restored the field to model state with no+ # constraint behind it, which is the state-versus-schema drift this helper exists to stop.+ # Use AddForeignKeyNotValid to add the constraint back in a new migration instead.+ reversible = False+ reduces_to_sql = True++ def __init__(self, table: str, column: str | None = None, to_table: str | None = None) -> None:+ if column is None and to_table is None:+ raise ValueError("DropForeignKey needs a column, a to_table, or both")+ self.table = table+ self.column = column+ self.to_table = to_table++ def state_forwards(self, app_label, state) -> None:+ pass++ def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:+ # A product app in products/db_routing.yaml migrates on its own database. Django still+ # traverses this migration on the other aliases, and a raw catalog query cannot tell+ # them apart, so a same-named table elsewhere would lose its foreign key.+ if not router.allow_migrate(schema_editor.connection.alias, app_label):+ return+ for name in self._constraint_names(schema_editor):+ schema_editor.execute(+ f"ALTER TABLE {schema_editor.quote_name(self.table)} DROP CONSTRAINT {schema_editor.quote_name(name)}"+ )++ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:+ raise NotImplementedError("DropForeignKey is irreversible; add the constraint back with AddForeignKeyNotValid")++ def describe(self) -> str:+ target = self.column or f"-> {self.to_table}"+ return f"Drop foreign key on {self.table} ({target})"++ def _constraint_names(self, schema_editor) -> list[str]:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(+ _CONSTRAINT_NAMES_SQL,+ {"table": self.table, "to_table": self.to_table, "column": self.column},+ )+ return sorted({row[0] for row in cursor.fetchall()})diff --git a/posthog/migration_helpers/test_deprecate_field.py b/posthog/migration_helpers/test_deprecate_field.pynew file mode 100644index 000000000000..f44040de680e--- /dev/null+++ b/posthog/migration_helpers/test_deprecate_field.py@@ -0,0 +1,75 @@+"""Tests for the deprecate_field helper.++The helper decides what to return from sys.argv, because a model class body runs at import+time, before anything else can say what this process is about to do. That coupling is easy+to break by accident, so both directions are pinned here.+"""++import sys++import pytest+from unittest.mock import patch++from django.db import models++from parameterized import parameterized++from posthog.migration_helpers.deprecate_field import DeprecatedField, FieldDeprecatedError, deprecate_field+from posthog.models.personal_api_key import PersonalAPIKey++[email protected]([("makemigrations",), ("analyze_migration_risk",)])+def test_migration_commands_get_the_real_field(command: str) -> None:+ with patch.object(sys, "argv", ["manage.py", command]):+ field: models.CharField = models.CharField(max_length=8, null=True)++ assert deprecate_field(field) is field++[email protected]([("runserver",), ("shell",)])+def test_other_commands_get_a_descriptor(command: str) -> None:+ with patch.object(sys, "argv", ["manage.py", command]):+ assert isinstance(deprecate_field(models.CharField(max_length=8, null=True)), DeprecatedField)+++def test_a_migration_command_in_a_later_argument_does_not_count() -> None:+ with patch.object(sys, "argv", ["pytest", "-k", "migrate"]):+ assert isinstance(deprecate_field(models.CharField(max_length=8, null=True)), DeprecatedField)+++def test_a_non_nullable_field_is_refused() -> None:+ with pytest.raises(FieldDeprecatedError, match="null=True"):+ deprecate_field(models.CharField(max_length=8, null=False))+++class _Holder:+ field = DeprecatedField()+++class _StrictHolder:+ field = DeprecatedField(raise_on_access=True)+++def test_a_read_returns_none() -> None:+ with pytest.warns(DeprecationWarning, match="_Holder.field"):+ assert _Holder().field is None+++def test_a_write_is_dropped() -> None:+ holder = _Holder()++ with pytest.warns(DeprecationWarning, match="writing to deprecated field"):+ holder.field = "kept nowhere"++ with pytest.warns(DeprecationWarning):+ assert holder.field is None+++def test_raise_on_access_raises_instead_of_warning() -> None:+ with pytest.raises(FieldDeprecatedError, match="_StrictHolder.field"):+ _ = _StrictHolder().field+++def test_a_model_field_reports_its_own_name() -> None:+ with pytest.warns(DeprecationWarning, match="PersonalAPIKey.value"):+ assert PersonalAPIKey().value is Nonediff --git a/posthog/migration_helpers/test_drop_foreign_key.py b/posthog/migration_helpers/test_drop_foreign_key.pynew file mode 100644index 000000000000..bb9144e37934--- /dev/null+++ b/posthog/migration_helpers/test_drop_foreign_key.py@@ -0,0 +1,110 @@+"""Functional tests for DropForeignKey.++Each test builds a real parent/child pair with real Django-shaped foreign keys, so the+catalog lookup runs against the same pg_constraint rows a migration would see.+"""++import uuid++import pytest++from django.db import connection++from posthog.migration_helpers import DropForeignKey+++def temp_tables():+ suffix = uuid.uuid4().hex[:8]+ parent_a = f"test_dropfk_parent_a_{suffix}"+ parent_b = f"test_dropfk_parent_b_{suffix}"+ child = f"test_dropfk_child_{suffix}"+ with connection.cursor() as cursor:+ cursor.execute(f'CREATE TABLE "{parent_a}" (id serial primary key)')+ cursor.execute(f'CREATE TABLE "{parent_b}" (id serial primary key)')+ # Hash-suffixed names, the way Django writes them, so nothing here can be guessed.+ cursor.execute(+ f"""+ CREATE TABLE "{child}" (+ id serial primary key,+ owner_id int CONSTRAINT "{child}_owner_id_9a1bc3de_fk" REFERENCES "{parent_a}"(id)+ DEFERRABLE INITIALLY DEFERRED,+ other_id int CONSTRAINT "{child}_other_id_4f2ea8b1_fk" REFERENCES "{parent_b}"(id)+ DEFERRABLE INITIALLY DEFERRED+ )+ """+ )+ try:+ yield child, parent_a, parent_b+ finally:+ with connection.cursor() as cursor:+ for table in (child, parent_a, parent_b):+ cursor.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')+++def _apply(op):+ schema_editor = connection.schema_editor(atomic=False)+ schema_editor.__enter__()+ try:+ op.database_forwards("posthog", schema_editor, from_state=None, to_state=None)+ finally:+ schema_editor.__exit__(None, None, None)+++def _fk_columns(child):+ with connection.cursor() as cursor:+ cursor.execute(+ """+ SELECT att.attname+ FROM pg_constraint con+ JOIN pg_class src ON src.oid = con.conrelid+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ANY(con.conkey)+ WHERE con.contype = 'f' AND src.relname = %s+ """,+ [child],+ )+ return {row[0] for row in cursor.fetchall()}+++def test_drops_only_the_named_column(temp_tables):+ child, _, _ = temp_tables++ _apply(DropForeignKey(child, column="owner_id"))++ assert _fk_columns(child) == {"other_id"}+++def test_drops_only_the_named_parent(temp_tables):+ child, parent_a, _ = temp_tables++ _apply(DropForeignKey(child, to_table=parent_a))++ assert _fk_columns(child) == {"other_id"}+++def test_a_second_run_is_a_no_op(temp_tables):+ child, _, _ = temp_tables+ op = DropForeignKey(child, column="owner_id")++ _apply(op)+ _apply(op)++ assert _fk_columns(child) == {"other_id"}+++def test_the_drop_cannot_be_reversed():+ op = DropForeignKey("test_dropfk_child", column="owner_id")++ # Migration.unapply checks the flag first and never reaches database_backwards, so the+ # top-level path needs its own assertion.+ assert op.reversible is False+ with pytest.raises(NotImplementedError, match="AddForeignKeyNotValid"):+ op.database_backwards("posthog", None, None, None)+++def test_needs_a_column_or_a_parent():+ with pytest.raises(ValueError, match="column, a to_table"):+ DropForeignKey("test_dropfk_child")diff --git a/posthog/migration_helpers/test_untrack_field.py b/posthog/migration_helpers/test_untrack_field.pynew file mode 100644index 000000000000..af45c9eeacf1--- /dev/null+++ b/posthog/migration_helpers/test_untrack_field.py@@ -0,0 +1,43 @@+"""Tests for the untrack_field helper.++The database_operations pass-through is the one that carries weight: a DropForeignKey that+never reaches the migration leaves behind the orphaned constraint this helper exists to clear.+"""++import pytest++from django.db import migrations++from posthog.migration_helpers import DropForeignKey, untrack_field+++def test_every_field_leaves_model_state():+ operation = untrack_field("mymodel", "owner", "other")++ assert isinstance(operation, migrations.SeparateDatabaseAndState)+ removals = [op for op in operation.state_operations if isinstance(op, migrations.RemoveField)]++ assert len(removals) == len(operation.state_operations)+ assert [(op.model_name, op.name) for op in removals] == [+ ("mymodel", "owner"),+ ("mymodel", "other"),+ ]+++def test_the_database_operations_reach_the_migration():+ drop = DropForeignKey("posthog_mymodel", column="owner_id")++ operation = untrack_field("mymodel", "owner", database_operations=[drop])++ assert operation.database_operations == [drop]+++def test_the_column_stays_when_nothing_is_passed():+ operation = untrack_field("mymodel", "owner")++ assert operation.database_operations == []+++def test_no_field_names_is_refused():+ with pytest.raises(ValueError, match="at least one field name"):+ untrack_field("mymodel")diff --git a/posthog/migration_helpers/untrack_field.py b/posthog/migration_helpers/untrack_field.pynew file mode 100644index 000000000000..5ccfbc9c3047--- /dev/null+++ b/posthog/migration_helpers/untrack_field.py@@ -0,0 +1,45 @@+"""Take fields out of Django's model state and leave their columns in Postgres."""++from django.db import migrations+from django.db.migrations.operations.base import Operation+++def untrack_field(+ model_name: str,+ *field_names: str,+ database_operations: list[Operation] | None = None,+) -> migrations.SeparateDatabaseAndState:+ """Stop Django tracking one or more fields, without dropping their columns.++ This is phase 1 of a column retirement for a field you want off the model class now.+ Django names every concrete field in every SELECT and INSERT it writes, so the field has+ to leave model state in a deploy where the column still exists. Otherwise the release+ that drops the column is also the first release whose code stops asking for it, and+ every pod still on the old release fails every query against the table.++ Delete the field from the model, run makemigrations, then replace the generated+ RemoveField operations with this helper.++ Use deprecate_field() instead when you would rather keep the field on the model and+ write no migration at all.++ The field must already be null=True, for the same reason deprecate_field() refuses a+ field that is not. Django stops naming the column in INSERTs once the field leaves state,+ so a NOT NULL column with no database default rejects every insert the next release+ writes. This helper takes field names rather than fields, so it cannot check that for you.++ Args:+ model_name: The model the fields belong to, lowercase, as migrations spell it.+ field_names: One or more fields to take out of model state.+ database_operations: Operations to run alongside the state change. Pass+ DropForeignKey(...) when an untracked column carries a foreign key. That drop is+ required: Django stops cascading into a relation it cannot see, and the deferred+ constraint then fails the parent delete at COMMIT, permanently.+ """+ if not field_names:+ raise ValueError("untrack_field needs at least one field name")++ return migrations.SeparateDatabaseAndState(+ state_operations=[migrations.RemoveField(model_name=model_name, name=name) for name in field_names],+ database_operations=database_operations,+ )diff --git a/posthog/models/personal_api_key.py b/posthog/models/personal_api_key.pyindex 14353d0f7601..acce1ecf44b1 100644--- a/posthog/models/personal_api_key.py+++ b/posthog/models/personal_api_key.py@@ -6,9 +6,9 @@ from django.db import modelsfrom django.db.models import Q, QuerySetfrom django.utils import timezone-from django_deprecate_fields import deprecate_fieldfrom prometheus_client import Counter+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import EncryptionModeType, generate_random_token, hash_key_valuediff --git a/posthog/models/user.py b/posthog/models/user.pyindex 8c626c4f74eb..bb240a43c0fc 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -10,13 +10,13 @@ from django.db.models.signals import pre_savefrom django.dispatch import receiverfrom django.utils.translation import gettext_lazy as _-from django_deprecate_fields import deprecate_fieldfrom rest_framework.exceptions import ValidationErrorfrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import STRIPPED_EMAIL_EXPRESSION, EmailLookupHandler, EmailNormalizer+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.organization_notification_lock import GovernedSetting, effective_notification_settingsfrom posthog.settings import INSTANCE_TAG, SITE_URLdiff --git a/products/annotations/backend/models/annotation.py b/products/annotations/backend/models/annotation.pyindex bfd6f41590c4..258a9bc917a3 100644--- a/products/annotations/backend/models/annotation.py+++ b/products/annotations/backend/models/annotation.py@@ -3,8 +3,7 @@ from typing import Optionalfrom django.db import modelsfrom django.utils import timezone-from django_deprecate_fields import deprecate_field-+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixindiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 7834de626176..719f8170208f 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -11,7 +11,6 @@ from django.db import models, transactionfrom django.utils import timezoneimport structlog-from django_deprecate_fields import deprecate_fieldfrom rest_framework.exceptions import ValidationErrorfrom posthog.kafka_client.client import ClickhouseProducer@@ -19,6 +18,7 @@ from posthog.kafka_client.topics import (KAFKA_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE,KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT,)+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.event.util import format_clickhouse_timestampfrom posthog.models.integration import Integrationfrom posthog.models.scoping.root_mixin import TeamScopedRootMixin@@ -192,9 +192,9 @@ class ErrorTrackingExternalReference(UUIDTModel):)integration = models.ForeignKey(Integration, on_delete=models.CASCADE, related_name="+")# DEPRECATED: provider can be fetched through the integration model- provider = deprecate_field(models.TextField(null=False, blank=False))+ provider = deprecate_field(models.TextField(null=True, blank=False))# DEPRECATED: ids should be placed inside the external_context json field- external_id = deprecate_field(models.TextField(null=False, blank=False))+ external_id = deprecate_field(models.TextField(null=True, blank=False))external_context = models.JSONField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 991ba4a77657..f923e94e9b2f 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -10,9 +10,8 @@ from django.db.models.fields.json import KeyTransformfrom django.http import HttpRequestfrom django.utils import timezone-from django_deprecate_fields import deprecate_field-from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixindiff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.pyindex cd1b226bcfce..44bbbdf7e2dc 100644--- a/products/product_analytics/backend/models/insight.py+++ b/products/product_analytics/backend/models/insight.py@@ -7,11 +7,11 @@ from django.db.models import Q, QuerySetfrom django.utils import timezoneimport structlog-from django_deprecate_fields import deprecate_fieldfrom rest_framework.exceptions import ValidationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.logging.timing import timed+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentationdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 259faee65652..1c2487293e47 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -11,9 +11,9 @@ from django.utils import timezonefrom django.utils.functional import Promisefrom asgiref.sync import async_to_sync-from django_deprecate_fields import deprecate_fieldfrom pydantic import ValidationError+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.team.extensions import register_team_extension_signaldiff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.pyindex 6bcfc38b33ce..278ad4c28a2f 100644--- a/products/surveys/backend/models.py+++ b/products/surveys/backend/models.py@@ -11,8 +11,8 @@ from django.db.models.signals import post_delete, post_save, pre_savefrom django.dispatch import receiverfrom dateutil.rrule import DAILY, rrule-from django_deprecate_fields import deprecate_field+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentationdiff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex 0f2954ee2a85..5d78318db645 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -14,10 +14,10 @@ from django.db import models, transactionfrom django.utils import timezonefrom dateutil import parser-from django_deprecate_fields import deprecate_fieldfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception+from posthog.migration_helpers import deprecate_fieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_reprfrom posthog.sync import database_sync_to_async@@ -213,7 +213,7 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields3_folder_name = models.CharField(max_length=400, null=True, blank=True)# Deprecated in favour of `sync_frequency_interval`sync_frequency = deprecate_field(- models.CharField(max_length=128, choices=SyncFrequency, default=SyncFrequency.DAILY, blank=True)+ models.CharField(max_length=128, choices=SyncFrequency, default=SyncFrequency.DAILY, blank=True, null=True))sync_frequency_interval = models.DurationField(default=timedelta(hours=6), null=True, blank=True)sync_time_of_day = models.TimeField(null=True, blank=True, help_text="Time of day to run the sync (UTC)")diff --git a/pyproject.toml b/pyproject.tomlindex 4bb4fd2861e4..9f6dea7de6f0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -41,7 +41,6 @@ dependencies = ["django~=5.2.0","django-axes[ipware]==8.3.1","django-cors-headers~=4.9.0",- "django-deprecate-fields==0.2.3","django-extensions~=4.1.0","django-filter~=26.1","django-loginas==0.3.14",diff --git a/uv.lock b/uv.lockindex 9258c9a4d3c9..45d46c60667b 100644--- a/uv.lock+++ b/uv.lock@@ -1865,18 +1865,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/30/d8/19ed1e47badf477d17fb177c1c19b5a21da0fd2d9f093f23be3fb86c5fab/django_cors_headers-4.9.0-py3-none-any.whl", hash = "sha256:15c7f20727f90044dcee2216a9fd7303741a864865f0c3657e28b7056f61b449", size = 12809, upload-time = "2025-09-18T10:40:50.843Z" },]-[[package]]-name = "django-deprecate-fields"-version = "0.2.3"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "django" },-]-sdist = { url = "https://files.pythonhosted.org/packages/3a/dc/281214543a8e3ebd67294e6a2765d425481726834bf6fe662013dff56eed/django_deprecate_fields-0.2.3.tar.gz", hash = "sha256:d3898d46abe8f338c870e9ef5040dd2f27f3f205e34f5aa2536427d7ffad8aad", size = 7579, upload-time = "2026-01-20T17:50:34.322Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/fe/f7/352dee1616b5653ff09f2b0035f07573accb98954a85c009c08bc7625217/django_deprecate_fields-0.2.3-py3-none-any.whl", hash = "sha256:8510a4bfa23ea7c9d5dddcf7593fa5c8dcc4defcbfad97bf6c4b6deed6abc311", size = 8428, upload-time = "2026-01-20T17:50:33.058Z" },-]-[[package]]name = "django-extensions"version = "4.1"@@ -5581,7 +5569,6 @@ dependencies = [{ name = "django-admin-inline-paginator" },{ name = "django-axes", extra = ["ipware"] },{ name = "django-cors-headers" },- { name = "django-deprecate-fields" },{ name = "django-extensions" },{ name = "django-filter" },{ name = "django-loginas" },@@ -5863,7 +5850,6 @@ requires-dist = [{ name = "django-admin-inline-paginator", specifier = "===0.4.0" },{ name = "django-axes", extras = ["ipware"], specifier = "==8.3.1" },{ name = "django-cors-headers", specifier = "~=4.9.0" },- { name = "django-deprecate-fields", specifier = "==0.2.3" },{ name = "django-extensions", specifier = "~=4.1.0" },{ name = "django-filter", specifier = "~=26.1" },{ name = "django-loginas", specifier = "==0.3.14" },