:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): retire the four foreign keys deprecate_field left orphaned (#98290)
Julian Bez52c6600a3957
diff --git a/posthog/migration_helpers/deprecate_field.py b/posthog/migration_helpers/deprecate_field.pyindex 7a3c75455845..2a004555b7f8 100644--- a/posthog/migration_helpers/deprecate_field.py+++ b/posthog/migration_helpers/deprecate_field.py@@ -88,6 +88,11 @@ def deprecate_field(field_instance: object, raise_on_access: bool = False) -> obmigration 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.+ Not for a foreign key. Hiding one leaves its constraint in the database with no migration+ to remove it, and Django then stops cascading into a relation it cannot see, so the+ deferred constraint fails the parent delete at COMMIT. Retire a relation with+ untrack_field() and DropForeignKey() instead.+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 themodel keeps the ALTER TABLE it needs visible in review and scored by the risk analyzer.@@ -97,6 +102,14 @@ def deprecate_field(field_instance: object, raise_on_access: bool = False) -> obraise_on_access: Raise FieldDeprecatedError instead of logging a warning. Use it toprove no caller is left before the column is dropped."""+ # remote_field covers ForeignKey, OneToOneField and ManyToManyField in one test, where an+ # isinstance check on ForeignKey alone would let the other two through.+ if getattr(field_instance, "remote_field", None) is not None:+ raise FieldDeprecatedError(+ "deprecate_field() cannot hide a relation. It writes no migration, so the foreign key "+ "constraint would stay with nothing to remove it, and a parent delete would then fail "+ "at COMMIT. Use untrack_field() with DropForeignKey() in a migration instead."+ )if getattr(field_instance, "null", False) is not True:raise FieldDeprecatedError("deprecate_field() needs a field that is already null=True, because nothing writes "diff --git a/posthog/migration_helpers/test_deprecate_field.py b/posthog/migration_helpers/test_deprecate_field.pyindex f44040de680e..a9ae2e9412e5 100644--- a/posthog/migration_helpers/test_deprecate_field.py+++ b/posthog/migration_helpers/test_deprecate_field.py@@ -37,6 +37,18 @@ def test_a_migration_command_in_a_later_argument_does_not_count() -> None:assert isinstance(deprecate_field(models.CharField(max_length=8, null=True)), DeprecatedField)+ [+ ("foreign_key", models.ForeignKey("posthog.Team", null=True, on_delete=models.CASCADE)),+ ("one_to_one", models.OneToOneField("posthog.Team", null=True, on_delete=models.CASCADE)),+ ("many_to_many", models.ManyToManyField("posthog.Team")),+ ]+)+def test_a_relation_is_refused(_name: str, field: models.Field) -> None:+ with pytest.raises(FieldDeprecatedError, match="untrack_field"):+ deprecate_field(field)++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))diff --git a/products/error_tracking/backend/migrations/0037_untrack_assignment_user_group.py b/products/error_tracking/backend/migrations/0037_untrack_assignment_user_group.pynew file mode 100644index 000000000000..225c1282facd--- /dev/null+++ b/products/error_tracking/backend/migrations/0037_untrack_assignment_user_group.py@@ -0,0 +1,44 @@+from django.db import migrations++from posthog.migration_helpers import DropForeignKey, untrack_field+++class Migration(migrations.Migration):+ """Take the `user_group` fields out of Django's state and drop their constraints.++ deprecate_field() had hidden these three columns from the ORM, so Django stopped+ cascading into them while their foreign keys to posthog_usergroup stayed. Those+ constraints are DEFERRABLE INITIALLY DEFERRED, so deleting a user group finished its+ cascade and then failed at COMMIT. Team deletion reaches the same failure, because a+ team delete cascades into its user groups.++ The columns stay. Only Django's state and the constraints change here.+ """++ dependencies = [+ ("error_tracking", "0036_add_stackframe_js_frames_index"),+ ]++ operations = [+ untrack_field(+ "errortrackingissueassignment",+ "user_group",+ database_operations=[+ DropForeignKey("posthog_errortrackingissueassignment", column="user_group_id"),+ ],+ ),+ untrack_field(+ "errortrackinggroupingrule",+ "user_group",+ database_operations=[+ DropForeignKey("posthog_errortrackinggroupingrule", column="user_group_id"),+ ],+ ),+ untrack_field(+ "errortrackingassignmentrule",+ "user_group",+ database_operations=[+ DropForeignKey("posthog_errortrackingassignmentrule", column="user_group_id"),+ ],+ ),+ ]diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txtindex c49f8d127df4..ac37b6e638d6 100644--- a/products/error_tracking/backend/migrations/max_migration.txt+++ b/products/error_tracking/backend/migrations/max_migration.txt@@ -1 +1 @@-0036_add_stackframe_js_frames_index+0037_untrack_assignment_user_groupdiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 719f8170208f..029f06771c73 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -222,7 +222,6 @@ class ErrorTrackingIssueAssignment(UUIDTModel):team = models.ForeignKey("posthog.Team", null=True, on_delete=models.CASCADE, db_index=False, related_name="+")user = models.ForeignKey("posthog.User", null=True, on_delete=models.CASCADE, related_name="+")# DEPRECATED: issues can only be assigned to users or roles- user_group = deprecate_field(models.ForeignKey("posthog.UserGroup", null=True, on_delete=models.CASCADE))role = models.ForeignKey("ee.Role", null=True, on_delete=models.CASCADE, related_name="+")created_at = models.DateTimeField(auto_now_add=True)@@ -428,7 +427,6 @@ class ErrorTrackingAssignmentRule(UUIDTModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")user = models.ForeignKey("posthog.User", null=True, on_delete=models.CASCADE, related_name="+")# DEPRECATED: issues can only be assigned to users or roles- user_group = deprecate_field(models.ForeignKey("posthog.UserGroup", null=True, on_delete=models.CASCADE))role = models.ForeignKey("ee.Role", null=True, on_delete=models.CASCADE, related_name="+")order_key = models.IntegerField(null=False, blank=False)bytecode = models.JSONField(null=False, blank=False) # The bytecode of the rule@@ -490,7 +488,6 @@ class ErrorTrackingGroupingRule(UUIDTModel):# in so far as we permit all of these to be nulluser = models.ForeignKey("posthog.User", null=True, on_delete=models.CASCADE, related_name="+")# DEPRECATED: issues can only be assigned to users or roles- user_group = deprecate_field(models.ForeignKey("posthog.UserGroup", null=True, on_delete=models.CASCADE))role = models.ForeignKey("ee.Role", null=True, on_delete=models.CASCADE, related_name="+")# Users will probably find it convenient to be able to add a short description to grouping rulesdiff --git a/products/signals/backend/migrations/0127_untrack_signalreport_conversation.py b/products/signals/backend/migrations/0127_untrack_signalreport_conversation.pynew file mode 100644index 000000000000..509cb5b4ba6f--- /dev/null+++ b/products/signals/backend/migrations/0127_untrack_signalreport_conversation.py@@ -0,0 +1,28 @@+from django.db import migrations++from posthog.migration_helpers import DropForeignKey, untrack_field+++class Migration(migrations.Migration):+ """Take `conversation` out of Django's state and drop its constraint.++ deprecate_field() had hidden the column from the ORM, so Django stopped setting it to+ NULL when a conversation was deleted while the foreign key stayed. The constraint is+ DEFERRABLE INITIALLY DEFERRED, so the delete finished and then failed at COMMIT.++ The column stays. Only Django's state and the constraint change here.+ """++ dependencies = [+ ("signals", "0126_signalteamconfig_issue_tracking_config_and_more"),+ ]++ operations = [+ untrack_field(+ "signalreport",+ "conversation",+ database_operations=[+ DropForeignKey("signals_signalreport", column="conversation_id"),+ ],+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex 2528dd8bdd6c..0f66021efe96 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0126_signalteamconfig_issue_tracking_config_and_more+0127_untrack_signalreport_conversationdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 1c2487293e47..3f346a24a9a6 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -340,9 +340,6 @@ class SignalReport(UUIDModel):)cluster_centroid_updated_at = deprecate_field(models.DateTimeField(blank=True, null=True))# Deprecated - unused- conversation = deprecate_field(- models.ForeignKey("posthog_ai.Conversation", null=True, blank=True, on_delete=models.SET_NULL)- )relevant_user_count = deprecate_field(models.IntegerField(blank=True, null=True))class Meta: