: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
refactor(tags): re-land the legacy tagged item key untrack (#105497)
Julian Bez558bdcdccb0a
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.mdindex 43a9d0117841..5fe8d6a65b6c 100644--- a/.agents/skills/django-migrations/SKILL.md+++ b/.agents/skills/django-migrations/SKILL.md@@ -102,6 +102,7 @@ Two things a callable does not do for you:- **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 under a budget below `deadlock_timeout`, so a lock cycle tends to end with the migration retried rather than a live read killed, and it is idempotent under a retry. It refuses a partitioned or inherited table, because its lock list does not cover the members of a hierarchy.+- **Drop the check and unique rules on a retiring column** → `DropColumnConstraints(table, columns=[...])`, before the release that stops writing the column. It finds every check, unique and exclusion constraint and every unique index on those columns in the catalog, including ones an earlier swap left behind that no migration names, and drops them under one bounded lock. Never type a Django-generated name into `DROP CONSTRAINT IF EXISTS`: a wrong name succeeds and drops nothing. The risk analyzer blocks a forward drop of a name with Django's hash suffix.- **Drop a foreign key left behind by a retirement** → `DropForeignKey(table, column=...)` or `DropForeignKey(table, to_table=...)`. It reads the name from `pg_constraint`, so nothing is hardcoded and a retry is a no-op. It locks every parent and then the child in one bounded phase, the same as `SafeDropTable`. The transaction holds those locks until `COMMIT`, so give one op every key on the table (`column=["a_id", "b_id"]`) and keep it alone in its migration, next to state-only operations at most. The risk analyzer blocks two drops, or a drop beside other database operations, in one atomic migration. For keys into several busy parents, use `atomic = False` with one op per key instead, so each drop commits alone, and acknowledge the migration in `atomic_false_acknowledged_migrations.txt`.All concurrent-index ops require `atomic = False`.diff --git a/.semgrep/rules/security/max-tools-require-serializer.py b/.semgrep/rules/security/max-tools-require-serializer.pyindex 4f68edf0c0e6..2191c93102d0 100644--- a/.semgrep/rules/security/max-tools-require-serializer.py+++ b/.semgrep/rules/security/max-tools-require-serializer.py@@ -57,7 +57,7 @@ def safe_different_model(team_id):def safe_tagged_item(tag, flag):# TaggedItem not in list - no dedicated serializer# ok: max-tools-direct-model-create- TaggedItem.objects.create(tag=tag, feature_flag=flag)+ flag.tagged_items.create(tag=tag)def safe_experiment_not_in_list(team):diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.mdindex 0d105ffc4be8..28eb08d7bd9d 100644--- a/docs/published/handbook/engineering/safe-django-migrations.md+++ b/docs/published/handbook/engineering/safe-django-migrations.md@@ -321,6 +321,22 @@ When the keys point at several busy parents, one lock phase has to win every par**`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`.+**Check and unique rules on the column go before the release that stops writing it.** A check that requires the column rejects every insert once nothing fills it, and a unique rule over it guards nothing. Drop them with `DropColumnConstraints`, in a migration before the one that untracks the field:++```python+from posthog.migration_helpers import DropColumnConstraints++migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterUniqueTogether(name="mymodel", unique_together=set()),+ migrations.RemoveConstraint(model_name="mymodel", name="one_owner_set"),+ ],+ database_operations=[DropColumnConstraints("posthog_mymodel", columns=["owner_id"])],+)+```++It finds every check, unique and exclusion constraint and every unique index that covers the columns in the catalog, and drops them under one bounded lock on the table. Do not hand-write `DROP CONSTRAINT IF EXISTS <name>` or `DROP INDEX IF EXISTS <name>` for this. Django names a `unique_together` constraint with a hash suffix, and a long-lived database can hold unique indexes that earlier constraint swaps left behind and no migration file names any more. A typed name finds neither, and `IF EXISTS` hides the miss. The migration risk analyzer blocks a forward drop of a name with Django's hash suffix. Keep this operation alone in its migration too.+### If you must drop the columnOnly 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.diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex a7dcb6c2bf4d..1640185e488c 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -1726,19 +1726,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -2413,19 +2400,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -4011,19 +3985,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -7340,19 +7301,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -8023,19 +7971,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -12748,19 +12683,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -16162,19 +16084,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",diff --git a/posthog/management/migration_analysis/analyzer.py b/posthog/management/migration_analysis/analyzer.pyindex 797ab9914699..de11c8b7fbff 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,+ DropColumnConstraintsAnalyzer,DropForeignKeyAnalyzer,DropIndexConcurrentlyAnalyzer,ExtensionAnalyzer,@@ -108,6 +109,7 @@ class RiskAnalyzer:"AddConstraintNotValid": AddConstraintNotValidAnalyzer(),"ValidateConstraint": ValidateConstraintAnalyzer(),"DropForeignKey": DropForeignKeyAnalyzer(),+ "DropColumnConstraints": DropColumnConstraintsAnalyzer(),"SafeDropTable": SafeDropTableAnalyzer(),"SeparateDatabaseAndState": SeparateDatabaseAndStateAnalyzer(),# Postgres extension installs are safe under live load. Sharing onediff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex c05b654ad1bf..5eb5c5827066 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -43,3 +43,6 @@ posthog.1370_backfill_taggeditem_generic_pointer# selects reports that still hold no cached judgment, and each value is recomputed from the# artefact log.signals.0154_backfill_report_actionability+# Drops the 13 legacy tagged item foreign keys one per transaction, so each drop locks one busy parent and+# the child instead of all 14 tables at once. Re-running is a no-op: DropForeignKey reads what is left from pg_constraint.+posthog.1383_taggeditem_untrack_legacy_keysdiff --git a/posthog/management/migration_analysis/operations.py b/posthog/management/migration_analysis/operations.pyindex d076bb36f363..d1a922c285e2 100644--- a/posthog/management/migration_analysis/operations.py+++ b/posthog/management/migration_analysis/operations.py@@ -1018,6 +1018,32 @@ Irreversible. Add the constraint back with `AddForeignKeyNotValid` in a new migr)+class DropColumnConstraintsAnalyzer(OperationAnalyzer):+ """The check and unique rules that go with a retiring column.++ Every drop is a catalog change on one table, taken under one bounded lock phase, so it+ scores with DropForeignKey. LockPhaseTransactionPolicy checks the rest of the transaction.+ """++ operation_type = "DropColumnConstraints"+ default_score = 1++ def analyze(self, op) -> OperationRisk:+ return OperationRisk(+ type=self.operation_type,+ score=1,+ reason="DROP CONSTRAINT and DROP INDEX for retiring columns are catalog changes (bounded lock phase, no table scan)",+ details={"table": getattr(op, "table", None), "columns": getattr(op, "columns", None)},+ guidance=f"""Finds every check and unique rule on the columns in the catalog, so it also drops rules no migration file names any more. Run it before the release that stops writing the columns, because a check that requires them then rejects every insert.++The transaction holds the table lock until COMMIT. Keep this op alone in its migration, next to state-only operations at most.++Irreversible. Add a rule back 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/policies.py b/posthog/management/migration_analysis/policies.pyindex e00743fbb5e6..8574517387a6 100644--- a/posthog/management/migration_analysis/policies.py+++ b/posthog/management/migration_analysis/policies.py@@ -953,13 +953,13 @@ class OrphanedForeignKeyPolicy(MigrationPolicy):)-_LOCK_PHASE_OPERATIONS = {"DropForeignKey", "SafeDropTable"}+_LOCK_PHASE_OPERATIONS = {"DropColumnConstraints", "DropForeignKey", "SafeDropTable"}class LockPhaseTransactionPolicy(MigrationPolicy):- """Keep a DropForeignKey or SafeDropTable alone in its transaction.+ """Keep a DropForeignKey, DropColumnConstraints or SafeDropTable alone in its transaction.- Both take their locks in a bounded, parent-first phase (posthog/migration_helpers/lock_phase.py),+ Each takes its locks in a bounded, parent-first phase (posthog/migration_helpers/lock_phase.py),but the transaction holds the locks until COMMIT. A second lock phase then waits for newparents while the first one's parents stay locked. Another operation that runs first holdsits table while the lock phase waits for the parents, and one that runs after waits for new@@ -1001,6 +1001,49 @@ class LockPhaseTransactionPolicy(MigrationPolicy):return violations+class GeneratedNameDropPolicy(MigrationPolicy):+ """Block a hand-typed drop of a constraint or index whose name Django generated.++ Django names an unnamed unique_together, index or foreign key with an eight-character+ hash of its columns. A name typed from a local database or an older migration can differ+ from the one a long-lived database holds, and `IF EXISTS` turns that miss into a migration+ that succeeds and drops nothing. Rules left behind this way stay in production while every+ fresh database lacks them. The helpers find the rule in the catalog instead. Only forward+ SQL is checked, because a reverse drops what its own forward just created.+ """++ _DROP = re.compile(+ r"DROP\s+(?:CONSTRAINT|INDEX(?:\s+CONCURRENTLY)?)\s+(?:IF\s+EXISTS\s+)?\"?(\w+)\"?",+ re.IGNORECASE,+ )+ # Django's shapes: an eight-character hash before a suffix, a bare eight-character hash, and+ # the six-character digest of an unnamed models.Index. Only the bare hash must hold a+ # letter, so a date such as _20260923 at the end of a chosen name does not match.+ _GENERATED = re.compile(+ r"_[0-9a-f]{8}_(?:uniq|like|check|idx|fk_\w+)$|_(?=[0-9]*[a-f])[0-9a-f]{8}$|_[0-9a-f]{6}_idx$"+ )++ def check_operation(self, op) -> list[str]:+ if op.__class__.__name__ != "RunSQL":+ return []+ sql = _without_sql_comments(str(getattr(op, "sql", "")))+ names = sorted({name for name in self._DROP.findall(sql) if self._GENERATED.search(name)})+ if not names:+ return []+ return [+ f"❌ BLOCKED: RunSQL drops {', '.join(names)} by a name Django generated. A long-lived database "+ "can hold the rule under another name, or hold rules no migration names any more, and IF EXISTS "+ "hides the miss. Find it in the catalog: DropColumnConstraints(table, columns=[...]) for the check "+ "and unique rules on a retiring column, DropForeignKey for a foreign key, or Django's own "+ "AlterUniqueTogether and RemoveIndex, which resolve the name from state or by column."+ ]++ def check_migration(self, migration) -> list[str]:+ if not is_posthog_app(migration.app_label, migration):+ return []+ return [violation for op in _descend(migration.operations) for violation in self.check_operation(op)]++POSTHOG_POLICIES = [UUIDPrimaryKeyPolicy(),AtomicFalsePolicy(),@@ -1008,4 +1051,5 @@ POSTHOG_POLICIES = [HotTableAlterPolicy(),OrphanedForeignKeyPolicy(),LockPhaseTransactionPolicy(),+ GeneratedNameDropPolicy(),]diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.pyindex 04ffec1e7cdd..8b0371cab4e1 100644--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py@@ -12,6 +12,7 @@ from posthog.management.migration_analysis.models import MigrationRisk, Operatiofrom posthog.management.migration_analysis.policies import (AtomicFalsePolicy,ConcurrentIndexIdempotencyPolicy,+ GeneratedNameDropPolicy,HotTableAlterPolicy,LockPhaseTransactionPolicy,OrphanedForeignKeyPolicy,@@ -20,6 +21,7 @@ from posthog.management.migration_analysis.utils import _model_name_for_tablefrom posthog.migration_helpers import (AddConstraintNotValid,AddForeignKeyNotValid,+ DropColumnConstraints,DropForeignKey,SafeAddIndexConcurrently,SafeDropTable,@@ -2990,6 +2992,7 @@ class TestLockPhaseTransactionPolicy:("another_operation_first", True, ["remove_constraint", "untrack_one"], ["RemoveConstraint"]),("both_shapes_at_once", True, ["remove_constraint", "untrack_two"], ["column=[...]", "RemoveConstraint"]),("a_table_drop_beside_a_key_drop", True, ["untrack_one", "safe_drop"], ["SafeDropTable"]),+ ("column_rules_beside_a_key_drop", True, ["drop_rules", "untrack_one"], ["DropColumnConstraints"]),("a_no_op_beside_the_drop", True, ["no_op_sql", "untrack_one"], []),("a_state_only_django_op_beside_the_drop", True, ["alter_options", "untrack_one"], []),("two_drops_nested_one_level_down", True, ["nested_two"], ["column=[...]"]),@@ -3004,6 +3007,7 @@ class TestLockPhaseTransactionPolicy:"untrack_two": self._untrack(owner, other),"remove_constraint": migrations.RemoveConstraint(model_name="child", name="exactly_one_owner"),"safe_drop": SafeDropTable("posthog_retired"),+ "drop_rules": DropColumnConstraints("posthog_child", columns=["owner_id"]),"no_op_sql": migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop),"alter_options": migrations.AlterModelOptions(name="child", options={"ordering": ["id"]}),"nested_two": migrations.SeparateDatabaseAndState(database_operations=[self._untrack(owner, other)]),@@ -3020,3 +3024,67 @@ class TestLockPhaseTransactionPolicy:for violation, fragment in zip(violations, expected):assert violation.startswith("❌ BLOCKED")assert fragment in violation+++class TestGeneratedNameDropPolicy:+ @parameterized.expand(+ [+ (+ "unique_together_with_if_exists",+ 'ALTER TABLE "posthog_x" DROP CONSTRAINT IF EXISTS "posthog_x_tag_id_owner_id_734394e1_uniq"',+ None,+ ["posthog_x_tag_id_owner_id_734394e1_uniq"],+ ),+ (+ "foreign_key",+ "ALTER TABLE posthog_x DROP CONSTRAINT posthog_x_owner_id_9a1bc3de_fk_posthog_team_id",+ None,+ ["posthog_x_owner_id_9a1bc3de_fk_posthog_team_id"],+ ),+ (+ "index_dropped_concurrently",+ 'DROP INDEX CONCURRENTLY IF EXISTS "posthog_x_owner_id_5a6b7c8d"',+ None,+ ["posthog_x_owner_id_5a6b7c8d"],+ ),+ (+ "index_together_idx",+ 'DROP INDEX IF EXISTS "posthog_x_team_id_owner_id_1a2b3c4d_idx"',+ None,+ ["posthog_x_team_id_owner_id_1a2b3c4d_idx"],+ ),+ (+ "unnamed_models_index",+ 'DROP INDEX IF EXISTS "posthog_eve_team_id_26dbfb_idx"',+ None,+ ["posthog_eve_team_id_26dbfb_idx"],+ ),+ (+ "all_digit_hash_before_a_suffix",+ 'ALTER TABLE "posthog_x" DROP CONSTRAINT IF EXISTS "posthog_x_tag_id_owner_id_12345678_uniq"',+ None,+ ["posthog_x_tag_id_owner_id_12345678_uniq"],+ ),+ ("a_chosen_name", 'ALTER TABLE "posthog_x" DROP CONSTRAINT IF EXISTS "exactly_one_owner"', None, []),+ ("a_date_in_a_chosen_name", 'DROP INDEX IF EXISTS "posthog_x_backfill_20260923"', None, []),+ (+ "only_the_reverse",+ 'ALTER TABLE "posthog_x" ADD CONSTRAINT "posthog_x_tag_id_owner_id_734394e1_uniq" UNIQUE (tag_id)',+ 'ALTER TABLE "posthog_x" DROP CONSTRAINT IF EXISTS "posthog_x_tag_id_owner_id_734394e1_uniq"',+ [],+ ),+ ("inside_a_comment", '-- DROP CONSTRAINT "posthog_x_tag_id_owner_id_734394e1_uniq"\nSELECT 1', None, []),+ ]+ )+ def test_a_generated_name_is_not_typed_into_a_drop(self, _name, sql, reverse_sql, expected):+ run_sql = migrations.RunSQL(sql, reverse_sql or migrations.RunSQL.noop)+ migration = MagicMock()+ migration.app_label = "posthog"+ migration.name = "0001_test"+ migration.operations = [migrations.SeparateDatabaseAndState(database_operations=[run_sql])]++ violations = GeneratedNameDropPolicy().check_migration(migration)++ assert len(violations) == (1 if expected else 0)+ for name in expected:+ assert name in violations[0]diff --git a/posthog/migration_helpers/__init__.py b/posthog/migration_helpers/__init__.pyindex b7190571bcad..9af67b730e4f 100644--- a/posthog/migration_helpers/__init__.py+++ b/posthog/migration_helpers/__init__.py@@ -5,6 +5,7 @@ from posthog.migration_helpers.concurrent_index import (SafeRemoveIndexConcurrently,)from posthog.migration_helpers.deprecate_field import deprecate_field+from posthog.migration_helpers.drop_column_constraints import DropColumnConstraintsfrom 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@@ -15,6 +16,7 @@ __all__ = ["AddConstraintNotValid","AddForeignKeyNotValid","CreateIndexConcurrently",+ "DropColumnConstraints","DropForeignKey","DropIndexConcurrently","SafeAddIndexConcurrently",diff --git a/posthog/migration_helpers/drop_column_constraints.py b/posthog/migration_helpers/drop_column_constraints.pynew file mode 100644index 000000000000..d1cbe4494781--- /dev/null+++ b/posthog/migration_helpers/drop_column_constraints.py@@ -0,0 +1,167 @@+"""Drop the rules a retiring column still enforces, found in the catalog rather than by name.++A column that leaves Django's state keeps every check and unique rule the database holds on+it. Once the code stops filling the column, a check that requires it rejects every insert,+and a unique rule over it guards nothing. So those rules go before the release that stops+writing the column, inside the `SeparateDatabaseAndState` that removes them from state:++ from posthog.migration_helpers import DropColumnConstraints++ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterUniqueTogether(name="mymodel", unique_together=set()),+ migrations.RemoveConstraint(model_name="mymodel", name="one_owner_set"),+ ],+ database_operations=[+ DropColumnConstraints("posthog_mymodel", columns=["owner_id", "legacy_id"]),+ ],+ )++Do not hand-write `DROP CONSTRAINT IF EXISTS <name>` or `DROP INDEX IF EXISTS <name>` for+this. Django names a `unique_together` constraint with a hash suffix, and a typed name that+does not match turns `IF EXISTS` into a migration that succeeds and drops nothing. A+database can also hold rules no migration file names any more, because an earlier swap left+them behind. This op finds every rule by the columns it covers, so it drops those too.++It drops, when any of their columns is one of `columns`:++- check, unique and exclusion constraints,+- unique indexes that no constraint owns. Postgres stores a Django `UniqueConstraint` with a+ `condition` as a plain unique index, and a swap that drops a constraint but not its index+ leaves one too.++It keeps foreign keys, which `DropForeignKey` handles, the primary key, and plain indexes,+which a later `DROP COLUMN` takes with the column.++Every drop touches only the one table, so the op locks it with `lock_tables` and drops+everything under that one lock. The drops are catalog changes and scan nothing. The op is+idempotent under a bin/migrate retry, and irreversible.+"""++from collections.abc import Sequence++from django.db import router, transaction+from django.db.migrations.operations.base import Operation++from posthog.dataclasses import frozen+from posthog.migration_helpers.lock_phase import lock_tables++# `unnest` rather than the `&&` array operator: an extension such as intarray makes+# `smallint[] && smallint[]` ambiguous, and the query then fails on that database only.+_COLUMNS_SQL = """+ SELECT att.attname+ FROM pg_class rel+ JOIN pg_attribute att ON att.attrelid = rel.oid+ WHERE rel.relname = %(table)s AND pg_table_is_visible(rel.oid) AND att.attname = ANY(%(columns)s::name[])+"""++_RULES_SQL = """+ WITH target AS (+ SELECT oid FROM pg_class WHERE relname = %(table)s AND pg_table_is_visible(oid)+ ), retiring AS (+ SELECT att.attnum FROM pg_attribute att, target+ WHERE att.attrelid = target.oid AND att.attname = ANY(%(columns)s::name[])+ )+ SELECT NULL AS schema, con.conname, 'constraint'+ FROM pg_constraint con, target+ WHERE con.conrelid = target.oid+ AND con.contype IN ('c', 'u', 'x')+ AND EXISTS (SELECT 1 FROM unnest(con.conkey) AS key(attnum) WHERE key.attnum IN (SELECT attnum FROM retiring))+ UNION+ SELECT nsp.nspname, idx.relname, 'index'+ FROM pg_index ix+ JOIN target ON ix.indrelid = target.oid+ JOIN pg_class idx ON idx.oid = ix.indexrelid+ JOIN pg_namespace nsp ON nsp.oid = idx.relnamespace+ -- An index depends on each column in its keys, its expressions and its predicate.+ JOIN pg_depend dep ON dep.classid = 'pg_class'::regclass AND dep.objid = ix.indexrelid+ AND dep.refclassid = 'pg_class'::regclass AND dep.refobjid = ix.indrelid+ WHERE ix.indisunique+ AND NOT ix.indisprimary+ AND NOT EXISTS (SELECT 1 FROM pg_constraint owner WHERE owner.conindid = ix.indexrelid)+ AND dep.refobjsubid IN (SELECT attnum FROM retiring)+"""+++@frozen+class _Rule:+ schema: str | None+ name: str+ is_index: bool+++class DropColumnConstraints(Operation):+ """Drop every check and unique rule on `table` that covers one of `columns`.++ Tracks no Django state. Use it inside `database_operations` of the same+ `SeparateDatabaseAndState` that removes the constraints from state.++ Arguments:+ table: the table, e.g. `"posthog_mymodel"`. A raw table name, like `DropForeignKey`.+ columns: the retiring columns, e.g. `["owner_id"]`. Note the `_id` suffix Django+ gives foreign key columns.+ """++ # The dropped definitions are recorded nowhere this op can read, so a reverse could only+ # be a no-op, and that would put the rules back into model state without the database.+ reversible = False+ reduces_to_sql = True++ def __init__(self, table: str, columns: Sequence[str]) -> None:+ if isinstance(columns, str) or not columns:+ raise ValueError("DropColumnConstraints needs a list of columns")+ self.table = table+ self.columns = list(columns)++ def state_forwards(self, app_label, state) -> None:+ pass++ def _check_columns_exist(self, schema_editor) -> None:+ # A typo would otherwise find no rules and succeed, while the state operations beside+ # this op still remove the rules from state. A column that exists with no rules left+ # is the idempotent case.+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(_COLUMNS_SQL, {"table": self.table, "columns": self.columns})+ found = {row[0] for row in cursor.fetchall()}+ missing = [column for column in self.columns if column not in found]+ if missing:+ raise ValueError(f"DropColumnConstraints: {self.table} has no column {', '.join(missing)}")++ def _rules(self, schema_editor) -> list[_Rule]:+ with schema_editor.connection.cursor() as cursor:+ cursor.execute(_RULES_SQL, {"table": self.table, "columns": self.columns})+ return [+ _Rule(schema=schema, name=name, is_index=kind == "index")+ for schema, name, kind in sorted(cursor.fetchall(), key=lambda row: (row[2], row[1]))+ ]++ 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. A raw+ # catalog query cannot tell the aliases apart, so check the router first.+ if not router.allow_migrate(schema_editor.connection.alias, app_label):+ return+ self._check_columns_exist(schema_editor)+ rules = self._rules(schema_editor)+ if not rules:+ return+ constraints = [rule.name for rule in rules if not rule.is_index]+ # DROP INDEX resolves an unqualified name through search_path, which can reach a+ # same-named index in another schema, so each index carries the schema it was found in.+ indexes = [+ f"{schema_editor.quote_name(rule.schema)}.{schema_editor.quote_name(rule.name)}"+ for rule in rules+ if rule.is_index+ ]+ with transaction.atomic(using=schema_editor.connection.alias):+ lock_tables(schema_editor, [self.table])+ if constraints:+ drops = ", ".join(f"DROP CONSTRAINT {schema_editor.quote_name(name)}" for name in constraints)+ schema_editor.execute(f"ALTER TABLE {schema_editor.quote_name(self.table)} {drops}")+ if indexes:+ schema_editor.execute(f"DROP INDEX {', '.join(indexes)}")++ def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:+ raise NotImplementedError("DropColumnConstraints is irreversible; add the rules back in a new migration")++ def describe(self) -> str:+ return f"Drop check and unique rules on {self.table} ({', '.join(self.columns)})"diff --git a/posthog/migration_helpers/test_drop_column_constraints.py b/posthog/migration_helpers/test_drop_column_constraints.pynew file mode 100644index 000000000000..363e307311e8--- /dev/null+++ b/posthog/migration_helpers/test_drop_column_constraints.py@@ -0,0 +1,97 @@+import uuid++import pytest++from django.db import connection++from posthog.migration_helpers import DropColumnConstraints+++def temp_table():+ suffix = uuid.uuid4().hex[:8]+ parent = f"test_dropcc_parent_{suffix}"+ table = f"test_dropcc_{suffix}"+ with connection.cursor() as cursor:+ cursor.execute(f'CREATE TABLE "{parent}" (id serial primary key)')+ cursor.execute(+ f"""+ CREATE TABLE "{table}" (+ id serial primary key,+ tag_id int NOT NULL,+ keeper_id int,+ legacy_a_id int CONSTRAINT "{table}_legacy_a_id_1c2d3e4f_fk" REFERENCES "{parent}"(id),+ legacy_b_id int,+ CONSTRAINT "{table}_tag_id_legacy_a_id_9f8e7d6c_uniq" UNIQUE (tag_id, legacy_a_id, legacy_b_id),+ CONSTRAINT "exactly_one_legacy_key" CHECK ((legacy_a_id IS NULL) <> (legacy_b_id IS NULL)),+ CONSTRAINT "keeper_positive" CHECK (keeper_id > 0)+ )+ """+ )+ cursor.execute(+ f'CREATE UNIQUE INDEX "{table}_tag_id_legacy_a_id_5a6b7c8d_uniq" ON "{table}" (tag_id, legacy_a_id)'+ )+ cursor.execute(+ f'CREATE UNIQUE INDEX "unique_legacy_b_{suffix}" ON "{table}" (tag_id) WHERE legacy_b_id IS NOT NULL'+ )+ cursor.execute(f'CREATE UNIQUE INDEX "unique_keeper_{suffix}" ON "{table}" (tag_id, keeper_id)')+ cursor.execute(f'CREATE INDEX "{table}_legacy_a_id_idx" ON "{table}" (legacy_a_id)')+ try:+ yield table, suffix+ finally:+ with connection.cursor() as cursor:+ cursor.execute(f'DROP TABLE IF EXISTS "{table}" CASCADE')+ cursor.execute(f'DROP TABLE IF EXISTS "{parent}" CASCADE')+++def _apply(op):+ with connection.schema_editor(atomic=False) as schema_editor:+ op.database_forwards("posthog", schema_editor, from_state=None, to_state=None)+++def _rules(table):+ with connection.cursor() as cursor:+ cursor.execute(+ """+ SELECT con.conname FROM pg_constraint con JOIN pg_class t ON t.oid = con.conrelid+ WHERE t.relname = %(table)s+ UNION+ SELECT i.relname FROM pg_index ix+ JOIN pg_class t ON t.oid = ix.indrelid JOIN pg_class i ON i.oid = ix.indexrelid+ WHERE t.relname = %(table)s+ """,+ {"table": table},+ )+ return {row[0] for row in cursor.fetchall()}+++def test_drops_every_rule_on_the_retiring_columns_and_keeps_the_rest(temp_table):+ table, suffix = temp_table+ op = DropColumnConstraints(table, columns=["legacy_a_id", "legacy_b_id"])++ _apply(op)+ _apply(op)++ assert _rules(table) == {+ f"{table}_pkey",+ f"{table}_legacy_a_id_1c2d3e4f_fk",+ "keeper_positive",+ f"unique_keeper_{suffix}",+ f"{table}_legacy_a_id_idx",+ }+++def test_a_misspelled_column_fails_instead_of_dropping_nothing(temp_table):+ table, _ = temp_table++ with pytest.raises(ValueError, match="no column legacy_c_id"):+ _apply(DropColumnConstraints(table, columns=["legacy_a_id", "legacy_c_id"]))++ assert f"{table}_tag_id_legacy_a_id_9f8e7d6c_uniq" in _rules(table)+++def test_needs_a_list_of_columns():+ with pytest.raises(ValueError, match="list of columns"):+ DropColumnConstraints("test_dropcc", columns="legacy_a_id")diff --git a/posthog/migrations/1382_taggeditem_drop_legacy_constraints.py b/posthog/migrations/1382_taggeditem_drop_legacy_constraints.pynew file mode 100644index 000000000000..e60367962b4b--- /dev/null+++ b/posthog/migrations/1382_taggeditem_drop_legacy_constraints.py@@ -0,0 +1,47 @@+from django.db import migrations++from posthog.migration_helpers import DropColumnConstraints++# The per-model foreign keys TaggedItem carried before the generic pointer replaced them.+LEGACY_FIELDS = (+ "dashboard",+ "insight",+ "event_definition",+ "property_definition",+ "action",+ "feature_flag",+ "experiment_saved_metric",+ "ticket",+ "account",+ "endpoint",+ "replay_scanner",+ "project",+ "experiment",+)+++class Migration(migrations.Migration):+ # The constraints go before the release that stops filling the legacy keys. That release+ # sets no legacy key, so the check would reject every insert while both releases run.+ # DropColumnConstraints finds them by column, so it also takes the unique indexes earlier+ # constraint swaps left on long-lived databases, and does nothing where the first version+ # of 1376 already dropped them.+ dependencies = [+ ("posthog", "1381_codex_user_integration_unique_index"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterUniqueTogether(name="taggeditem", unique_together=set()),+ *[+ migrations.RemoveConstraint(model_name="taggeditem", name=f"unique_{field}_tagged_item")+ for field in LEGACY_FIELDS+ ],+ migrations.RemoveConstraint(model_name="taggeditem", name="exactly_one_related_object"),+ ],+ database_operations=[+ DropColumnConstraints("posthog_taggeditem", columns=[f"{field}_id" for field in LEGACY_FIELDS]),+ ],+ ),+ ]diff --git a/posthog/migrations/1383_taggeditem_untrack_legacy_keys.py b/posthog/migrations/1383_taggeditem_untrack_legacy_keys.pynew file mode 100644index 000000000000..8f14e708c8d2--- /dev/null+++ b/posthog/migrations/1383_taggeditem_untrack_legacy_keys.py@@ -0,0 +1,42 @@+from django.db import migrations++from posthog.migration_helpers import DropForeignKey, untrack_field++# The per-model foreign keys TaggedItem carried before the generic pointer replaced them.+LEGACY_FIELDS = (+ "dashboard",+ "insight",+ "event_definition",+ "property_definition",+ "action",+ "feature_flag",+ "experiment_saved_metric",+ "ticket",+ "account",+ "endpoint",+ "replay_scanner",+ "project",+ "experiment",+)+++class Migration(migrations.Migration):+ # Each DropForeignKey commits in a transaction of its own, so one drop locks one busy+ # parent and the child rather than all 14 tables at once. A retry skips the keys a+ # failed run already dropped, because DropForeignKey reads what is left from pg_constraint.+ atomic = False++ dependencies = [+ ("posthog", "1382_taggeditem_drop_legacy_constraints"),+ ]++ operations = [+ # The columns stay, so a pod on the old release keeps reading and writing them. Their+ # foreign keys cannot: Django stops cascading into a relation it no longer tracks, and+ # a deferred constraint would then fail every parent delete at COMMIT.+ untrack_field(+ "taggeditem",+ *LEGACY_FIELDS,+ database_operations=[DropForeignKey("posthog_taggeditem", column=f"{field}_id") for field in LEGACY_FIELDS],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 4ef2ce7ca55f..7de68b9bd074 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1381_codex_user_integration_unique_index+1383_taggeditem_untrack_legacy_keysdiff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex c932b05d67dd..35ed0bf52b10 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -588,7 +588,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {"ReplayScanner": [*replay_scanner_machine_fields, "observations", "backfills", "prompt_suggestions", "alerts"],"VisionAlertConfiguration": [*vision_alert_machine_fields, "events", "matches"],"DataQualityCheckSchedule": ["subject_type", "subject_uuid", "next_run_at", "last_run_at", "last_suite_run"],- # The generic pointer mirrors whichever per-model foreign key is set, so it is never a user edit.+ # The pointer names the tagged object, which a row never changes, and content_type and team+ # are model objects the diff cannot serialize."TaggedItem": ["content_type", "object_id", "object_uuid", "team"],"StamphogRepoConfig": [# Reverse relation to the repo's review history. The diff would read every pull request rowdiff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.pyindex f5c5d764ff85..692732b96cf5 100644--- a/posthog/models/tagged_item.py+++ b/posthog/models/tagged_item.py@@ -16,28 +16,11 @@ from posthog.models.tagged_item_registry import (object_column_for,require_taggable,taggable_for_content_type_id,- taggable_for_legacy_field,)-from posthog.models.utils import UUIDTModel, build_partial_uniqueness_constraint, build_unique_relationship_check+from posthog.models.utils import UUIDTModelGENERIC_POINTER_FIELDS = ("content_type", "object_id", "object_uuid", "team")-RELATED_OBJECTS = (- "dashboard",- "insight",- "event_definition",- "property_definition",- "action",- "feature_flag",- "experiment_saved_metric",- "ticket",- "account",- "endpoint",- "replay_scanner",- "project",- "experiment",-)-class TaggedItemQuerySet(models.QuerySet):"""Ways of selecting tagged items by what they tag, without naming a column."""@@ -68,7 +51,7 @@ class TaggedItemQuerySet(models.QuerySet):for obj in objs:if obj.tag_id in tags:obj.tag = tags[obj.tag_id]- obj.sync_foreign_keys()+ obj.sync_team()return super().bulk_create(objs, *args, **kwargs)@@ -83,113 +66,12 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):We want to deprecate model-specific tags and refactor tag relationships into a separate table that keeps track oftag-object relationships.- Models that are taggable throughout the app are listed as separate fields below.+ Models that are taggable throughout the app are listed in `TAGGABLE_MODELS`.https://docs.djangoproject.com/en/4.0/ref/contrib/contenttypes/#generic-relations"""tag = models.ForeignKey("Tag", on_delete=models.CASCADE, related_name="tagged_items")- # When adding a new taggeditem-model relationship, make sure to add the foreign key field and append field name to- # the `RELATED_OBJECTS` tuple above.- dashboard = models.ForeignKey(- "dashboards.Dashboard",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- insight = models.ForeignKey(- "product_analytics.Insight",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- event_definition = models.ForeignKey(- "event_definitions.EventDefinition",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- property_definition = models.ForeignKey(- "event_definitions.PropertyDefinition",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- action = models.ForeignKey(- "actions.Action",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- feature_flag = models.ForeignKey(- "feature_flags.FeatureFlag",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- experiment_saved_metric = models.ForeignKey(- "experiments.ExperimentSavedMetric",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- ticket = models.ForeignKey(- "conversations.Ticket",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- account = models.ForeignKey(- "customer_analytics.Account",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- endpoint = models.ForeignKey(- "endpoints.Endpoint",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- replay_scanner = models.ForeignKey(- "replay_vision.ReplayScanner",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- )- project = models.ForeignKey(- "posthog.Project",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- # posthog_project is read on nearly every request, so creating this FK's database- # constraint inline would lock it. A later migration adds the constraint NOT VALID- # and validates it separately.- db_constraint=False,- )- experiment = models.ForeignKey(- "experiments.Experiment",- on_delete=models.CASCADE,- null=True,- blank=True,- related_name="+",- # Same deferred-FK pattern as project: the constraint lands NOT VALID in a later- # migration and is validated separately, keeping the lock on posthog_experiment brief.- db_constraint=False,- )-# db_index=False on both keys below: Django would build that index non-concurrently# inside the AddField transaction, locking the table.content_type = models.ForeignKey(@@ -218,7 +100,6 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):uuid_object = GenericForeignKey("content_type", "object_uuid")class Meta:- unique_together = ("tag", *RELATED_OBJECTS)indexes = [# Most integer-keyed models declare BigAutoField, so Django casts object_id to bigint# when it joins to them, and the unique index on the raw column cannot serve that join.@@ -229,17 +110,7 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):name="taggeditem_object_id_bigint",),]- # Make sure to add new key to uniqueness constraint when extending tag functionality to new modelconstraints = [- *[- build_partial_uniqueness_constraint(- field="tag", related_field=related_field, constraint_name=f"unique_{related_field}_tagged_item"- )- for related_field in RELATED_OBJECTS- ],- models.CheckConstraint(- condition=build_unique_relationship_check(RELATED_OBJECTS), name="exactly_one_related_object"- ),models.CheckConstraint(condition=Q(content_type__isnull=False, team__isnull=False)& (@@ -261,10 +132,17 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):]def clean(self):+ """Ensure the row names exactly one taggable object, through the column its model uses."""super().clean()- """Ensure that exactly one of object columns can be set."""- if sum(map(bool, [getattr(self, o_field) for o_field in RELATED_OBJECTS])) != 1:- raise ValidationError("Exactly one object field must be set.")+ if self.content_type_id is None:+ raise ValidationError("A tagged item must have a content type.")+ if (self.object_id is None) == (self.object_uuid is None):+ raise ValidationError("Exactly one object column must be set.")+ entry = self._taggable_entry+ if entry is None:+ raise ValidationError("The content type is not a taggable model.")+ if getattr(self, entry.object_field) is None:+ raise ValidationError(f"A tag on {self.content_type} belongs on {entry.object_field}.")objects = TaggedItemQuerySet.as_manager()@@ -299,51 +177,15 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):return self.uuid_objectreturn None- def sync_legacy_foreign_key(self) -> None:- """Point the per-model foreign key at the object the generic pointer names."""- entry = self._taggable_entry- # A row built with a content type and only a legacy key keeps that key.- if entry is None or getattr(self, entry.object_field) is None:- return- for legacy_field in RELATED_OBJECTS:- setattr(self, f"{legacy_field}_id", None)- setattr(self, f"{entry.legacy_field}_id", getattr(self, entry.object_field))-- def sync_foreign_keys(self) -> None:- """Make the two pointer shapes agree, preferring the generic one when it is set."""- if self.content_type_id is not None:- self.sync_legacy_foreign_key()- self.sync_generic_columns()-- def sync_generic_columns(self) -> None:- """Fill the generic pointer from whichever per-model foreign key is set.-- Reads `<field>_id` rather than `<field>`, so it resolves the target without loading it.- """- self.content_type = None- self.object_id = None- self.object_uuid = None- for legacy_field in RELATED_OBJECTS:- related_id = getattr(self, f"{legacy_field}_id", None)- if related_id is None:- continue-- entry = taggable_for_legacy_field(legacy_field)- if entry is None:- continue-- self.content_type = content_type_for_entry(entry)- setattr(self, entry.object_field, related_id)- self.team_id = self.tag.team_id- return+ def sync_team(self) -> None:+ """Take the team from the tag, which is the row's owner."""+ self.team_id = self.tag.team_iddef save(self, *args, **kwargs):- if self.content_type_id is not None:- self.sync_legacy_foreign_key()- self.full_clean(exclude=GENERIC_POINTER_FIELDS)- self.sync_generic_columns()+ self.sync_team()+ self.full_clean()if kwargs.get("update_fields"):- kwargs["update_fields"] = {*kwargs["update_fields"], *GENERIC_POINTER_FIELDS, *RELATED_OBJECTS}+ kwargs["update_fields"] = {*kwargs["update_fields"], *GENERIC_POINTER_FIELDS}return super().save(*args, **kwargs)def __str__(self) -> str:diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.pyindex ddf642ad827c..8e271a1c4ff2 100644--- a/posthog/models/test/test_tagged_item_model.py+++ b/posthog/models/test/test_tagged_item_model.py@@ -7,25 +7,36 @@ from django.db import modelsfrom parameterized import parameterizedfrom posthog.models import Tag, TaggedItem, Team+from posthog.models.tagged_items_relation import Taggablefrom products.actions.backend.models.action import Actionfrom products.dashboards.backend.models.dashboard import Dashboard-from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.event_definitions.backend.models import EventDefinitionfrom products.product_analytics.backend.facade.models import Insightclass TestTaggedItem(BaseTest):+ def _taggable(self, kind: str) -> Taggable:+ if kind == "dashboard":+ return Dashboard.objects.create(team_id=self.team.id, name="dashboard")+ if kind == "insight":+ return Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)+ if kind == "event_definition":+ return EventDefinition.objects.create(team=self.team, name="event")+ return Action.objects.create(team=self.team, name="action")+def test_exactly_one_object_constraint(self):- # Setupdashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")- insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)- DashboardTile.objects.create(insight=insight, dashboard=dashboard)+ event_definition = EventDefinition.objects.create(team=self.team, name="event")tag = Tag.objects.create(name="tag", team_id=self.team.id)- # Before migration you can create duplicate tagged itemswith self.assertRaises(ValidationError):- TaggedItem.objects.create(dashboard_id=dashboard.id, insight_id=insight.id, tag_id=tag.id)+ TaggedItem.objects.create(+ tag_id=tag.id,+ content_type=ContentType.objects.get_for_model(Dashboard),+ object_id=dashboard.id,+ object_uuid=event_definition.id,+ )def test_at_least_one_constraint(self):tag = Tag.objects.create(name="tag", team_id=self.team.id)@@ -33,75 +44,65 @@ class TestTaggedItem(BaseTest):with self.assertRaises(ValidationError):TaggedItem.objects.create(tag_id=tag.id)- def test_uniqueness_constraint_dashboard(self):+ def test_content_type_is_required(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)- TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)with self.assertRaises(ValidationError):- TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)+ TaggedItem.objects.create(tag_id=tag.id, object_id=dashboard.id)- def test_uniqueness_constraint_insight(self):- dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")- insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)- DashboardTile.objects.create(insight=insight, dashboard=dashboard)+ def test_unregistered_content_type_is_rejected(self):tag = Tag.objects.create(name="tag", team_id=self.team.id)- TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)with self.assertRaises(ValidationError):- TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)+ TaggedItem.objects.create(+ tag_id=tag.id, content_type=ContentType.objects.get_for_model(Team), object_id=self.team.id+ )- def test_uniqueness_constraint_event_definition(self):- try:- from ee.models import EnterpriseEventDefinition- except ImportError:- pass- else:- event_definition = EnterpriseEventDefinition.objects.create(- team=self.team, name="enterprise event", owner=self.user+ def test_object_column_must_match_the_content_type(self):+ """A row filed under the wrong typed column reads back as no object at all."""+ event_definition = EventDefinition.objects.create(team=self.team, name="event")+ tag = Tag.objects.create(name="tag", team_id=self.team.id)++ with self.assertRaises(ValidationError):+ TaggedItem.objects.create(+ tag_id=tag.id,+ content_type=ContentType.objects.get_for_model(EventDefinition),+ object_id=self.team.id,)- tag = Tag.objects.create(name="tag", team_id=self.team.id)+ assert event_definition.tagged_items.count() == 0- TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)- with self.assertRaises(ValidationError):- TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)+ @parameterized.expand(["dashboard", "insight", "event_definition", "action"])+ def test_uniqueness_constraint(self, kind: str):+ tag = Tag.objects.create(name="tag", team_id=self.team.id)+ obj = self._taggable(kind)++ obj.tagged_items.create(tag=tag)+ with self.assertRaises(ValidationError):+ obj.tagged_items.create(tag=tag)def test_uniqueness_constraint_property_definition(self):try:from ee.models import EnterprisePropertyDefinitionexcept ImportError:- pass- else:- property_definition = EnterprisePropertyDefinition.objects.create(- team=self.team, name="enterprise property"- )- tag = Tag.objects.create(name="tag", team_id=self.team.id)-- TaggedItem.objects.create(property_definition_id=property_definition.id, tag_id=tag.id)- with self.assertRaises(ValidationError):- TaggedItem.objects.create(property_definition_id=property_definition.id, tag_id=tag.id)+ self.skipTest("needs the ee app")- def test_uniqueness_constraint_action(self):- action = Action.objects.create(team=self.team, name="enterprise property")+ property_definition = EnterprisePropertyDefinition.objects.create(team=self.team, name="enterprise property")tag = Tag.objects.create(name="tag", team_id=self.team.id)- TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)+ property_definition.tagged_items.create(tag=tag)with self.assertRaises(ValidationError):- TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)+ property_definition.tagged_items.create(tag=tag)class TestTaggedItemGenericColumns(BaseTest):- """The generic pointer is filled from whichever per-model foreign key is set.-- Both shapes are written until the migration finishes, so these assert the new columns- agree with the old ones rather than replace them.- """+ """The pointer columns name the tagged object, and the team follows the tag."""def test_integer_keyed_object_fills_object_id(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)+ tagged_item = dashboard.tagged_items.create(tag=tag)tagged_item.refresh_from_db()assert tagged_item.object_id == dashboard.id@@ -113,7 +114,7 @@ class TestTaggedItemGenericColumns(BaseTest):event_definition = EventDefinition.objects.create(team=self.team, name="event")tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)+ tagged_item = event_definition.tagged_items.create(tag=tag)tagged_item.refresh_from_db()assert tagged_item.object_uuid == event_definition.id@@ -131,21 +132,24 @@ class TestTaggedItemGenericColumns(BaseTest):event_definition = EnterpriseEventDefinition.objects.create(team=self.team, name="enterprise event")tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)+ tagged_item = event_definition.tagged_items.create(tag=tag)tagged_item.refresh_from_db()assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)assert tagged_item.content_type != ContentType.objects.get_for_model(EnterpriseEventDefinition)assert tagged_item.object_uuid == event_definition.id- def test_bulk_create_fills_the_generic_columns(self):+ def test_bulk_create_fills_the_team(self):"""bulk_create never calls save(), and the Zendesk import writes ticket tags through it."""dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")event_definition = EventDefinition.objects.create(team=self.team, name="event")tag = Tag.objects.create(name="tag", team_id=self.team.id)TaggedItem.objects.bulk_create(- [TaggedItem(tag=tag, dashboard=dashboard), TaggedItem(tag=tag, event_definition=event_definition)]+ [+ TaggedItem.for_content_object(tag, dashboard),+ TaggedItem.for_content_object(tag, event_definition),+ ])by_type = {item.related_object_type: item for item in TaggedItem.objects.filter(tag=tag)}@@ -158,33 +162,21 @@ class TestTaggedItemGenericColumns(BaseTest):def test_bulk_create_loads_uncached_tags_once(self):dashboards = [Dashboard.objects.create(team_id=self.team.id, name=f"dashboard {i}") for i in range(3)]tag = Tag.objects.create(name="tag", team_id=self.team.id)- rows = [TaggedItem(tag_id=tag.id, dashboard=dashboard) for dashboard in dashboards]- ContentType.objects.get_for_model(Dashboard)+ content_type = ContentType.objects.get_for_model(Dashboard)+ rows = [+ TaggedItem(tag_id=tag.id, content_type=content_type, object_id=dashboard.id) for dashboard in dashboards+ ]with self.assertNumQueries(2):TaggedItem.objects.bulk_create(rows)assert all(row.team_id == tag.team_id for row in rows)- def test_retargeting_a_row_clears_the_other_object_column(self):- dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")- event_definition = EventDefinition.objects.create(team=self.team, name="event")- tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)-- tagged_item.dashboard = None- tagged_item.event_definition = event_definition- tagged_item.sync_generic_columns()-- assert tagged_item.object_id is None- assert tagged_item.object_uuid == event_definition.id- assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)-- def test_save_with_update_fields_persists_the_generic_columns(self):+ def test_save_with_update_fields_persists_the_team(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)other_team = Team.objects.create(organization=self.organization, name="other")- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)+ tagged_item = dashboard.tagged_items.create(tag=tag)TaggedItem.objects.filter(pk=tagged_item.pk).update(team_id=other_team.id)tagged_item = TaggedItem.objects.get(pk=tagged_item.pk)@@ -196,12 +188,10 @@ class TestTaggedItemGenericColumns(BaseTest):def test_team_follows_the_tag(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")other_team = Team.objects.create(organization=self.organization, name="other")- tagged_item = TaggedItem.objects.create(- dashboard_id=dashboard.id, tag=Tag.objects.create(name="tag", team_id=self.team.id)- )+ tagged_item = dashboard.tagged_items.create(tag=Tag.objects.create(name="tag", team_id=self.team.id))tagged_item.tag = Tag.objects.create(name="tag", team_id=other_team.id)- tagged_item.sync_generic_columns()+ tagged_item.sync_team()assert tagged_item.team_id == other_team.id@@ -209,7 +199,7 @@ class TestTaggedItemGenericColumns(BaseTest):insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)+ tagged_item = insight.tagged_items.create(tag=tag)assert tagged_item.related_object_type == "insight"assert tagged_item.content_object == insight@@ -218,8 +208,8 @@ class TestTaggedItemGenericColumns(BaseTest):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")other_dashboard = Dashboard.objects.create(team_id=self.team.id, name="other dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)- TaggedItem.objects.create(dashboard_id=other_dashboard.id, tag_id=tag.id)+ tagged_item = dashboard.tagged_items.create(tag=tag)+ other_dashboard.tagged_items.create(tag=tag)assert list(TaggedItem.objects.for_object(dashboard)) == [tagged_item]assert TaggedItem.objects.for_model(Dashboard).count() == 2@@ -227,15 +217,15 @@ class TestTaggedItemGenericColumns(BaseTest):class TestTaggedItemsRelation(BaseTest):- def test_reverse_accessor_writes_both_pointer_shapes(self):+ def test_reverse_accessor_writes_the_pointer(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)tagged_item, _ = dashboard.tagged_items.get_or_create(tag=tag)tagged_item.refresh_from_db()- assert tagged_item.dashboard_id == dashboard.idassert tagged_item.object_id == dashboard.id+ assert tagged_item.content_type == ContentType.objects.get_for_model(Dashboard)assert tagged_item.team_id == tag.team_idassert list(dashboard.tagged_items.all()) == [tagged_item]@@ -252,25 +242,7 @@ class TestTaggedItemsRelation(BaseTest):target.tagged_items.set([item])item.refresh_from_db()- assert (item.object_id, item.dashboard_id) == (source.id, source.id)-- def test_reads_ignore_the_legacy_key(self):- followed = Dashboard.objects.create(team_id=self.team.id, name="followed")- ignored = Dashboard.objects.create(team_id=self.team.id, name="ignored")- tag = Tag.objects.create(name="tag", team_id=self.team.id)- item = TaggedItem.objects.create(dashboard_id=followed.id, tag=tag)- TaggedItem.objects.filter(pk=item.pk).update(dashboard_id=ignored.id)- item.refresh_from_db()- both = [followed.pk, ignored.pk]-- assert list(followed.tagged_items.all()) == [item]- assert list(ignored.tagged_items.all()) == []- assert list(Dashboard.objects.filter(tagged_items__tag=tag)) == [followed]- assert list(Dashboard.objects.filter(pk__in=both).exclude(tagged_items__tag=tag)) == [ignored]- prefetched = Dashboard.objects.filter(pk__in=both).prefetch_related("tagged_items")- assert {d.pk: list(d.tagged_items.all()) for d in prefetched} == {followed.pk: [item], ignored.pk: []}- assert list(TaggedItem.objects.for_object(followed)) == [item]- assert item.content_object == followed+ assert item.object_id == source.id@parameterized.expand([("integer key", "dashboard"), ("uuid key", "event_definition")])def test_filter_and_prefetch_through_the_relation(self, _name: str, kind: str):@@ -324,13 +296,13 @@ class TestTaggedItemsRelation(BaseTest):assert not TaggedItem.objects.for_model(Dashboard).exists()- def test_bulk_create_from_content_objects_fills_the_legacy_key(self):+ def test_bulk_create_from_content_objects_fills_the_pointer(self):dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")tag = Tag.objects.create(name="tag", team_id=self.team.id)TaggedItem.objects.bulk_create([TaggedItem.for_content_object(tag, dashboard)])tagged_item = TaggedItem.objects.for_object(dashboard).get()- assert tagged_item.dashboard_id == dashboard.id+ assert tagged_item.object_id == dashboard.idassert tagged_item.related_object_type == "dashboard"assert tagged_item.content_object == dashboarddiff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambrindex 1731e46adf3a..f233c7f0eff7 100644--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr@@ -317,19 +317,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -343,19 +330,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -1287,19 +1261,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -1313,19 +1274,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",diff --git a/posthog/test/repo_invariants/test_taggable_registry.py b/posthog/test/repo_invariants/test_taggable_registry.pyindex 661f6964faf4..665ca1f16bbb 100644--- a/posthog/test/repo_invariants/test_taggable_registry.py+++ b/posthog/test/repo_invariants/test_taggable_registry.py@@ -5,7 +5,7 @@ import pytestfrom django.apps import appsfrom django.db import models-from posthog.models.tagged_item import RELATED_OBJECTS, TaggedItem+from posthog.models.tagged_item import TaggedItemfrom posthog.models.tagged_item_registry import (OBJECT_ID,OBJECT_UUID,@@ -23,10 +23,6 @@ def _model_for(entry: TaggableModel) -> type[models.Model]:return apps.get_model(entry.model_label)-def test_registry_matches_the_foreign_key_fields() -> None:- assert {entry.legacy_field for entry in TAGGABLE_MODELS} == set(RELATED_OBJECTS)--def test_registry_entries_are_unique() -> None:labels = [entry.model_label for entry in TAGGABLE_MODELS]legacy_fields = [entry.legacy_field for entry in TAGGABLE_MODELS]@@ -50,11 +46,6 @@ def test_object_column_matches_the_primary_key_type(entry: TaggableModel) -> Non)[email protected]("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)-def test_registry_points_at_the_same_model_as_the_foreign_key(entry: TaggableModel) -> None:- assert TaggedItem._meta.get_field(entry.legacy_field).related_model is _model_for(entry)--@pytest.mark.parametrize("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)def test_object_column_holds_the_primary_key_range(entry: TaggableModel) -> None:"""`object_id` is a plain integer, so a bigint-keyed model must still fit inside it."""diff --git a/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.py b/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.pydeleted file mode 100644index ede9b6a26b70..000000000000--- a/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.py+++ /dev/null@@ -1,49 +0,0 @@-from typing import Any--from posthog.test.base import NonAtomicTestMigrations---class BackfillTaggedItemGenericPointerTest(NonAtomicTestMigrations):- migrate_from = "1369_taggeditem_legacy_reverse_accessors"- migrate_to = "1373_taggeditem_generic_pointer_unique"-- def setUpBeforeMigration(self, apps: Any) -> None:- tag_model = apps.get_model("posthog", "Tag")- tagged_item_model = apps.get_model("posthog", "TaggedItem")- dashboard_model = apps.get_model("dashboards", "Dashboard")- event_definition_model = apps.get_model("event_definitions", "EventDefinition")-- self.tag_team_id = self.team.id- tag = tag_model.objects.create(name="tag", team_id=self.team.id)- self.dashboard = dashboard_model.objects.create(team_id=self.team.id, name="dashboard")- self.event_definition = event_definition_model.objects.create(team_id=self.team.id, name="event")-- # Historical models skip TaggedItem.save(), so these rows start with no generic pointer,- # like rows written before the pointer columns existed.- self.dashboard_item = tagged_item_model.objects.create(tag=tag, dashboard_id=self.dashboard.id)- self.event_definition_item = tagged_item_model.objects.create(- tag=tag, event_definition_id=self.event_definition.id- )-- def test_backfill_fills_the_generic_pointer(self) -> None:- assert self.apps is not None- tagged_item_model = self.apps.get_model("posthog", "TaggedItem")- content_type_model = self.apps.get_model("contenttypes", "ContentType")-- dashboard_item = tagged_item_model.objects.get(pk=self.dashboard_item.pk)- assert (- dashboard_item.content_type_id- == content_type_model.objects.get(app_label="dashboards", model="dashboard").id- )- assert dashboard_item.object_id == self.dashboard.id- assert dashboard_item.object_uuid is None- assert dashboard_item.team_id == self.tag_team_id-- event_definition_item = tagged_item_model.objects.get(pk=self.event_definition_item.pk)- assert (- event_definition_item.content_type_id- == content_type_model.objects.get(app_label="event_definitions", model="eventdefinition").id- )- assert event_definition_item.object_uuid == self.event_definition.id- assert event_definition_item.object_id is None- assert event_definition_item.team_id == self.tag_team_iddiff --git a/products/actions/backend/api/test/__snapshots__/test_action.ambr b/products/actions/backend/api/test/__snapshots__/test_action.ambrindex 4a7e333879d1..cd1a33da88e0 100644--- a/products/actions/backend/api/test/__snapshots__/test_action.ambr+++ b/products/actions/backend/api/test/__snapshots__/test_action.ambr@@ -459,19 +459,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -1087,19 +1074,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex c535b2b787bf..ebf4bec9ff41 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -96,7 +96,7 @@ class TestCustomerAnalyticsFacade(BaseTest):ignored_at = timezone.now()account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123", ignored_at=ignored_at)tag = Tag.objects.create(name="enterprise", team_id=self.team.id)- TaggedItem.objects.create(tag=tag, account=account)+ account.tagged_items.create(tag=tag)notebook = Notebook.objects.create(team=self.team,created_by=self.user,@@ -242,7 +242,7 @@ class TestCustomerAnalyticsFacade(BaseTest):).model_dump(mode="json"),)tag = Tag.objects.create(name="enterprise", team_id=self.team.id)- TaggedItem.objects.create(tag=tag, account=account)+ account.tagged_items.create(tag=tag)result = facade.get_external_account(self.team.id, "acme-1")@@ -444,7 +444,7 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):def test_create_account_sets_tags(self):view = self._create(name="Tagged", tags=["enterprise", "priority"])account = Account.objects.unscoped().get(id=str(view.id))- assert sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)) == [+ assert sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True)) == ["enterprise","priority",]diff --git a/products/customer_analytics/backend/test/test_upsert_account.py b/products/customer_analytics/backend/test/test_upsert_account.pyindex 037cf600b24c..b4575f929a80 100644--- a/products/customer_analytics/backend/test/test_upsert_account.py+++ b/products/customer_analytics/backend/test/test_upsert_account.py@@ -30,7 +30,7 @@ class TestUpsertAccountTool(BaseTest):async def _tags_for(self, account: Account) -> list[str]:return await sync_to_async(- lambda: sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))+ lambda: sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True)))()@sync_to_asyncdiff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 57876d094e25..8ca4e45004b0 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -949,7 +949,7 @@ class TestAccountViewSet(APIBaseTest):["enterprise", "priority"],)self.assertEqual(- sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)),+ sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True)),["enterprise", "priority"],)diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex c77d1028c9a6..f1debe6e8048 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -786,19 +786,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 1f4b30312885..734865e0477b 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -11845,7 +11845,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):flag = FeatureFlag.objects.get(key="flag-with-eval-tags")# Check that tags are created- tagged_items = TaggedItem.objects.filter(feature_flag=flag)+ tagged_items = TaggedItem.objects.for_object(flag)self.assertEqual(tagged_items.count(), 3)tag_names = sorted([item.tag.name for item in tagged_items])self.assertEqual(tag_names, ["app", "docs", "marketing"])@@ -11938,7 +11938,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):self.assertEqual(FeatureFlagEvaluationContext.objects.filter(feature_flag=flag).count(), 0)# Regular tags should still exist- tagged_items = TaggedItem.objects.filter(feature_flag=flag)+ tagged_items = TaggedItem.objects.for_object(flag)self.assertEqual(tagged_items.count(), 2)@pytest.mark.eediff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.pyindex 200b9b924cd7..6dcb204e046b 100644--- a/products/feature_flags/backend/test/test_max_tools.py+++ b/products/feature_flags/backend/test/test_max_tools.py@@ -620,6 +620,6 @@ class TestCreateFeatureFlagTool(APIBaseTest):@database_sync_to_asyncdef get_tags():- return list(TaggedItem.objects.filter(feature_flag=flag).values_list("tag__name", flat=True))+ return list(TaggedItem.objects.for_object(flag).values_list("tag__name", flat=True))return await get_tags()diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 9b7abd05e125..ef5ae50e4b80 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -6,7 +6,7 @@ from typing import Any, Union, castfrom django.conf import settingsfrom django.db import transaction-from django.db.models import Count, Exists, F, Max, OuterRef, QuerySet+from django.db.models import Count, Exists, F, Max, QuerySetfrom django.db.models.query_utils import Qfrom django.utils.functional import SimpleLazyObjectfrom django.utils.timezone import now@@ -2108,7 +2108,7 @@ class InsightViewSet(if tags_list:# A semi-join returns one row per insight, so the list needs no# `.distinct()` sort over the wide insight JSON columns.- matching_tags = TaggedItem.objects.filter(insight_id=OuterRef("pk"), tag__name__in=tags_list)+ matching_tags = TaggedItem.objects.matching_outer(Insight).filter(tag__name__in=tags_list)queryset = queryset.filter(Exists(matching_tags))elif key == "created_by":created_by_filter = request.GET["created_by"]diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambrindex 490a0c1a7c4f..25c32980db2a 100644--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr@@ -1276,19 +1276,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",@@ -1306,19 +1293,6 @@'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",- "posthog_taggeditem"."dashboard_id",- "posthog_taggeditem"."insight_id",- "posthog_taggeditem"."event_definition_id",- "posthog_taggeditem"."property_definition_id",- "posthog_taggeditem"."action_id",- "posthog_taggeditem"."feature_flag_id",- "posthog_taggeditem"."experiment_saved_metric_id",- "posthog_taggeditem"."ticket_id",- "posthog_taggeditem"."account_id",- "posthog_taggeditem"."endpoint_id",- "posthog_taggeditem"."replay_scanner_id",- "posthog_taggeditem"."project_id",- "posthog_taggeditem"."experiment_id","posthog_taggeditem"."content_type_id","posthog_taggeditem"."object_id","posthog_taggeditem"."object_uuid",diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.pyindex 13ddb81d5bdb..beeb7a3ace83 100644--- a/products/product_analytics/backend/tests/api/test_insight.py+++ b/products/product_analytics/backend/tests/api/test_insight.py@@ -846,14 +846,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)def test_list_does_not_duplicate_insights_with_multiple_matching_tags(self, _name: str, query: str) -> None:from posthog.models.tag import Tag- from posthog.models.tagged_item import TaggedIteminsight = Insight.objects.create(short_id="search-tg", name="needle", team=self.team, filters={"events": [{"id": "$pageview"}]})for tag_name in ("needle-tag-a", "needle-tag-b", "needle-tag-c"):tag = Tag.objects.create(name=tag_name, team=self.team)- TaggedItem.objects.create(insight=insight, tag=tag)+ insight.tagged_items.create(tag=tag)response = self.client.get(f"/api/projects/{self.team.id}/insights/?{query}")assert response.status_code == status.HTTP_200_OKdiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 77414bc6c180..f19033ac6968 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -947,7 +947,7 @@ class TestReplayScannerTags(_VisionAPITestCase):def _tag_names(self, scanner_id: str) -> list[str]:return sorted(- TaggedItem.objects.filter(replay_scanner_id=scanner_id).values_list("tag__name", flat=True),+ TaggedItem.objects.for_objects(ReplayScanner, [scanner_id]).values_list("tag__name", flat=True),)@parameterized.expand(