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): bump dependent flag versions when a dependency changes (#78418)

Gustavo H. Strassburger2a5db421d8a5
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
index fa3d60056708..274a7693e3d7 100644
--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx
+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx
@@ -462,6 +462,36 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:
),
}
}
+ // A flag this one depends on changed its definition: same story as above, only
+ // this flag's version moved. job_type must stay in sync with
+ // FLAG_DEPENDENCY_UPDATED_JOB_TYPE in
+ // products/feature_flags/backend/flag_version_sync.py.
+ if (logItem.detail.trigger?.job_type === 'flag_dependency_updated') {
+ const { flag_id, flag_key } = logItem.detail.trigger.payload ?? {}
+ return {
+ description: (
+ <SentenceList
+ listParts={[
+ <Fragment key="flag-dependency-updated">
+ changed the definition of linked flag{' '}
+ {flag_id ? (
+ <Link to={urls.featureFlag(flag_id)}>{flag_key || `#${flag_id}`}</Link>
+ ) : (
+ <span>{flag_key || 'unknown'}</span>
+ )}
+ </Fragment>,
+ ]}
+ prefix={getActorName(logItem)}
+ suffix={
+ <>
+ on {asNotification && ' the flag '}
+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}
+ </>
+ }
+ />
+ ),
+ }
+ }
let changes: Description[] = []
let changeSuffix: Description = (
<>
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index 84955e62c4cd..b24a08b6c1bb 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -44,6 +44,18 @@
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.10
+ '''
+ SELECT "posthog_featureflag"."active" AS "active",
+ "posthog_featureflag"."deleted" AS "deleted",
+ "posthog_featureflag"."filters" AS "filters",
+ "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.11
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -68,7 +80,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.11
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -91,7 +103,141 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.13
+ '''
+ 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",
+ "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."event_retention_months",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."llm_gateway_overspend_allowance_usd",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."plugins_opt_in",
+ "posthog_team"."opt_out_capture",
+ "posthog_team"."event_names",
+ "posthog_team"."event_names_with_usage",
+ "posthog_team"."event_properties",
+ "posthog_team"."event_properties_with_usage",
+ "posthog_team"."event_properties_numerical",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."revenue_tracking_config",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model"
+ FROM "posthog_featureflag"
+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND NOT "posthog_featureflag"."deleted"
+ AND "posthog_team"."project_id" = 99999
+ AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.14
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -110,7 +256,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.13
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.15
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -127,7 +273,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.14
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.16
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -145,7 +291,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.15
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.17
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -163,7 +309,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.16
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.18
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -208,7 +354,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.17
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -253,7 +399,24 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.18
+# 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 "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -264,7 +427,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.19
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -275,24 +438,7 @@
WHERE "ee_featureflagroleaccess"."feature_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.22
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -336,7 +482,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.21
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -438,7 +584,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.22
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -475,7 +621,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -577,7 +723,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -621,7 +767,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -668,7 +814,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -698,7 +844,7 @@
UPDATE
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -728,54 +874,6 @@
LIMIT 1
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'feature_flag'
- AND NOT ("posthog_filesystem"."shortcut"
- AND "posthog_filesystem"."shortcut" IS NOT NULL))
- '''
-# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
- '''
- SELECT "posthog_filesystemshortcut"."id",
- "posthog_filesystemshortcut"."team_id",
- "posthog_filesystemshortcut"."user_id",
- "posthog_filesystemshortcut"."path",
- "posthog_filesystemshortcut"."type",
- "posthog_filesystemshortcut"."ref",
- "posthog_filesystemshortcut"."href",
- "posthog_filesystemshortcut"."order",
- "posthog_filesystemshortcut"."created_at",
- "posthog_filesystemshortcut"."surface"
- FROM "posthog_filesystemshortcut"
- WHERE (("posthog_filesystemshortcut"."surface" IS NULL
- OR "posthog_filesystemshortcut"."surface" = 'web')
- AND "posthog_filesystemshortcut"."ref" = '0001'
- AND "posthog_filesystemshortcut"."team_id" = 99999
- AND "posthog_filesystemshortcut"."type" = 'feature_flag'
- AND NOT ("posthog_filesystemshortcut"."path" = 'flag-1'
- AND "posthog_filesystemshortcut"."href" = '__skipped__'
- AND "posthog_filesystemshortcut"."href" IS NOT NULL))
- '''
-# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.3
'''
SELECT "posthog_scheduledchange"."id",
@@ -849,24 +947,218 @@
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.30
'''
- SELECT "posthog_integration"."id",
- "posthog_integration"."team_id",
- "posthog_integration"."kind",
- "posthog_integration"."integration_id",
- "posthog_integration"."config",
- "posthog_integration"."sensitive_config",
- "posthog_integration"."repository_cache",
- "posthog_integration"."repository_cache_updated_at",
- "posthog_integration"."errors",
- "posthog_integration"."created_at",
- "posthog_integration"."created_by_id"
+ SELECT "posthog_featureflag"."active" AS "active",
+ "posthog_featureflag"."deleted" AS "deleted",
+ "posthog_featureflag"."filters" AS "filters",
+ "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.31
+ '''
+ SELECT "posthog_filesystem"."team_id",
+ "posthog_filesystem"."id",
+ "posthog_filesystem"."path",
+ "posthog_filesystem"."depth",
+ "posthog_filesystem"."type",
+ "posthog_filesystem"."ref",
+ "posthog_filesystem"."href",
+ "posthog_filesystem"."shortcut",
+ "posthog_filesystem"."meta",
+ "posthog_filesystem"."created_at",
+ "posthog_filesystem"."created_by_id",
+ "posthog_filesystem"."surface",
+ "posthog_filesystem"."project_id"
+ FROM "posthog_filesystem"
+ WHERE (("posthog_filesystem"."surface" IS NULL
+ OR "posthog_filesystem"."surface" = 'web')
+ AND "posthog_filesystem"."ref" = '0001'
+ AND "posthog_filesystem"."team_id" = 99999
+ AND "posthog_filesystem"."type" = 'feature_flag'
+ AND NOT ("posthog_filesystem"."shortcut"
+ AND "posthog_filesystem"."shortcut" IS NOT NULL))
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32
+ '''
+ SELECT "posthog_filesystemshortcut"."id",
+ "posthog_filesystemshortcut"."team_id",
+ "posthog_filesystemshortcut"."user_id",
+ "posthog_filesystemshortcut"."path",
+ "posthog_filesystemshortcut"."type",
+ "posthog_filesystemshortcut"."ref",
+ "posthog_filesystemshortcut"."href",
+ "posthog_filesystemshortcut"."order",
+ "posthog_filesystemshortcut"."created_at",
+ "posthog_filesystemshortcut"."surface"
+ FROM "posthog_filesystemshortcut"
+ WHERE (("posthog_filesystemshortcut"."surface" IS NULL
+ OR "posthog_filesystemshortcut"."surface" = 'web')
+ AND "posthog_filesystemshortcut"."ref" = '0001'
+ AND "posthog_filesystemshortcut"."team_id" = 99999
+ AND "posthog_filesystemshortcut"."type" = 'feature_flag'
+ AND NOT ("posthog_filesystemshortcut"."path" = 'flag-1'
+ AND "posthog_filesystemshortcut"."href" = '__skipped__'
+ AND "posthog_filesystemshortcut"."href" IS NOT NULL))
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33
+ '''
+ 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",
+ "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."event_retention_months",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."llm_gateway_overspend_allowance_usd",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."plugins_opt_in",
+ "posthog_team"."opt_out_capture",
+ "posthog_team"."event_names",
+ "posthog_team"."event_names_with_usage",
+ "posthog_team"."event_properties",
+ "posthog_team"."event_properties_with_usage",
+ "posthog_team"."event_properties_numerical",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."revenue_tracking_config",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model"
+ FROM "posthog_featureflag"
+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")
+ WHERE (NOT ("posthog_featureflag"."deleted")
+ AND NOT "posthog_featureflag"."deleted"
+ AND "posthog_team"."project_id" = 99999
+ AND (jsonb_path_exists(filters, '$.** ? (@.type == "flag")')))
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34
+ '''
+ SELECT "posthog_integration"."id",
+ "posthog_integration"."team_id",
+ "posthog_integration"."kind",
+ "posthog_integration"."integration_id",
+ "posthog_integration"."config",
+ "posthog_integration"."sensitive_config",
+ "posthog_integration"."repository_cache",
+ "posthog_integration"."repository_cache_updated_at",
+ "posthog_integration"."errors",
+ "posthog_integration"."created_at",
+ "posthog_integration"."created_by_id"
FROM "posthog_integration"
WHERE ("posthog_integration"."kind" = 'vercel'
AND "posthog_integration"."team_id" = 99999)
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.31
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -883,7 +1175,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.32
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -901,7 +1193,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.33
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -919,7 +1211,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.34
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -964,7 +1256,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.35
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -1009,7 +1301,44 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.36
+# 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 "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1020,7 +1349,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.37
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1031,7 +1360,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.38
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -1075,7 +1404,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.39
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.43
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1177,44 +1506,7 @@
LIMIT 21
'''
# ---
-# 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.44
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1240,7 +1532,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.41
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.45
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1266,7 +1558,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.42
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.46
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1292,7 +1584,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.43
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.47
'''
SELECT "posthog_scheduledchange"."id",
"posthog_scheduledchange"."record_id",
@@ -1318,7 +1610,7 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.44
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.48
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 7f436459fc54..10dd2e174d16 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -179,6 +179,7 @@ post_save:products.early_access_features.backend.signals.create_waitlist_survey_
post_save:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_save
post_save:products.event_definitions.backend.models.property_definition._invalidate_has_person_email_on_save
post_save:products.exports.backend.models.subscription.subscription_saved
+post_save:products.feature_flags.backend.flag_version_sync.bump_dependent_flag_versions_on_flag_definition_change
post_save:products.feature_flags.backend.flag_version_sync.bump_flag_versions_on_cohort_definition_change
post_save:products.feature_flags.backend.flags_cache.cohort_changed_flags_cache
post_save:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cache
@@ -239,6 +240,7 @@ pre_save:products.conversations.backend.signals.handle_comment_soft_delete
pre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policy
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.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/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
index b2651c04febf..9e7e2e96e0a9 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr
@@ -1628,6 +1628,26 @@
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49
+ '''
+ SELECT "posthog_featureflag"."active" AS "active",
+ "posthog_featureflag"."deleted" AS "deleted",
+ "posthog_featureflag"."filters" AS "filters",
+ "posthog_featureflag"."key" AS "key"
+ FROM "posthog_featureflag"
+ WHERE "posthog_featureflag"."id" = 99999
+ ORDER BY "posthog_featureflag"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."organization_id"
+ FROM "posthog_team"
+ WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -1652,15 +1672,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
- '''
- SELECT "posthog_team"."id",
- "posthog_team"."organization_id"
- FROM "posthog_team"
- WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -1683,7 +1695,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -1702,7 +1714,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -1719,7 +1731,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -1737,7 +1749,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
@@ -1755,7 +1767,7 @@
WHERE "posthog_taggeditem"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -1800,7 +1812,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -1845,7 +1857,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1856,7 +1868,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -1867,7 +1879,44 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
+ '''
+ 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"."key" = 'copied-flag-key'
+ AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
+ AND "posthog_team"."project_id" = 99999
+ AND "posthog_featureflag"."team_id" IN (1,
+ 2,
+ 3,
+ 4,
+ 5 /* ... */))
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.60
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -1910,44 +1959,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
- '''
- 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"."key" = 'copied-flag-key'
- AND "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
- AND "posthog_team"."project_id" = 99999
- AND "posthog_featureflag"."team_id" IN (1,
- 2,
- 3,
- 4,
- 5 /* ... */))
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.60
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -1990,7 +2002,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -2035,7 +2047,7 @@
WHERE "posthog_survey"."linked_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63
'''
SELECT "posthog_earlyaccessfeature"."id",
"posthog_earlyaccessfeature"."team_id",
@@ -2053,7 +2065,7 @@
WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -2106,7 +2118,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65
'''
SELECT "posthog_dashboard"."id",
"posthog_dashboard"."name",
@@ -2135,7 +2147,7 @@
AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -2188,7 +2200,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67
'''
SELECT 1 AS "a"
FROM "posthog_team"
@@ -2197,7 +2209,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68
'''
SELECT "posthog_featureflagevaluationcontext"."id",
"posthog_featureflagevaluationcontext"."feature_flag_id",
@@ -2213,7 +2225,7 @@
WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.69
'''
SELECT "posthog_tag"."name" AS "tag__name"
FROM "posthog_taggeditem"
diff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.py
index 39ca05185dd9..ee535d4e68ef 100644
--- a/products/feature_flags/backend/flag_version_sync.py
+++ b/products/feature_flags/backend/flag_version_sync.py
@@ -1,11 +1,12 @@
"""
-Bumps FeatureFlag.version when a cohort referenced by the flag changes its conditions.
+Bumps FeatureFlag.version when something a flag depends on changes: a cohort it
+references, or another flag it depends on.
SDKs consuming the local-evaluation payload use a flag's ``version`` to detect when its
definition changed. A flag's effective definition includes the conditions of every
-cohort it references (directly or through nested cohorts), so editing a cohort's
-conditions must bump the version of every flag using it — even though the flag rows
-themselves didn't change.
+cohort it references (directly or through nested cohorts) and the definition of every
+flag it depends on (directly or transitively), so editing either must bump the version
+of every flag downstream — even though those flag rows themselves didn't change.
Each bump also writes a FeatureFlag activity log entry ("flag history"). That entry is
load-bearing, not just informational: ``version_history.reconstruct_flag_at_version``
@@ -16,13 +17,20 @@ entry — which is exactly what a silent bump would create.
Membership recalculation bookkeeping must never bump versions: the periodic
recalculation cycle saves every stale dynamic cohort roughly every 15 minutes, and
version churn there would invalidate every SDK cache (and the payload ETag) with no
-definition change. The pre_save snapshot plus value comparison below guarantees only
-real condition changes bump.
+definition change. The same goes for flag edits that leave the flag's conditions alone
+(renames, folder moves, analytics bookkeeping). The pre_save snapshot plus value
+comparison below guarantees only real definition changes bump.
+
+The bumps run synchronously inside the triggering save's transaction rather than on
+commit: ``refresh_flag_cache_on_updates`` connects at model-import time, i.e. before
+this module is wired in ``apps.ready()``, so its own ``on_commit`` callback runs first
+and would rebuild the flag cache with the pre-bump versions.
"""
+from collections import defaultdict
from typing import Any
-from django.db import transaction
+from django.db import models, transaction
from django.db.models import Value
from django.db.models.functions import Coalesce
from django.db.models.signals import post_save, pre_save
@@ -41,22 +49,34 @@ logger = structlog.get_logger(__name__)
# Also referenced by the frontend flag activity describer — keep the two in sync.
COHORT_CONDITIONS_UPDATED_JOB_TYPE = "cohort_conditions_updated"
+FLAG_DEPENDENCY_UPDATED_JOB_TYPE = "flag_dependency_updated"
# Fields that make up a cohort's conditions. Saves that persist a value change to any
# of these bump the versions of flags referencing the cohort; everything else
# (recalculation bookkeeping, renames, folder moves) must not.
COHORT_DEFINITION_FIELDS = frozenset({"filters", "query", "groups", "is_static"})
+# Fields of a flag that change how a flag depending on it ("flag_evaluates_to") resolves:
+# `filters` is the condition set the dependent inherits, `active` and `deleted` make the
+# dependency resolve false and drop it from the payload, and `key` is embedded in the
+# dependent's own payload (local evaluation rewrites the stored flag id to the key and
+# inlines a dependency_chain of keys). Delivery and metadata attributes are deliberately
+# out: `ensure_experience_continuity`, `evaluation_runtime` and `bucketing_identifier`
+# shape how the base flag itself is served rather than what it resolves to, and
+# name/folder/analytics bookkeeping don't touch conditions at all. `archived` is covered
+# transitively: the `archived_flag_must_be_disabled` constraint means archiving always
+# moves `active` too.
+FLAG_DEFINITION_FIELDS = frozenset({"filters", "active", "deleted", "key"})
+
_DEFINITION_BEFORE_SAVE_ATTR = "_definition_before_save"
-@receiver(pre_save, sender=Cohort)
-def capture_cohort_definition_before_save(
- sender: type[Cohort],
- instance: Cohort,
- raw: bool = False,
- update_fields: frozenset[str] | None = None,
- **kwargs: Any,
+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.
@@ -68,10 +88,49 @@ def capture_cohort_definition_before_save(
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 = COHORT_DEFINITION_FIELDS if update_fields is None else COHORT_DEFINITION_FIELDS.intersection(update_fields)
+ fields = definition_fields if update_fields is None else definition_fields.intersection(update_fields)
if not fields:
return
- setattr(instance, _DEFINITION_BEFORE_SAVE_ATTR, Cohort.objects.filter(pk=instance.pk).values(*fields).first())
+ # 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],
+ instance: Cohort,
+ raw: bool = False,
+ update_fields: frozenset[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ _capture_definition_before_save(instance, Cohort.objects, COHORT_DEFINITION_FIELDS, update_fields, raw)
+
+
+@receiver(pre_save, sender=FeatureFlag)
+def capture_flag_definition_before_save(
+ sender: type[FeatureFlag],
+ instance: FeatureFlag,
+ raw: bool = False,
+ update_fields: frozenset[str] | None = None,
+ **kwargs: Any,
+) -> 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
+ )
@receiver(post_save, sender=Cohort)
@@ -84,13 +143,55 @@ def bump_flag_versions_on_cohort_definition_change(
) -> None:
if raw or created:
return
- before = instance.__dict__.pop(_DEFINITION_BEFORE_SAVE_ATTR, None)
+ if _changed_definition_fields(instance) is None:
+ return
+
+ project_id = instance.team.project_id
+ referencing_flags = _flags_referencing_cohort(instance)
+ if not referencing_flags:
+ return
+ # Flags depending on a flag whose cohort conditions moved are downstream of the same
+ # change. The bump below is a bulk update, which fires no signals, so the flag
+ # receiver can never pick these up — this path has to expand them itself.
+ dependents = _dependent_flags(referencing_flags, project_id)
+ # Only the flags that actually reference the cohort name it in their history; a flag
+ # further down the chain doesn't reference it, so it names the flag it depends on.
+ triggers: dict[int, Trigger] = {flag.pk: _cohort_conditions_trigger(instance) for flag in referencing_flags}
+ triggers.update({dependent.pk: _flag_dependency_trigger(origin) for dependent, origin in dependents})
+ _bump_flag_versions(referencing_flags + [dependent for dependent, _ in dependents], project_id, triggers)
+
+
+@receiver(post_save, sender=FeatureFlag)
+def bump_dependent_flag_versions_on_flag_definition_change(
+ sender: type[FeatureFlag],
+ instance: FeatureFlag,
+ created: bool = False,
+ raw: bool = False,
+ **kwargs: Any,
+) -> None:
+ if raw or created:
+ return
+ before = _changed_definition_fields(instance)
if before is None:
return
- if all(getattr(instance, field) == value for field, value in before.items()):
+ # An already-deleted flag is in no payload, so edits to it (e.g. the tombstone rename
+ # that frees a key for reuse) can't change how any dependent resolves. A save that
+ # leaves `deleted` out of update_fields doesn't snapshot it, and doesn't write it
+ # either, so the instance's value is the persisted one.
+ if before.get("deleted", instance.deleted) and instance.deleted:
return
- flags = _flags_referencing_cohort(instance)
+ project_id = instance.team.project_id
+ # The saved flag is excluded: whoever edited it already bumped and logged its version.
+ dependents = _dependent_flags([instance], project_id)
+ _bump_flag_versions(
+ [dependent for dependent, _ in dependents],
+ project_id,
+ {dependent.pk: _flag_dependency_trigger(origin) for dependent, origin in dependents},
+ )
+
+
+def _bump_flag_versions(flags: list[FeatureFlag], project_id: int, triggers: dict[int, Trigger]) -> None:
if not flags:
return
with transaction.atomic():
@@ -100,34 +201,52 @@ def bump_flag_versions_on_cohort_definition_change(
# a mismatched entry breaks version-history reconstruction the same way a
# missing one does. pk order keeps the lock order consistent.
old_versions = dict(
- FeatureFlag.objects.filter(pk__in=[flag.pk for flag in flags], team__project_id=instance.team.project_id)
+ FeatureFlag.objects.filter(pk__in=[flag.pk for flag in flags], team__project_id=project_id)
.select_for_update(of=("self",))
.order_by("pk")
.values_list("pk", "version")
)
- # Bypassing FeatureFlag.save() (and its signals) is intentional: the cohort
- # save already triggers the team's cache invalidation, and the flag rows'
- # own fields are untouched, so updated_at/last_modified_by stay as they were.
+ # Bypassing FeatureFlag.save() (and its signals) is intentional: the triggering
+ # save already invalidates the project's flag cache, and these flags' own fields
+ # are untouched, so updated_at/last_modified_by stay as they were. It's also why
+ # the dependent set above is expanded transitively up front — no post_save fires
+ # for these rows to continue the cascade (and nothing can recurse).
# The flag-history entry the signal path would have produced is written
# explicitly below instead.
- FeatureFlag.objects.filter(pk__in=old_versions.keys(), team__project_id=instance.team.project_id).update(
+ FeatureFlag.objects.filter(pk__in=old_versions.keys(), team__project_id=project_id).update(
version=Coalesce("version", Value(0)) + 1
)
bulk_log_activity(
[
- _flag_version_bump_entry(flag, old_version=old_versions[flag.pk], cohort=instance)
+ _flag_version_bump_entry(flag, old_version=old_versions[flag.pk], trigger=triggers[flag.pk])
for flag in flags
if flag.pk in old_versions
]
)
-def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, cohort: Cohort) -> LogActivityEntry:
- """Build the flag-history entry for a cohort-driven version bump.
+def _cohort_conditions_trigger(cohort: Cohort) -> Trigger:
+ return Trigger(
+ job_type=COHORT_CONDITIONS_UPDATED_JOB_TYPE,
+ job_id=str(cohort.pk),
+ payload={"cohort_id": cohort.pk, "cohort_name": cohort.name},
+ )
+
+
+def _flag_dependency_trigger(flag: FeatureFlag) -> Trigger:
+ return Trigger(
+ job_type=FLAG_DEPENDENCY_UPDATED_JOB_TYPE,
+ job_id=str(flag.pk),
+ payload={"flag_id": flag.pk, "flag_key": flag.key},
+ )
+
+
+def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, trigger: Trigger) -> LogActivityEntry:
+ """Build the flag-history entry for a dependency-driven version bump.
The acting user comes from activity_storage (populated by middleware for API
- requests, i.e. whoever edited the cohort); outside a request the entry is logged
- as a system action.
+ requests, i.e. whoever edited the cohort or upstream flag); outside a request the
+ entry is logged as a system action.
"""
return LogActivityEntry(
organization_id=flag.team.organization_id,
@@ -148,15 +267,85 @@ def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, cohort:
after=(old_version or 0) + 1,
)
],
- trigger=Trigger(
- job_type=COHORT_CONDITIONS_UPDATED_JOB_TYPE,
- job_id=str(cohort.pk),
- payload={"cohort_id": cohort.pk, "cohort_name": cohort.name},
- ),
+ trigger=trigger,
),
)
+def _direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:
+ """Flag ids this flag has a ``flag_evaluates_to`` release condition on.
+
+ Same parse as ``flags_cache._extract_direct_dependency_ids`` (a dependency is keyed by
+ the referenced flag's id in ``key``), minus its inactive/deleted short-circuit: a
+ disabled flag still ships in the local-evaluation payload so dependencies can resolve
+ it, so its dependents still need the bump. Tolerant of malformed values so one bad
+ sibling flag can't break the save that triggered this.
+ """
+ dependency_ids: set[int] = set()
+ try:
+ conditions = flag.conditions
+ except Exception:
+ # A sibling flag with malformed filters must neither break the save nor suppress
+ # the bump for healthy flags.
+ logger.exception("flag_version_sync_dependency_parse_failed", flag_id=flag.pk, team_id=flag.team_id)
+ capture_exception()
+ return dependency_ids
+ for condition in conditions:
+ for prop in condition.get("properties") or []:
+ if prop.get("type") != "flag":
+ continue
+ try:
+ dependency_ids.add(int(prop["key"]))
+ except (ValueError, KeyError, TypeError):
+ continue
+ return dependency_ids
+
+
+def _dependent_flags(sources: list[FeatureFlag], project_id: int) -> list[tuple[FeatureFlag, FeatureFlag]]:
+ """Non-deleted flags in the project that transitively depend on any source flag.
+
+ Returns ``(dependent, origin)`` pairs, where origin is the source flag the chain
+ started from — that's what the dependent's history entry names. Sources are never
+ returned: their own versions are bumped by whatever changed them, and skipping them
+ is also what makes a dependency cycle terminate here.
+
+ Matches the payload semantics of local evaluation (all non-deleted flags, active or
+ not). Deliberately not the ``find_dependent_flags`` lookup in the flag API, which is
+ scoped to one team's active flags for the disable/delete guards, and lives in a module
+ too heavy to import at app startup. One query builds the whole reverse graph so the
+ walk below needs no further round trips.
+ """
+ candidate_flags = list(
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static predicate, no user input)
+ FeatureFlag.objects.filter(team__project_id=project_id, deleted=False)
+ .extra(where=["""jsonb_path_exists(filters, '$.** ? (@.type == "flag")')"""])
+ # select_related: the activity entry per bumped flag reads flag.team.organization_id.
+ .select_related("team")
+ )
+ if not candidate_flags:
+ return []
+
+ dependents_of: dict[int, list[FeatureFlag]] = defaultdict(list)
+ for flag in candidate_flags:
+ for dependency_id in _direct_flag_dependency_ids(flag):
+ dependents_of[dependency_id].append(flag)
+
+ dependents: list[tuple[FeatureFlag, FeatureFlag]] = []
+ seen = {flag.pk for flag in sources}
+ frontier = [(flag.pk, flag) for flag in sources]
+ while frontier:
+ next_frontier: list[tuple[int, FeatureFlag]] = []
+ for flag_id, origin in frontier:
+ for dependent in dependents_of.get(flag_id, []):
+ if dependent.pk in seen:
+ continue
+ seen.add(dependent.pk)
+ dependents.append((dependent, origin))
+ next_frontier.append((dependent.pk, origin))
+ frontier = next_frontier
+ return dependents
+
+
def _flags_referencing_cohort(cohort: Cohort) -> list[FeatureFlag]:
"""Non-deleted flags in the cohort's project whose conditions reach this cohort.
diff --git a/products/feature_flags/backend/test/test_flag_version_sync.py b/products/feature_flags/backend/test/test_flag_version_sync.py
index 036a16641fdb..e86ba9d04150 100644
--- a/products/feature_flags/backend/test/test_flag_version_sync.py
+++ b/products/feature_flags/backend/test/test_flag_version_sync.py
@@ -6,6 +6,7 @@ from parameterized import parameterized
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.activity_logging.utils import activity_storage
+from posthog.models.team import Team
from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -30,6 +31,18 @@ def _person_filters(email: str) -> dict:
}
+def _flag_dependency_filters(dependency_flag_id: int | str) -> dict:
+ return {
+ "groups": [
+ {
+ "properties": [
+ {"key": str(dependency_flag_id), "type": "flag", "operator": "flag_evaluates_to", "value": True}
+ ]
+ }
+ ]
+ }
+
+
def _cohort_filters(cohort_id: int) -> dict:
return {
"properties": {
@@ -156,6 +169,47 @@ class TestFlagVersionSync(BaseTest):
assert at_v1["version"] == 1
assert at_v1["filters"] == original_filters
+ def test_cohort_condition_change_cascades_through_flag_dependencies(self):
+ cohort = self._create_cohort("cohort", _person_filters("[email protected]"))
+ flag_using_cohort = self._create_flag("uses-cohort", cohort.pk)
+ # The cohort bump is a bulk update, which fires no signals, so this path has to
+ # expand flag dependents itself or these two never move.
+ dependent = FeatureFlag.objects.create(
+ team=self.team,
+ key="dependent",
+ created_by=self.user,
+ filters=_flag_dependency_filters(flag_using_cohort.pk),
+ )
+ transitive = FeatureFlag.objects.create(
+ team=self.team, key="transitive", created_by=self.user, filters=_flag_dependency_filters(dependent.pk)
+ )
+
+ cohort.filters = _person_filters("[email protected]")
+ cohort.save()
+
+ for flag in (flag_using_cohort, dependent, transitive):
+ flag.refresh_from_db()
+ assert flag.version == 2
+
+ # Each flag's history names the source it actually reaches: only the flag with the
+ # cohort condition names the cohort, and a flag further down the chain names the
+ # flag it depends on rather than a cohort it has no reference to.
+ (cohort_entry,) = _updated_entries(flag_using_cohort)
+ assert cohort_entry.detail is not None
+ assert cohort_entry.detail["trigger"] == {
+ "job_type": "cohort_conditions_updated",
+ "job_id": str(cohort.pk),
+ "payload": {"cohort_id": cohort.pk, "cohort_name": "cohort"},
+ }
+ for flag in (dependent, transitive):
+ (entry,) = _updated_entries(flag)
+ assert entry.detail is not None
+ assert entry.detail["trigger"] == {
+ "job_type": "flag_dependency_updated",
+ "job_id": str(flag_using_cohort.pk),
+ "payload": {"flag_id": flag_using_cohort.pk, "flag_key": flag_using_cohort.key},
+ }
+
def test_malformed_sibling_flag_does_not_block_save_or_bump(self):
cohort = self._create_cohort("cohort", _person_filters("[email protected]"))
healthy_flag = self._create_flag("healthy", cohort.pk)
@@ -211,3 +265,199 @@ class TestFlagVersionSync(BaseTest):
assert flag.version == 1
# Recalculation bookkeeping must not spam flag history either.
assert _updated_entries(flag) == []
+
+
+class TestFlagDependencyVersionSync(BaseTest):
+ def _create_flag(self, key: str, filters: dict, **kwargs) -> FeatureFlag:
+ return FeatureFlag.objects.create(team=self.team, key=key, created_by=self.user, filters=filters, **kwargs)
+
+ def _create_chain(self) -> tuple[FeatureFlag, FeatureFlag, FeatureFlag]:
+ base = self._create_flag("base", {"groups": [{"properties": [], "rollout_percentage": 100}]})
+ dependent = self._create_flag("dependent", _flag_dependency_filters(base.pk))
+ transitive = self._create_flag("transitive", _flag_dependency_filters(dependent.pk))
+ return base, dependent, transitive
+
+ def test_flag_definition_change_bumps_versions_of_flags_depending_on_it(self):
+ base, dependent, transitive = self._create_chain()
+ # dependent also depends on transitive, so the walk revisits an already-bumped
+ # flag; validation rejects cycles but a direct write can still leave one behind.
+ FeatureFlag.objects.filter(pk=dependent.pk).update(
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": str(base.pk), "type": "flag", "operator": "flag_evaluates_to", "value": True},
+ {"key": str(transitive.pk), "type": "flag", "operator": "flag_evaluates_to", "value": True},
+ ]
+ }
+ ]
+ }
+ )
+ inactive = self._create_flag("inactive", _flag_dependency_filters(base.pk), active=False)
+ unrelated = self._create_flag("unrelated", {"groups": [{"properties": [], "rollout_percentage": 50}]})
+ # A dependency key that isn't a flag id must be skipped, not crash the save.
+ malformed = self._create_flag("malformed", _flag_dependency_filters("not-a-number"))
+ deleted = self._create_flag("deleted", _flag_dependency_filters(base.pk))
+ FeatureFlag.objects_including_soft_deleted.filter(pk=deleted.pk).update(deleted=True)
+ # Legacy rows can have a NULL version; the bump must produce 1, not NULL.
+ FeatureFlag.objects.filter(pk=transitive.pk).update(version=None)
+ # Dependencies are validated project-wide, so a sibling team's flag is downstream
+ # too — while another project's flag must never be touched.
+ sibling_team = Team.objects.create(organization=self.organization, project=self.team.project, name="sibling")
+ sibling_dependent = FeatureFlag.objects.create(
+ team=sibling_team, key="sibling-dependent", created_by=self.user, filters=_flag_dependency_filters(base.pk)
+ )
+ other_project_team = Team.objects.create(organization=self.organization, name="other project")
+ other_project_dependent = FeatureFlag.objects.create(
+ team=other_project_team,
+ key="other-project-dependent",
+ created_by=self.user,
+ filters=_flag_dependency_filters(base.pk),
+ )
+
+ base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}
+ base.save()
+
+ for flag, expected_version in (
+ (base, 1), # bumped by whoever edits it, not by this receiver
+ (dependent, 2),
+ (transitive, 1), # NULL -> 1
+ (inactive, 2), # local evaluation ships disabled flags so dependencies resolve
+ (sibling_dependent, 2),
+ (unrelated, 1),
+ (malformed, 1),
+ (deleted, 1),
+ (other_project_dependent, 1),
+ ):
+ flag.refresh_from_db()
+ assert flag.version == expected_version, flag.key
+ assert _updated_entries(unrelated) == []
+ assert _updated_entries(deleted) == []
+ assert _updated_entries(other_project_dependent) == []
+
+ @parameterized.expand(
+ [
+ ("filters", {"filters": {"groups": [{"properties": [], "rollout_percentage": 10}]}}, None, 2),
+ ("active", {"active": False}, ["active"], 2),
+ ("key", {"key": "renamed"}, ["key"], 2),
+ ("name_only", {"name": "renamed"}, None, 1),
+ ("analytics_bookkeeping_only", {"has_enriched_analytics": True}, ["has_enriched_analytics"], 1),
+ # A definition field changed in memory but excluded from update_fields is not
+ # persisted, so it must not bump either.
+ (
+ "unpersisted_definition_change",
+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 10}]}},
+ ["name"],
+ 1,
+ ),
+ ("unchanged_full_save", {}, None, 1),
+ ]
+ )
+ def test_only_definition_changes_bump_dependents(
+ self, _name: str, attrs: dict, update_fields, expected_version: int
+ ):
+ base, dependent, _ = self._create_chain()
+
+ for field, value in attrs.items():
+ setattr(base, field, value)
+ base.save(update_fields=update_fields) if update_fields is not None else base.save()
+
+ dependent.refresh_from_db()
+ assert dependent.version == expected_version
+ if expected_version == 1:
+ # Metadata edits must not churn SDK caches or spam dependents' flag history.
+ assert _updated_entries(dependent) == []
+
+ def test_editing_an_already_deleted_flag_does_not_bump_dependents(self):
+ base, dependent, _ = self._create_chain()
+
+ base.deleted = True
+ base.save(update_fields=["deleted"])
+ dependent.refresh_from_db()
+ assert dependent.version == 2
+
+ # Freeing the key for reuse renames the tombstone, which is in no payload either
+ # way, so it must not bump a second time.
+ base.key = "base-deleted-1"
+ base.save(update_fields=["key"])
+
+ dependent.refresh_from_db()
+ assert dependent.version == 2
+ assert len(_updated_entries(dependent)) == 1
+
+ def test_restoring_a_soft_deleted_flag_bumps_its_dependents(self):
+ base, dependent, _ = self._create_chain()
+
+ base.deleted = True
+ base.save(update_fields=["deleted"])
+ dependent.refresh_from_db()
+ assert dependent.version == 2
+
+ # A restored base re-enters the local-evaluation payload, so its dependents are
+ # stale again. Snapshotting through objects_including_soft_deleted is what makes
+ # this read as deleted True -> False; the default manager hides the row, so the
+ # snapshot would come back empty and the restore would bump nothing.
+ base.deleted = False
+ base.save(update_fields=["deleted"])
+
+ dependent.refresh_from_db()
+ assert dependent.version == 3
+ # Both bumps are logged with contiguous versions, which is what
+ # reconstruct_flag_at_version walks. ActivityLog has no default ordering.
+ transitions = []
+ for entry in _updated_entries(dependent):
+ detail = entry.detail
+ assert detail is not None
+ change = detail["changes"][0]
+ transitions.append((change["before"], change["after"]))
+ assert sorted(transitions) == [(1, 2), (2, 3)]
+
+ def test_sibling_flag_with_non_dict_filters_does_not_block_save_or_bump(self):
+ base, dependent, _ = self._create_chain()
+ # filters is a JSONField with no shape validation, so a row can hold a non-dict;
+ # FeatureFlag.conditions calls .get() on it and raises. That must not abort the
+ # save being made to an unrelated flag. The malformed-key case in the chain test
+ # can't reach this: a bad key inside a well-shaped dict is caught further in.
+ broken = self._create_flag("broken", _flag_dependency_filters(base.pk))
+ FeatureFlag.objects.filter(pk=broken.pk).update(filters=[{"properties": []}, {"type": "flag"}])
+
+ base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}
+ base.save()
+
+ dependent.refresh_from_db()
+ assert dependent.version == 2
+ # The unparseable flag is skipped rather than bumped: its dependencies can't be
+ # read, so it is not known to depend on anything.
+ broken.refresh_from_db()
+ assert broken.version == 1
+
+ def test_dependency_driven_bump_is_attributed_and_reconstructable(self):
+ base, dependent, _ = self._create_chain()
+ original_filters = dependent.get_filters()
+ activity_storage.set_user(self.user)
+ self.addCleanup(activity_storage.clear_all)
+
+ base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}
+ base.save()
+
+ (entry,) = _updated_entries(dependent)
+ assert entry.user == self.user
+ detail = entry.detail
+ assert detail is not None
+ assert detail["name"] == dependent.key
+ assert detail["changes"] == [
+ {"type": "FeatureFlag", "action": "changed", "field": "version", "before": 1, "after": 2}
+ ]
+ assert detail["trigger"] == {
+ "job_type": "flag_dependency_updated",
+ "job_id": str(base.pk),
+ "payload": {"flag_id": base.pk, "flag_key": base.key},
+ }
+
+ # Without the entry above this raises VersionHistoryIncomplete: version 2 exists
+ # on the row with nothing in the activity log accounting for it.
+ dependent.refresh_from_db()
+ at_v1 = reconstruct_flag_at_version(dependent, 1, self.team.pk)
+ assert at_v1["version"] == 1
+ assert at_v1["filters"] == original_filters
+ assert at_v1["is_historical"] is True