Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): keep the replay relink alive under activity-signal muting (#86720)

Phil Haackcea364fcfc1d
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index 85f8eac75236..28ebe8612c06 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -56,6 +56,15 @@
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.11
+ '''
+ SELECT "posthog_featureflag"."key" AS "key"
+ FROM "posthog_featureflag"
+ WHERE "posthog_featureflag"."id" = 99999
+ ORDER BY "posthog_featureflag"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -80,7 +89,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.13
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -103,7 +112,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.13
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.14
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -237,7 +246,7 @@
AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.14
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.15
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -256,7 +265,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.15
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.16
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -273,7 +282,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.16
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.17
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -292,7 +301,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.17
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.18
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -311,7 +320,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.18
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -356,7 +365,24 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.2
+ '''
+ SELECT "posthog_organizationintegration"."id",
+ "posthog_organizationintegration"."organization_id",
+ "posthog_organizationintegration"."kind",
+ "posthog_organizationintegration"."integration_id",
+ "posthog_organizationintegration"."config",
+ "posthog_organizationintegration"."sensitive_config",
+ "posthog_organizationintegration"."created_by_id",
+ "posthog_organizationintegration"."created_at",
+ "posthog_organizationintegration"."updated_at"
+ FROM "posthog_organizationintegration"
+ WHERE ("posthog_organizationintegration"."kind" = 'vercel'
+ AND "posthog_organizationintegration"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.20
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -401,24 +427,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.2
- '''
- SELECT "posthog_organizationintegration"."id",
- "posthog_organizationintegration"."organization_id",
- "posthog_organizationintegration"."kind",
- "posthog_organizationintegration"."integration_id",
- "posthog_organizationintegration"."config",
- "posthog_organizationintegration"."sensitive_config",
- "posthog_organizationintegration"."created_by_id",
- "posthog_organizationintegration"."created_at",
- "posthog_organizationintegration"."updated_at"
- FROM "posthog_organizationintegration"
- WHERE ("posthog_organizationintegration"."kind" = 'vercel'
- AND "posthog_organizationintegration"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)
- LIMIT 21
- '''
-# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.20
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -429,7 +438,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.22
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -440,7 +449,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.22
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -485,7 +494,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -587,7 +596,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -624,7 +633,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -726,7 +735,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -771,7 +780,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -818,7 +827,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -848,36 +857,6 @@
UPDATE
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
- '''
- SELECT "posthog_featureflag"."id",
- "posthog_featureflag"."key",
- "posthog_featureflag"."name",
- "posthog_featureflag"."filters",
- "posthog_featureflag"."team_id",
- "posthog_featureflag"."created_by_id",
- "posthog_featureflag"."created_at",
- "posthog_featureflag"."updated_at",
- "posthog_featureflag"."deleted",
- "posthog_featureflag"."active",
- "posthog_featureflag"."archived",
- "posthog_featureflag"."version",
- "posthog_featureflag"."last_modified_by_id",
- "posthog_featureflag"."ensure_experience_continuity",
- "posthog_featureflag"."usage_dashboard_id",
- "posthog_featureflag"."has_enriched_analytics",
- "posthog_featureflag"."is_remote_configuration",
- "posthog_featureflag"."has_encrypted_payloads",
- "posthog_featureflag"."evaluation_runtime",
- "posthog_featureflag"."bucketing_identifier",
- "posthog_featureflag"."last_called_at"
- FROM "posthog_featureflag"
- WHERE (NOT ("posthog_featureflag"."deleted")
- AND "posthog_featureflag"."id" = 99999)
- ORDER BY "posthog_featureflag"."id" ASC
- LIMIT 1
- '''
-# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.3
'''
SELECT "posthog_scheduledchange"."id",
@@ -950,6 +929,36 @@
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.30
+ '''
+ SELECT "posthog_featureflag"."id",
+ "posthog_featureflag"."key",
+ "posthog_featureflag"."name",
+ "posthog_featureflag"."filters",
+ "posthog_featureflag"."team_id",
+ "posthog_featureflag"."created_by_id",
+ "posthog_featureflag"."created_at",
+ "posthog_featureflag"."updated_at",
+ "posthog_featureflag"."deleted",
+ "posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
+ "posthog_featureflag"."version",
+ "posthog_featureflag"."last_modified_by_id",
+ "posthog_featureflag"."ensure_experience_continuity",
+ "posthog_featureflag"."usage_dashboard_id",
+ "posthog_featureflag"."has_enriched_analytics",
+ "posthog_featureflag"."is_remote_configuration",
+ "posthog_featureflag"."has_encrypted_payloads",
+ "posthog_featureflag"."evaluation_runtime",
+ "posthog_featureflag"."bucketing_identifier",
+ "posthog_featureflag"."last_called_at"
+ FROM "posthog_featureflag"
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND "posthog_featureflag"."id" = 99999)
+ ORDER BY "posthog_featureflag"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.31
'''
SELECT "posthog_featureflag"."active" AS "active",
"posthog_featureflag"."deleted" AS "deleted",
@@ -961,7 +970,16 @@
LIMIT 1
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.31
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32
+ '''
+ SELECT "posthog_featureflag"."key" AS "key"
+ FROM "posthog_featureflag"
+ WHERE "posthog_featureflag"."id" = 99999
+ ORDER BY "posthog_featureflag"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -986,7 +1004,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -1009,7 +1027,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -1143,7 +1161,7 @@
AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -1162,7 +1180,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -1179,7 +1197,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -1198,7 +1216,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -1217,7 +1235,44 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.4
+ '''
+ SELECT "posthog_featureflag"."id",
+ "posthog_featureflag"."key",
+ "posthog_featureflag"."name",
+ "posthog_featureflag"."filters",
+ "posthog_featureflag"."team_id",
+ "posthog_featureflag"."created_by_id",
+ "posthog_featureflag"."created_at",
+ "posthog_featureflag"."updated_at",
+ "posthog_featureflag"."deleted",
+ "posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
+ "posthog_featureflag"."version",
+ "posthog_featureflag"."last_modified_by_id",
+ "posthog_featureflag"."ensure_experience_continuity",
+ "posthog_featureflag"."usage_dashboard_id",
+ "posthog_featureflag"."has_enriched_analytics",
+ "posthog_featureflag"."is_remote_configuration",
+ "posthog_featureflag"."has_encrypted_payloads",
+ "posthog_featureflag"."evaluation_runtime",
+ "posthog_featureflag"."bucketing_identifier",
+ "posthog_featureflag"."last_called_at"
+ FROM "posthog_featureflag"
+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND ("posthog_featureflag"."team_id" =
+ (SELECT U0."parent_team_id" AS "parent_team_id"
+ FROM "posthog_team" U0
+ WHERE U0."id" = 99999
+ LIMIT 1)
+ OR ("posthog_team"."parent_team_id" IS NULL
+ AND "posthog_featureflag"."team_id" = 99999))
+ AND "posthog_featureflag"."id" = 99999)
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.40
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -1262,7 +1317,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -1307,44 +1362,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.4
- '''
- SELECT "posthog_featureflag"."id",
- "posthog_featureflag"."key",
- "posthog_featureflag"."name",
- "posthog_featureflag"."filters",
- "posthog_featureflag"."team_id",
- "posthog_featureflag"."created_by_id",
- "posthog_featureflag"."created_at",
- "posthog_featureflag"."updated_at",
- "posthog_featureflag"."deleted",
- "posthog_featureflag"."active",
- "posthog_featureflag"."archived",
- "posthog_featureflag"."version",
- "posthog_featureflag"."last_modified_by_id",
- "posthog_featureflag"."ensure_experience_continuity",
- "posthog_featureflag"."usage_dashboard_id",
- "posthog_featureflag"."has_enriched_analytics",
- "posthog_featureflag"."is_remote_configuration",
- "posthog_featureflag"."has_encrypted_payloads",
- "posthog_featureflag"."evaluation_runtime",
- "posthog_featureflag"."bucketing_identifier",
- "posthog_featureflag"."last_called_at"
- FROM "posthog_featureflag"
- INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
- WHERE (NOT ("posthog_featureflag"."deleted")
- AND ("posthog_featureflag"."team_id" =
- (SELECT U0."parent_team_id" AS "parent_team_id"
- FROM "posthog_team" U0
- WHERE U0."id" = 99999
- LIMIT 1)
- OR ("posthog_team"."parent_team_id" IS NULL
- AND "posthog_featureflag"."team_id" = 99999))
- AND "posthog_featureflag"."id" = 99999)
- LIMIT 21
- '''
-# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.40
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1355,7 +1373,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.43
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1366,7 +1384,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.44
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -1411,7 +1429,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.43
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.45
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1513,7 +1531,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.44
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.46
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1539,7 +1557,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.45
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.47
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1565,7 +1583,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.46
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.48
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1591,7 +1609,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.47
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.49
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1617,35 +1635,6 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.48
- '''
- SELECT "posthog_featureflag"."id",
- "posthog_featureflag"."key",
- "posthog_featureflag"."name",
- "posthog_featureflag"."filters",
- "posthog_featureflag"."team_id",
- "posthog_featureflag"."created_by_id",
- "posthog_featureflag"."created_at",
- "posthog_featureflag"."updated_at",
- "posthog_featureflag"."deleted",
- "posthog_featureflag"."active",
- "posthog_featureflag"."archived",
- "posthog_featureflag"."version",
- "posthog_featureflag"."last_modified_by_id",
- "posthog_featureflag"."ensure_experience_continuity",
- "posthog_featureflag"."usage_dashboard_id",
- "posthog_featureflag"."has_enriched_analytics",
- "posthog_featureflag"."is_remote_configuration",
- "posthog_featureflag"."has_encrypted_payloads",
- "posthog_featureflag"."evaluation_runtime",
- "posthog_featureflag"."bucketing_identifier",
- "posthog_featureflag"."last_called_at"
- FROM "posthog_featureflag"
- WHERE (NOT ("posthog_featureflag"."deleted")
- AND "posthog_featureflag"."key" = 'flag-1')
- LIMIT 21
- '''
-# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.5
'''
SELECT "posthog_team"."id",
@@ -1748,6 +1737,35 @@
LIMIT 21
'''
# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.50
+ '''
+ SELECT "posthog_featureflag"."id",
+ "posthog_featureflag"."key",
+ "posthog_featureflag"."name",
+ "posthog_featureflag"."filters",
+ "posthog_featureflag"."team_id",
+ "posthog_featureflag"."created_by_id",
+ "posthog_featureflag"."created_at",
+ "posthog_featureflag"."updated_at",
+ "posthog_featureflag"."deleted",
+ "posthog_featureflag"."active",
+ "posthog_featureflag"."archived",
+ "posthog_featureflag"."version",
+ "posthog_featureflag"."last_modified_by_id",
+ "posthog_featureflag"."ensure_experience_continuity",
+ "posthog_featureflag"."usage_dashboard_id",
+ "posthog_featureflag"."has_enriched_analytics",
+ "posthog_featureflag"."is_remote_configuration",
+ "posthog_featureflag"."has_encrypted_payloads",
+ "posthog_featureflag"."evaluation_runtime",
+ "posthog_featureflag"."bucketing_identifier",
+ "posthog_featureflag"."last_called_at"
+ FROM "posthog_featureflag"
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND "posthog_featureflag"."key" = 'flag-1')
+ LIMIT 21
+ '''
+# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.6
'''
SELECT "posthog_organization"."id",
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index c8084c1f2dcb..58debb86ba69 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -35,7 +35,6 @@ model_activity:products.data_tools.backend.activity_logging.handle_expression_ac
model_activity:products.experiments.backend.activity_logging.handle_experiment_change
model_activity:products.exports.backend.models.subscription.log_subscription_activity
model_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_change
-model_activity:products.feature_flags.backend.session_recording_links.relink_teams_on_key_change
model_activity:products.legal_documents.backend.signals.handle_legal_document_change
model_activity:products.logs.backend.activity_logging.handle_logs_alert_activity
model_activity:products.logs.backend.activity_logging.handle_logs_retention_rule_activity
@@ -197,6 +196,7 @@ post_save:products.feature_flags.backend.local_evaluation.evaluation_context_cha
post_save:products.feature_flags.backend.local_evaluation.evaluation_context_name_changed
post_save:products.feature_flags.backend.local_evaluation.experiment_changed
post_save:products.feature_flags.backend.local_evaluation.feature_flag_changed
+post_save:products.feature_flags.backend.session_recording_links.relink_teams_on_key_change
post_save:products.managed_warehouse.backend.models._observe_duckgres_server_save
post_save:products.review_hog.backend.receivers.handle_task_run_saved
post_save:products.signals.backend.receivers.capture_status_change_analytics
@@ -256,6 +256,7 @@ pre_save:products.customer_analytics.backend.models.account._enforce_account_gro
pre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name
pre_save:products.feature_flags.backend.flag_version_sync.capture_cohort_definition_before_save
pre_save:products.feature_flags.backend.flag_version_sync.capture_flag_definition_before_save
+pre_save:products.feature_flags.backend.session_recording_links.capture_replay_link_key_before_save
pre_save:products.signals.backend.receivers.capture_prior_state
pre_save:products.surveys.backend.models.pre_save_survey
user_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activity
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 2bbffe7a4e72..b529eb70d224 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -120,6 +120,7 @@ from products.feature_flags.backend.session_recording_links import (
REPLAY_LINKED_FLAG_DELETE_ERROR,
replay_linked_flag_ids,
teams_linking_flag,
+ teams_linking_flag_in_project,
)
from products.feature_flags.backend.types import PropertyFilterType
from products.feature_flags.backend.user_blast_radius import get_user_blast_radius
@@ -1948,24 +1949,39 @@ class FeatureFlagSerializer(
soft_deleted_qs = soft_deleted_qs.exclude(pk=exclude_pk)
for flag in soft_deleted_qs:
+ if teams_linking_flag_in_project(self.context["project_id"], flag.id).exists():
+ # Hard-deleting fires no save, so nothing relinks the teams gating replay on
+ # this tombstone and they keep the key the new flag is about to claim. Rename
+ # instead and `relink_teams_on_key_change` moves them onto the tombstone. The
+ # blocker check still runs first: renaming a flag an active dependent references
+ # would silently break that dependent, whether or not a team links it for replay.
+ self._raise_if_key_reuse_blocked(flag)
+ flag.key = flag.tombstoned_key()
+ flag.save(update_fields=["key"])
+ continue
try:
flag.delete()
except (deletion.RestrictedError, deletion.ProtectedError):
- blockers = []
- active_experiment_ids = list(flag.experiment_set.filter(deleted=False).values_list("id", flat=True))
- if active_experiment_ids:
- blockers.append(f"active experiment(s) with ID(s): {', '.join(map(str, active_experiment_ids))}")
- eaf_count = flag.features.count()
- if eaf_count:
- blockers.append(f"{eaf_count} early access feature(s)")
- if blockers:
- raise exceptions.ValidationError(
- f"Cannot reuse key '{flag.key}': a soft-deleted flag with this key is still "
- f"referenced by {' and '.join(blockers)}. Please contact support."
- )
+ self._raise_if_key_reuse_blocked(flag)
flag.key = flag.tombstoned_key()
flag.save(update_fields=["key"])
+ def _raise_if_key_reuse_blocked(self, flag: FeatureFlag) -> None:
+ # An active dependent (Experiment via RESTRICT, EarlyAccessFeature via PROTECT) means the
+ # tombstone can't be freed without silently breaking that dependent, so refuse the reuse.
+ blockers = []
+ active_experiment_ids = list(flag.experiment_set.filter(deleted=False).values_list("id", flat=True))
+ if active_experiment_ids:
+ blockers.append(f"active experiment(s) with ID(s): {', '.join(map(str, active_experiment_ids))}")
+ eaf_count = flag.features.count()
+ if eaf_count:
+ blockers.append(f"{eaf_count} early access feature(s)")
+ if blockers:
+ raise exceptions.ValidationError(
+ f"Cannot reuse key '{flag.key}': a soft-deleted flag with this key is still "
+ f"referenced by {' and '.join(blockers)}. Please contact support."
+ )
+
def _reraise_duplicate_key_violation(self, exc: IntegrityError) -> NoReturn:
# The "unique key for team" DB constraint is the authoritative guard on key
# uniqueness. A concurrent create or rename can slip a duplicate in between the
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 9dc9b8ee1acb..8e8de5291496 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -37,6 +37,7 @@ from posthog.models.group.util import create_group
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.signals import mute_selected_signals
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -8116,9 +8117,13 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_active_experiment(self, mode: str):
# If a tombstone is still referenced by an active experiment (invariant
# violation), renaming it would silently break the experiment. Error out.
+ # A team gating replay on the tombstone must not change that: the replay relink
+ # takes the rename path, which would otherwise skip this check.
legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="inconsistent-key")
exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=legacy_flag)
FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)
+ self.team.session_recording_linked_flag = {"id": legacy_flag.id, "key": "inconsistent-key"}
+ self.team.save()
if mode == "create":
response = self.client.post(
@@ -8149,7 +8154,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
def test_reuse_key_with_inconsistent_soft_deleted_flag_referenced_by_eaf(self, mode: str):
# EarlyAccessFeature.feature_flag uses on_delete=PROTECT (sibling of
# RESTRICT). A tombstone with an EAF must surface the same defensive
- # error, not a 500.
+ # error, not a 500. A team gating replay on it must not skip that check
+ # by diverting to the rename path.
legacy_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="eaf-key")
EarlyAccessFeature.objects.create(
team=self.team,
@@ -8159,6 +8165,8 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
feature_flag=legacy_flag,
)
FeatureFlag.objects_including_soft_deleted.filter(pk=legacy_flag.pk).update(deleted=True)
+ self.team.session_recording_linked_flag = {"id": legacy_flag.id, "key": "eaf-key"}
+ self.team.save()
if mode == "create":
response = self.client.post(
@@ -14550,3 +14558,48 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):
sibling_team.refresh_from_db()
assert sibling_team.session_recording_linked_flag == linked_flag_before
assert sibling_team.id not in {call.args[0] for call in mock_refresh.call_args_list}
+
+ def test_rename_still_relinks_teams_while_the_activity_signal_is_muted(self) -> None:
+ # mute_selected_signals is for mass-deletion scenarios where firing the activity-log
+ # signal thousands of times would be wasteful, but it silences every @mutable_receiver
+ # indiscriminately. Muting the audit log must not also stop teams recording sessions.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate")
+ self._link_flag(self.team, {"id": flag.id, "key": "replay-gate"})
+
+ with self.captureOnCommitCallbacks(execute=True):
+ with mute_selected_signals():
+ flag.key = "replay-gate-v2"
+ flag.save()
+
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+
+ @parameterized.expand([("create",), ("rename",)])
+ def test_freeing_a_tombstoned_key_relinks_teams_to_the_tombstone(self, mode: str) -> None:
+ # Nothing here blocks the hard delete, which is what makes this the interesting case:
+ # a hard delete fires no save, so a team gating replay on this tombstone would be left
+ # on the key the new flag is about to claim. _free_key_held_by_soft_deleted_flags keeps
+ # the row and renames it instead, and the relink follows it to the tombstone. The rename
+ # path frees the key inside the update transaction, where the tombstone and the claiming
+ # flag each schedule their own relink, so it needs its own coverage.
+ old_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate", deleted=True)
+ self._link_flag(self.team, {"id": old_flag.id, "key": "replay-gate"})
+
+ with self.captureOnCommitCallbacks(execute=True):
+ if mode == "create":
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"name": "New gate", "key": "replay-gate"},
+ )
+ else:
+ claiming_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-tmp")
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{claiming_flag.id}/",
+ {"key": "replay-gate"},
+ )
+
+ assert response.status_code in (status.HTTP_200_OK, status.HTTP_201_CREATED), response.content
+ old_flag.refresh_from_db()
+ assert old_flag.key == f"replay-gate:deleted:{old_flag.id}"
+ self.team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": old_flag.id, "key": old_flag.key}
diff --git a/products/feature_flags/backend/field_snapshots.py b/products/feature_flags/backend/field_snapshots.py
new file mode 100644
index 000000000000..6863126aa2a4
--- /dev/null
+++ b/products/feature_flags/backend/field_snapshots.py
@@ -0,0 +1,50 @@
+"""Snapshots a model's persisted field values across a save, for signal receivers that act
+only when a save really changed something.
+
+A ``pre_save`` receiver stores the values the save is about to overwrite; its ``post_save``
+counterpart compares them against the instance. Each receiver passes its own attribute and
+field set, so two features watching the same model never depend on which fields the other
+happens to watch.
+"""
+
+from typing import Any
+
+from django.db import models
+
+
+def capture_fields_before_save(
+ instance: models.Model,
+ manager: models.Manager[Any],
+ fields: frozenset[str],
+ *,
+ attr: str,
+ update_fields: frozenset[str] | None,
+ raw: bool,
+) -> None:
+ """Snapshot the persisted fields this save may overwrite.
+
+ Always resets the snapshot first so a failed earlier save can never leak a stale
+ capture into a later save's comparison.
+ """
+ setattr(instance, attr, None)
+ if raw or instance.pk is None:
+ return
+ # Only fields this save will actually persist: a field changed in memory but excluded
+ # from update_fields is not written, so it must not count.
+ persisted_fields = fields if update_fields is None else fields.intersection(update_fields)
+ if not persisted_fields:
+ return
+ # sorted(): set iteration order varies between processes, and it reaches the SELECT's
+ # column list — an unstable query string defeats plan reuse and makes the query
+ # snapshots that cover flag saves fail at random.
+ setattr(instance, attr, manager.filter(pk=instance.pk).values(*sorted(persisted_fields)).first())
+
+
+def snapshot_if_changed(instance: models.Model, *, attr: str) -> dict[str, Any] | None:
+ """Pop the pre_save snapshot and return it only if a snapshotted value changed."""
+ before = instance.__dict__.pop(attr, None)
+ if before is None:
+ return None
+ if all(getattr(instance, field) == value for field, value in before.items()):
+ return None
+ return before
diff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.py
index 4daa58d6bd59..1138b30c02fd 100644
--- a/products/feature_flags/backend/flag_version_sync.py
+++ b/products/feature_flags/backend/flag_version_sync.py
@@ -30,7 +30,7 @@ pre-bump versions.
from collections import defaultdict
from typing import Any
-from django.db import models, transaction
+from django.db import transaction
from django.db.models import Value
from django.db.models.functions import Coalesce
from django.db.models.signals import post_save, pre_save
@@ -43,6 +43,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, LogActi
from posthog.models.activity_logging.utils import activity_storage
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
+from products.feature_flags.backend.field_snapshots import capture_fields_before_save, snapshot_if_changed
from products.feature_flags.backend.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -71,42 +72,6 @@ FLAG_DEFINITION_FIELDS = frozenset({"filters", "active", "deleted", "key"})
_DEFINITION_BEFORE_SAVE_ATTR = "_definition_before_save"
-def _capture_definition_before_save(
- instance: models.Model,
- manager: models.Manager[Any],
- definition_fields: frozenset[str],
- update_fields: frozenset[str] | None,
- raw: bool,
-) -> None:
- """Snapshot the persisted definition fields this save may overwrite.
-
- Always resets the snapshot first so a failed earlier save can never leak a stale
- capture into a later save's comparison.
- """
- setattr(instance, _DEFINITION_BEFORE_SAVE_ATTR, None)
- if raw or instance.pk is None:
- return
- # Only fields this save will actually persist: a definition field changed in
- # memory but excluded from update_fields is not written, so it must not count.
- fields = definition_fields if update_fields is None else definition_fields.intersection(update_fields)
- if not fields:
- return
- # sorted(): set iteration order varies between processes, and it reaches the SELECT's
- # column list — an unstable query string defeats plan reuse and makes the query
- # snapshots that cover flag saves fail at random.
- setattr(instance, _DEFINITION_BEFORE_SAVE_ATTR, manager.filter(pk=instance.pk).values(*sorted(fields)).first())
-
-
-def _changed_definition_fields(instance: models.Model) -> dict[str, Any] | None:
- """Pop the pre_save snapshot and return it only if a snapshotted value changed."""
- before = instance.__dict__.pop(_DEFINITION_BEFORE_SAVE_ATTR, None)
- if before is None:
- return None
- if all(getattr(instance, field) == value for field, value in before.items()):
- return None
- return before
-
-
@receiver(pre_save, sender=Cohort)
def capture_cohort_definition_before_save(
sender: type[Cohort],
@@ -115,7 +80,14 @@ def capture_cohort_definition_before_save(
update_fields: frozenset[str] | None = None,
**kwargs: Any,
) -> None:
- _capture_definition_before_save(instance, Cohort.objects, COHORT_DEFINITION_FIELDS, update_fields, raw)
+ capture_fields_before_save(
+ instance,
+ Cohort.objects,
+ COHORT_DEFINITION_FIELDS,
+ attr=_DEFINITION_BEFORE_SAVE_ATTR,
+ update_fields=update_fields,
+ raw=raw,
+ )
@receiver(pre_save, sender=FeatureFlag)
@@ -128,8 +100,13 @@ def capture_flag_definition_before_save(
) -> None:
# objects_including_soft_deleted so restoring a soft-deleted flag reads as a
# deleted True -> False change instead of snapshotting nothing.
- _capture_definition_before_save(
- instance, FeatureFlag.objects_including_soft_deleted, FLAG_DEFINITION_FIELDS, update_fields, raw
+ capture_fields_before_save(
+ instance,
+ FeatureFlag.objects_including_soft_deleted,
+ FLAG_DEFINITION_FIELDS,
+ attr=_DEFINITION_BEFORE_SAVE_ATTR,
+ update_fields=update_fields,
+ raw=raw,
)
@@ -143,7 +120,7 @@ def bump_flag_versions_on_cohort_definition_change(
) -> None:
if raw or created:
return
- if _changed_definition_fields(instance) is None:
+ if snapshot_if_changed(instance, attr=_DEFINITION_BEFORE_SAVE_ATTR) is None:
return
project_id = instance.team.project_id
@@ -171,7 +148,7 @@ def bump_dependent_flag_versions_on_flag_definition_change(
) -> None:
if raw or created:
return
- before = _changed_definition_fields(instance)
+ before = snapshot_if_changed(instance, attr=_DEFINITION_BEFORE_SAVE_ATTR)
if before is None:
return
# An already-deleted flag is in no payload, so edits to it (e.g. the tombstone rename
diff --git a/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py b/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py
index aaf7efe5b7b3..5390230c2cbc 100644
--- a/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py
+++ b/products/feature_flags/backend/management/commands/repair_replay_linked_flag_keys.py
@@ -15,17 +15,17 @@ still wants a recording gate at all.
import json
from collections import Counter
from collections.abc import Iterator
-from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.db.models import QuerySet
+from posthog.dataclasses import frozen
from posthog.models import Team
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.feature_flags.backend.session_recording_links import update_linked_flag_key
+from products.feature_flags.backend.session_recording_links import linked_flag_id, update_linked_flag_key
class Outcome(StrEnum):
@@ -37,7 +37,7 @@ class Outcome(StrEnum):
MALFORMED = "malformed"
-@dataclass(frozen=True, kw_only=True)
+@frozen
class _FlagRow:
key: str
deleted: bool
@@ -57,19 +57,6 @@ def _iter_team_chunks(queryset: QuerySet[Team], chunk_size: int) -> Iterator[lis
last_id = chunk[-1].id
-def _linked_flag_id(linked_flag: Any) -> int | None:
- if not isinstance(linked_flag, dict):
- return None
- stored_id = linked_flag.get("id")
- # The column is schemaless, so anything an API client or the admin's JSON widget sent can be
- # here. Only an int is acted on; every other shape is reported as malformed for a human to
- # look at rather than coerced. `bool` is excluded explicitly because it subclasses `int`, so
- # `{"id": true}` would otherwise repair against flag 1.
- if isinstance(stored_id, bool) or not isinstance(stored_id, int):
- return None
- return stored_id
-
-
class Command(BaseCommand):
help = "Rewrite stale flag keys in teams' session replay linked flag settings"
@@ -121,7 +108,7 @@ class Command(BaseCommand):
def _load_flags(self, teams: list[Team]) -> dict[int, _FlagRow]:
flag_ids = {
- flag_id for team in teams if (flag_id := _linked_flag_id(team.session_recording_linked_flag)) is not None
+ flag_id for team in teams if (flag_id := linked_flag_id(team.session_recording_linked_flag)) is not None
}
if not flag_ids:
return {}
@@ -139,7 +126,7 @@ class Command(BaseCommand):
linked_flag = team.session_recording_linked_flag
detail: dict[str, Any] = {"team_id": team.id, "project_id": team.project_id, "linked_flag": linked_flag}
- stored_id = _linked_flag_id(linked_flag)
+ stored_id = linked_flag_id(linked_flag)
if stored_id is None:
return Outcome.MALFORMED, detail
diff --git a/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py b/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py
index c354eaef58fd..d16b7650ac0b 100644
--- a/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py
+++ b/products/feature_flags/backend/management/commands/test/test_repair_replay_linked_flag_keys.py
@@ -5,6 +5,7 @@ from typing import Any
from posthog.test.base import BaseTest
from django.core.management import call_command
+from django.core.management.base import CommandError
from parameterized import parameterized
@@ -127,3 +128,26 @@ class TestRepairReplayLinkedFlagKeys(BaseTest):
assert report["outcomes"] == {"repaired": 1}
sibling_team.refresh_from_db()
assert sibling_team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+
+ def test_repairs_every_team_across_chunk_boundaries(self) -> None:
+ # A chunk size smaller than the number of scanned teams forces _iter_team_chunks through
+ # more than one page; every team must still be repaired, not just the first chunk's.
+ teams = [self.team] + [
+ Team.objects.create(organization=self.organization, project=self.team.project) for _ in range(2)
+ ]
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-gate-v2")
+ for team in teams:
+ self._link_flag(team, {"id": flag.id, "key": "replay-gate"})
+
+ report = self._run("--live-run", "--chunk-size", "1", teams=teams)
+
+ assert report["outcomes"] == {"repaired": 3}
+ for team in teams:
+ team.refresh_from_db()
+ assert team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}
+
+ def test_rejects_a_zero_chunk_size(self) -> None:
+ # A zero chunk slices to an empty list every time, so the command would report scanning
+ # zero teams instead of failing loudly.
+ with self.assertRaises(CommandError):
+ self._run("--live-run", "--chunk-size", "0", teams=[self.team])
diff --git a/products/feature_flags/backend/session_recording_links.py b/products/feature_flags/backend/session_recording_links.py
index 7d8d07a5e9dd..013336b5c318 100644
--- a/products/feature_flags/backend/session_recording_links.py
+++ b/products/feature_flags/backend/session_recording_links.py
@@ -11,13 +11,15 @@ from typing import Any
from django.db import transaction
from django.db.models import QuerySet
+from django.db.models.signals import post_save, pre_save
+from django.dispatch import receiver
import structlog
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
-from posthog.models.signals import model_activity_signal, mutable_receiver
+from products.feature_flags.backend.field_snapshots import capture_fields_before_save, snapshot_if_changed
from products.feature_flags.backend.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -27,13 +29,32 @@ REPLAY_LINKED_FLAG_DELETE_ERROR = (
)
+def linked_flag_id(linked_flag: Any) -> int | None:
+ """The flag id a stored replay link points at, or None when it holds no usable one."""
+ if not isinstance(linked_flag, dict):
+ return None
+ stored_id = linked_flag.get("id")
+ # The column is schemaless, so anything an API client or the admin's JSON widget sent can be
+ # here. Only an int is usable, and every other shape is left for the caller to handle rather
+ # than coerced. `bool` is excluded explicitly because it subclasses `int`, so `{"id": true}`
+ # would otherwise read as a link to flag 1.
+ if isinstance(stored_id, bool) or not isinstance(stored_id, int):
+ return None
+ return stored_id
+
+
def teams_linking_flag(feature_flag: FeatureFlag) -> QuerySet[Team]:
"""Every team gating session recording on this flag."""
+ return teams_linking_flag_in_project(feature_flag.team.project_id, feature_flag.id)
+
+
+def teams_linking_flag_in_project(project_id: int, flag_id: int) -> QuerySet[Team]:
+ """Every team in this project gating session recording on the flag with this id."""
# Scoped by project rather than by team: any team in the project can gate recording on a flag
# owned by a sibling team.
return Team.objects.filter(
- project_id=feature_flag.team.project_id,
- session_recording_linked_flag__contains={"id": feature_flag.id},
+ project_id=project_id,
+ session_recording_linked_flag__contains={"id": flag_id},
)
@@ -72,6 +93,8 @@ def update_linked_flag_key(team: Team, expected_flag_id: int, new_key: str) -> N
.values_list("session_recording_linked_flag", flat=True)
.first()
)
+ # Don't route this through `linked_flag_id`: it stays loose to match the jsonb comparison
+ # `teams_linking_flag` selected on, where a stored float id equals an int one.
if not isinstance(linked_flag, dict) or linked_flag.get("id") != expected_flag_id:
# Someone pointed the team at a different flag since the caller looked it up; that
# edit isn't ours to touch, and this rename has nothing left to fix here.
@@ -116,17 +139,49 @@ def relink_teams(feature_flag: FeatureFlag) -> None:
capture_exception()
-@mutable_receiver(model_activity_signal, sender=FeatureFlag)
+_KEY_BEFORE_SAVE_ATTR = "_replay_link_key_before_save"
+
+
+@receiver(pre_save, sender=FeatureFlag)
+def capture_replay_link_key_before_save(
+ sender: type[FeatureFlag],
+ instance: FeatureFlag,
+ raw: bool = False,
+ update_fields: frozenset[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ # Its own snapshot rather than sharing the one `flag_version_sync` takes: relinking must
+ # not hinge on which fields another feature happens to watch.
+ # objects_including_soft_deleted so the tombstone rename a soft-deleted flag gets when
+ # `_free_key_held_by_soft_deleted_flags` frees its key for reuse is captured too.
+ capture_fields_before_save(
+ instance,
+ FeatureFlag.objects_including_soft_deleted,
+ frozenset({"key"}),
+ attr=_KEY_BEFORE_SAVE_ATTR,
+ update_fields=update_fields,
+ raw=raw,
+ )
+
+
+@receiver(post_save, sender=FeatureFlag)
def relink_teams_on_key_change(
- sender: Any, before_update: FeatureFlag | None, after_update: FeatureFlag | None, **kwargs: Any
+ sender: type[FeatureFlag],
+ instance: FeatureFlag,
+ created: bool = False,
+ raw: bool = False,
+ **kwargs: Any,
) -> None:
- # Wired to the model signal rather than to FeatureFlagSerializer so renames from the Django
- # admin, a shell, or a Celery task keep the link intact too. `before_update` is None on create;
- # `after_update` is None on delete.
- if before_update is None or after_update is None or before_update.key == after_update.key:
+ # Wired to plain model signals rather than to FeatureFlagSerializer so renames from the
+ # Django admin, a shell, or a Celery task keep the link intact too, and rather than to
+ # model_activity_signal because activity logging is tunable in ways recording must not
+ # inherit: `mute_selected_signals()` and the activity-log `signal_exclusions` can both
+ # silently drop that signal, and a skipped relink turns replay off for every linking team.
+ # The snapshot is only a change detector; `relink_teams` re-reads the stored key itself.
+ if raw or created or snapshot_if_changed(instance, attr=_KEY_BEFORE_SAVE_ATTR) is None:
return
- # Unlike `repair_replay_linked_flag_keys`, this has no `after_update.deleted` guard, including
+ # Unlike `repair_replay_linked_flag_keys`, this has no `instance.deleted` guard, including
# for the tombstone rename `_free_key_held_by_soft_deleted_flags` does when freeing a
# soft-deleted flag's key for reuse. That's intentional: relinking still rewrites a team's
# stored key to the flag's new, id-suffixed tombstone, which no live flag's key can equal.
@@ -136,4 +191,4 @@ def relink_teams_on_key_change(
# Deferred to commit because the serializer renames inside a transaction that holds
# `select_for_update` on the flag row, and taking team locks in that window invites deadlocks.
# Outside a transaction (admin, shell) `on_commit` runs the callback immediately.
- transaction.on_commit(lambda: relink_teams(after_update))
+ transaction.on_commit(lambda: relink_teams(instance))
diff --git a/products/feature_flags/backend/test/test_session_recording_links.py b/products/feature_flags/backend/test/test_session_recording_links.py
index 47633bf62c9c..b2cd26cf0926 100644
--- a/products/feature_flags/backend/test/test_session_recording_links.py
+++ b/products/feature_flags/backend/test/test_session_recording_links.py
@@ -1,4 +1,5 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
from posthog.models import Team
@@ -58,3 +59,34 @@ class TestRelinkTeams(BaseTest):
self.team.refresh_from_db()
assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-c"}
+
+ def test_one_teams_write_failure_does_not_strand_its_siblings(self) -> None:
+ # relink_teams wraps each team's update in its own try/except so that one row it can't
+ # write (a lock timeout, a constraint violation) doesn't stop the rename from reaching
+ # every other team gating replay on the same flag.
+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="gate-old")
+ other_team = Team.objects.create(organization=self.organization, project=self.team.project)
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": "gate-old"}
+ self.team.save()
+ other_team.session_recording_linked_flag = {"id": flag.id, "key": "gate-old"}
+ other_team.save()
+
+ real_update_linked_flag_key = update_linked_flag_key
+
+ def _raise_for_other_team(team: Team, expected_flag_id: int, new_key: str) -> None:
+ if team.pk == other_team.pk:
+ raise Exception("simulated write failure")
+ real_update_linked_flag_key(team, expected_flag_id, new_key)
+
+ flag.key = "gate-new"
+ with patch(
+ "products.feature_flags.backend.session_recording_links.update_linked_flag_key",
+ side_effect=_raise_for_other_team,
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ flag.save()
+
+ self.team.refresh_from_db()
+ other_team.refresh_from_db()
+ assert self.team.session_recording_linked_flag == {"id": flag.id, "key": "gate-new"}
+ assert other_team.session_recording_linked_flag == {"id": flag.id, "key": "gate-old"}