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(approvals): make feature-flag approval policies non-bypassable (#67329)

Yasend23046aa9171
diff --git a/posthog/tasks/process_scheduled_changes.py b/posthog/tasks/process_scheduled_changes.py
index f0df533817dc..700a67fdaa81 100644
--- a/posthog/tasks/process_scheduled_changes.py
+++ b/posthog/tasks/process_scheduled_changes.py
@@ -16,6 +16,8 @@ from prometheus_client import Counter
from posthog.exceptions_capture import capture_exception
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.scheduled_changes import apply_gated_scheduled_change, regate_recurring_scheduled_change
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.scheduled_change import ScheduledChange
@@ -160,7 +162,14 @@ def process_scheduled_changes() -> None:
try:
with transaction.atomic():
scheduled_changes = (
- ScheduledChange.objects.select_for_update(nowait=True)
+ # Scope the row lock to the ScheduledChange rows only (of=("self",)) — a bare
+ # select_related would widen select_for_update's lock to the joined change_request /
+ # created_by rows, adding contention with the approve flow that mutates ChangeRequest.
+ ScheduledChange.objects.select_for_update(nowait=True, of=("self",))
+ # No select_related("change_request"): apply_gated_scheduled_change always re-fetches
+ # the bound CR under select_for_update (the prefetched copy can be stale), and the
+ # rest of the loop only reads change_request_id — a local column needing no join.
+ .select_related("created_by")
.filter(
executed_at__isnull=True,
scheduled_at__lte=timezone.now(),
@@ -189,9 +198,18 @@ def process_scheduled_changes() -> None:
# Execute the change on the model instance
model = models[scheduled_change.model_name]
instance = model.objects.get(id=scheduled_change.record_id, team_id=scheduled_change.team_id)
- instance.scheduled_changes_dispatcher(
- scheduled_change.payload, scheduled_change.created_by, scheduled_change_id=scheduled_change.id
- )
+
+ # Approval-aware dispatch: a scheduled change whose payload flips a policy-gated
+ # field carries a bound ChangeRequest created at scheduling time. We only apply
+ # it through the approved path once that CR is approved; if it is still pending
+ # when the fire window closes, the CR is expired and the change is skipped. An
+ # unbound (ungated) change dispatches through the serializer as before.
+ if apply_gated_scheduled_change(scheduled_change, instance):
+ instance.scheduled_changes_dispatcher(
+ scheduled_change.payload,
+ scheduled_change.created_by,
+ scheduled_change_id=scheduled_change.id,
+ )
# Handle recurring vs one-time schedules.
# A recurring schedule uses either a cron expression or a fixed recurrence interval.
@@ -258,6 +276,39 @@ def process_scheduled_changes() -> None:
scheduled_change.last_executed_at = now
scheduled_change.save()
else:
+ # A bound ChangeRequest is single-use; the next occurrence needs its own
+ # approval. Always re-gate against the flag's current state and rebind
+ # (None when no policy now applies, so the next fire dispatches ungated).
+ # Re-gating must run *before* scheduled_at/last_executed_at are written:
+ # 1. A row born ungated (change_request_id is None, no policy matched at
+ # creation) must still be re-evaluated — a policy enabled since then
+ # has to gate every future occurrence, so we can't skip re-gating on a
+ # null binding.
+ # 2. Re-gating can raise PolicyConflict; running it first lets that
+ # exception propagate before the advanced scheduled_at is persisted, so
+ # the failure handler stops advancing the schedule rather than silently
+ # skipping the conflicting occurrence.
+ try:
+ new_change_request = regate_recurring_scheduled_change(scheduled_change, instance)
+ except ApprovalRequired:
+ # A pending/approved CR for the same flag+action already exists (a
+ # second schedule, or an immediate edit awaiting approval), so this
+ # occurrence can't be given its own gate yet. Defer instead of
+ # advancing: advancing would require either a fresh CR (which the
+ # conflict forbids) or a null binding, and a null binding dispatches
+ # the next fire ungated — the exact bypass this gating closes. Leave
+ # the row untouched (scheduled_at unchanged) so the next sweep
+ # re-gates it, and don't route through the failure handler, so a
+ # transient duplicate doesn't retry the schedule to exhaustion and
+ # mark it permanently failed. It self-heals once the conflicting CR
+ # resolves. PolicyConflict is deliberately not caught — that's a
+ # genuine, non-transient conflict the failure handler should record.
+ logger.info(
+ "Deferring recurring scheduled change; a conflicting change request is awaiting approval",
+ scheduled_change_id=scheduled_change.id,
+ )
+ continue
+ scheduled_change.change_request = new_change_request
scheduled_change.scheduled_at = next_run
scheduled_change.last_executed_at = now
scheduled_change.save()
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index 120be89faa3a..65691cc221b2 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -44,6 +44,31 @@
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.10
+ '''
+ 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.11
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -66,7 +91,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.11
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -85,48 +110,6 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.12
- '''
- SELECT "posthog_organization"."id",
- "posthog_organization"."name",
- "posthog_organization"."slug",
- "posthog_organization"."logo_media_id",
- "posthog_organization"."created_at",
- "posthog_organization"."updated_at",
- "posthog_organization"."is_active",
- "posthog_organization"."is_not_active_reason",
- "posthog_organization"."session_cookie_age",
- "posthog_organization"."is_member_join_email_enabled",
- "posthog_organization"."is_ai_data_processing_approved",
- "posthog_organization"."is_ai_training_opted_in",
- "posthog_organization"."is_ai_training_locked",
- "posthog_organization"."is_ai_training_cta_shown",
- "posthog_organization"."enforce_2fa",
- "posthog_organization"."members_can_invite",
- "posthog_organization"."members_can_create_projects",
- "posthog_organization"."members_can_use_personal_api_keys",
- "posthog_organization"."allow_publicly_shared_resources",
- "posthog_organization"."default_role_id",
- "posthog_organization"."plugins_access_level",
- "posthog_organization"."for_internal_metrics",
- "posthog_organization"."default_experiment_stats_method",
- "posthog_organization"."default_anonymize_ips",
- "posthog_organization"."is_hipaa",
- "posthog_organization"."is_pending_deletion",
- "posthog_organization"."customer_id",
- "posthog_organization"."available_product_features",
- "posthog_organization"."usage",
- "posthog_organization"."never_drop_data",
- "posthog_organization"."customer_trust_scores",
- "posthog_organization"."setup_section_2_completed",
- "posthog_organization"."personalization",
- "posthog_organization"."domain_whitelist",
- "posthog_organization"."is_platform"
- FROM "posthog_organization"
- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
- LIMIT 21
- '''
-# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.13
'''
SELECT "posthog_organizationintegration"."id",
@@ -493,52 +476,6 @@
'''
# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.23
- '''
- SELECT "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_password_reset_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in"
- FROM "posthog_user"
- WHERE "posthog_user"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -640,7 +577,95 @@
LIMIT 21
'''
# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.24
+ '''
+ SELECT "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organization"
+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.25
+ '''
+ SELECT "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_password_reset_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_user"
+ WHERE "posthog_user"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -672,7 +697,7 @@
UPDATE
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.26
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -704,7 +729,7 @@
LIMIT 1
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.27
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -729,7 +754,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.28
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -752,25 +777,6 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.29
- '''
- 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.3
'''
SELECT "posthog_scheduledchange"."id",
@@ -788,57 +794,75 @@
"posthog_scheduledchange"."end_date",
"posthog_scheduledchange"."timezone",
"posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
"posthog_scheduledchange"."created_at",
"posthog_scheduledchange"."created_by_id",
- "posthog_scheduledchange"."updated_at"
- FROM "posthog_scheduledchange"
- WHERE ("posthog_scheduledchange"."executed_at" IS NULL
- AND "posthog_scheduledchange"."scheduled_at" <= '2023-12-21 09:00:00+00:00'::timestamptz)
- ORDER BY "posthog_scheduledchange"."scheduled_at" ASC
- LIMIT 10000
- FOR
- UPDATE NOWAIT
- '''
-# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.30
- '''
- SELECT "posthog_organization"."id",
- "posthog_organization"."name",
- "posthog_organization"."slug",
- "posthog_organization"."logo_media_id",
- "posthog_organization"."created_at",
- "posthog_organization"."updated_at",
- "posthog_organization"."is_active",
- "posthog_organization"."is_not_active_reason",
- "posthog_organization"."session_cookie_age",
- "posthog_organization"."is_member_join_email_enabled",
- "posthog_organization"."is_ai_data_processing_approved",
- "posthog_organization"."is_ai_training_opted_in",
- "posthog_organization"."is_ai_training_locked",
- "posthog_organization"."is_ai_training_cta_shown",
- "posthog_organization"."enforce_2fa",
- "posthog_organization"."members_can_invite",
- "posthog_organization"."members_can_create_projects",
- "posthog_organization"."members_can_use_personal_api_keys",
- "posthog_organization"."allow_publicly_shared_resources",
- "posthog_organization"."default_role_id",
- "posthog_organization"."plugins_access_level",
- "posthog_organization"."for_internal_metrics",
- "posthog_organization"."default_experiment_stats_method",
- "posthog_organization"."default_anonymize_ips",
- "posthog_organization"."is_hipaa",
- "posthog_organization"."is_pending_deletion",
- "posthog_organization"."customer_id",
- "posthog_organization"."available_product_features",
- "posthog_organization"."usage",
- "posthog_organization"."never_drop_data",
- "posthog_organization"."customer_trust_scores",
- "posthog_organization"."setup_section_2_completed",
- "posthog_organization"."personalization",
- "posthog_organization"."domain_whitelist",
- "posthog_organization"."is_platform"
- FROM "posthog_organization"
- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ "posthog_scheduledchange"."updated_at",
+ "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_password_reset_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_scheduledchange"
+ LEFT OUTER JOIN "posthog_user" ON ("posthog_scheduledchange"."created_by_id" = "posthog_user"."id")
+ WHERE ("posthog_scheduledchange"."executed_at" IS NULL
+ AND "posthog_scheduledchange"."scheduled_at" <= '2023-12-21 09:00:00+00:00'::timestamptz)
+ ORDER BY "posthog_scheduledchange"."scheduled_at" ASC
+ LIMIT 10000
+ FOR
+ UPDATE OF "posthog_scheduledchange" NOWAIT
+ '''
+# ---
+# 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"
+ FROM "posthog_integration"
+ WHERE ("posthog_integration"."kind" = 'vercel'
+ AND "posthog_integration"."team_id" = 99999)
LIMIT 21
'''
# ---
@@ -1207,6 +1231,7 @@
"posthog_scheduledchange"."end_date",
"posthog_scheduledchange"."timezone",
"posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
"posthog_scheduledchange"."created_at",
"posthog_scheduledchange"."created_by_id",
"posthog_scheduledchange"."updated_at"
@@ -1232,6 +1257,7 @@
"posthog_scheduledchange"."end_date",
"posthog_scheduledchange"."timezone",
"posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
"posthog_scheduledchange"."created_at",
"posthog_scheduledchange"."created_by_id",
"posthog_scheduledchange"."updated_at"
@@ -1257,6 +1283,7 @@
"posthog_scheduledchange"."end_date",
"posthog_scheduledchange"."timezone",
"posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
"posthog_scheduledchange"."created_at",
"posthog_scheduledchange"."created_by_id",
"posthog_scheduledchange"."updated_at"
@@ -1282,6 +1309,7 @@
"posthog_scheduledchange"."end_date",
"posthog_scheduledchange"."timezone",
"posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
"posthog_scheduledchange"."created_at",
"posthog_scheduledchange"."created_by_id",
"posthog_scheduledchange"."updated_at"
@@ -1321,53 +1349,213 @@
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.5
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.45
'''
- SELECT "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_password_reset_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in"
- FROM "posthog_user"
- WHERE "posthog_user"."id" = 99999
+ SELECT "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"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "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_team"
+ WHERE "posthog_team"."id" = 99999
LIMIT 21
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.6
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.46
+ '''
+ SELECT "posthog_scheduledchange"."id",
+ "posthog_scheduledchange"."record_id",
+ "posthog_scheduledchange"."model_name",
+ "posthog_scheduledchange"."payload",
+ "posthog_scheduledchange"."scheduled_at",
+ "posthog_scheduledchange"."executed_at",
+ "posthog_scheduledchange"."failure_reason",
+ "posthog_scheduledchange"."failure_count",
+ "posthog_scheduledchange"."is_recurring",
+ "posthog_scheduledchange"."recurrence_interval",
+ "posthog_scheduledchange"."last_executed_at",
+ "posthog_scheduledchange"."cron_expression",
+ "posthog_scheduledchange"."end_date",
+ "posthog_scheduledchange"."timezone",
+ "posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
+ "posthog_scheduledchange"."created_at",
+ "posthog_scheduledchange"."created_by_id",
+ "posthog_scheduledchange"."updated_at"
+ FROM "posthog_scheduledchange"
+ WHERE "posthog_scheduledchange"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.47
+ '''
+ SELECT "posthog_scheduledchange"."id",
+ "posthog_scheduledchange"."record_id",
+ "posthog_scheduledchange"."model_name",
+ "posthog_scheduledchange"."payload",
+ "posthog_scheduledchange"."scheduled_at",
+ "posthog_scheduledchange"."executed_at",
+ "posthog_scheduledchange"."failure_reason",
+ "posthog_scheduledchange"."failure_count",
+ "posthog_scheduledchange"."is_recurring",
+ "posthog_scheduledchange"."recurrence_interval",
+ "posthog_scheduledchange"."last_executed_at",
+ "posthog_scheduledchange"."cron_expression",
+ "posthog_scheduledchange"."end_date",
+ "posthog_scheduledchange"."timezone",
+ "posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
+ "posthog_scheduledchange"."created_at",
+ "posthog_scheduledchange"."created_by_id",
+ "posthog_scheduledchange"."updated_at"
+ FROM "posthog_scheduledchange"
+ WHERE "posthog_scheduledchange"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.48
+ '''
+ SELECT "posthog_scheduledchange"."id",
+ "posthog_scheduledchange"."record_id",
+ "posthog_scheduledchange"."model_name",
+ "posthog_scheduledchange"."payload",
+ "posthog_scheduledchange"."scheduled_at",
+ "posthog_scheduledchange"."executed_at",
+ "posthog_scheduledchange"."failure_reason",
+ "posthog_scheduledchange"."failure_count",
+ "posthog_scheduledchange"."is_recurring",
+ "posthog_scheduledchange"."recurrence_interval",
+ "posthog_scheduledchange"."last_executed_at",
+ "posthog_scheduledchange"."cron_expression",
+ "posthog_scheduledchange"."end_date",
+ "posthog_scheduledchange"."timezone",
+ "posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
+ "posthog_scheduledchange"."created_at",
+ "posthog_scheduledchange"."created_by_id",
+ "posthog_scheduledchange"."updated_at"
+ FROM "posthog_scheduledchange"
+ WHERE "posthog_scheduledchange"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.49
+ '''
+ SELECT "posthog_scheduledchange"."id",
+ "posthog_scheduledchange"."record_id",
+ "posthog_scheduledchange"."model_name",
+ "posthog_scheduledchange"."payload",
+ "posthog_scheduledchange"."scheduled_at",
+ "posthog_scheduledchange"."executed_at",
+ "posthog_scheduledchange"."failure_reason",
+ "posthog_scheduledchange"."failure_count",
+ "posthog_scheduledchange"."is_recurring",
+ "posthog_scheduledchange"."recurrence_interval",
+ "posthog_scheduledchange"."last_executed_at",
+ "posthog_scheduledchange"."cron_expression",
+ "posthog_scheduledchange"."end_date",
+ "posthog_scheduledchange"."timezone",
+ "posthog_scheduledchange"."team_id",
+ "posthog_scheduledchange"."change_request_id",
+ "posthog_scheduledchange"."created_at",
+ "posthog_scheduledchange"."created_by_id",
+ "posthog_scheduledchange"."updated_at"
+ FROM "posthog_scheduledchange"
+ WHERE "posthog_scheduledchange"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.5
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1469,7 +1657,126 @@
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"."rollback_conditions",
+ "posthog_featureflag"."performed_rollback",
+ "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",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organization"
+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.7
+ '''
+ SELECT "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_password_reset_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_user"
+ WHERE "posthog_user"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.8
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -1501,7 +1808,7 @@
UPDATE
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.8
+# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.9
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -1533,28 +1840,3 @@
LIMIT 1
'''
# ---
-# name: TestProcessScheduledChanges.test_schedule_feature_flag_multiple_changes.9
- '''
- 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))
- '''
-# ---
diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.py
index 788905c1e1c6..88a1bb4f3f9c 100644
--- a/products/approvals/backend/actions/base.py
+++ b/products/approvals/backend/actions/base.py
@@ -1,6 +1,8 @@
from abc import ABC, abstractmethod
from typing import Any, Optional
+from posthog.models import Team
+
class BaseAction(ABC):
"""
@@ -34,14 +36,27 @@ class BaseAction(ABC):
@classmethod
def _get_team(cls, view):
if hasattr(view, "context"):
- return view.context.get("get_team", lambda: None)()
+ team = view.context.get("get_team", lambda: None)()
+ if team is not None:
+ return team
+ # Internal callers omit get_team; derive from the instance/team_id so
+ # detection stays fail-closed instead of silently skipping the gate.
+ instance = getattr(view, "instance", None)
+ team = getattr(instance, "team", None)
+ if team is None and view.context.get("team_id"):
+ team = Team.objects.filter(id=view.context["team_id"]).first()
+ return team
else:
return getattr(view, "team", None)
@classmethod
def _get_organization(cls, view):
if hasattr(view, "context"):
- return view.context.get("get_organization", lambda: None)()
+ org = view.context.get("get_organization", lambda: None)()
+ if org is not None:
+ return org
+ team = cls._get_team(view)
+ return team.organization if team is not None else None
else:
return getattr(view, "organization", None)
diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.py
index 3bd6a9d02e99..a484b241e87b 100644
--- a/products/approvals/backend/actions/feature_flags.py
+++ b/products/approvals/backend/actions/feature_flags.py
@@ -9,6 +9,58 @@ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerialize
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+def _get_validated_change(request, view, *args, **kwargs) -> dict[str, Any]:
+ """Resolve the change actually being saved.
+
+ @approval_gate wraps both ``FeatureFlagSerializer.update(self, instance, validated_data)``
+ (the validated change is ``args[1]``) and ``create(self, validated_data)`` (the validated
+ change is ``args[0]`` — a dict, with no instance). The raw HTTP request body is NOT the
+ source of truth: internal callers (experiment launch/pause/resume, ship_variant) drive
+ ``serializer.update()`` from a POST whose body has no flag delta, yet the serializer's
+ validated_data carries the real change. Read from validated_data first and only fall back to
+ ``request.data`` when no validated change is available (e.g. direct detection calls in tests).
+ """
+ change: Optional[dict[str, Any]] = None
+
+ if len(args) >= 2 and isinstance(args[1], dict):
+ change = args[1]
+ elif len(args) == 1 and isinstance(args[0], dict):
+ # create(self, validated_data): the lone positional arg is the change itself.
+ change = args[0]
+ elif isinstance(kwargs.get("validated_data"), dict):
+ change = kwargs["validated_data"]
+ elif isinstance(getattr(view, "validated_data", None), dict):
+ change = view.validated_data
+ else:
+ request_data = getattr(request, "data", None)
+ change = request_data if isinstance(request_data, dict) else {}
+
+ # FeatureFlagSerializer maps the `filters` field to `get_filters` in validated_data
+ # (the rename back to `filters` happens inside update(), after the gate runs). Normalize
+ # to the input field name `filters` so detection/intent — and the re-applied
+ # full_request_data — read it regardless of the change's origin.
+ if "get_filters" in change:
+ normalized = {k: v for k, v in change.items() if k != "get_filters"}
+ normalized.setdefault("filters", change["get_filters"])
+ change = normalized
+
+ return change
+
+
+def _get_flag_instance(view, *args, **kwargs) -> Optional[FeatureFlag]:
+ """Resolve the FeatureFlag being changed, or None on a create.
+
+ @approval_gate wraps both ``update(self, instance, validated_data)`` (args[0] is the
+ instance) and ``create(self, validated_data)`` (args[0] is the validated change dict, not
+ a flag). BaseAction._get_instance returns args[0] indiscriminately, so on a create it hands
+ back the dict — here we keep an instance only when it is an actual FeatureFlag.
+ """
+ if hasattr(view, "context") and "request" in view.context:
+ instance = args[0] if args else None
+ return instance if isinstance(instance, FeatureFlag) else None
+ return view.get_object()
+
+
def _check_version_staleness(intent_data: dict[str, Any], context: Optional[dict[str, Any]] = None) -> bool:
"""Check staleness by comparing stored version precondition against current instance version."""
instance = context.get("instance") if context else None
@@ -23,6 +75,71 @@ def _check_version_staleness(intent_data: dict[str, Any], context: Optional[dict
return False
+def _resolve_existing_flag(change_request) -> Optional[FeatureFlag]:
+ """Find the flag a change request operates on, if it already exists.
+
+ For an update CR that's the stored flag_id/resource_id. For a create CR there is no row yet,
+ but once applied the flag exists keyed by its `key` — resolving it here keeps re-validation
+ and re-apply idempotent (no spurious unique-key failure, no duplicate).
+ """
+ flag_id = change_request.intent.get("flag_id") or change_request.resource_id
+ if flag_id:
+ try:
+ return FeatureFlag.objects.get(id=flag_id, team_id=change_request.team_id)
+ except FeatureFlag.DoesNotExist:
+ return None
+
+ key = change_request.intent.get("full_request_data", {}).get("key")
+ if key:
+ # nosemgrep: idor-lookup-without-team (team_id from the approved change request)
+ return FeatureFlag.objects.filter(team_id=change_request.team_id, key=key, deleted=False).first()
+
+ return None
+
+
+def _apply_create(validated_intent: dict[str, Any], context: Optional[dict[str, Any]]) -> FeatureFlag:
+ """Create the flag described by an approved create change request.
+
+ The CR has no resource row yet, so we drive FeatureFlagSerializer.create() from the stored
+ payload. The apply path (apply_change_request) always threads team/team_id/project_id and a
+ request context. Idempotency: if a live flag with this key already exists for the team (e.g.
+ the CR is re-applied), return it instead of creating a duplicate.
+ """
+ if not context or not context.get("team_id"):
+ raise ApplyFailed("Cannot apply feature flag create without team context")
+
+ full_request_data = validated_intent["full_request_data"]
+ key = full_request_data.get("key")
+ team_id = context["team_id"]
+
+ if key:
+ # nosemgrep: idor-lookup-without-team (team_id resolved from the approved change request)
+ existing = FeatureFlag.objects.filter(team_id=team_id, key=key, deleted=False).first()
+ if existing:
+ return existing
+
+ serializer_context = {
+ "team": context.get("team"),
+ "team_id": team_id,
+ "project_id": context.get("project_id"),
+ # Already approved — keep the gate from re-firing on this serializer.
+ "approval_apply": True,
+ }
+ if "request" in context:
+ serializer_context["request"] = context["request"]
+
+ serializer = FeatureFlagSerializer(data=full_request_data, context=serializer_context)
+
+ if not serializer.is_valid():
+ raise ApplyFailed(f"Serializer validation failed: {serializer.errors}")
+
+ try:
+ with transaction.atomic():
+ return serializer.save()
+ except Exception as e:
+ raise ApplyFailed(f"Serializer save failed: {str(e)}")
+
+
class FeatureFlagActionBase(BaseAction):
"""Base class for feature flag state change actions."""
@@ -64,37 +181,41 @@ class FeatureFlagActionBase(BaseAction):
def prepare_context(cls, change_request, base_context: dict) -> dict:
context = base_context.copy()
- flag_id = change_request.intent.get("flag_id") or change_request.resource_id
- if flag_id:
- try:
- instance = FeatureFlag.objects.get(id=flag_id, team_id=change_request.team_id)
- context["instance"] = instance
- except FeatureFlag.DoesNotExist:
- pass
+ instance = _resolve_existing_flag(change_request)
+ if instance is not None:
+ context["instance"] = instance
return context
+ # Whether this action should fire when a brand-new flag is born in the target state.
+ # Enabling a new flag is gated; a new disabled flag is harmless, so disable opts out.
+ gate_on_create: bool = False
+
@classmethod
def detect(cls, request, view, *args, **kwargs) -> bool:
- if request.method not in ["PATCH", "PUT"]:
- return False
-
try:
- flag = cls._get_instance(view, *args, **kwargs)
- if not flag:
- return False
+ flag = _get_flag_instance(view, *args, **kwargs)
except Exception:
return False
- desired_active = request.data.get("active")
- current_active = flag.active
+ change = _get_validated_change(request, view, *args, **kwargs)
- if (
- desired_active is None
- or desired_active != cls.target_active_state
- or current_active == cls.target_active_state
- ):
- return False
+ if flag is None:
+ # Create: gate only when the flag is born in the gated target state.
+ # FeatureFlag.active defaults to True, so a create that omits `active`
+ # still lands enabled — treat missing as the model default.
+ desired_active = change.get("active", True)
+ if not cls.gate_on_create or desired_active is not True or cls.target_active_state is not True:
+ return False
+ else:
+ desired_active = change.get("active")
+ current_active = flag.active
+ if (
+ desired_active is None
+ or desired_active != cls.target_active_state
+ or current_active == cls.target_active_state
+ ):
+ return False
team = cls._get_team(view)
if not team:
@@ -104,19 +225,31 @@ class FeatureFlagActionBase(BaseAction):
@classmethod
def extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:
- flag = cls._get_instance(view, *args, **kwargs)
+ flag = _get_flag_instance(view, *args, **kwargs)
+ change = _get_validated_change(request, view, *args, **kwargs)
gated_changes = {}
for field in cls.intent_fields:
- if field in request.data:
- gated_changes[field] = request.data[field]
+ if field in change:
+ gated_changes[field] = change[field]
+
+ if flag is None:
+ # Create: no row yet — baseline is a disabled flag and the payload is the create body.
+ return {
+ "flag_id": None,
+ "flag_key": change.get("key"),
+ "current_state": {"active": False},
+ "gated_changes": gated_changes,
+ "full_request_data": dict(change),
+ "preconditions": {"version": None, "updated_at": None},
+ }
return {
"flag_id": flag.id,
"flag_key": flag.key,
"current_state": {"active": flag.active},
"gated_changes": gated_changes,
- "full_request_data": dict(request.data),
+ "full_request_data": dict(change),
"preconditions": {
"version": flag.version,
"updated_at": flag.updated_at.isoformat() if flag.updated_at else None,
@@ -125,6 +258,9 @@ class FeatureFlagActionBase(BaseAction):
@classmethod
def apply(cls, validated_intent: dict[str, Any], user, context: Optional[dict[str, Any]] = None) -> FeatureFlag:
+ if not validated_intent.get("flag_id"):
+ return _apply_create(validated_intent, context)
+
with transaction.atomic():
# nosemgrep: idor-lookup-without-team (flag_id from validated change request intent, originally team-scoped)
flag = FeatureFlag.objects.select_for_update().get(id=validated_intent["flag_id"])
@@ -143,6 +279,8 @@ class FeatureFlagActionBase(BaseAction):
"team": context.get("team") if context else flag.team,
"team_id": context.get("team_id") if context else flag.team_id,
"project_id": context.get("project_id") if context else flag.team.project_id,
+ # Already approved — keep the gate from re-firing on this serializer.
+ "approval_apply": True,
}
if context and "request" in context:
@@ -179,6 +317,7 @@ class EnableFeatureFlagAction(FeatureFlagActionBase):
version = 1
description = "Enable a feature flag"
target_active_state = True
+ gate_on_create = True
@classmethod
def get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:
@@ -323,28 +462,27 @@ class UpdateFeatureFlagAction(BaseAction):
@classmethod
def detect(cls, request, view, *args, **kwargs) -> bool:
- if request.method not in ["PATCH", "PUT"]:
- return False
-
try:
- flag = cls._get_instance(view, *args, **kwargs)
- if not flag:
- return False
+ flag = _get_flag_instance(view, *args, **kwargs)
except Exception:
return False
- desired_active = request.data.get("active")
- current_active = flag.active
+ change = _get_validated_change(request, view, *args, **kwargs)
- if desired_active is not None and desired_active != current_active:
- if "filters" not in request.data:
- return False
+ if flag is not None:
+ desired_active = change.get("active")
+ current_active = flag.active
+ if desired_active is not None and desired_active != current_active:
+ if "filters" not in change:
+ return False
- new_filters = request.data.get("filters")
+ new_filters = change.get("filters")
if not new_filters:
return False
- old_filters = flag.filters or {}
+ # On a create there is no prior flag — compare the new rollout against an empty baseline,
+ # so a flag born with any rollout trips an "any change / >0" policy.
+ old_filters = (flag.filters or {}) if flag is not None else {}
if not cls._has_gateable_field_changes(old_filters, new_filters):
return False
@@ -357,10 +495,11 @@ class UpdateFeatureFlagAction(BaseAction):
@classmethod
def extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:
- flag = cls._get_instance(view, *args, **kwargs)
+ flag = _get_flag_instance(view, *args, **kwargs)
+ change = _get_validated_change(request, view, *args, **kwargs)
- old_filters = flag.filters or {}
- new_filters = request.data.get("filters", {})
+ old_filters = (flag.filters or {}) if flag is not None else {}
+ new_filters = change.get("filters", {})
old_rollout_percentages = cls._extract_rollout_percentages(old_filters)
new_rollout_percentages = cls._extract_rollout_percentages(new_filters)
@@ -368,8 +507,8 @@ class UpdateFeatureFlagAction(BaseAction):
triggered_paths = cls._get_triggered_paths(old_filters, new_filters)
return {
- "flag_id": flag.id,
- "flag_key": flag.key,
+ "flag_id": flag.id if flag is not None else None,
+ "flag_key": flag.key if flag is not None else change.get("key"),
"current_state": {
"rollout_percentage": old_rollout_percentages,
},
@@ -377,10 +516,10 @@ class UpdateFeatureFlagAction(BaseAction):
"rollout_percentage": new_rollout_percentages,
},
"triggered_paths": triggered_paths,
- "full_request_data": dict(request.data),
+ "full_request_data": dict(change),
"preconditions": {
- "version": flag.version,
- "updated_at": flag.updated_at.isoformat() if flag.updated_at else None,
+ "version": flag.version if flag is not None else None,
+ "updated_at": (flag.updated_at.isoformat() if flag.updated_at else None) if flag is not None else None,
},
}
@@ -407,18 +546,17 @@ class UpdateFeatureFlagAction(BaseAction):
def prepare_context(cls, change_request, base_context: dict) -> dict:
context = base_context.copy()
- flag_id = change_request.intent.get("flag_id") or change_request.resource_id
- if flag_id:
- try:
- instance = FeatureFlag.objects.get(id=flag_id, team_id=change_request.team_id)
- context["instance"] = instance
- except FeatureFlag.DoesNotExist:
- pass
+ instance = _resolve_existing_flag(change_request)
+ if instance is not None:
+ context["instance"] = instance
return context
@classmethod
def apply(cls, validated_intent: dict[str, Any], user, context: Optional[dict[str, Any]] = None) -> FeatureFlag:
+ if not validated_intent.get("flag_id"):
+ return _apply_create(validated_intent, context)
+
with transaction.atomic():
# nosemgrep: idor-lookup-without-team (flag_id from validated change request intent, originally team-scoped)
flag = FeatureFlag.objects.select_for_update().get(id=validated_intent["flag_id"])
@@ -433,6 +571,8 @@ class UpdateFeatureFlagAction(BaseAction):
"team": context.get("team") if context else flag.team,
"team_id": context.get("team_id") if context else flag.team_id,
"project_id": context.get("project_id") if context else flag.team.project_id,
+ # Already approved — keep the gate from re-firing on this serializer.
+ "approval_apply": True,
}
if context and "request" in context:
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.py
index 08b6a4801652..a465a73451db 100644
--- a/products/approvals/backend/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -4,6 +4,7 @@ from functools import wraps
from typing import Any, Literal, Optional, Union
from django.conf import settings
+from django.db import transaction
from django.utils import timezone
from rest_framework import status
@@ -12,9 +13,10 @@ from rest_framework.response import Response
from posthog.constants import AvailableFeature
from posthog.event_usage import report_user_action
+from posthog.models import Team
from products.approvals.backend.actions.registry import get_action
-from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
from products.approvals.backend.models import ChangeRequest, ChangeRequestState
from products.approvals.backend.notifications import send_approval_requested_notification
from products.approvals.backend.policies import PolicyDecision, PolicyEngine
@@ -43,13 +45,25 @@ class GateResult:
def _extract_context(view_or_serializer, request=None) -> tuple[Optional[Any], Optional[Any], Optional[Any]]:
"""Extract request, team, organization from either serializer or viewset."""
if hasattr(view_or_serializer, "context") and isinstance(view_or_serializer.context, dict):
- req = view_or_serializer.context.get("request")
- team = view_or_serializer.context.get("get_team", lambda: None)()
- org = view_or_serializer.context.get("get_organization", lambda: None)()
+ ctx = view_or_serializer.context
+ req = ctx.get("request")
+ team = ctx.get("get_team", lambda: None)()
+ org = ctx.get("get_organization", lambda: None)()
+ # Internal callers build contexts with team_id/get_team but no get_organization,
+ # so the gate must derive team/org from the instance instead of failing open.
+ if team is None:
+ instance = getattr(view_or_serializer, "instance", None)
+ team = getattr(instance, "team", None)
+ if team is None and ctx.get("team_id"):
+ team = Team.objects.filter(id=ctx["team_id"]).first()
+ if org is None and team is not None:
+ org = team.organization
return req, team, org
else:
team = getattr(view_or_serializer, "team", None)
org = getattr(view_or_serializer, "organization", None)
+ if org is None and team is not None:
+ org = team.organization
return request, team, org
@@ -150,7 +164,15 @@ def _create_change_request(
request=request,
)
- send_approval_requested_notification(change_request)
+ # Fire the approval-requested notification only after the surrounding
+ # transaction commits. On the scheduled-change create/update and copy-flags
+ # paths this runs inside a `with transaction.atomic()` block; if that
+ # transaction rolls back (e.g. the ScheduledChange insert fails a constraint),
+ # the CR row is rolled back too, so notifying synchronously would ping an
+ # approver about a change request that no longer exists. on_commit fires
+ # immediately on the autocommit (direct-request) path, so behavior there is
+ # unchanged.
+ transaction.on_commit(lambda: send_approval_requested_notification(change_request))
return change_request
@@ -203,8 +225,8 @@ def _evaluate_gate(
extra={
"action": action_class.key,
"user": request.user.id,
- "method": request.method,
- "path": request.path,
+ "method": getattr(request, "method", ""),
+ "path": getattr(request, "path", ""),
},
)
@@ -343,13 +365,13 @@ def _result_to_exception(result: GateResult) -> None:
raise APIException(result.error_message)
if result.action == "policy_conflict":
- raise ValidationError(
- {
- "code": "policy_conflict",
- "error": result.error_message,
- "conflicting_policies": result.conflicting_policies,
- "guidance": "Split your changes into separate API calls to address each policy independently",
- }
+ # A plain ValidationError would be flattened by the exceptions-hog handler into a generic
+ # `invalid_input` code, losing the conflict signal. Raise a dedicated exception the ViewSet
+ # renders into the same `policy_conflict` body as the viewset path (see _result_to_response).
+ raise PolicyConflict(
+ conflicting_policies=result.conflicting_policies,
+ message=result.error_message or "This change matches multiple approval policies",
+ guidance="Split your changes into separate API calls to address each policy independently",
)
if result.action == "duplicate":
@@ -464,6 +486,11 @@ def approval_gate(action_refs: Union[type, str, list]):
if not actions:
return method(self, *args, **kwargs)
+ # The approved change is applied through this same serializer; re-gating it
+ # here would block (or duplicate) a change that is already approved.
+ if isinstance(getattr(self, "context", None), dict) and self.context.get("approval_apply"):
+ return method(self, *args, **kwargs)
+
is_serializer = hasattr(self, "context") and isinstance(self.context, dict) and "request" in self.context
if is_serializer:
@@ -481,18 +508,19 @@ def approval_gate(action_refs: Union[type, str, list]):
if not _is_approvals_enabled(organization):
return method(self, *args, **kwargs)
- # Find first action that matches and has a policy
- matched_action = None
- matched_policy = None
-
+ # Collect every action that matches this change AND has an enabled policy — not just
+ # the first. The approved change is applied by replaying the full validated payload
+ # (see actions.feature_flags._apply_create / apply), so a change that trips more than one
+ # policy-backed action (e.g. a create that both enables the flag and sets its rollout)
+ # would satisfy a single policy while the other policies' gated fields sail through
+ # unapproved. Gating on only the first match reopens exactly that bypass.
+ matches: list[tuple[Any, Any]] = []
for action_class in actions:
try:
if action_class.detect(request, self, *args, **kwargs):
policy = _check_policy_for_action(action_class, team, organization)
if policy:
- matched_action = action_class
- matched_policy = policy
- break
+ matches.append((action_class, policy))
except Exception as e:
logger.error(
"Error in action detect()",
@@ -500,20 +528,38 @@ def approval_gate(action_refs: Union[type, str, list]):
exc_info=True,
)
- if not matched_action or not matched_policy:
+ if not matches:
return method(self, *args, **kwargs)
- # Evaluate the gate with matched action
- result = _evaluate_gate(
- action_class=matched_action,
- request=request,
- team=team,
- organization=organization,
- policy=matched_policy,
- view_or_serializer=self,
- args=args,
- kwargs=kwargs,
- )
+ if len(matches) > 1:
+ # A single ChangeRequest can only carry one action's approval, but the apply path
+ # replays the whole payload — so we cannot safely gate a change that needs approval
+ # under several policies at once. Reject it (fail closed) and tell the caller to
+ # split it, mirroring the multi-policy conflict handling in _evaluate_gate.
+ logger.warning(
+ "Change matches multiple policy-backed actions",
+ extra={"actions": [action_class.key for action_class, _ in matches]},
+ )
+ result = GateResult(
+ action="policy_conflict",
+ conflicting_policies=[
+ {"id": str(policy.id), "name": str(policy), "action_key": action_class.key}
+ for action_class, policy in matches
+ ],
+ error_message="This change requires approval under multiple policies",
+ )
+ else:
+ matched_action, matched_policy = matches[0]
+ result = _evaluate_gate(
+ action_class=matched_action,
+ request=request,
+ team=team,
+ organization=organization,
+ policy=matched_policy,
+ view_or_serializer=self,
+ args=args,
+ kwargs=kwargs,
+ )
# Convert result to appropriate output format
if is_serializer:
diff --git a/products/approvals/backend/exceptions.py b/products/approvals/backend/exceptions.py
index 53cf97f7853f..a26e81415f3d 100644
--- a/products/approvals/backend/exceptions.py
+++ b/products/approvals/backend/exceptions.py
@@ -44,6 +44,22 @@ class ApprovalRequired(ApprovalException):
super().__init__(message)
+class PolicyConflict(ApprovalException):
+ """
+ Raised when a single change would require approval under more than one policy.
+
+ Raised from serializer methods (mirroring ApprovalRequired) so the ViewSet can catch it and
+ return a 400 telling the caller to split the change — a single ChangeRequest can only carry
+ one action's approval, so a change matching several policy-backed actions can't be gated safely.
+ """
+
+ def __init__(self, conflicting_policies: list, message: str, guidance: str):
+ self.conflicting_policies = conflicting_policies
+ self.message = message
+ self.guidance = guidance
+ super().__init__(message)
+
+
class ChangeRequestError(ApprovalException):
"""Base exception for change request service operations."""
diff --git a/products/approvals/backend/migrations/0002_alter_changerequest_validation_status.py b/products/approvals/backend/migrations/0002_alter_changerequest_validation_status.py
new file mode 100644
index 000000000000..5662803ee62d
--- /dev/null
+++ b/products/approvals/backend/migrations/0002_alter_changerequest_validation_status.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("approvals", "0001_migrate_approvals_models"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="changerequest",
+ name="validation_status",
+ field=models.CharField(
+ choices=[
+ ("valid", "Valid"),
+ ("invalid", "Invalid"),
+ ("stale", "Stale (resource changed)"),
+ ],
+ default="valid",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/approvals/backend/migrations/max_migration.txt b/products/approvals/backend/migrations/max_migration.txt
index 21e2fe39a8a9..5476a3a14938 100644
--- a/products/approvals/backend/migrations/max_migration.txt
+++ b/products/approvals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_migrate_approvals_models
+0002_alter_changerequest_validation_status
diff --git a/products/approvals/backend/mixins.py b/products/approvals/backend/mixins.py
index bc8766c9f3d1..16d536499bd5 100644
--- a/products/approvals/backend/mixins.py
+++ b/products/approvals/backend/mixins.py
@@ -1,17 +1,17 @@
from rest_framework import status
from rest_framework.response import Response
-from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
from products.approvals.backend.serializers import ChangeRequestSerializer
class ApprovalHandlingMixin:
"""
- Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
- This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- on serializer methods and converts them into proper HTTP 409 Conflict responses with
- change request details.
+ Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ decorator on serializer methods and converts them into the same responses the viewset path
+ produces (see decorators._result_to_response), so both paths share one contract.
"""
def handle_exception(self, exc: Exception) -> Response:
@@ -31,4 +31,15 @@ class ApprovalHandlingMixin:
status=status.HTTP_409_CONFLICT,
)
+ if isinstance(exc, PolicyConflict):
+ return Response(
+ {
+ "code": "policy_conflict",
+ "error": exc.message,
+ "conflicting_policies": exc.conflicting_policies,
+ "guidance": exc.guidance,
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
return super().handle_exception(exc) # type: ignore[misc]
diff --git a/products/approvals/backend/models.py b/products/approvals/backend/models.py
index c993b8bbb3ee..28a9fcab3b0a 100644
--- a/products/approvals/backend/models.py
+++ b/products/approvals/backend/models.py
@@ -22,7 +22,6 @@ class ChangeRequestState(models.TextChoices):
class ValidationStatus(models.TextChoices):
VALID = "valid", "Valid"
INVALID = "invalid", "Invalid"
- EXPIRED = "expired", "Expired"
STALE = "stale", "Stale (resource changed)"
diff --git a/products/approvals/backend/scheduled_changes.py b/products/approvals/backend/scheduled_changes.py
new file mode 100644
index 000000000000..8835a02ce2c1
--- /dev/null
+++ b/products/approvals/backend/scheduled_changes.py
@@ -0,0 +1,357 @@
+"""Creation-time approval gating for feature-flag scheduled changes.
+
+A ``ScheduledChange`` row is created ungated and later applied by the Celery task
+``process_scheduled_changes`` via ``FeatureFlag.scheduled_changes_dispatcher``. Without this
+module a scheduled change could flip a policy-gated field (enabling a flag, raising rollout)
+with no approval. Here we evaluate the same approval actions the request-time gate uses
+(``decorators._evaluate_gate``) against the change a scheduled row *would* apply, and — when an
+enabled policy requires approval — create a pending ``ChangeRequest`` bound to the scheduled
+change. The applier then keys off that binding (see ``process_scheduled_changes``).
+"""
+
+import logging
+from typing import TYPE_CHECKING, Any, NamedTuple, Optional
+
+from django.db import transaction
+from django.http import HttpRequest
+
+from products.approvals.backend import decorators
+from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
+from products.approvals.backend.notifications import send_approval_expired_notification
+from products.approvals.backend.services import apply_change_request
+
+if TYPE_CHECKING:
+ from products.feature_flags.backend.models.feature_flag import FeatureFlag
+ from products.feature_flags.backend.models.scheduled_change import ScheduledChange
+
+logger = logging.getLogger(__name__)
+
+
+class _GatedAction(NamedTuple):
+ """The enabled approval action + policy that gates a scheduled change, plus the request-time
+ gate context needed to evaluate it. Named so the slots can't be silently reordered at the one
+ callsite that unpacks them (mirrors the structured ``GateResult`` returned by ``_evaluate_gate``).
+ """
+
+ action_class: Any
+ policy: Any
+ serializer: Any
+ http_request: HttpRequest
+ gate_args: tuple
+
+
+def scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """Translate a scheduled-change payload into the serializer-shaped change it would apply.
+
+ Thin wrapper over the shared ``build_scheduled_change_serializer_data`` that the apply-time
+ dispatcher (``FeatureFlag.scheduled_changes_dispatcher``) also uses, so the gate sees exactly
+ the change the applier would make. Returns ``None`` when the payload is malformed or its
+ operation is unrecognized — the applier surfaces those errors at apply time, the gate simply
+ declines to create a CR for a change it cannot interpret.
+ """
+ # Deferred: this module is imported by posthog.tasks, which feature_flags transitively imports —
+ # an eager import would create a circular import at startup.
+ from products.feature_flags.backend.models.feature_flag import ( # noqa: PLC0415
+ build_scheduled_change_serializer_data,
+ )
+
+ return build_scheduled_change_serializer_data(flag, payload)
+
+
+def _detect_gated_action(flag: "FeatureFlag", payload: dict[str, Any], user) -> Optional[_GatedAction]:
+ """Detect the enabled approval action + policy that gates a scheduled change — no side effects.
+
+ Runs only the request-time gate's *detection* (``action.detect`` + ``_check_policy_for_action``)
+ against the flag's current state, so no ``ChangeRequest`` is created and no notification is sent.
+ Returns ``(matched_action, matched_policy, serializer, http_request, gate_args)`` when an enabled
+ policy gates the change the payload would apply, else ``None`` (approvals disabled, malformed
+ payload, or no gated action matches). Shared by ``gate_scheduled_change`` (which then evaluates
+ the gate to create/reuse a CR) and by the fire-time re-check that keeps creation-time and
+ request-time gating in lockstep.
+ """
+ # Deferred: feature_flags' serializer/actions transitively import posthog.tasks, which imports
+ # this module — eager imports would create a circular import at startup.
+ from products.approvals.backend.actions.feature_flags import ( # noqa: PLC0415
+ DisableFeatureFlagAction,
+ EnableFeatureFlagAction,
+ UpdateFeatureFlagAction,
+ )
+ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer # noqa: PLC0415
+
+ team = flag.team
+ organization = team.organization
+
+ if not decorators._is_approvals_enabled(organization):
+ return None
+
+ serializer_data = scheduled_change_serializer_data(flag, payload)
+ if serializer_data is None:
+ return None
+
+ feature_flag_actions = [EnableFeatureFlagAction, DisableFeatureFlagAction, UpdateFeatureFlagAction]
+
+ # Build a partial-update serializer over the real flag so detect()/extract_intent() read the
+ # change out of validated_data exactly as they do for an API-driven update.
+ http_request = HttpRequest()
+ http_request.user = user or flag.created_by # type: ignore[assignment]
+ http_request.method = "PATCH"
+ context = {
+ "request": http_request,
+ "team_id": team.id,
+ "project_id": team.project_id,
+ "get_team": lambda: team,
+ "get_organization": lambda: organization,
+ }
+ serializer = FeatureFlagSerializer(instance=flag, data=serializer_data, partial=True, context=context)
+ if not serializer.is_valid():
+ # An invalid change can't be applied either; let the applier surface the error.
+ return None
+
+ # The gate's serializer path reads the validated change from args[1] (update's validated_data).
+ gate_args: tuple = (flag, dict(serializer.validated_data))
+
+ for action_class in feature_flag_actions:
+ try:
+ if action_class.detect(http_request, serializer, *gate_args):
+ policy = decorators._check_policy_for_action(action_class, team, organization)
+ if policy:
+ return _GatedAction(action_class, policy, serializer, http_request, gate_args)
+ except Exception:
+ logger.exception(
+ "Error detecting action for scheduled change",
+ extra={"action": action_class.key, "flag_id": flag.id},
+ )
+
+ return None
+
+
+def gate_scheduled_change(
+ flag: "FeatureFlag",
+ payload: dict[str, Any],
+ user,
+ current_change_request: Optional[ChangeRequest] = None,
+) -> Optional[ChangeRequest]:
+ """Evaluate the approval gate for a scheduled change and create a pending CR if required.
+
+ Returns the created ``ChangeRequest`` when an enabled policy gates the change the scheduled
+ payload would apply, otherwise ``None`` (no policy, approvals disabled, or the change doesn't
+ match any gated action). Reuses the request-time gate's action detection and CR creation so
+ creation-time gating and request-time gating stay in lockstep.
+
+ ``current_change_request`` is the CR already bound to the schedule being (re)gated, if any.
+ Re-gating an unchanged action after a payload edit legitimately rediscovers that same pending
+ CR; passing it here lets us tell "reuse my own binding" apart from "bind to someone else's
+ pending request" (see the duplicate handling below).
+
+ Raises ``PolicyConflict`` when the change matches more than one enabled policy: a single
+ ``ChangeRequest`` can only carry one approval, so binding one would let the other policy's
+ gated change ride along unapproved. We fail closed rather than save the row ungated — callers
+ surface this as a 400 (creation/update) or skip the change (copy / recurring re-gate).
+
+ Raises ``ApprovalRequired`` when the only matching request is a pending or approved duplicate
+ that is not this schedule's own binding: binding it would let this schedule fire another
+ change's approval at a moment that approval never covered (the second-schedule / immediate-
+ change-then-schedule bypass). Fail closed.
+ """
+ detection = _detect_gated_action(flag, payload, user)
+ if detection is None:
+ return None
+
+ result = decorators._evaluate_gate(
+ action_class=detection.action_class,
+ request=detection.http_request,
+ team=flag.team,
+ organization=flag.team.organization,
+ policy=detection.policy,
+ view_or_serializer=detection.serializer,
+ args=detection.gate_args,
+ kwargs={},
+ )
+
+ if result.action == "policy_conflict":
+ # Multiple enabled policies match this change. We can't bind a single CR that satisfies
+ # all of them, and returning None here would save the schedule ungated and let the Celery
+ # applier dispatch it with no approval. Fail closed.
+ raise PolicyConflict(
+ conflicting_policies=result.conflicting_policies,
+ message=result.error_message or "This change matches multiple approval policies",
+ guidance="Split your changes into separate scheduled changes to address each policy independently",
+ )
+
+ if result.action == "require_approval":
+ return result.change_request
+
+ if result.action == "duplicate":
+ existing = result.change_request
+ # Reusing a pending CR is only safe when it is *this* schedule's own binding — e.g. re-gating
+ # an unchanged action after a payload edit rediscovers the CR already bound to the row. Any
+ # other duplicate must fail closed:
+ # - A pending CR belonging to another schedule (or an immediate change) would, once bound
+ # here, let this schedule fire that approval at a time it never covered — e.g. create a
+ # future gated schedule, then a second schedule for the same flag/action at an earlier
+ # time that rides the same pending CR and applies early once approved.
+ # - An approved CR is likewise not ours to fire on our own timing.
+ # The caller surfaces this as a 409 (creation/update) or skips the change (copy / recurring
+ # re-gate).
+ if (
+ existing is not None
+ and existing.state == ChangeRequestState.PENDING
+ and current_change_request is not None
+ and existing.id == current_change_request.id
+ ):
+ return existing
+ if existing is not None:
+ raise ApprovalRequired(
+ change_request=existing,
+ message=(
+ "A change for this feature flag is already awaiting approval or its scheduled "
+ "application. Wait for it to resolve before scheduling another change."
+ ),
+ required_approvers={},
+ error_code="change_request_pending",
+ )
+ return None
+
+ return None
+
+
+def _unbound_change_is_now_gated(scheduled_change: "ScheduledChange", flag: "FeatureFlag") -> bool:
+ """True when a schedule with no bound CR would flip a policy-gated field against the flag's
+ *current* state.
+
+ Detection only (no CR is created, no notification sent) — a fire-time re-check that closes the
+ stale-read bypass where a change that was a harmless no-op at scheduling time becomes a real,
+ policy-gated change by the time it fires because the flag drifted in between. Takes the flag the
+ sweep already loaded rather than re-querying the row (and its team/organization) under the open
+ transaction.
+ """
+ return _detect_gated_action(flag, scheduled_change.payload, scheduled_change.created_by) is not None
+
+
+def _expire_change_request(change_request: ChangeRequest, scheduled_change: "ScheduledChange", reason: str) -> None:
+ """Expire a scheduled change's bound CR (terminal state) and notify its requester.
+
+ Centralizes the expire → save → log → notify ritual shared by the fire-window-closed (PENDING)
+ and approved-but-stale branches of ``apply_gated_scheduled_change``. The notification mirrors
+ ``expire_old_change_requests`` (the canonical expiry sweep), so whoever requested — and, in the
+ stale case, approved — the change is told it was discarded instead of it silently vanishing.
+
+ The notification is deferred with ``transaction.on_commit`` because this runs inside the sweep's
+ ``transaction.atomic()``: emailing / realtime-dispatching before commit would fire even if the
+ surrounding transaction later rolls back.
+ """
+ change_request.state = ChangeRequestState.EXPIRED
+ change_request.save(update_fields=["state"])
+ logger.info(
+ reason,
+ extra={
+ "scheduled_change_id": scheduled_change.id,
+ "change_request_id": str(change_request.id),
+ },
+ )
+
+ def _notify() -> None:
+ try:
+ send_approval_expired_notification(change_request)
+ except Exception:
+ logger.warning(
+ "Failed to send change-request expiry notification for scheduled change",
+ extra={
+ "scheduled_change_id": scheduled_change.id,
+ "change_request_id": str(change_request.id),
+ },
+ )
+
+ transaction.on_commit(_notify)
+
+
+def apply_gated_scheduled_change(scheduled_change: "ScheduledChange", flag: "FeatureFlag") -> bool:
+ """Decide what to do with a gated scheduled change at fire time.
+
+ Returns ``True`` when the caller should dispatch the change through the normal
+ ``scheduled_changes_dispatcher`` path (no binding CR and no policy now gates the change, or the
+ CR has already been applied via the approved path here), and ``False`` when the change must be
+ skipped (its CR is still pending and the fire window has closed, so the CR is expired and nothing
+ is applied; or an unbound change would now flip a policy-gated field with no approval).
+
+ - Bound CR is APPROVED and not stale: apply via ``apply_change_request`` (the approved,
+ non-re-gating path) and return ``False`` so the caller does not dispatch again.
+ - Bound CR is still PENDING: the fire window has closed (the row is only processed once
+ ``scheduled_at <= now``), so mark the CR EXPIRED and return ``False`` — skip the change.
+ - Bound CR is in any other terminal state (APPLIED/REJECTED/EXPIRED/FAILED): do not re-apply;
+ return ``False``.
+ - No bound CR: re-check the gate against the flag's *current* state. A schedule binds no CR when
+ its change was a no-op at scheduling time (e.g. an enable scheduled while the flag was already
+ active), but the flag can drift before the fire window — a stale-read bypass where the schedule
+ would re-enable a since-disabled flag with the enable policy never consulted. If a policy now
+ gates the change, fail closed (return ``False``, skip); otherwise dispatch as before (``True``).
+
+ Must be called inside the sweep's ``transaction.atomic()``: the bound CR is re-fetched under a
+ row lock so this decision reads the latest committed state and serializes with
+ ``ChangeRequestService.approve()``.
+ """
+ if scheduled_change.change_request_id is None:
+ return not _unbound_change_is_now_gated(scheduled_change, flag)
+
+ # Re-fetch under a row lock rather than trusting the prefetched copy. The sweep locks only the
+ # ScheduledChange rows (select_for_update(of=("self",))), so a concurrent approve() that flips
+ # this CR PENDING→APPROVED between the sweep's SELECT and here would otherwise be read as
+ # still-PENDING and wrongly expired below — dropping a valid approval. Locking blocks until any
+ # in-flight approve() commits and reads its result (approve() takes the same CR lock first).
+ # Scope to the schedule's team: the bound CR always shares its team, and it keeps the lookup
+ # tenant-isolated (idor-lookup-without-team).
+ change_request = ChangeRequest.objects.select_for_update().get(
+ pk=scheduled_change.change_request_id, team_id=scheduled_change.team_id
+ )
+
+ if (
+ change_request.state == ChangeRequestState.APPROVED
+ and change_request.validation_status != ValidationStatus.STALE
+ ):
+ apply_change_request(change_request)
+ return False
+
+ if change_request.state == ChangeRequestState.PENDING:
+ # Time window closed with no approval — expire the request (terminal) and skip the change.
+ _expire_change_request(
+ change_request,
+ scheduled_change,
+ "Expired pending change request for scheduled change past its fire window",
+ )
+ return False
+
+ if change_request.state == ChangeRequestState.APPROVED:
+ # Reachable only when STALE (the approved-and-not-stale case applied and returned above).
+ # Expire it here (terminal) rather than leaning on the hourly expire_old_change_requests
+ # sweep: for a recurring schedule the next re-gate runs immediately, and a stale-approved
+ # CR left in [PENDING, APPROVED] would be rediscovered by the flag-scoped duplicate check
+ # as a duplicate it can't reuse (reuse requires PENDING), raising ApprovalRequired and
+ # retrying the schedule to exhaustion long before the sweep (expires_at is policy-tunable
+ # and can be days out) would clear it.
+ _expire_change_request(
+ change_request,
+ scheduled_change,
+ "Expired approved-but-stale change request for scheduled change",
+ )
+ return False
+
+ # APPLIED / REJECTED / EXPIRED / FAILED: nothing to apply.
+ return False
+
+
+def regate_recurring_scheduled_change(
+ scheduled_change: "ScheduledChange", flag: "FeatureFlag"
+) -> Optional[ChangeRequest]:
+ """Create a fresh pending CR for the next occurrence of a recurring gated schedule.
+
+ A bound ChangeRequest is single-use — it carries one occurrence's intent. When a recurring
+ schedule advances to its next fire, re-run the gate against the flag's current state so the
+ next occurrence is independently gated. Returns the new CR (or None if no policy now applies).
+ Takes the flag the sweep already loaded rather than re-querying it.
+
+ May raise ``PolicyConflict`` when the next occurrence would match multiple policies; the
+ scheduled-change task's error handling then records the failure and stops advancing the
+ schedule rather than dispatching the occurrence ungated.
+ """
+ return gate_scheduled_change(flag, scheduled_change.payload, scheduled_change.created_by)
diff --git a/products/approvals/backend/services.py b/products/approvals/backend/services.py
index 4e75ca84fbc4..01c9274899ce 100644
--- a/products/approvals/backend/services.py
+++ b/products/approvals/backend/services.py
@@ -242,6 +242,25 @@ class ChangeRequestService:
change_request.state = ChangeRequestState.APPROVED
change_request.save()
+ # A change request bound to a scheduled change must not be applied on approval:
+ # the scheduled applier (process_scheduled_changes) applies it only once
+ # scheduled_at is reached. Auto-applying here would let an approver fire a
+ # future-dated flag change immediately, defeating the schedule.
+ if change_request.scheduled_changes.exists():
+ logger.info(
+ "Quorum reached for scheduled change; deferring application to fire time",
+ extra={
+ "change_request_id": str(change_request.id),
+ "action_key": change_request.action_key,
+ },
+ )
+ return ApproveResult(
+ status="approved",
+ message="Quorum reached. Change approved and will be applied at its scheduled time.",
+ change_request=change_request,
+ auto_applied=False,
+ )
+
logger.info(
"Quorum reached, auto-applying change request",
extra={
diff --git a/products/approvals/backend/tests/test_create_feature_flag_gate.py b/products/approvals/backend/tests/test_create_feature_flag_gate.py
new file mode 100644
index 000000000000..dd995331f6c2
--- /dev/null
+++ b/products/approvals/backend/tests/test_create_feature_flag_gate.py
@@ -0,0 +1,264 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from products.approvals.backend.actions.feature_flags import (
+ DisableFeatureFlagAction,
+ EnableFeatureFlagAction,
+ UpdateFeatureFlagAction,
+)
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState
+from products.approvals.backend.services import ChangeRequestService
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestCreateDetection(APIBaseTest):
+ """On a create, @approval_gate wraps FeatureFlagSerializer.create(self, validated_data),
+ so there is no instance — args[0] is the validated change dict. Enable must fire when the
+ new flag is born active; update must fire when its rollout meets a gated condition. Creating
+ a disabled flag stays free, and disable never fires on a create."""
+
+ def _serializer_view(self) -> MagicMock:
+ view = MagicMock()
+ view.context = {"request": MagicMock(), "get_team": lambda: self.team}
+ return view
+
+ def _post_request(self) -> MagicMock:
+ request = MagicMock()
+ request.method = "POST"
+ request.data = {}
+ return request
+
+ def test_enable_detects_when_new_flag_born_active(self):
+ view = self._serializer_view()
+ # create() is called as create(self, validated_data) -> args = (validated_data,)
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, {"key": "f", "active": True})
+ assert result is True
+
+ def test_enable_does_not_fire_when_new_flag_disabled(self):
+ view = self._serializer_view()
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, {"key": "f", "active": False})
+ assert result is False
+
+ def test_enable_fires_when_active_absent_on_create(self):
+ # FeatureFlag.active defaults to True, so a create that omits `active` is still born
+ # enabled — the gate must fire, otherwise the enable policy is trivially bypassed.
+ view = self._serializer_view()
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, {"key": "f"})
+ assert result is True
+
+ def test_disable_never_fires_on_create(self):
+ view = self._serializer_view()
+ result = DisableFeatureFlagAction.detect(self._post_request(), view, {"key": "f", "active": False})
+ assert result is False
+
+ def test_update_detects_rollout_on_create(self):
+ view = self._serializer_view()
+ # Born at 100% trips an "any rollout change / >0" policy against an empty baseline.
+ validated_data = {"key": "f", "get_filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}}
+ result = UpdateFeatureFlagAction.detect(self._post_request(), view, validated_data)
+ assert result is True
+
+ def test_update_does_not_fire_on_create_without_rollout(self):
+ view = self._serializer_view()
+ validated_data = {"key": "f", "get_filters": {"groups": [{"properties": []}]}}
+ result = UpdateFeatureFlagAction.detect(self._post_request(), view, validated_data)
+ assert result is False
+
+ def test_enable_extract_intent_on_create_has_no_flag_id(self):
+ view = self._serializer_view()
+ intent = EnableFeatureFlagAction.extract_intent(self._post_request(), view, {"key": "f", "active": True})
+ assert intent["flag_id"] is None
+ assert intent["current_state"] == {"active": False}
+ assert intent["gated_changes"] == {"active": True}
+ assert intent["full_request_data"]["key"] == "f"
+
+ def test_update_extract_intent_on_create_uses_empty_baseline(self):
+ view = self._serializer_view()
+ validated_data = {"key": "f", "get_filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}}
+ intent = UpdateFeatureFlagAction.extract_intent(self._post_request(), view, validated_data)
+ assert intent["flag_id"] is None
+ assert intent["current_state"]["rollout_percentage"] == []
+ assert intent["gated_changes"]["rollout_percentage"][0]["value"] == 100
+ assert intent["full_request_data"]["filters"]["groups"][0]["rollout_percentage"] == 100
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestCreateFlagGateAPI(APIBaseTest):
+ """End-to-end: creating a flag that lands in a guarded state must require approval and NOT
+ create the row until approved."""
+
+ def _enable_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _update_policy(self, conditions: dict[str, Any] | None = None) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions=conditions if conditions is not None else {},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def test_create_active_flag_under_enable_policy_requires_approval(self, _mock_enabled):
+ self._enable_policy()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-active", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ assert not FeatureFlag.objects.filter(team=self.team, key="born-active").exists()
+
+ def test_create_flag_without_active_under_enable_policy_requires_approval(self, _mock_enabled):
+ # Omitting `active` lands the flag enabled (model default True), so the enable policy
+ # must still gate it — the create must not slip through unapproved.
+ self._enable_policy()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-active-implicit", "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ assert not FeatureFlag.objects.filter(team=self.team, key="born-active-implicit").exists()
+
+ def test_create_disabled_flag_under_enable_policy_succeeds(self, _mock_enabled):
+ self._enable_policy()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-disabled", "active": False, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 201
+ assert FeatureFlag.objects.filter(team=self.team, key="born-disabled", active=False).exists()
+
+ def test_create_active_flag_without_policy_succeeds(self, _mock_enabled):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "no-policy", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 201
+ assert FeatureFlag.objects.filter(team=self.team, key="no-policy", active=True).exists()
+
+ def test_approve_create_change_request_creates_flag_once(self, _mock_enabled):
+ self._enable_policy()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-active", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+ assert response.status_code == 409
+ cr_id = response.json()["change_request_id"]
+
+ cr = ChangeRequest.objects.get(id=cr_id)
+ assert cr.resource_id is None
+ result = ChangeRequestService(cr, self.user).approve()
+ assert result.status == "applied"
+
+ flags = FeatureFlag.objects.filter(team=self.team, key="born-active")
+ assert flags.count() == 1
+ flag = flags.first()
+ assert flag is not None
+ assert flag.active is True
+ assert flag.filters["groups"][0]["rollout_percentage"] == 100
+
+ def test_create_rollout_gated_flag_requires_approval_then_applies(self, _mock_enabled):
+ # any-change-from-baseline: a born-at-100% flag trips a >0 condition.
+ self._update_policy({"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0})
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "rollout-gated", "active": False, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+ assert response.status_code == 409
+ assert not FeatureFlag.objects.filter(team=self.team, key="rollout-gated").exists()
+
+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])
+ ChangeRequestService(cr, self.user).approve()
+
+ flag = FeatureFlag.objects.get(team=self.team, key="rollout-gated")
+ assert flag.filters["groups"][0]["rollout_percentage"] == 100
+
+ def test_create_active_flag_with_rollout_under_both_policies_is_rejected(self, _mock_enabled):
+ # A create that both enables the flag AND sets its rollout trips the enable policy and the
+ # rollout-update policy at once. A single ChangeRequest carries one action's approval, and
+ # the apply path replays the whole create payload — so gating on just the enable would let
+ # the rollout change land unapproved. The gate must reject it (fail closed) and ask the
+ # caller to split the change, creating neither the flag nor a partial ChangeRequest.
+ self._enable_policy()
+ self._update_policy({"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0})
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-active-rollout", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 400, response.content
+ assert response.json().get("code") == "policy_conflict"
+ assert not FeatureFlag.objects.filter(team=self.team, key="born-active-rollout").exists()
+ assert ChangeRequest.objects.count() == 0
+
+ def test_create_remote_config_flag_without_filters_requires_rollout_approval(self, _mock_enabled):
+ # A remote-config create carries no `filters`; the serializer synthesizes a 100% rollout.
+ # That default must be materialized before the gate runs, otherwise the create slips past
+ # the rollout policy and lands a 100% rollout unapproved.
+ self._update_policy({"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0})
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "remote-config-flag", "active": False, "is_remote_configuration": True},
+ format="json",
+ )
+
+ assert response.status_code == 409, response.content
+ assert response.json().get("code") == "approval_required"
+ assert not FeatureFlag.objects.filter(team=self.team, key="remote-config-flag").exists()
+
+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])
+ ChangeRequestService(cr, self.user).approve()
+
+ flag = FeatureFlag.objects.get(team=self.team, key="remote-config-flag")
+ assert flag.filters["groups"][0]["rollout_percentage"] == 100
+
+ def test_reapplying_create_change_request_does_not_duplicate(self, _mock_enabled):
+ self._enable_policy()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-active", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])
+ ChangeRequestService(cr, self.user).approve()
+ assert FeatureFlag.objects.filter(team=self.team, key="born-active").count() == 1
+
+ # Re-apply the already-applied CR: must not create a second row.
+ from products.approvals.backend.services import apply_change_request
+
+ cr.refresh_from_db()
+ cr.state = ChangeRequestState.APPROVED
+ cr.save()
+ apply_change_request(cr)
+ assert FeatureFlag.objects.filter(team=self.team, key="born-active").count() == 1
diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.py
new file mode 100644
index 000000000000..1d79f09aa31f
--- /dev/null
+++ b/products/approvals/backend/tests/test_decorators.py
@@ -0,0 +1,105 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.models import ApprovalPolicy
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestApprovalGateFailsClosed(APIBaseTest):
+ """The gate must derive team/org from the serializer instance when the
+ context lacks get_team/get_organization callables, instead of silently
+ skipping the approval workflow (fail-closed, not fail-open)."""
+
+ def _create_disabled_flag(self) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ key="test-flag",
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ active=False,
+ created_by=self.user,
+ )
+
+ def _create_enable_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _drf_request(self, data: dict[str, Any]) -> MagicMock:
+ # detect()/extract_intent() read request.data, so the request must carry the payload.
+ request = MagicMock()
+ request.method = "PATCH"
+ request.data = data
+ request.user = self.user
+ request.path = f"/api/projects/{self.team.id}/feature_flags/"
+ return request
+
+ def _serializer(self, flag: FeatureFlag, data: dict[str, Any], context: dict[str, Any]) -> FeatureFlagSerializer:
+ serializer = FeatureFlagSerializer(instance=flag, data=data, partial=True, context=context)
+ serializer.is_valid()
+ return serializer
+
+ def test_gate_blocks_when_context_lacks_org_and_team_callables(self, _mock_enabled):
+ flag = self._create_disabled_flag()
+ self._create_enable_policy()
+ request = self._drf_request({"active": True})
+
+ # Internal caller context: team_id present, but NO get_team/get_organization callables.
+ serializer = self._serializer(
+ flag,
+ {"active": True},
+ {"request": request, "team_id": self.team.id, "project_id": self.team.project_id},
+ )
+
+ with self.assertRaises(ApprovalRequired):
+ serializer.save()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_gate_blocks_with_full_org_context(self, _mock_enabled):
+ flag = self._create_disabled_flag()
+ self._create_enable_policy()
+ request = self._drf_request({"active": True})
+
+ serializer = self._serializer(
+ flag,
+ {"active": True},
+ {
+ "request": request,
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ },
+ )
+
+ with self.assertRaises(ApprovalRequired):
+ serializer.save()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_gate_passes_through_when_no_policy(self, _mock_enabled):
+ flag = self._create_disabled_flag()
+ request = self._drf_request({"active": True})
+
+ serializer = self._serializer(
+ flag,
+ {"active": True},
+ {"request": request, "team_id": self.team.id, "project_id": self.team.project_id},
+ )
+
+ serializer.save()
+
+ flag.refresh_from_db()
+ assert flag.active is True
diff --git a/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py
new file mode 100644
index 000000000000..dffdc9a8c2fb
--- /dev/null
+++ b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py
@@ -0,0 +1,550 @@
+"""Consolidated adversarial bypass matrix for feature-flag approval gating.
+
+This is the living catalog of every mutation path that can change a policy-gated
+feature-flag field, and the regression lock proving each one routes through the
+approval gate. The headline invariant: with an enabled policy, NOTHING changes a
+gated field without an approval — every write either creates a pending ChangeRequest
+and leaves the flag untouched, or (for the control cases) applies normally because no
+policy guards it.
+
+Each closed bypass below maps to a fix on this branch:
+ - direct PATCH enable/disable/update -> the baseline control the gate exists for
+ - experiment launch / pause / resume -> flag flips routed through FeatureFlagSerializer
+ - experiment ship_variant -> variant rollout rewrite gated by feature_flag.update
+ - web-experiment variant rollout edit -> update_experiment() variant write, gated by feature_flag.update
+ - copy onto existing-active / copy-as-active -> copy_flags lands the row in a guarded state
+ - create-active / create-rollout -> create() born in a guarded state
+ - delete + recreate-as-active -> re-create path is gated like any other create
+ - scheduled update_status / rollout change -> gated at scheduling time, expired if the window closes first
+
+The per-path detection/extract/end-to-end edge cases live in the dedicated task test
+files (test_decorators, test_update_feature_flag_action, test_create_feature_flag_gate,
+test_scheduled_change_gating, test_experiment_service_approvals, and the copy gate class
+in products/feature_flags/.../test_organization_feature_flag.py). This file asserts the
+headline "gated field UNCHANGED + a pending ChangeRequest created + 0 applied" outcome for
+each path in one place so a future regression on any single bypass fails loudly here.
+"""
+
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from rest_framework.test import APIRequestFactory
+
+from posthog.constants import AvailableFeature
+from posthog.tasks.process_scheduled_changes import process_scheduled_changes
+
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState
+from products.approvals.backend.services import ChangeRequestService
+from products.experiments.backend.experiment_service import ExperimentService
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.scheduled_change import ScheduledChange
+
+
+def _enable_policy_for(test: "FeatureFlagBypassMatrixBase", action_key: str) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=test.organization,
+ team=test.team,
+ action_key=action_key,
+ conditions={},
+ approver_config={"quorum": 1, "users": [test.user.id]},
+ created_by=test.user,
+ )
+
+
+def _any_rollout_change_policy(test: "FeatureFlagBypassMatrixBase") -> ApprovalPolicy:
+ # >0 from an empty/zero baseline fires on any non-trivial rollout write.
+ return ApprovalPolicy.objects.create(
+ organization=test.organization,
+ team=test.team,
+ action_key="feature_flag.update",
+ conditions={"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0},
+ approver_config={"quorum": 1, "users": [test.user.id]},
+ created_by=test.user,
+ )
+
+
+class FeatureFlagBypassMatrixBase(APIBaseTest):
+ """Shared setup. Concrete subclasses force the approvals feature on via the
+ _is_approvals_enabled patch, matching the convention used across the per-task tests."""
+
+ def _flag(self, *, active: bool, key: str = "matrix-flag", rollout: int = 50) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ key=key,
+ filters={"groups": [{"properties": [], "rollout_percentage": rollout}]},
+ active=active,
+ created_by=self.user,
+ )
+
+ def _assert_one_pending_zero_applied(self) -> None:
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.PENDING).count() == 1
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPLIED).count() == 0
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestDirectAndCreateBypassMatrix(FeatureFlagBypassMatrixBase):
+ """Paths that run through FeatureFlagSerializer.update()/create() over the public flag API.
+
+ Each case: drive the mutation under an enabled policy, then assert the gated field is
+ UNCHANGED, exactly one pending ChangeRequest exists, and nothing was applied.
+ """
+
+ def _patch(self, flag: FeatureFlag, data: dict[str, Any]) -> Any:
+ return self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", data, format="json")
+
+ def _post(self, data: dict[str, Any]) -> Any:
+ return self.client.post(f"/api/projects/{self.team.id}/feature_flags/", data, format="json")
+
+ def test_direct_patch_enable_is_gated(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.enable")
+ flag = self._flag(active=False)
+
+ response = self._patch(flag, {"active": True})
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ flag.refresh_from_db()
+ assert flag.active is False
+ self._assert_one_pending_zero_applied()
+
+ def test_direct_patch_disable_is_gated(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.disable")
+ flag = self._flag(active=True)
+
+ response = self._patch(flag, {"active": False})
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ flag.refresh_from_db()
+ assert flag.active is True
+ self._assert_one_pending_zero_applied()
+
+ def test_direct_patch_rollout_change_is_gated(self, _mock_enabled):
+ _any_rollout_change_policy(self)
+ flag = self._flag(active=True, rollout=20)
+
+ response = self._patch(flag, {"filters": {"groups": [{"properties": [], "rollout_percentage": 90}]}})
+
+ assert response.status_code == 409
+ flag.refresh_from_db()
+ assert flag.filters["groups"][0]["rollout_percentage"] == 20
+ self._assert_one_pending_zero_applied()
+
+ def test_create_active_is_gated(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.enable")
+
+ response = self._post(
+ {"key": "born-active", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}}
+ )
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ assert not FeatureFlag.objects.filter(team=self.team, key="born-active").exists()
+ self._assert_one_pending_zero_applied()
+
+ def test_delete_then_recreate_as_active_is_gated(self, _mock_enabled):
+ # Soft-deleting a flag then re-creating it as active is just another create() — it must
+ # not be a way to land a flag in a guarded state without approval.
+ existing = self._flag(active=False, key="recreate-flag")
+ self._patch(existing, {"deleted": True})
+ existing.refresh_from_db()
+ assert existing.deleted is True
+
+ _enable_policy_for(self, "feature_flag.enable")
+
+ response = self._post(
+ {"key": "recreate-flag", "active": True, "filters": {"groups": [{"rollout_percentage": 100}]}}
+ )
+
+ assert response.status_code == 409
+ assert response.json().get("code") == "approval_required"
+ assert not FeatureFlag.objects.filter(team=self.team, key="recreate-flag", active=True, deleted=False).exists()
+ self._assert_one_pending_zero_applied()
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestScheduledChangeBypassMatrix(FeatureFlagBypassMatrixBase):
+ """Scheduled changes are gated at scheduling time (a pending CR is bound to the row); the
+ Celery applier only applies once approved, and expires the CR if the fire window closes first.
+ A gated scheduled change must therefore leave the flag untouched and the CR EXPIRED."""
+
+ def _schedule(self, flag: FeatureFlag, payload: dict, scheduled_at: datetime) -> ScheduledChange:
+ from products.approvals.backend.scheduled_changes import gate_scheduled_change
+
+ return ScheduledChange.objects.create(
+ team=self.team,
+ record_id=str(flag.id),
+ model_name="FeatureFlag",
+ payload=payload,
+ scheduled_at=scheduled_at,
+ created_by=self.user,
+ change_request=gate_scheduled_change(flag, payload, self.user),
+ )
+
+ def test_scheduled_enable_is_gated(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.enable")
+ flag = self._flag(active=False)
+
+ scheduled = self._schedule(
+ flag, {"operation": "update_status", "value": True}, datetime.now(UTC) - timedelta(seconds=30)
+ )
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPLIED).count() == 0
+
+ def test_scheduled_disable_is_gated(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.disable")
+ flag = self._flag(active=True)
+
+ scheduled = self._schedule(
+ flag, {"operation": "update_status", "value": False}, datetime.now(UTC) - timedelta(seconds=30)
+ )
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ assert flag.active is True
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+
+ def test_scheduled_rollout_change_is_gated(self, _mock_enabled):
+ _any_rollout_change_policy(self)
+ flag = self._flag(active=False, key="sched-rollout")
+
+ scheduled = self._schedule(
+ flag,
+ {
+ "operation": "add_release_condition",
+ "value": {
+ "groups": [
+ {
+ "variant": None,
+ "properties": [],
+ "rollout_percentage": 90,
+ "aggregation_group_type_index": None,
+ }
+ ],
+ "payloads": {},
+ "multivariate": None,
+ },
+ },
+ timezone.now() - timedelta(seconds=30),
+ )
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ rollouts = [g.get("rollout_percentage") for g in flag.filters.get("groups", [])]
+ assert 90 not in rollouts
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestExperimentBypassMatrix(APIBaseTest):
+ """Experiment lifecycle transitions flip the linked flag through FeatureFlagSerializer, so each
+ must pass through the gate: launch/resume (enable), pause (disable), ship_variant + variant
+ rollout edits (update). A gated transition raises ApprovalRequired and leaves the flag untouched."""
+
+ _METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "m1",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ }
+
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+
+ def _service(self) -> ExperimentService:
+ return ExperimentService(team=self.team, user=self.user)
+
+ def _request(self) -> Any:
+ request = APIRequestFactory().post("/fake")
+ request.user = self.user
+ return request
+
+ def _policy(self, action_key: str) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key=action_key,
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _draft(self, key: str) -> Experiment:
+ return self._service().create_experiment(
+ name="Matrix",
+ feature_flag_key=key,
+ metrics=[self._METRIC],
+ primary_metrics_ordered_uuids=["m1"],
+ allow_unknown_events=True,
+ )
+
+ def _launched(self, key: str) -> Experiment:
+ experiment = self._draft(key)
+ self._service().launch_experiment(experiment, request=self._request())
+ experiment.refresh_from_db()
+ return experiment
+
+ def _assert_pending_zero_applied(self) -> None:
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.PENDING).count() == 1
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPLIED).count() == 0
+
+ def test_launch_is_gated(self, _mock_enabled):
+ experiment = self._draft("m-launch")
+ self._policy("feature_flag.enable")
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().launch_experiment(experiment, request=self._request())
+
+ experiment.refresh_from_db()
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+ assert experiment.start_date is None
+ self._assert_pending_zero_applied()
+
+ def test_pause_is_gated(self, _mock_enabled):
+ experiment = self._launched("m-pause")
+ assert experiment.feature_flag.active is True
+ self._policy("feature_flag.disable")
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().pause_experiment(experiment, request=self._request())
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is True
+ self._assert_pending_zero_applied()
+
+ def test_resume_is_gated(self, _mock_enabled):
+ experiment = self._launched("m-resume")
+ self._service().pause_experiment(experiment, request=self._request())
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+ self._policy("feature_flag.enable")
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().resume_experiment(experiment, request=self._request())
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+ self._assert_pending_zero_applied()
+
+ def test_ship_variant_is_gated(self, _mock_enabled):
+ experiment = self._launched("m-ship")
+ original_variants = experiment.feature_flag.filters["multivariate"]["variants"]
+ self._policy("feature_flag.update")
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().ship_variant(experiment, variant_key="test", request=self._request())
+
+ experiment.refresh_from_db()
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants
+ assert experiment.end_date is None
+ self._assert_pending_zero_applied()
+
+ def test_web_experiment_variant_rollout_edit_is_gated(self, _mock_enabled):
+ # update_experiment() writes a variant/rollout change back through FeatureFlagSerializer.
+ # It routes through feature_flag.update, raises ApprovalRequired, and leaves the flag's
+ # variants untouched. The gated flag write runs OUTSIDE update_experiment's atomic block
+ # (like ship_variant/launch/pause/resume), so the pending ChangeRequest the gate created
+ # survives for an approver to act on.
+ experiment = self._launched("m-web")
+ original_variants = experiment.feature_flag.filters["multivariate"]["variants"]
+ self._policy("feature_flag.update")
+
+ new_variants = [
+ {"key": "control", "rollout_percentage": 10},
+ {"key": "test", "rollout_percentage": 90},
+ ]
+
+ # Mirror the DRF serializer context the experiment viewset hands to update_experiment.
+ context = {
+ "request": self._request(),
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ }
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().update_experiment(
+ experiment,
+ {"parameters": {"feature_flag_variants": new_variants}, "update_feature_flag_params": True},
+ serializer_context=context,
+ )
+
+ # Security invariant: the gated field is unchanged and nothing was applied.
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants
+ # The gated flag write runs outside the atomic block, so the pending CR survives.
+ self._assert_pending_zero_applied()
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestCopyBypassMatrix(APIBaseTest):
+ """copy_flags routes through FeatureFlagSerializer create()/update(), so a copy that lands the
+ destination flag in a guarded state must gate. The gate raises inside serializer.save(), which
+ copy_flags surfaces as a per-project failure — the destination row is NOT made/mutated."""
+
+ def setUp(self):
+ super().setUp()
+ from posthog.models import Team
+
+ self.team_1 = self.team
+ self.team_2 = Team.objects.create(organization=self.organization)
+ self.source_flag = FeatureFlag.objects.create(
+ team=self.team_1,
+ created_by=self.user,
+ key="copy-matrix-flag",
+ active=True,
+ filters={"groups": [{"rollout_percentage": 100}]},
+ )
+
+ def _enable_policy(self, team: Any) -> None:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _copy(self, target_ids: list[int]) -> Any:
+ return self.client.post(
+ f"/api/organizations/{self.organization.id}/feature_flags/copy_flags",
+ {
+ "feature_flag_key": self.source_flag.key,
+ "from_project": self.source_flag.team_id,
+ "target_project_ids": target_ids,
+ },
+ )
+
+ def test_copy_active_to_new_target_is_gated(self, _mock_enabled):
+ self._enable_policy(self.team_2)
+
+ response = self._copy([self.team_2.id])
+
+ assert response.status_code == 200
+ assert response.json()["success"] == []
+ assert not FeatureFlag.objects.filter(team=self.team_2, key=self.source_flag.key).exists()
+
+ def test_copy_onto_existing_active_target_is_gated(self, _mock_enabled):
+ existing = FeatureFlag.objects.create(
+ team=self.team_2,
+ created_by=self.user,
+ key=self.source_flag.key,
+ active=False,
+ filters={"groups": [{"rollout_percentage": 0}]},
+ )
+ self._enable_policy(self.team_2)
+
+ response = self._copy([self.team_2.id])
+
+ assert response.status_code == 200
+ assert response.json()["success"] == []
+ existing.refresh_from_db()
+ assert existing.active is False
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestBypassMatrixControls(FeatureFlagBypassMatrixBase):
+ """Explicit controls: the gate must NOT fire where no policy guards the change, and an approved
+ change must actually apply. These guard against over-gating and prove the apply path works."""
+
+ def test_create_disabled_flag_under_enable_policy_succeeds(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.enable")
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/",
+ {"key": "born-disabled", "active": False, "filters": {"groups": [{"rollout_percentage": 100}]}},
+ format="json",
+ )
+
+ assert response.status_code == 201
+ assert FeatureFlag.objects.filter(team=self.team, key="born-disabled", active=False).exists()
+ assert ChangeRequest.objects.count() == 0
+
+ def test_enable_without_policy_applies_normally(self, _mock_enabled):
+ flag = self._flag(active=False)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"active": True}, format="json"
+ )
+
+ assert response.status_code == 200
+ flag.refresh_from_db()
+ assert flag.active is True
+ assert ChangeRequest.objects.count() == 0
+
+ def test_approving_pending_cr_applies_the_change(self, _mock_enabled):
+ _enable_policy_for(self, "feature_flag.enable")
+ flag = self._flag(active=False)
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"active": True}, format="json"
+ )
+ assert response.status_code == 409
+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])
+ assert cr.state == ChangeRequestState.PENDING
+
+ result = ChangeRequestService(cr, self.user).approve()
+ assert result.status == "applied"
+
+ flag.refresh_from_db()
+ assert flag.active is True
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.APPLIED
+
+ def test_scheduled_cr_past_window_is_expired_not_applied(self, _mock_enabled):
+ from products.approvals.backend.scheduled_changes import gate_scheduled_change
+
+ _enable_policy_for(self, "feature_flag.enable")
+ flag = self._flag(active=False)
+
+ payload = {"operation": "update_status", "value": True}
+ scheduled = ScheduledChange.objects.create(
+ team=self.team,
+ record_id=str(flag.id),
+ model_name="FeatureFlag",
+ payload=payload,
+ scheduled_at=datetime.now(UTC) - timedelta(seconds=30),
+ created_by=self.user,
+ change_request=gate_scheduled_change(flag, payload, self.user),
+ )
+ cr = scheduled.change_request
+ assert cr is not None
+ assert cr.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.EXPIRED
+ flag.refresh_from_db()
+ assert flag.active is False
diff --git a/products/approvals/backend/tests/test_scheduled_change_gating.py b/products/approvals/backend/tests/test_scheduled_change_gating.py
new file mode 100644
index 000000000000..ae9ceb30c989
--- /dev/null
+++ b/products/approvals/backend/tests/test_scheduled_change_gating.py
@@ -0,0 +1,749 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from posthog.models import User
+from posthog.tasks.process_scheduled_changes import process_scheduled_changes
+
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState, ValidationStatus
+from products.approvals.backend.services import ChangeRequestService
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.scheduled_change import ScheduledChange
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestScheduledChangeGating(APIBaseTest):
+ """A scheduled change that would flip a policy-gated field must not apply without approval.
+
+ Gating happens at scheduling time (a pending ChangeRequest is bound to the row); the Celery
+ applier only applies once that CR is approved, and expires it if the fire window closes first.
+ """
+
+ def _disabled_flag(self, key: str = "sched-flag") -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ key=key,
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ active=False,
+ created_by=self.user,
+ )
+
+ def _enable_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _update_policy(self, conditions: dict[str, Any] | None = None) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions=conditions if conditions is not None else {},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _schedule(self, flag: FeatureFlag, payload: dict, scheduled_at: datetime) -> ScheduledChange:
+ return ScheduledChange.objects.create(
+ team=self.team,
+ record_id=str(flag.id),
+ model_name="FeatureFlag",
+ payload=payload,
+ scheduled_at=scheduled_at,
+ created_by=self.user,
+ change_request=self._gate(flag, payload),
+ )
+
+ def _gate(self, flag: FeatureFlag, payload: dict) -> ChangeRequest | None:
+ from products.approvals.backend.scheduled_changes import gate_scheduled_change
+
+ return gate_scheduled_change(flag, payload, self.user)
+
+ def test_scheduled_enable_under_policy_creates_pending_cr_and_does_not_apply(self, _mock_enabled):
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ datetime.now(UTC) - timedelta(seconds=30),
+ )
+
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPROVED).count() == 0
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+
+ def test_approving_scheduled_cr_defers_apply_to_fire_time(self, _mock_enabled):
+ # A scheduled change's CR must not apply on approval: reaching quorum before scheduled_at
+ # would let an approver fire a future-dated flag change early. The CR stays APPROVED and
+ # only the scheduled applier flips the flag once the fire window is reached.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ cr = scheduled.change_request
+ assert cr is not None
+
+ ChangeRequestService(cr, self.user).approve()
+
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.APPROVED
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ # Move the fire window into the past and let the applier apply via the approved path.
+ scheduled.scheduled_at = timezone.now() - timedelta(seconds=30)
+ scheduled.save()
+ process_scheduled_changes()
+
+ # Reload into a fresh instance so the narrowed type from the earlier assert is widened.
+ flag = FeatureFlag.objects.get(pk=flag.pk)
+ assert flag.active is True
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.APPLIED
+
+ def test_pending_cr_past_window_is_expired_and_change_skipped(self, _mock_enabled):
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() - timedelta(seconds=30),
+ )
+ cr = scheduled.change_request
+ assert cr is not None
+ assert cr.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.EXPIRED
+ flag.refresh_from_db()
+ assert flag.active is False
+ scheduled.refresh_from_db()
+ assert scheduled.executed_at is not None
+
+ def test_unbound_schedule_that_becomes_gated_by_drift_is_not_applied(self, _mock_enabled):
+ # Stale-read bypass: scheduling an enable while the flag is already active binds no CR (the
+ # change is a no-op at scheduling time, so the enable policy never fires). If the flag is
+ # disabled before the fire window, dispatching ungated would re-enable it with the enable
+ # policy never consulted. The fire-time re-gate must catch the drift and skip the change.
+ self._enable_policy()
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="already-active-flag",
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ active=True,
+ created_by=self.user,
+ )
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ # No-op against the then-active flag: nothing bound.
+ assert scheduled.change_request is None
+
+ # Flag drifts to disabled, then the fire window opens.
+ flag.active = False
+ flag.save()
+ scheduled.scheduled_at = timezone.now() - timedelta(seconds=30)
+ scheduled.save()
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ # The enable must not have applied — a policy now gates it and it was never approved.
+ assert flag.active is False
+
+ def test_scheduled_rollout_change_under_update_policy_is_gated(self, _mock_enabled):
+ self._update_policy({"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0})
+ flag = self._disabled_flag(key="rollout-flag")
+
+ new_condition: dict[str, Any] = {
+ "variant": None,
+ "properties": [],
+ "rollout_percentage": 90,
+ "aggregation_group_type_index": None,
+ }
+ scheduled = self._schedule(
+ flag,
+ {
+ "operation": "add_release_condition",
+ "value": {"groups": [new_condition], "payloads": {}, "multivariate": None},
+ },
+ timezone.now() - timedelta(seconds=30),
+ )
+
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ # The new 90% condition must not have been appended (change was gated, not applied).
+ rollouts = [g.get("rollout_percentage") for g in flag.filters.get("groups", [])]
+ assert 90 not in rollouts
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+
+ def test_scheduled_change_matching_multiple_policies_is_rejected(self, _mock_enabled):
+ # A scheduled enable that matches more than one enabled policy can't be bound to a single
+ # CR. It must fail closed at creation (400) with no row, rather than save ungated and let
+ # the Celery applier dispatch it with no approval at all.
+ self._enable_policy()
+ self._org_enable_policy() # org-level policy also matches the enable, creating the conflict
+ flag = self._disabled_flag()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(hours=1)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 400, response.content
+ assert response.json()["code"] == "policy_conflict"
+ assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 0
+
+ def test_scheduled_change_without_policy_applies_normally(self, _mock_enabled):
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ datetime.now(UTC) - timedelta(seconds=30),
+ )
+ assert scheduled.change_request is None
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ assert flag.active is True
+ scheduled.refresh_from_db()
+ assert scheduled.executed_at is not None
+
+ def test_patching_payload_to_gated_change_binds_pending_cr(self, _mock_enabled):
+ # create() only gates the initial payload. A schedule born harmless (a disable, ungated
+ # because no disable policy) must not become a way to apply a gated enable when its payload
+ # is later PATCHed — the update path re-runs the gate and binds a pending CR.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": False},
+ timezone.now() + timedelta(hours=1),
+ )
+ assert scheduled.change_request is None
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/",
+ {"payload": {"operation": "update_status", "value": True}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ reloaded = ScheduledChange.objects.get(id=scheduled.id)
+ assert reloaded.change_request is not None
+ assert reloaded.change_request.state == ChangeRequestState.PENDING
+
+ def test_patching_payload_to_ungated_change_expires_stale_cr(self, _mock_enabled):
+ # The inverse: a gated schedule repointed at an ungated payload must drop its binding and
+ # expire the now-orphaned pending CR, so it can't be approved into applying the old change.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ old_cr = scheduled.change_request
+ assert old_cr is not None and old_cr.state == ChangeRequestState.PENDING
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/",
+ {"payload": {"operation": "update_status", "value": False}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ scheduled.refresh_from_db()
+ assert scheduled.change_request is None
+ old_cr.refresh_from_db()
+ assert old_cr.state == ChangeRequestState.EXPIRED
+
+ def test_regate_on_payload_change_gates_as_editing_user_not_creator(self, _mock_enabled):
+ # Re-gating must evaluate as the user making the edit, not the schedule's creator: a creator
+ # with approval bypass would otherwise let any editor PATCH in a gated payload that stays
+ # unbound and applies unapproved. The bound CR is attributed to the editor.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": False},
+ timezone.now() + timedelta(hours=1),
+ )
+ assert scheduled.change_request is None
+
+ editor = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.client.force_login(editor)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/",
+ {"payload": {"operation": "update_status", "value": True}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ reloaded = ScheduledChange.objects.get(id=scheduled.id)
+ assert reloaded.change_request is not None
+ assert reloaded.change_request.created_by == editor
+ assert reloaded.change_request.created_by != self.user
+
+ def test_patching_gated_schedule_with_same_action_reuses_bound_cr(self, _mock_enabled):
+ # Re-gating a gated schedule whose payload edit keeps the same gated action must reuse the
+ # row's own pending CR — not fail closed on it as a duplicate, and not mint a second one.
+ # This is the only path that reaches the current_change_request reuse branch in
+ # gate_scheduled_change (every other PATCH test goes ungated↔gated).
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ original_cr = scheduled.change_request
+ assert original_cr is not None and original_cr.state == ChangeRequestState.PENDING
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/",
+ {"payload": {"operation": "update_status", "value": True}},
+ format="json",
+ )
+
+ assert response.status_code == 200, response.content
+ reloaded = ScheduledChange.objects.get(id=scheduled.id)
+ assert reloaded.change_request is not None
+ assert reloaded.change_request.id == original_cr.id
+ assert reloaded.change_request.state == ChangeRequestState.PENDING
+ # No second CR minted for the flag — the schedule's own binding was reused.
+ assert ChangeRequest.objects.filter(resource_id=str(flag.id)).count() == 1
+
+ def test_scheduled_variant_rollout_change_under_policy_is_gated(self, _mock_enabled):
+ # update_variants writes into the flag's live multivariate filters. Unless the gate deep-copies
+ # first, the in-place mutation makes detect() compare the changed rollout against itself, bind
+ # no CR, and let the variant change dispatch unapproved.
+ self._update_policy({"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0})
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="variant-flag",
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ active=True,
+ created_by=self.user,
+ )
+
+ scheduled = self._schedule(
+ flag,
+ {
+ "operation": "update_variants",
+ "value": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 20},
+ {"key": "test", "rollout_percentage": 80},
+ ]
+ },
+ },
+ timezone.now() - timedelta(seconds=30),
+ )
+
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ variant_rollouts = {v["key"]: v["rollout_percentage"] for v in flag.filters["multivariate"]["variants"]}
+ # The gated change must not have applied — variants stay at their original 50/50 split.
+ assert variant_rollouts == {"control": 50, "test": 50}
+ scheduled.change_request.refresh_from_db()
+ assert scheduled.change_request.state == ChangeRequestState.EXPIRED
+
+ def test_cannot_retime_a_gated_schedule_with_live_change_request(self, _mock_enabled):
+ # An approver signs off on a change firing in a specific window. Retiming an approved schedule
+ # to fire immediately applies it outside the approval, so timing edits are blocked while the
+ # bound CR is pending or approved.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=2),
+ )
+ cr = scheduled.change_request
+ assert cr is not None
+ ChangeRequestService(cr, self.user).approve()
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.APPROVED
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/",
+ {"scheduled_at": (timezone.now() - timedelta(seconds=30)).isoformat()},
+ format="json",
+ )
+
+ assert response.status_code == 400, response.content
+ scheduled.refresh_from_db()
+ assert scheduled.scheduled_at > timezone.now()
+
+ def test_second_schedule_cannot_bind_an_already_approved_change_request(self, _mock_enabled):
+ # A second schedule for the same flag+action would bind the first schedule's already-approved
+ # CR via duplicate detection and could fire it at an arbitrary time. It must fail closed.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ first = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=2),
+ )
+ cr = first.change_request
+ assert cr is not None
+ ChangeRequestService(cr, self.user).approve()
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.APPROVED
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() - timedelta(seconds=30)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 409, response.content
+ assert response.json()["code"] == "change_request_pending"
+ assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 1
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_second_schedule_cannot_bind_an_unapproved_pending_change_request(self, _mock_enabled):
+ # A second schedule for the same flag+action must not ride the first schedule's still-pending
+ # CR: once that CR is approved, the earlier-timed second schedule would fire it before the
+ # window the approval was created for. Binding across schedules must fail closed.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ first = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=2),
+ )
+ cr = first.change_request
+ assert cr is not None and cr.state == ChangeRequestState.PENDING
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(minutes=5)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 409, response.content
+ assert response.json()["code"] == "change_request_pending"
+ # The second schedule is not created, and no new CR bound to the first's pending request.
+ assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 1
+ assert ChangeRequest.objects.filter(resource_id=str(flag.id)).count() == 1
+
+ def _recurring_enable_schedule(self, flag: FeatureFlag, *, gated: bool) -> ScheduledChange:
+ payload = {"operation": "update_status", "value": True}
+ return ScheduledChange.objects.create(
+ team=self.team,
+ record_id=str(flag.id),
+ model_name="FeatureFlag",
+ payload=payload,
+ scheduled_at=timezone.now() - timedelta(seconds=30),
+ is_recurring=True,
+ recurrence_interval="daily",
+ created_by=self.user,
+ change_request=self._gate(flag, payload) if gated else None,
+ )
+
+ def _org_enable_policy(self) -> ApprovalPolicy:
+ # Org-level (team=None) enable policy — matches the same enable as the team-level one, so a
+ # change gated by both fails closed with a policy conflict.
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=None,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def test_regate_recurring_binds_fresh_cr_when_policy_applies(self, _mock_enabled):
+ # regate_recurring_scheduled_change re-evaluates the flag's current state for the next
+ # occurrence. With a matching policy enabled it binds a fresh pending CR — this is what lets
+ # process_scheduled_changes re-gate a schedule (including one born ungated, change_request
+ # None) instead of flipping the gated field unapproved on every recurrence.
+ from products.approvals.backend.scheduled_changes import regate_recurring_scheduled_change
+
+ self._enable_policy()
+ flag = self._disabled_flag()
+ scheduled = self._recurring_enable_schedule(flag, gated=False)
+ assert scheduled.change_request is None
+
+ cr = regate_recurring_scheduled_change(scheduled, flag)
+
+ assert cr is not None
+ assert cr.state == ChangeRequestState.PENDING
+
+ def test_regate_recurring_raises_on_policy_conflict(self, _mock_enabled):
+ # When the next occurrence would match more than one enabled policy, regate fails closed with
+ # PolicyConflict rather than binding a single CR that can't satisfy both.
+ from products.approvals.backend.exceptions import PolicyConflict
+ from products.approvals.backend.scheduled_changes import regate_recurring_scheduled_change
+
+ self._enable_policy()
+ self._org_enable_policy()
+ flag = self._disabled_flag()
+ scheduled = self._recurring_enable_schedule(flag, gated=False)
+
+ with self.assertRaises(PolicyConflict):
+ regate_recurring_scheduled_change(scheduled, flag)
+
+ def test_recurring_regate_conflict_does_not_advance_schedule(self, _mock_enabled):
+ # process_scheduled_changes re-gates before advancing scheduled_at. If the next occurrence's
+ # re-gate raises PolicyConflict, that must propagate before the advance is persisted, so the
+ # schedule stays on the conflicting occurrence (failure recorded) rather than silently
+ # skipping ahead. The bound CR keeps the flag disabled: the pending CR is expired at fire
+ # time without applying, so re-gating sees the unchanged (disabled) flag and conflicts.
+ self._enable_policy()
+ flag = self._disabled_flag()
+ scheduled = self._recurring_enable_schedule(flag, gated=True)
+ assert scheduled.change_request is not None
+
+ # A second enable policy makes the next occurrence's re-gate match two policies → conflict.
+ self._org_enable_policy()
+
+ process_scheduled_changes()
+
+ scheduled.refresh_from_db()
+ # scheduled_at not advanced into the future (a daily advance would push it ~1 day out) — the
+ # conflicting occurrence is not skipped.
+ assert scheduled.scheduled_at < timezone.now()
+ assert scheduled.executed_at is None
+ assert scheduled.failure_count == 1
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_deleting_scheduled_change_expires_bound_pending_cr(self, _mock_enabled):
+ # Deleting a gated schedule must expire its bound pending CR. Otherwise the CR outlives the
+ # schedule and, on reaching quorum, ChangeRequestService.approve() auto-applies it
+ # immediately — its scheduled-deferral keys off the now-deleted schedule row, so the flag
+ # change fires without the schedule it was approved for.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ cr = scheduled.change_request
+ assert cr is not None and cr.state == ChangeRequestState.PENDING
+
+ response = self.client.delete(f"/api/projects/{self.team.id}/scheduled_changes/{scheduled.id}/")
+
+ assert response.status_code == 204, response.content
+ cr.refresh_from_db()
+ assert cr.state == ChangeRequestState.EXPIRED
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_failed_row_insert_rolls_back_the_created_cr(self, _mock_enabled):
+ # create() mints the pending CR and inserts the bound row in one transaction. If the row
+ # insert fails after the CR is created, the CR must roll back with it — otherwise it is
+ # orphaned, and once it reaches quorum ChangeRequestService.approve() auto-applies it
+ # immediately (its scheduled-deferral keys off a schedule row that never got saved),
+ # bypassing the schedule. Guards the create() transaction boundary.
+ from django.db import IntegrityError
+
+ from rest_framework import serializers
+
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ # Fail the row insert (super().create) after the gate has minted the pending CR.
+ with patch.object(serializers.ModelSerializer, "create", side_effect=IntegrityError("boom")):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(hours=1)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 500, response.content
+ # The atomic wrap rolled the minted CR back with the failed row insert; neither survives.
+ assert ChangeRequest.objects.count() == 0
+ assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 0
+
+ def test_rolled_back_orphan_cr_does_not_notify_approvers(self, _mock_enabled):
+ # The approver notification is deferred to transaction.on_commit, so a rolled-back orphan CR
+ # (the row insert fails after the gate mints the CR) must NOT ping an approver about a change
+ # request that no longer exists. Django's TestCase wraps each test in a transaction, so an
+ # on_commit callback only runs if the outer block explicitly commits; here the inner atomic
+ # rolls back, so the callback is discarded and the notification never fires.
+ from django.db import IntegrityError
+
+ from rest_framework import serializers
+
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ with patch("products.approvals.backend.decorators.send_approval_requested_notification") as mock_notify:
+ with patch.object(serializers.ModelSerializer, "create", side_effect=IntegrityError("boom")):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(hours=1)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 500, response.content
+ assert ChangeRequest.objects.count() == 0
+ mock_notify.assert_not_called()
+
+ def test_successful_scheduled_create_notifies_approvers_once(self, _mock_enabled):
+ # Happy path for the deferred notification: on a successful gated scheduled create the CR
+ # commits and the on_commit callback fires exactly once. captureOnCommitCallbacks(execute=True)
+ # is required because TestCase's surrounding transaction otherwise swallows on_commit.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ with patch("products.approvals.backend.decorators.send_approval_requested_notification") as mock_notify:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(hours=1)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 201, response.content
+ cr = ChangeRequest.objects.get(resource_id=str(flag.id))
+ assert cr.state == ChangeRequestState.PENDING
+ mock_notify.assert_called_once_with(cr)
+
+ def test_approved_then_stale_cr_is_not_applied(self, _mock_enabled):
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ scheduled = self._schedule(
+ flag,
+ {"operation": "update_status", "value": True},
+ timezone.now() + timedelta(hours=1),
+ )
+ cr = scheduled.change_request
+ assert cr is not None
+
+ # Force the approved-but-stale combination: applier must skip (not apply) a stale CR.
+ cr.state = ChangeRequestState.APPROVED
+ cr.validation_status = ValidationStatus.STALE
+ cr.save()
+
+ scheduled.scheduled_at = timezone.now() - timedelta(seconds=30)
+ scheduled.save()
+ process_scheduled_changes()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ def test_recurring_approved_then_stale_cr_survives_and_regates(self, _mock_enabled):
+ # A recurring schedule whose bound CR is approved-but-stale must not die at fire time. The
+ # stale CR is expired (not applied), then the next occurrence re-gates to a fresh pending CR
+ # and the schedule advances — rather than leaving the stale-approved CR in [PENDING, APPROVED]
+ # for the flag-scoped duplicate check to rediscover, raise ApprovalRequired on, and retry to
+ # exhaustion. This exercises the regate path that the one-time variant above never reaches.
+ self._enable_policy()
+ flag = self._disabled_flag()
+ scheduled = self._recurring_enable_schedule(flag, gated=True)
+ old_cr = scheduled.change_request
+ assert old_cr is not None
+
+ old_cr.state = ChangeRequestState.APPROVED
+ old_cr.validation_status = ValidationStatus.STALE
+ old_cr.save()
+
+ process_scheduled_changes()
+
+ old_cr.refresh_from_db()
+ assert old_cr.state == ChangeRequestState.EXPIRED
+ scheduled.refresh_from_db()
+ # Survived: advanced to a future occurrence, still active, no failures recorded.
+ assert scheduled.scheduled_at > timezone.now()
+ assert scheduled.executed_at is None
+ assert scheduled.failure_count == 0
+ # Rebound to a fresh pending CR for the next occurrence, not the expired one.
+ assert scheduled.change_request is not None
+ assert scheduled.change_request.id != old_cr.id
+ assert scheduled.change_request.state == ChangeRequestState.PENDING
+ # The stale change never applied.
+ flag.refresh_from_db()
+ assert flag.active is False
diff --git a/products/approvals/backend/tests/test_update_feature_flag_action.py b/products/approvals/backend/tests/test_update_feature_flag_action.py
index d3aa5592c807..e84207bdf1b2 100644
--- a/products/approvals/backend/tests/test_update_feature_flag_action.py
+++ b/products/approvals/backend/tests/test_update_feature_flag_action.py
@@ -5,7 +5,11 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from products.approvals.backend.actions.feature_flags import UpdateFeatureFlagAction
+from products.approvals.backend.actions.feature_flags import (
+ DisableFeatureFlagAction,
+ EnableFeatureFlagAction,
+ UpdateFeatureFlagAction,
+)
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.approvals.backend.policies import PolicyEngine
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -99,6 +103,96 @@ class TestUpdateFeatureFlagActionDetect(APIBaseTest):
assert result is False
+class TestDetectFromValidatedData(APIBaseTest):
+ """The gate decorates FeatureFlagSerializer.update(self, instance, validated_data), so the
+ actual change lives in validated_data — NOT the raw HTTP request body. Internal callers
+ (experiment toggles, ship_variant) drive update() from a POST whose body has no flag delta,
+ so detection must read validated_data."""
+
+ def _create_flag(self, *, active: bool = True, filters: dict[str, Any] | None = None) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ key="vd-flag",
+ active=active,
+ filters=filters or {"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+
+ def _serializer_view(self) -> MagicMock:
+ # Serializer-style view: _get_instance reads args[0] when "request" is in context.
+ view = MagicMock()
+ view.context = {"request": MagicMock(), "get_team": lambda: self.team}
+ return view
+
+ def _post_request(self) -> MagicMock:
+ # A POST whose body carries no flag delta — the failure mode the fix addresses.
+ request = MagicMock()
+ request.method = "POST"
+ request.data = {}
+ return request
+
+ def test_enable_detects_from_validated_data_when_request_body_empty(self):
+ flag = self._create_flag(active=False)
+ view = self._serializer_view()
+
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, flag, {"active": True})
+
+ assert result is True
+
+ def test_disable_detects_from_validated_data_when_request_body_empty(self):
+ flag = self._create_flag(active=True)
+ view = self._serializer_view()
+
+ result = DisableFeatureFlagAction.detect(self._post_request(), view, flag, {"active": False})
+
+ assert result is True
+
+ def test_enable_does_not_fire_when_already_active(self):
+ flag = self._create_flag(active=True)
+ view = self._serializer_view()
+
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, flag, {"active": True})
+
+ assert result is False
+
+ def test_update_detects_rollout_change_from_validated_data(self):
+ flag = self._create_flag(filters={"groups": [{"properties": [], "rollout_percentage": 50}]})
+ view = self._serializer_view()
+ # FeatureFlagSerializer puts the filters change under `get_filters` in validated_data.
+ validated_data = {"get_filters": {"groups": [{"properties": [], "rollout_percentage": 90}]}}
+
+ result = UpdateFeatureFlagAction.detect(self._post_request(), view, flag, validated_data)
+
+ assert result is True
+
+ def test_update_extract_intent_reads_get_filters_from_validated_data(self):
+ flag = self._create_flag(filters={"groups": [{"properties": [], "rollout_percentage": 50}]})
+ view = self._serializer_view()
+ validated_data = {"get_filters": {"groups": [{"properties": [], "rollout_percentage": 90}]}}
+
+ intent = UpdateFeatureFlagAction.extract_intent(self._post_request(), view, flag, validated_data)
+
+ assert intent["gated_changes"]["rollout_percentage"][0]["value"] == 90
+ # full_request_data is re-applied verbatim, so it must carry the input field name.
+ assert intent["full_request_data"]["filters"]["groups"][0]["rollout_percentage"] == 90
+ assert "get_filters" not in intent["full_request_data"]
+
+ def test_enable_fires_on_create_born_active(self):
+ # A brand-new flag born active is gated (create-as-single-arg, the production shape).
+ view = self._serializer_view()
+
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, {"key": "f", "active": True})
+
+ assert result is True
+
+ def test_enable_does_not_fire_on_create_born_disabled(self):
+ view = self._serializer_view()
+
+ result = EnableFeatureFlagAction.detect(self._post_request(), view, {"key": "f", "active": False})
+
+ assert result is False
+
+
class TestUpdateFeatureFlagActionExtractIntent(APIBaseTest):
def _create_flag(self, filters: dict[str, Any]) -> FeatureFlag:
return FeatureFlag.objects.create(
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 8963af11b787..095e8f8de3b4 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -1504,7 +1504,45 @@ class ExperimentService:
# Launch
# ------------------------------------------------------------------
- @transaction.atomic
+ def _set_flag_active_gated(self, feature_flag: FeatureFlag, active: bool, request: Any) -> None:
+ """Flip a flag's active state THROUGH the approval gate.
+
+ Routing the flip through FeatureFlagSerializer.update() honours the
+ @approval_gate so the feature_flag.enable/disable policies apply. Raises
+ ApprovalRequired (which surfaces as a 409 + change_request_id) when a
+ policy requires approval; in that case the flag is left untouched.
+
+ The gate's detect()/extract_intent() read the serializer's validated_data
+ (the actual change being saved), so the incoming experiment launch/pause/
+ resume request is passed straight through — no synthetic PATCH request is
+ needed.
+
+ Pass BOTH get_team and get_organization so the gate resolves the policy
+ from context rather than falling back to instance derivation.
+ """
+ # Internal callers may omit a request; FeatureFlagSerializer.update() needs
+ # request.user, so fall back to the service's user via a minimal request.
+ flag_request = request if getattr(request, "user", None) is not None else _ServiceRequest(self.user)
+ serializer = FeatureFlagSerializer(
+ instance=feature_flag,
+ data={"active": active},
+ partial=True,
+ context={
+ "request": flag_request,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.team.organization,
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ },
+ )
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+
+ # Not @transaction.atomic: the flag flip goes through the FeatureFlagSerializer
+ # approval workflow, which conflicts with atomic (an ApprovalRequired propagating
+ # out of an atomic block would roll back the just-created ChangeRequest). The flag
+ # is flipped through the gate first, so an ApprovalRequired aborts before any
+ # experiment mutation.
def launch_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
"""Launch a draft experiment: validate readiness, set start_date, activate feature flag."""
if not experiment.is_draft:
@@ -1515,6 +1553,11 @@ class ExperimentService:
self._assert_flag_not_deleted_for_launch(feature_flag)
self._validate_existing_flag(feature_flag)
+ # Activate the feature flag through the approval gate first. If approval is
+ # required this raises ApprovalRequired (-> 409) before we touch the experiment,
+ # so start_date stays None and the experiment is not launched.
+ self._set_flag_active_gated(feature_flag, True, request)
+
# Set start_date
experiment.start_date = timezone.now()
@@ -1534,10 +1577,6 @@ class ExperimentService:
),
)
- # Activate feature flag
- feature_flag.active = True
- feature_flag.save()
-
experiment.save()
self._report_experiment_launched(experiment, request=request)
@@ -1757,7 +1796,8 @@ class ExperimentService:
# Pause / Resume
# ------------------------------------------------------------------
- @transaction.atomic
+ # Not @transaction.atomic — the flag flip goes through the FeatureFlagSerializer
+ # approval workflow, which conflicts with atomic (see _set_flag_active_gated).
def pause_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
"""Pause a running experiment: deactivate its feature flag so it is no longer served by /decide."""
if experiment.is_draft:
@@ -1771,8 +1811,9 @@ class ExperimentService:
if not feature_flag.active:
raise ValidationError("Experiment is already paused.")
- feature_flag.active = False
- feature_flag.save(update_fields=["active"])
+ # Deactivate through the approval gate. An ApprovalRequired (-> 409) aborts the
+ # pause before we report it, leaving the flag active.
+ self._set_flag_active_gated(feature_flag, False, request)
# Re-fetch so the serializer sees the updated flag
experiment.feature_flag = feature_flag
@@ -1781,7 +1822,8 @@ class ExperimentService:
return experiment
- @transaction.atomic
+ # Not @transaction.atomic — the flag flip goes through the FeatureFlagSerializer
+ # approval workflow, which conflicts with atomic (see _set_flag_active_gated).
def resume_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
"""Resume a paused experiment: reactivate its feature flag so /decide serves variants again."""
if experiment.is_draft:
@@ -1795,8 +1837,9 @@ class ExperimentService:
if feature_flag.active:
raise ValidationError("Experiment is not paused.")
- feature_flag.active = True
- feature_flag.save(update_fields=["active"])
+ # Reactivate through the approval gate. An ApprovalRequired (-> 409) aborts the
+ # resume before we report it, leaving the flag paused.
+ self._set_flag_active_gated(feature_flag, True, request)
# Re-fetch so the serializer sees the updated flag
experiment.feature_flag = feature_flag
@@ -2702,6 +2745,8 @@ class ExperimentService:
"request": request,
"team_id": self.team.id,
"project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.team.organization,
},
)
flag_serializer.is_valid(raise_exception=True)
@@ -2808,7 +2853,12 @@ class ExperimentService:
# Update
# ------------------------------------------------------------------
- @transaction.atomic
+ # Not @transaction.atomic: the gated feature-flag write
+ # (_sync_feature_flag_on_update) goes through the FeatureFlagSerializer approval
+ # workflow, which conflicts with atomic — an ApprovalRequired propagating out of
+ # an atomic block would roll back the just-created pending ChangeRequest. That flag
+ # write runs first, outside any transaction; the experiment-state writes that follow
+ # are wrapped in a narrow `with transaction.atomic()` block so they stay all-or-nothing.
def update_experiment(
self,
experiment: Experiment,
@@ -2904,121 +2954,13 @@ class ExperimentService:
saved_metrics_data: list[dict] = update_data.pop("saved_metrics_ids", []) or []
update_data.pop("get_feature_flag_key", None)
- # --- saved metrics sync (update-in-place) -----------
- old_saved_metric_uuids: dict[str, set[str]] = {"primary": set(), "secondary": set()}
- if update_saved_metrics:
- existing_links = {
- link.saved_metric_id: link
- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all()
- }
-
- for link in existing_links.values():
- if link.saved_metric.query:
- uuid = link.saved_metric.query.get("uuid")
- if uuid:
- metric_type = (link.metadata or {}).get("type", "primary")
- if metric_type == "primary":
- old_saved_metric_uuids["primary"].add(uuid)
- else:
- old_saved_metric_uuids["secondary"].add(uuid)
-
- new_saved_metric_ids = {sm["id"] for sm in saved_metrics_data}
- existing_saved_metric_ids = set(existing_links.keys())
-
- # Delete links no longer in the list (one by one to trigger activity logging)
- to_delete = existing_saved_metric_ids - new_saved_metric_ids
- for saved_metric_id in to_delete:
- existing_links[saved_metric_id].delete()
-
- # Update or create links
- for saved_metric_data in saved_metrics_data:
- saved_metric_id = saved_metric_data["id"]
- new_metadata = saved_metric_data.get("metadata") or {}
-
- if saved_metric_id in existing_links:
- existing_link = existing_links[saved_metric_id]
- if (existing_link.metadata or {}) != new_metadata:
- existing_link.metadata = new_metadata
- existing_link.save(update_fields=["metadata", "updated_at"])
- else:
- saved_metric_serializer = ExperimentToSavedMetricSerializer(
- data={
- "experiment": experiment.id,
- "saved_metric": saved_metric_id,
- "metadata": new_metadata,
- },
- context=context,
- )
- saved_metric_serializer.is_valid(raise_exception=True)
- saved_metric_serializer.save()
-
- # --- feature flag sync ------------------------------------------------
- # Draft experiments always sync parameters to the linked feature flag.
- # Running experiments only sync when update_feature_flag_params=True,
- # to prevent accidental side effects (e.g. overwrites when the frontend
- # spreads stale parameters alongside unrelated updates, or an agent
- # calls MCP with too many params).
- if experiment.is_draft or update_feature_flag_params:
- holdout = experiment.holdout
- if "holdout" in update_data:
- holdout = update_data["holdout"]
-
- if update_data.get("parameters"):
- variants = update_data["parameters"].get("feature_flag_variants", [])
- aggregation_group_type_index = update_data["parameters"].get("aggregation_group_type_index")
-
- existing_groups = feature_flag.filters.get("groups", [])
- experiment_rollout_percentage = update_data["parameters"].get("rollout_percentage")
- if experiment_rollout_percentage is not None and existing_groups:
- new_groups = [
- {**existing_groups[0], "rollout_percentage": experiment_rollout_percentage},
- *existing_groups[1:],
- ]
- else:
- new_groups = list(existing_groups)
-
- new_filters = {
- **feature_flag.filters,
- "groups": new_groups,
- "multivariate": {"variants": variants or list(DEFAULT_VARIANTS)},
- "aggregation_group_type_index": aggregation_group_type_index,
- **holdout_filters_for_flag(holdout.id if holdout else None, holdout.filters if holdout else None),
- }
- if "feature_flag_payloads" in update_data["parameters"]:
- new_filters["payloads"] = update_data["parameters"]["feature_flag_payloads"]
-
- flag_update_data: dict[str, Any] = {"filters": new_filters}
- if "ensure_experience_continuity" in update_data["parameters"]:
- flag_update_data["ensure_experience_continuity"] = update_data["parameters"][
- "ensure_experience_continuity"
- ]
-
- existing_flag_serializer = FeatureFlagSerializer(
- feature_flag,
- data=flag_update_data,
- partial=True,
- context=context,
- )
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
- elif "holdout" in update_data:
- existing_flag_serializer = FeatureFlagSerializer(
- feature_flag,
- data={
- "filters": {
- **feature_flag.filters,
- **holdout_filters_for_flag(
- holdout.id if holdout else None, holdout.filters if holdout else None
- ),
- }
- },
- partial=True,
- context=context,
- )
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
-
- # --- validate updated fields ------------------------------------------
+ # --- validate updated fields (BEFORE any mutation) --------------------
+ # Run the pure payload validations that can raise 400 *before* the flag
+ # write below. PostHog has no ATOMIC_REQUESTS, so _sync_feature_flag_on_update
+ # autocommits; validating after it would let an invalid payload persist a
+ # flag change while the request still 400s, leaving the flag and experiment
+ # inconsistent. These checks read update_data + the experiment only (no DB
+ # writes), so they are safe to hoist ahead of the flag write.
# Revalidate the baseline whenever either side of the constraint changes:
# the stats_config itself, or the variant set it references. A variants-only
# PATCH (e.g. updateDistribution) that renames/removes the current baseline
@@ -3046,55 +2988,128 @@ class ExperimentService:
if "metrics" in update_data or "metrics_secondary" in update_data:
self.validate_no_duplicate_metric_uuids(update_data.get("metrics"), update_data.get("metrics_secondary"))
- # --- fingerprint recalculation -------------------------------------
- start_date = update_data.get("start_date", experiment.start_date)
- stats_config = update_data.get("stats_config", experiment.stats_config)
- exposure_criteria = update_data.get("exposure_criteria", experiment.exposure_criteria)
- only_count_matured_users = update_data.get("only_count_matured_users", experiment.only_count_matured_users)
- # Canonical excluded_variants for fingerprints: prefer an explicit column update,
- # otherwise the stored canonical value. So a client PATCHing only excluded_variants
- # still fingerprints with the new exclusions.
- if "excluded_variants" in update_data:
- excluded_variants = update_data["excluded_variants"]
- else:
- excluded_variants = experiment.excluded_variants or []
+ # --- feature flag sync (OUTSIDE the atomic block) ---------------------
+ # The flag write goes through the FeatureFlagSerializer approval gate.
+ # It runs before (and outside) the experiment-state transaction below so
+ # that an ApprovalRequired propagating out of serializer.save() leaves the
+ # just-created pending ChangeRequest intact — wrapping it in atomic would
+ # roll the CR back, leaving an approver with nothing to act on. This mirrors
+ # launch/pause/resume/ship_variant, which gate the flag write non-atomically
+ # for the same reason. The flag write does not depend on any of the
+ # experiment-state writes below, so hoisting it is safe.
+ self._sync_feature_flag_on_update(experiment, update_data, feature_flag, context, update_feature_flag_params)
+
+ # --- feature flag activation on launch (OUTSIDE the atomic block) -----
+ # Setting a start_date on a draft launches it, which activates the linked
+ # flag. Route that flip through the approval gate — exactly like
+ # launch_experiment — so an enable policy can't be bypassed by launching
+ # via update_experiment. Runs outside the transaction for the same reason
+ # as the sync above: an ApprovalRequired must leave the pending
+ # ChangeRequest intact rather than roll it back.
+ if experiment.is_draft and update_data.get("start_date") is not None:
+ self._set_flag_active_gated(feature_flag, True, context.get("request"))
+
+ with transaction.atomic():
+ # --- saved metrics sync (update-in-place) -----------
+ old_saved_metric_uuids: dict[str, set[str]] = {"primary": set(), "secondary": set()}
+ if update_saved_metrics:
+ existing_links = {
+ link.saved_metric_id: link
+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all()
+ }
- for metric_field in ["metrics", "metrics_secondary"]:
- metrics = update_data.get(metric_field, getattr(experiment, metric_field, None))
- if metrics:
- update_data[metric_field] = self._recompute_fingerprints(
- metrics,
- start_date,
- stats_config,
- exposure_criteria,
- only_count_matured_users=only_count_matured_users,
- excluded_variants=excluded_variants,
- )
+ for link in existing_links.values():
+ if link.saved_metric.query:
+ uuid = link.saved_metric.query.get("uuid")
+ if uuid:
+ metric_type = (link.metadata or {}).get("type", "primary")
+ if metric_type == "primary":
+ old_saved_metric_uuids["primary"].add(uuid)
+ else:
+ old_saved_metric_uuids["secondary"].add(uuid)
+
+ new_saved_metric_ids = {sm["id"] for sm in saved_metrics_data}
+ existing_saved_metric_ids = set(existing_links.keys())
+
+ # Delete links no longer in the list (one by one to trigger activity logging)
+ to_delete = existing_saved_metric_ids - new_saved_metric_ids
+ for saved_metric_id in to_delete:
+ existing_links[saved_metric_id].delete()
+
+ # Update or create links
+ for saved_metric_data in saved_metrics_data:
+ saved_metric_id = saved_metric_data["id"]
+ new_metadata = saved_metric_data.get("metadata") or {}
+
+ if saved_metric_id in existing_links:
+ existing_link = existing_links[saved_metric_id]
+ if (existing_link.metadata or {}) != new_metadata:
+ existing_link.metadata = new_metadata
+ existing_link.save(update_fields=["metadata", "updated_at"])
+ else:
+ saved_metric_serializer = ExperimentToSavedMetricSerializer(
+ data={
+ "experiment": experiment.id,
+ "saved_metric": saved_metric_id,
+ "metadata": new_metadata,
+ },
+ context=context,
+ )
+ saved_metric_serializer.is_valid(raise_exception=True)
+ saved_metric_serializer.save()
+
+ # (stats_config / excluded_variants / duplicate-metric-uuid validation
+ # runs before the flag write above so a 400 can't leave a committed flag
+ # change behind.)
+
+ # --- fingerprint recalculation -------------------------------------
+ start_date = update_data.get("start_date", experiment.start_date)
+ stats_config = update_data.get("stats_config", experiment.stats_config)
+ exposure_criteria = update_data.get("exposure_criteria", experiment.exposure_criteria)
+ only_count_matured_users = update_data.get("only_count_matured_users", experiment.only_count_matured_users)
+ # Canonical excluded_variants for fingerprints: prefer an explicit column update,
+ # otherwise the stored canonical value. So a client PATCHing only excluded_variants
+ # still fingerprints with the new exclusions.
+ if "excluded_variants" in update_data:
+ excluded_variants = update_data["excluded_variants"]
+ else:
+ excluded_variants = experiment.excluded_variants or []
- # --- metric ordering sync + validation -----------------------------
- self._sync_ordering_with_metric_changes(experiment, update_data)
- self._sync_ordering_for_saved_metrics_on_update(
- experiment,
- update_data,
- old_saved_metric_uuids,
- saved_metrics_data if update_saved_metrics else None,
- )
- self._validate_metric_ordering_on_update(experiment, update_data)
-
- # --- feature flag activation on launch -----------------------------
- has_start_date = update_data.get("start_date") is not None
- if experiment.is_draft and has_start_date:
- feature_flag.active = True
- feature_flag.save()
-
- # --- apply changes and save ----------------------------------------
- # Feature-flag config was already synced to the flag above; strip it so it is not mirrored
- # into the deprecated `parameters` column. Reads re-derive it from the flag.
- if update_data.get("parameters") is not None:
- update_data["parameters"] = self._strip_feature_flag_config(update_data["parameters"])
- for attr, value in update_data.items():
- setattr(experiment, attr, value)
- experiment.save()
+ for metric_field in ["metrics", "metrics_secondary"]:
+ metrics = update_data.get(metric_field, getattr(experiment, metric_field, None))
+ if metrics:
+ update_data[metric_field] = self._recompute_fingerprints(
+ metrics,
+ start_date,
+ stats_config,
+ exposure_criteria,
+ only_count_matured_users=only_count_matured_users,
+ excluded_variants=excluded_variants,
+ )
+
+ # --- metric ordering sync + validation -----------------------------
+ # Unlike the pure validations hoisted above the flag write, ordering
+ # validation is coupled to the saved-metrics DB sync (it consumes
+ # old_saved_metric_uuids and the ordering mutations above), so it stays
+ # here. The residual — an invalid explicit ordering array combined with a
+ # flag change in the same request — is far narrower than the hoisted cases.
+ self._sync_ordering_with_metric_changes(experiment, update_data)
+ self._sync_ordering_for_saved_metrics_on_update(
+ experiment,
+ update_data,
+ old_saved_metric_uuids,
+ saved_metrics_data if update_saved_metrics else None,
+ )
+ self._validate_metric_ordering_on_update(experiment, update_data)
+
+ # --- apply changes and save ----------------------------------------
+ # Feature-flag config was already synced to the flag above; strip it so it is not mirrored
+ # into the deprecated `parameters` column. Reads re-derive it from the flag.
+ if update_data.get("parameters") is not None:
+ update_data["parameters"] = self._strip_feature_flag_config(update_data["parameters"])
+ for attr, value in update_data.items():
+ setattr(experiment, attr, value)
+ experiment.save()
if should_report_update:
changed_fields = self._compute_changed_fields(
@@ -3107,6 +3122,89 @@ class ExperimentService:
return experiment
+ def _sync_feature_flag_on_update(
+ self,
+ experiment: Experiment,
+ update_data: dict,
+ feature_flag: FeatureFlag,
+ context: dict,
+ update_feature_flag_params: bool,
+ ) -> None:
+ """Sync experiment parameters/holdout to the linked flag THROUGH the approval gate.
+
+ Draft experiments always sync parameters to the linked feature flag.
+ Running experiments only sync when update_feature_flag_params=True, to prevent
+ accidental side effects (e.g. overwrites when the frontend spreads stale
+ parameters alongside unrelated updates, or an agent calls MCP with too many
+ params).
+
+ Routing the write through FeatureFlagSerializer honours the @approval_gate, so a
+ policy-gated variant/rollout change raises ApprovalRequired. This runs OUTSIDE
+ update_experiment's atomic block (see the caller) so that raise leaves the
+ just-created pending ChangeRequest intact.
+ """
+ if not (experiment.is_draft or update_feature_flag_params):
+ return
+
+ holdout = experiment.holdout
+ if "holdout" in update_data:
+ holdout = update_data["holdout"]
+
+ if update_data.get("parameters"):
+ variants = update_data["parameters"].get("feature_flag_variants", [])
+ aggregation_group_type_index = update_data["parameters"].get("aggregation_group_type_index")
+
+ existing_groups = feature_flag.filters.get("groups", [])
+ experiment_rollout_percentage = update_data["parameters"].get("rollout_percentage")
+ if experiment_rollout_percentage is not None and existing_groups:
+ new_groups = [
+ {**existing_groups[0], "rollout_percentage": experiment_rollout_percentage},
+ *existing_groups[1:],
+ ]
+ else:
+ new_groups = list(existing_groups)
+
+ new_filters = {
+ **feature_flag.filters,
+ "groups": new_groups,
+ "multivariate": {"variants": variants or list(DEFAULT_VARIANTS)},
+ "aggregation_group_type_index": aggregation_group_type_index,
+ **holdout_filters_for_flag(holdout.id if holdout else None, holdout.filters if holdout else None),
+ }
+ if "feature_flag_payloads" in update_data["parameters"]:
+ new_filters["payloads"] = update_data["parameters"]["feature_flag_payloads"]
+
+ flag_update_data: dict[str, Any] = {"filters": new_filters}
+ if "ensure_experience_continuity" in update_data["parameters"]:
+ flag_update_data["ensure_experience_continuity"] = update_data["parameters"][
+ "ensure_experience_continuity"
+ ]
+
+ existing_flag_serializer = FeatureFlagSerializer(
+ feature_flag,
+ data=flag_update_data,
+ partial=True,
+ context=context,
+ )
+ existing_flag_serializer.is_valid(raise_exception=True)
+ existing_flag_serializer.save()
+ elif "holdout" in update_data:
+ existing_flag_serializer = FeatureFlagSerializer(
+ feature_flag,
+ data={
+ "filters": {
+ **feature_flag.filters,
+ **holdout_filters_for_flag(
+ holdout.id if holdout else None, holdout.filters if holdout else None
+ ),
+ }
+ },
+ partial=True,
+ context=context,
+ )
+ existing_flag_serializer.is_valid(raise_exception=True)
+ existing_flag_serializer.save()
+
def _compute_changed_fields(
self,
experiment: Experiment,
@@ -4209,6 +4307,7 @@ class ExperimentService:
"team_id": self.team.id,
"project_id": self.team.project_id,
"get_team": lambda: self.team,
+ "get_organization": lambda: self.team.organization,
}
@@ -4222,7 +4321,9 @@ class _ServiceRequest:
def __init__(self, user: Any):
self.user = user
self.method = "POST"
+ self.path = "/"
self.data: dict = {}
+ self.GET: dict = {}
self.META: dict = {}
self.headers: dict = {}
self.session: dict = {}
diff --git a/products/experiments/backend/test/test_experiment_service_approvals.py b/products/experiments/backend/test/test_experiment_service_approvals.py
new file mode 100644
index 000000000000..6ec33eab1bb0
--- /dev/null
+++ b/products/experiments/backend/test/test_experiment_service_approvals.py
@@ -0,0 +1,240 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework.exceptions import ValidationError
+from rest_framework.test import APIRequestFactory
+
+from posthog.constants import AvailableFeature
+
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState
+from products.experiments.backend.experiment_service import ExperimentService
+from products.experiments.backend.models.experiment import Experiment
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestExperimentServiceApprovals(APIBaseTest):
+ """launch/pause/resume flip the linked flag's `active` state, which must pass through
+ the FeatureFlagSerializer approval gate (action `feature_flag.enable`/`feature_flag.disable`)."""
+
+ _METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "m1",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ }
+
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+
+ def _service(self) -> ExperimentService:
+ return ExperimentService(team=self.team, user=self.user)
+
+ def _request(self) -> Any:
+ request = APIRequestFactory().post("/fake")
+ request.user = self.user
+ return request
+
+ def _create_enable_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _create_disable_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.disable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _create_update_policy(self) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _create_draft_experiment(self, feature_flag_key: str) -> Experiment:
+ return self._service().create_experiment(
+ name="Approval Test",
+ feature_flag_key=feature_flag_key,
+ metrics=[self._METRIC],
+ primary_metrics_ordered_uuids=["m1"],
+ allow_unknown_events=True,
+ )
+
+ def _create_launched_experiment(self, feature_flag_key: str) -> Experiment:
+ experiment = self._create_draft_experiment(feature_flag_key)
+ # Launch without a policy in place so the flag is genuinely active afterwards.
+ self._service().launch_experiment(experiment, request=self._request())
+ experiment.refresh_from_db()
+ return experiment
+
+ def test_launch_under_enable_policy_requires_approval(self, _mock_enabled):
+ experiment = self._create_draft_experiment("launch-gated")
+ self._create_enable_policy()
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().launch_experiment(experiment, request=self._request())
+
+ experiment.refresh_from_db()
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+ assert experiment.start_date is None
+
+ def test_launch_under_enable_policy_without_request_requires_approval(self, _mock_enabled):
+ # Internal callers (e.g. _create_running_experiment) invoke launch with request=None,
+ # which builds a _ServiceRequest shim. The gate must still raise ApprovalRequired
+ # rather than crashing on a missing request attribute.
+ experiment = self._create_draft_experiment("launch-gated-no-request")
+ self._create_enable_policy()
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().launch_experiment(experiment)
+
+ experiment.refresh_from_db()
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+ assert experiment.start_date is None
+
+ def test_pause_under_disable_policy_requires_approval(self, _mock_enabled):
+ experiment = self._create_launched_experiment("pause-gated")
+ assert experiment.feature_flag.active is True
+ self._create_disable_policy()
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().pause_experiment(experiment, request=self._request())
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is True
+
+ def test_resume_under_enable_policy_requires_approval(self, _mock_enabled):
+ experiment = self._create_launched_experiment("resume-gated")
+ # Pause it first (no policy yet) so it's genuinely paused.
+ self._service().pause_experiment(experiment, request=self._request())
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+
+ self._create_enable_policy()
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().resume_experiment(experiment, request=self._request())
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.active is False
+
+ def test_launch_without_policy_flips_flag_and_sets_start_date(self, _mock_enabled):
+ experiment = self._create_draft_experiment("launch-ungated")
+
+ launched = self._service().launch_experiment(experiment, request=self._request())
+
+ assert launched.start_date is not None
+ launched.feature_flag.refresh_from_db()
+ assert launched.feature_flag.active is True
+
+ def test_ship_variant_under_update_policy_requires_approval(self, _mock_enabled):
+ # ship_variant rewrites the flag's variant rollout (50/50 -> 100/0), a rollout_percentage
+ # change gated by feature_flag.update. It routes through FeatureFlagSerializer, so the gate
+ # must fire and leave the flag's filters untouched.
+ experiment = self._create_launched_experiment("ship-gated")
+ original_filters = experiment.feature_flag.filters
+ original_variants = original_filters["multivariate"]["variants"]
+ assert any(v["key"] == "test" and v["rollout_percentage"] == 50 for v in original_variants)
+
+ self._create_update_policy()
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().ship_variant(experiment, variant_key="test", request=self._request())
+
+ experiment.refresh_from_db()
+ experiment.feature_flag.refresh_from_db()
+ # Flag distribution unchanged and experiment not ended.
+ assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants
+ assert experiment.end_date is None
+
+ def test_update_experiment_variant_edit_under_update_policy_leaves_pending_cr(self, _mock_enabled):
+ # update_experiment() syncs a variant/rollout change back through FeatureFlagSerializer,
+ # gated by feature_flag.update. The gated flag write runs OUTSIDE the method's atomic block
+ # (like ship_variant/launch/pause/resume), so ApprovalRequired leaves the flag untouched
+ # AND the pending ChangeRequest survives for an approver to act on — it is not rolled back.
+ experiment = self._create_launched_experiment("update-gated")
+ original_variants = experiment.feature_flag.filters["multivariate"]["variants"]
+ self._create_update_policy()
+
+ new_variants = [
+ {"key": "control", "rollout_percentage": 10},
+ {"key": "test", "rollout_percentage": 90},
+ ]
+ context = {
+ "request": self._request(),
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ }
+
+ with self.assertRaises(ApprovalRequired):
+ self._service().update_experiment(
+ experiment,
+ {"parameters": {"feature_flag_variants": new_variants}, "update_feature_flag_params": True},
+ serializer_context=context,
+ )
+
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.PENDING).count() == 1
+ assert ChangeRequest.objects.filter(state=ChangeRequestState.APPLIED).count() == 0
+
+ def test_update_experiment_invalid_payload_does_not_commit_flag_variant_change(self, _mock_enabled):
+ # A single update that both rewrites the flag's variant rollout (update_feature_flag_params=True)
+ # and carries an invalid stats_config must fail closed WITHOUT committing the flag change. The flag
+ # write autocommits (no ATOMIC_REQUESTS), so the payload validation has to run before it — otherwise
+ # a 400 would leave the flag rewritten while the experiment stays untouched (flag/experiment drift).
+ # No policy here: without the pre-flag validation the flag write would succeed and commit.
+ experiment = self._create_launched_experiment("update-invalid-payload")
+ original_variants = experiment.feature_flag.filters["multivariate"]["variants"]
+
+ new_variants = [
+ {"key": "control", "rollout_percentage": 10},
+ {"key": "test", "rollout_percentage": 90},
+ ]
+ context = {
+ "request": self._request(),
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ }
+
+ with self.assertRaises(ValidationError):
+ self._service().update_experiment(
+ experiment,
+ {
+ "parameters": {"feature_flag_variants": new_variants},
+ "update_feature_flag_params": True,
+ # baseline_variant_key references a variant that does not exist in the resolved set.
+ "stats_config": {"baseline_variant_key": "nonexistent"},
+ },
+ serializer_context=context,
+ )
+
+ experiment.feature_flag.refresh_from_db()
+ # The invalid payload must not have committed the flag's variant rewrite.
+ assert experiment.feature_flag.filters["multivariate"]["variants"] == original_variants
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 7f5dcbbfa6a3..58d0d3c82ff5 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -345,11 +345,11 @@ export const getExperimentsUpdateUrl = (projectId: string, id: number) => {
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsUpdate = async (
projectId: string,
@@ -453,11 +453,11 @@ export const getExperimentsCreateExposureCohortForExperimentCreateUrl = (project
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsCreateExposureCohortForExperimentCreate = async (
projectId: string,
@@ -478,11 +478,11 @@ export const getExperimentsDuplicateCreateUrl = (projectId: string, id: number)
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsDuplicateCreate = async (
projectId: string,
@@ -627,11 +627,11 @@ export const getExperimentsMetricsRecalculationRetrieveUrl = (
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsMetricsRecalculationRetrieve = async (
projectId: string,
@@ -653,11 +653,11 @@ export const getExperimentsMetricsRecalculationLatestRetrieveUrl = (projectId: s
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsMetricsRecalculationLatestRetrieve = async (
projectId: string,
@@ -702,11 +702,11 @@ export const getExperimentsRecalculateTimeseriesCreateUrl = (projectId: string,
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsRecalculateTimeseriesCreate = async (
projectId: string,
@@ -832,11 +832,11 @@ export const getExperimentsTimeseriesResultsRetrieveUrl = (
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsTimeseriesResultsRetrieve = async (
projectId: string,
@@ -1002,11 +1002,11 @@ export const getExperimentsRequiresFlagImplementationRetrieveUrl = (projectId: s
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsRequiresFlagImplementationRetrieve = async (
projectId: string,
@@ -1023,11 +1023,11 @@ export const getExperimentsStatsRetrieveUrl = (projectId: string) => {
}
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const experimentsStatsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
return apiMutator<void>(getExperimentsStatsRetrieveUrl(projectId), {
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 954128db9100..35a230078531 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -866,11 +866,11 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
@@ -913,22 +913,22 @@ export const ExperimentsCopyToProjectCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsCreateExposureCohortForExperimentCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
@@ -1024,11 +1024,11 @@ export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod
.describe('Request body for triggering a metrics recalculation.')
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsRecalculateTimeseriesCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 66586536c414..8f6a25ddfafb 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -723,7 +723,6 @@ class EvaluationContextSerializerMixin(serializers.Serializer):
capture_exception(e)
def _log_evaluation_context_change(self, obj: FeatureFlag, before: list[str], after: list[str]) -> None:
-
from posthog.models.activity_logging.activity_log import Change, Detail
request = self.context.get("request")
@@ -1019,6 +1018,11 @@ class FeatureFlagSerializer(
self._validate_archived_flags_are_disabled(attrs)
self._validate_flag_limits()
+ # Materialize the remote-config 100% rollout default here, before the approval gate runs in
+ # create(), so a remote-config create trips the rollout policy instead of slipping past it.
+ if self.instance is None:
+ self._apply_remote_config_default_filters(attrs, filters_key="get_filters")
+
request = self.context.get("request")
if not request:
return attrs
@@ -1134,6 +1138,32 @@ class FeatureFlagSerializer(
if has_encrypted and not is_remote:
raise serializers.ValidationError("Encrypted payloads require the flag to be a remote configuration.")
+ @staticmethod
+ def _apply_remote_config_default_filters(validated_data: dict, filters_key: str) -> None:
+ """Remote-config flags always resolve to a 100% rollout.
+
+ Synthesize that default into ``validated_data`` so it is present *before* the approval gate
+ inspects the change. Otherwise a remote-config create with no ``filters`` would skip the
+ rollout (``feature_flag.update``) policy, and the 100% rollout would then be applied below
+ the gate unapproved. ``filters_key`` is ``get_filters`` during serializer validation (the
+ field's source) and ``filters`` once ``_update_filters`` has renamed it in ``create``.
+ """
+ if not validated_data.get("is_remote_configuration", False):
+ return
+
+ filters = validated_data.get(filters_key, {}) or {}
+ groups = filters.get("groups", [])
+
+ # If no groups exist, create one with 100% rollout
+ if not groups:
+ filters["groups"] = [{"properties": [], "rollout_percentage": 100, "variant": None}]
+ validated_data[filters_key] = filters
+ else:
+ # If groups exist, update any with 0% or None rollout to 100%
+ for group in groups:
+ if group.get("rollout_percentage") in [0, None]:
+ group["rollout_percentage"] = 100
+
def validate_key(self, value):
exclude_kwargs = {}
if self.instance:
@@ -1701,6 +1731,7 @@ class FeatureFlagSerializer(
flag.key = flag.tombstoned_key()
flag.save(update_fields=["key"])
+ @approval_gate(["feature_flag.enable", "feature_flag.update"])
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> FeatureFlag:
request = self.context["request"]
validated_data["created_by"] = request.user
@@ -1716,20 +1747,9 @@ class FeatureFlagSerializer(
should_create_usage_dashboard = validated_data.pop("_should_create_usage_dashboard")
self._update_filters(validated_data)
- # Set default filters for remote config flags to 100% rollout
- if validated_data.get("is_remote_configuration", False):
- filters = validated_data.get("filters", {}) or {}
- groups = filters.get("groups", [])
-
- # If no groups exist, create one with 100% rollout
- if not groups:
- filters["groups"] = [{"properties": [], "rollout_percentage": 100, "variant": None}]
- validated_data["filters"] = filters
- else:
- # If groups exist, update any with 0% or None rollout to 100%
- for group in groups:
- if group.get("rollout_percentage") in [0, None]:
- group["rollout_percentage"] = 100
+ # Safety net: validate() already materialized this for gated creates, but keep it here for
+ # any path that reaches create() without it (e.g. approved-CR re-apply builds a fresh payload).
+ self._apply_remote_config_default_filters(validated_data, filters_key="filters")
encrypt_flag_payloads(validated_data)
diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.py
index ff527e2c5528..456f3d0f4185 100644
--- a/products/feature_flags/backend/api/organization_feature_flag.py
+++ b/products/feature_flags/backend/api/organization_feature_flag.py
@@ -1,6 +1,7 @@
import copy
from typing import cast
+from django.db import transaction
from django.db.models import Case, IntegerField, Q, QuerySet, Value, When
import structlog
@@ -21,6 +22,8 @@ from posthog.rbac.user_access_control import UserAccessControl
from posthog.user_permissions import UserPermissions
from posthog.utils import safe_int
+from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
+from products.approvals.backend.scheduled_changes import gate_scheduled_change
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.encrypted_flag_payloads import (
@@ -614,17 +617,37 @@ class OrganizationFeatureFlagView(
# Remap cohort IDs in schedule payload
updated_payload = self._remap_cohort_ids_in_payload(schedule.payload, cohort_mapping, cohort_cache)
- ScheduledChange.objects.create(
- record_id=str(target_flag.id),
- model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
- payload=updated_payload,
- scheduled_at=schedule.scheduled_at,
- is_recurring=schedule.is_recurring,
- recurrence_interval=schedule.recurrence_interval,
- end_date=schedule.end_date,
- team=target_flag.team,
- created_by=user,
- )
+ # Gate the copied schedule against the target flag's policies, same as a directly
+ # created schedule — a copy that would enable/roll out a flag still needs approval.
+ # Gate the CR and create the bound row in one transaction: if the row insert fails after
+ # the CR is minted, the CR is orphaned and a later approval auto-applies it immediately,
+ # bypassing the schedule (the same invariant create() documents and wraps).
+ try:
+ with transaction.atomic():
+ change_request = gate_scheduled_change(target_flag, updated_payload, user)
+ ScheduledChange.objects.create(
+ record_id=str(target_flag.id),
+ model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
+ payload=updated_payload,
+ scheduled_at=schedule.scheduled_at,
+ is_recurring=schedule.is_recurring,
+ recurrence_interval=schedule.recurrence_interval,
+ end_date=schedule.end_date,
+ team=target_flag.team,
+ created_by=user,
+ change_request=change_request,
+ )
+ except (PolicyConflict, ApprovalRequired):
+ # The copied change can't be gated with a fresh single CR on the target — it either
+ # matches multiple policies (PolicyConflict) or would bind an already-approved
+ # duplicate (ApprovalRequired). Skip it (fail closed) rather than copy it ungated or
+ # riding on an unrelated approval — mirroring the permission skip above, we don't
+ # fail the whole copy over one schedule.
+ logger.warning(
+ "Skipping copy of scheduled change that cannot be independently gated on the target flag",
+ target_flag_id=target_flag.id,
+ )
+ continue
def _remap_cohort_ids_in_payload(self, payload, cohort_mapping, cohort_cache):
"""Remap cohort IDs in schedule payload to target project cohorts."""
diff --git a/products/feature_flags/backend/api/scheduled_change.py b/products/feature_flags/backend/api/scheduled_change.py
index f38a443820a8..5c5a3011f2a0 100644
--- a/products/feature_flags/backend/api/scheduled_change.py
+++ b/products/feature_flags/backend/api/scheduled_change.py
@@ -1,5 +1,7 @@
from typing import Any
+from django.db import transaction
+
from croniter import croniter # type: ignore[import-untyped,unused-ignore]
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
@@ -9,11 +11,37 @@ from rest_framework.exceptions import PermissionDenied
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
+from products.approvals.backend.mixins import ApprovalHandlingMixin
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState
+from products.approvals.backend.scheduled_changes import gate_scheduled_change
from products.feature_flags.backend.api.feature_flag import CanEditFeatureFlag
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.scheduled_change import ScheduledChange
+def _gate_scheduled_change_at_creation(
+ model_name: str | None,
+ record_id: Any,
+ team_id: int,
+ payload: dict,
+ user: Any,
+) -> ChangeRequest | None:
+ """Create a pending ChangeRequest if a scheduled change targets a policy-gated field.
+
+ Returns the CR to bind to the new ScheduledChange, or None when no policy applies (the
+ common case). Only feature-flag schedules are gated; a missing target flag is left to the
+ existing edit-permission check, which already validates the flag exists.
+ """
+ if model_name != ScheduledChange.AllowedModels.FEATURE_FLAG or not record_id:
+ return None
+
+ flag = FeatureFlag.objects.filter(id=record_id, team_id=team_id).first()
+ if flag is None:
+ return None
+
+ return gate_scheduled_change(flag, payload, user)
+
+
class ScheduledChangeSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
failure_reason = serializers.SerializerMethodField()
@@ -109,6 +137,8 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):
if instance.executed_at is not None and not instance.is_recurring:
raise serializers.ValidationError("Cannot modify a scheduled change that has already executed.")
+ self._reject_timing_change_on_gated_schedule(instance, data)
+
# For updates, merge with existing instance values
is_recurring = data.get("is_recurring", getattr(instance, "is_recurring", False) if instance else False)
recurrence_interval = data.get(
@@ -185,6 +215,36 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):
return data
+ # Fields that determine *when* a scheduled change fires. Re-gating (see update()) only covers
+ # *what* it applies, so these are locked once a schedule carries a live approval.
+ TIMING_FIELDS = ("scheduled_at", "cron_expression", "recurrence_interval", "end_date", "is_recurring")
+
+ def _reject_timing_change_on_gated_schedule(self, instance: ScheduledChange, data: dict) -> None:
+ """Block retiming a schedule whose bound ChangeRequest is still pending or approved.
+
+ An approver signs off on a change firing within a specific window. Re-gating only reacts to
+ payload edits, so without this an editor could wait for a future schedule to be approved and
+ then PATCH scheduled_at (or the recurrence config) to fire the approved change at a moment the
+ approval never covered — e.g. move it earlier to apply immediately. Deleting and recreating
+ the schedule re-gates from scratch, so this only forbids retiming a change mid-approval.
+ """
+ change_request = instance.change_request
+ if change_request is None or change_request.state not in (
+ ChangeRequestState.PENDING,
+ ChangeRequestState.APPROVED,
+ ):
+ return
+ changed = [field for field in self.TIMING_FIELDS if field in data and data[field] != getattr(instance, field)]
+ if changed:
+ raise serializers.ValidationError(
+ {
+ changed[0]: (
+ "Cannot change the timing of a scheduled change while its approval request is "
+ "pending or approved. Delete this schedule and create a new one to reschedule."
+ )
+ }
+ )
+
def _check_target_edit_permission(self, model_name: str | None, record_id: Any, team_id: int) -> FeatureFlag | None:
"""Enforce edit permission on the target record and return the resolved flag (None if not a flag)."""
if model_name != ScheduledChange.AllowedModels.FEATURE_FLAG or not record_id:
@@ -220,7 +280,24 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):
team = self.context["get_team"]()
validated_data["timezone"] = team.timezone
- return super().create(validated_data)
+ # Gate at scheduling time: if the change would flip a policy-gated field, create a pending
+ # ChangeRequest now and bind it so the applier only applies once approved (see
+ # process_scheduled_changes). NULL change_request means no policy applies — apply as before.
+ #
+ # Create the CR and the ScheduledChange row in one transaction: the applier defers a bound CR
+ # to fire time only while its schedule row exists (approve() keys off scheduled_changes.exists()).
+ # If the row insert failed after the CR was created, the CR would be orphaned and a later
+ # approval would auto-apply it immediately, bypassing the schedule.
+ with transaction.atomic():
+ validated_data["change_request"] = _gate_scheduled_change_at_creation(
+ validated_data.get("model_name"),
+ validated_data.get("record_id"),
+ validated_data["team_id"],
+ validated_data.get("payload", {}),
+ validated_data["created_by"],
+ )
+
+ return super().create(validated_data)
def update(self, instance: ScheduledChange, validated_data: dict) -> ScheduledChange:
# Enforce the same edit-permission check on updates. record_id/model_name can't be changed
@@ -229,11 +306,53 @@ class ScheduledChangeSerializer(serializers.ModelSerializer):
# Canonicalize any legacy non-canonical record_id so the access filter keeps matching it.
if feature_flag is not None:
instance.record_id = str(feature_flag.id)
- return super().update(instance, validated_data)
+
+ # Re-gate whenever the payload changes: create() only gates the payload the row is born with,
+ # so without this an editor could create an ungated schedule and then PATCH its payload to a
+ # policy-gated change, which the applier would dispatch with change_request=None (ungated).
+ if feature_flag is None or "payload" not in validated_data:
+ return super().update(instance, validated_data)
+
+ # Re-gate (which can mint a fresh CR) and bind it in one transaction, mirroring create(): if
+ # the row update fails after the new CR is created, the CR — and the old-CR expiry — roll
+ # back together, so a failed update can't orphan a pending CR that approve() then auto-applies
+ # immediately, bypassing the schedule.
+ with transaction.atomic():
+ validated_data["change_request"] = self._regate_on_payload_change(
+ instance, feature_flag, validated_data["payload"]
+ )
+ return super().update(instance, validated_data)
+
+ def _regate_on_payload_change(
+ self, instance: ScheduledChange, feature_flag: FeatureFlag, new_payload: dict
+ ) -> ChangeRequest | None:
+ """Re-evaluate the approval gate against a changed payload and return the CR to bind.
+
+ Expires any previously bound pending CR that the new payload no longer needs, so a stale
+ request can't be approved into applying a change the row no longer carries.
+
+ Gate as the user making the edit, not the original creator: a creator with approval-bypass
+ would otherwise let any editor PATCH in a gated payload that stays unbound and applies
+ unapproved.
+ """
+ existing = instance.change_request
+ # Pass the schedule's own bound CR so re-gating an unchanged action rediscovers and reuses it
+ # instead of failing closed on its own pending binding.
+ new_change_request = gate_scheduled_change(
+ feature_flag, new_payload, self.context["request"].user, current_change_request=existing
+ )
+ if (
+ existing is not None
+ and existing.state == ChangeRequestState.PENDING
+ and (new_change_request is None or new_change_request.id != existing.id)
+ ):
+ existing.state = ChangeRequestState.EXPIRED
+ existing.save(update_fields=["state"])
+ return new_change_request
@extend_schema(extensions={"x-product": "feature_flags"})
-class ScheduledChangeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+class ScheduledChangeViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""
Create, read, update and delete scheduled changes.
"""
@@ -287,7 +406,22 @@ class ScheduledChangeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# Deleting a schedule cancels a pending flag change, so require edit access on the
# target flag — mirroring the create/update checks enforced by the serializer.
self._assert_can_edit_target_flag(instance)
- super().perform_destroy(instance)
+ change_request = instance.change_request
+ with transaction.atomic():
+ super().perform_destroy(instance)
+ # Deleting the schedule cancels the change it carried, so expire the bound (non-terminal)
+ # ChangeRequest unless another schedule still shares it. Otherwise a pending CR would
+ # outlive its schedule and auto-apply on quorum: ChangeRequestService.approve() only
+ # defers application while a bound schedule row exists (scheduled_changes.exists()), so
+ # once the row is gone the deferral is skipped and the flag change fires immediately on
+ # approval — bypassing the scheduled timing the approval was granted for.
+ if (
+ change_request is not None
+ and change_request.state in (ChangeRequestState.PENDING, ChangeRequestState.APPROVED)
+ and not change_request.scheduled_changes.exists()
+ ):
+ change_request.state = ChangeRequestState.EXPIRED
+ change_request.save(update_fields=["state"])
def _inaccessible_feature_flag_ids(self) -> set[str]:
"""Return record_ids of feature flags in this project the user may not access."""
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 895c93aa81bb..52092903c025 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
@@ -250,6 +250,151 @@
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.14
+ '''
+ SELECT "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"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "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_team"
+ WHERE "posthog_team"."id" = 99999
+ ORDER BY "posthog_team"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15
+ '''
+ SELECT "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organization"
+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -281,7 +426,7 @@
AND "posthog_team"."project_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -383,7 +528,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -408,7 +553,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -427,7 +572,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -469,24 +614,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19
- '''
- 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: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.20
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -528,7 +656,24 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.20
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21
+ '''
+ 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: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -551,7 +696,7 @@
AND "posthog_filesystem"."type" = 'dashboard')
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23
'''
SELECT "posthog_dashboardtile"."id" AS "pk"
FROM "posthog_dashboardtile"
@@ -562,7 +707,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24
'''
SELECT "posthog_tag"."id",
"posthog_tag"."name",
@@ -580,7 +725,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -682,7 +827,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26
'''
SELECT 1 AS "a"
FROM "posthog_tag"
@@ -690,7 +835,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27
'''
SELECT 1 AS "a"
FROM "posthog_dashboard"
@@ -698,7 +843,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28
'''
SELECT 1 AS "a"
FROM "posthog_taggeditem"
@@ -706,7 +851,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29
'''
SELECT 1 AS "_check"
WHERE COALESCE((EXISTS
@@ -718,13 +863,22 @@
LIMIT 1)), true)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3
+ '''
+ SELECT 1 AS "a"
+ FROM "posthog_organizationmembership"
+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
+ AND "posthog_organizationmembership"."user_id" = 99999)
+ LIMIT 1
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30
'''
SELECT 1 AS "_check"
WHERE COALESCE(true, true)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31
'''
SELECT "posthog_tag"."id",
"posthog_tag"."name",
@@ -734,16 +888,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3
- '''
- SELECT 1 AS "a"
- FROM "posthog_organizationmembership"
- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid
- AND "posthog_organizationmembership"."user_id" = 99999)
- LIMIT 1
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -845,7 +990,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33
'''
SELECT "posthog_dashboard"."id",
"posthog_dashboard"."name",
@@ -875,7 +1020,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -898,7 +1043,7 @@
AND "posthog_filesystem"."type" = 'dashboard')
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35
'''
SELECT "posthog_dashboardtile"."id" AS "pk"
FROM "posthog_dashboardtile"
@@ -909,7 +1054,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1010,7 +1155,7 @@
WHERE "posthog_team"."primary_dashboard_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1099,44 +1244,16 @@
"posthog_team"."correlation_config",
"posthog_team"."session_recording_retention_period_days",
"posthog_team"."external_data_workspace_id",
- "posthog_team"."external_data_workspace_last_synced_at",
- "posthog_team"."api_query_rate_limit",
- "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_team"
- WHERE "posthog_team"."primary_dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."dashboard_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37
- '''
- SELECT "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_tag"
- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
- LIMIT 21
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "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_team"
+ WHERE "posthog_team"."primary_dashboard_id" = 99999
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38
@@ -1202,6 +1319,34 @@
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.40
+ '''
+ SELECT "posthog_taggeditem"."id",
+ "posthog_taggeditem"."tag_id",
+ "posthog_taggeditem"."dashboard_id",
+ "posthog_taggeditem"."insight_id",
+ "posthog_taggeditem"."event_definition_id",
+ "posthog_taggeditem"."property_definition_id",
+ "posthog_taggeditem"."action_id",
+ "posthog_taggeditem"."feature_flag_id",
+ "posthog_taggeditem"."experiment_saved_metric_id",
+ "posthog_taggeditem"."ticket_id",
+ "posthog_taggeditem"."account_id",
+ "posthog_taggeditem"."endpoint_id"
+ FROM "posthog_taggeditem"
+ WHERE "posthog_taggeditem"."dashboard_id" = 99999
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41
+ '''
+ SELECT "posthog_tag"."id",
+ "posthog_tag"."name",
+ "posthog_tag"."team_id"
+ FROM "posthog_tag"
+ WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42
'''
SELECT "posthog_dashboardtile"."id",
"posthog_dashboardtile"."dashboard_id",
@@ -1228,7 +1373,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.43
'''
SELECT "posthog_dashboardtile"."id",
"posthog_dashboardtile"."dashboard_id",
@@ -1255,7 +1400,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.44
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -1291,7 +1436,7 @@
AND "posthog_dashboarditem"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.43
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.45
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -1327,7 +1472,7 @@
AND "posthog_dashboarditem"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.44
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.46
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -1364,7 +1509,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.45
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.47
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -1401,7 +1546,7 @@
AND "posthog_dashboardtile"."dashboard_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.46
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.48
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -1426,7 +1571,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.47
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1528,43 +1673,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.48
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- WHERE "posthog_dashboarditem"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1666,7 +1775,43 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50
+ '''
+ SELECT "posthog_dashboarditem"."id",
+ "posthog_dashboarditem"."name",
+ "posthog_dashboarditem"."derived_name",
+ "posthog_dashboarditem"."description",
+ "posthog_dashboarditem"."team_id",
+ "posthog_dashboarditem"."filters",
+ "posthog_dashboarditem"."filters_hash",
+ "posthog_dashboarditem"."query",
+ "posthog_dashboarditem"."query_metadata",
+ "posthog_dashboarditem"."order",
+ "posthog_dashboarditem"."deleted",
+ "posthog_dashboarditem"."saved",
+ "posthog_dashboarditem"."created_at",
+ "posthog_dashboarditem"."refreshing",
+ "posthog_dashboarditem"."created_by_id",
+ "posthog_dashboarditem"."is_sample",
+ "posthog_dashboarditem"."short_id",
+ "posthog_dashboarditem"."favorited",
+ "posthog_dashboarditem"."refresh_attempt",
+ "posthog_dashboarditem"."last_modified_at",
+ "posthog_dashboarditem"."last_modified_by_id",
+ "posthog_dashboarditem"."dashboard_id",
+ "posthog_dashboarditem"."last_refresh",
+ "posthog_dashboarditem"."layouts",
+ "posthog_dashboarditem"."color",
+ "posthog_dashboarditem"."dive_dashboard_id",
+ "posthog_dashboarditem"."updated_at",
+ "posthog_dashboarditem"."deprecated_tags",
+ "posthog_dashboarditem"."tags"
+ FROM "posthog_dashboarditem"
+ WHERE "posthog_dashboarditem"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1768,7 +1913,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52
'''
SELECT "posthog_teamrevenueanalyticsconfig"."team_id",
"posthog_teamrevenueanalyticsconfig"."filter_test_accounts",
@@ -1781,7 +1926,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1883,7 +2028,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54
'''
SELECT "posthog_teammarketinganalyticsconfig"."team_id",
"posthog_teammarketinganalyticsconfig"."attribution_window_days",
@@ -1898,7 +2043,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2000,7 +2145,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56
'''
SELECT "customer_analytics_teamcustomeranalyticsconfig"."team_id",
"customer_analytics_teamcustomeranalyticsconfig"."activity_event",
@@ -2014,7 +2159,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2153,7 +2298,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2255,7 +2400,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59
'''
SELECT "posthog_dashboardtile"."id",
"posthog_dashboardtile"."dashboard_id",
@@ -2279,70 +2424,6 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58
- '''
- SELECT "posthog_dashboarditem"."id",
- "posthog_dashboarditem"."name",
- "posthog_dashboarditem"."derived_name",
- "posthog_dashboarditem"."description",
- "posthog_dashboarditem"."team_id",
- "posthog_dashboarditem"."filters",
- "posthog_dashboarditem"."filters_hash",
- "posthog_dashboarditem"."query",
- "posthog_dashboarditem"."query_metadata",
- "posthog_dashboarditem"."order",
- "posthog_dashboarditem"."deleted",
- "posthog_dashboarditem"."saved",
- "posthog_dashboarditem"."created_at",
- "posthog_dashboarditem"."refreshing",
- "posthog_dashboarditem"."created_by_id",
- "posthog_dashboarditem"."is_sample",
- "posthog_dashboarditem"."short_id",
- "posthog_dashboarditem"."favorited",
- "posthog_dashboarditem"."refresh_attempt",
- "posthog_dashboarditem"."last_modified_at",
- "posthog_dashboarditem"."last_modified_by_id",
- "posthog_dashboarditem"."dashboard_id",
- "posthog_dashboarditem"."last_refresh",
- "posthog_dashboarditem"."layouts",
- "posthog_dashboarditem"."color",
- "posthog_dashboarditem"."dive_dashboard_id",
- "posthog_dashboarditem"."updated_at",
- "posthog_dashboarditem"."deprecated_tags",
- "posthog_dashboarditem"."tags"
- FROM "posthog_dashboarditem"
- WHERE "posthog_dashboarditem"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59
- '''
- SELECT "posthog_dashboard"."id",
- "posthog_dashboard"."name",
- "posthog_dashboard"."description",
- "posthog_dashboard"."team_id",
- "posthog_dashboard"."pinned",
- "posthog_dashboard"."created_at",
- "posthog_dashboard"."created_by_id",
- "posthog_dashboard"."deleted",
- "posthog_dashboard"."last_accessed_at",
- "posthog_dashboard"."last_refresh",
- "posthog_dashboard"."filters",
- "posthog_dashboard"."variables",
- "posthog_dashboard"."breakdown_colors",
- "posthog_dashboard"."data_color_theme_id",
- "posthog_dashboard"."creation_mode",
- "posthog_dashboard"."restriction_level",
- "posthog_dashboard"."quick_filter_ids",
- "posthog_dashboard"."deprecated_tags",
- "posthog_dashboard"."tags",
- "posthog_dashboard"."share_token",
- "posthog_dashboard"."is_shared"
- FROM "posthog_dashboard"
- WHERE "posthog_dashboard"."id" = 99999
- LIMIT 21
- '''
-# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6
'''
SELECT "posthog_organizationmembership"."id",
@@ -2394,7 +2475,71 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.60
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.60
+ '''
+ SELECT "posthog_dashboarditem"."id",
+ "posthog_dashboarditem"."name",
+ "posthog_dashboarditem"."derived_name",
+ "posthog_dashboarditem"."description",
+ "posthog_dashboarditem"."team_id",
+ "posthog_dashboarditem"."filters",
+ "posthog_dashboarditem"."filters_hash",
+ "posthog_dashboarditem"."query",
+ "posthog_dashboarditem"."query_metadata",
+ "posthog_dashboarditem"."order",
+ "posthog_dashboarditem"."deleted",
+ "posthog_dashboarditem"."saved",
+ "posthog_dashboarditem"."created_at",
+ "posthog_dashboarditem"."refreshing",
+ "posthog_dashboarditem"."created_by_id",
+ "posthog_dashboarditem"."is_sample",
+ "posthog_dashboarditem"."short_id",
+ "posthog_dashboarditem"."favorited",
+ "posthog_dashboarditem"."refresh_attempt",
+ "posthog_dashboarditem"."last_modified_at",
+ "posthog_dashboarditem"."last_modified_by_id",
+ "posthog_dashboarditem"."dashboard_id",
+ "posthog_dashboarditem"."last_refresh",
+ "posthog_dashboarditem"."layouts",
+ "posthog_dashboarditem"."color",
+ "posthog_dashboarditem"."dive_dashboard_id",
+ "posthog_dashboarditem"."updated_at",
+ "posthog_dashboarditem"."deprecated_tags",
+ "posthog_dashboarditem"."tags"
+ FROM "posthog_dashboarditem"
+ WHERE "posthog_dashboarditem"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61
+ '''
+ SELECT "posthog_dashboard"."id",
+ "posthog_dashboard"."name",
+ "posthog_dashboard"."description",
+ "posthog_dashboard"."team_id",
+ "posthog_dashboard"."pinned",
+ "posthog_dashboard"."created_at",
+ "posthog_dashboard"."created_by_id",
+ "posthog_dashboard"."deleted",
+ "posthog_dashboard"."last_accessed_at",
+ "posthog_dashboard"."last_refresh",
+ "posthog_dashboard"."filters",
+ "posthog_dashboard"."variables",
+ "posthog_dashboard"."breakdown_colors",
+ "posthog_dashboard"."data_color_theme_id",
+ "posthog_dashboard"."creation_mode",
+ "posthog_dashboard"."restriction_level",
+ "posthog_dashboard"."quick_filter_ids",
+ "posthog_dashboard"."deprecated_tags",
+ "posthog_dashboard"."tags",
+ "posthog_dashboard"."share_token",
+ "posthog_dashboard"."is_shared"
+ FROM "posthog_dashboard"
+ WHERE "posthog_dashboard"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2496,7 +2641,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2635,7 +2780,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -2660,7 +2805,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2762,7 +2907,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -2798,7 +2943,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -2900,7 +3045,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -3039,7 +3184,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.69
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -3141,7 +3286,53 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.7
+ '''
+ SELECT "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_password_reset_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_user"
+ WHERE "posthog_user"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.70
'''
SELECT "posthog_dashboardtile"."id",
"posthog_dashboardtile"."dashboard_id",
@@ -3165,7 +3356,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.69
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.71
'''
SELECT "posthog_dashboarditem"."id",
"posthog_dashboarditem"."name",
@@ -3201,53 +3392,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.7
- '''
- SELECT "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_password_reset_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in"
- FROM "posthog_user"
- WHERE "posthog_user"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.70
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.72
'''
SELECT "posthog_dashboard"."id",
"posthog_dashboard"."name",
@@ -3275,7 +3420,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.71
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.73
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -3377,7 +3522,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.72
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.74
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -3516,7 +3661,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.73
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.75
'''
SELECT "posthog_featureflag"."id",
"posthog_featureflag"."key",
@@ -3548,7 +3693,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.74
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.76
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -3573,7 +3718,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.75
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.77
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -3596,7 +3741,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.76
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.78
'''
SELECT "posthog_integration"."id",
"posthog_integration"."team_id",
@@ -3615,7 +3760,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.77
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.79
'''
SELECT "posthog_organizationintegration"."id",
"posthog_organizationintegration"."organization_id",
@@ -3632,42 +3777,6 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.78
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."feature_flag_id" = 99999
- '''
-# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.79
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id"
- FROM "posthog_taggeditem"
- WHERE "posthog_taggeditem"."feature_flag_id" = 99999
- '''
-# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.8
'''
SELECT "posthog_organizationmembership"."id",
@@ -3718,6 +3827,42 @@
'''
# ---
# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.80
+ '''
+ SELECT "posthog_taggeditem"."id",
+ "posthog_taggeditem"."tag_id",
+ "posthog_taggeditem"."dashboard_id",
+ "posthog_taggeditem"."insight_id",
+ "posthog_taggeditem"."event_definition_id",
+ "posthog_taggeditem"."property_definition_id",
+ "posthog_taggeditem"."action_id",
+ "posthog_taggeditem"."feature_flag_id",
+ "posthog_taggeditem"."experiment_saved_metric_id",
+ "posthog_taggeditem"."ticket_id",
+ "posthog_taggeditem"."account_id",
+ "posthog_taggeditem"."endpoint_id"
+ FROM "posthog_taggeditem"
+ WHERE "posthog_taggeditem"."feature_flag_id" = 99999
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.81
+ '''
+ SELECT "posthog_taggeditem"."id",
+ "posthog_taggeditem"."tag_id",
+ "posthog_taggeditem"."dashboard_id",
+ "posthog_taggeditem"."insight_id",
+ "posthog_taggeditem"."event_definition_id",
+ "posthog_taggeditem"."property_definition_id",
+ "posthog_taggeditem"."action_id",
+ "posthog_taggeditem"."feature_flag_id",
+ "posthog_taggeditem"."experiment_saved_metric_id",
+ "posthog_taggeditem"."ticket_id",
+ "posthog_taggeditem"."account_id",
+ "posthog_taggeditem"."endpoint_id"
+ FROM "posthog_taggeditem"
+ WHERE "posthog_taggeditem"."feature_flag_id" = 99999
+ '''
+# ---
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.82
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -3762,7 +3907,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.81
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.83
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -3807,7 +3952,7 @@
WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.82
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.84
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -3818,7 +3963,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.83
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.85
'''
SELECT "ee_featureflagroleaccess"."id",
"ee_featureflagroleaccess"."feature_flag_id",
@@ -3829,7 +3974,7 @@
WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.84
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.86
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -3869,7 +4014,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.85
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.87
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -3909,7 +4054,7 @@
AND NOT "posthog_experiment"."deleted")
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.86
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.88
'''
SELECT "posthog_survey"."id",
"posthog_survey"."team_id",
@@ -3954,7 +4099,7 @@
WHERE "posthog_survey"."linked_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.87
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.89
'''
SELECT "posthog_earlyaccessfeature"."id",
"posthog_earlyaccessfeature"."team_id",
@@ -3969,7 +4114,15 @@
WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.88
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.9
+ '''
+ 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.90
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -4020,7 +4173,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.89
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.91
'''
SELECT "posthog_dashboard"."id",
"posthog_dashboard"."name",
@@ -4049,15 +4202,7 @@
AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.9
- '''
- 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.90
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.92
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -4108,7 +4253,7 @@
LIMIT 21
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.91
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.93
'''
SELECT 1 AS "a"
FROM "posthog_team"
@@ -4117,7 +4262,7 @@
LIMIT 1
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.92
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.94
'''
SELECT "posthog_featureflagevaluationcontext"."id",
"posthog_featureflagevaluationcontext"."feature_flag_id",
@@ -4133,7 +4278,7 @@
WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999
'''
# ---
-# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.93
+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.95
'''
SELECT "posthog_tag"."name" AS "tag__name"
FROM "posthog_taggeditem"
diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
index dd78fc29f02f..673254984c72 100644
--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py
@@ -1951,3 +1951,154 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):
body = self.client.get(self._url("shared_flag")).json()
for entry in body:
assert entry["evaluations_7d"] is None
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestOrganizationFeatureFlagCopyApprovalGate(APIBaseTest):
+ """Copying a flag routes through FeatureFlagSerializer create()/update(), so a copy that
+ lands the destination flag in a policy-guarded state must be gated. The gate raises inside
+ serializer.save(), which copy_flags surfaces as a per-project failure (the row is NOT made)."""
+
+ def setUp(self):
+ super().setUp()
+ self.team_1 = self.team
+ self.team_2 = Team.objects.create(organization=self.organization)
+ self.source_flag = FeatureFlag.objects.create(
+ team=self.team_1,
+ created_by=self.user,
+ key="copy-gate-flag",
+ active=True,
+ filters={"groups": [{"rollout_percentage": 100}]},
+ )
+
+ def _enable_policy(self, team) -> None:
+ from products.approvals.backend.models import ApprovalPolicy
+
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=team,
+ action_key="feature_flag.enable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _copy(self, target_ids: list[int], disable: bool = False) -> Any:
+ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"
+ return self.client.post(
+ url,
+ {
+ "feature_flag_key": self.source_flag.key,
+ "from_project": self.source_flag.team_id,
+ "target_project_ids": target_ids,
+ **({"disable_copied_flag": True} if disable else {}),
+ },
+ )
+
+ def test_copy_active_flag_to_new_target_under_policy_is_gated(self, _mock_enabled):
+ self._enable_policy(self.team_2)
+
+ response = self._copy([self.team_2.id])
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["success"] == []
+ assert len(body["failed"]) == 1
+ assert body["failed"][0]["project_id"] == self.team_2.id
+ assert not FeatureFlag.objects.filter(team=self.team_2, key=self.source_flag.key).exists()
+
+ def test_copy_active_flag_onto_existing_active_target_is_gated(self, _mock_enabled):
+ # Existing destination flag is enabled via update() — covered by Task 2; assert it here too.
+ existing = FeatureFlag.objects.create(
+ team=self.team_2,
+ created_by=self.user,
+ key=self.source_flag.key,
+ active=False,
+ filters={"groups": [{"rollout_percentage": 0}]},
+ )
+ self._enable_policy(self.team_2)
+
+ response = self._copy([self.team_2.id])
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["success"] == []
+ existing.refresh_from_db()
+ assert existing.active is False
+
+ def test_copy_disabled_flag_to_new_target_under_policy_succeeds(self, _mock_enabled):
+ self._enable_policy(self.team_2)
+
+ response = self._copy([self.team_2.id], disable=True)
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert len(body["success"]) == 1
+ assert body["failed"] == []
+ assert FeatureFlag.objects.filter(team=self.team_2, key=self.source_flag.key, active=False).exists()
+
+ def _copy_with_schedule(self, target_ids: list[int], disable: bool = False) -> Any:
+ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"
+ return self.client.post(
+ url,
+ {
+ "feature_flag_key": self.source_flag.key,
+ "from_project": self.source_flag.team_id,
+ "target_project_ids": target_ids,
+ "copy_schedule": True,
+ **({"disable_copied_flag": True} if disable else {}),
+ },
+ )
+
+ def test_copy_enable_schedule_under_policy_binds_pending_cr(self, _mock_enabled):
+ # A copied schedule that would enable the flag on the target must be gated exactly like a
+ # directly-created one: the target's enable policy binds a fresh pending CR to the copy.
+ from products.approvals.backend.models import ChangeRequestState
+
+ self._enable_policy(self.team_2)
+ ScheduledChange.objects.create(
+ record_id=str(self.source_flag.id),
+ model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
+ payload={"operation": "update_status", "value": True},
+ scheduled_at=timezone.now() + timedelta(days=1),
+ team=self.team_1,
+ created_by=self.user,
+ )
+
+ # Copy the flag disabled so the flag-copy itself isn't blocked by the enable policy; the
+ # copied schedule then targets a disabled flag and its enable is what gets gated.
+ response = self._copy_with_schedule([self.team_2.id], disable=True)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ copied_flag = FeatureFlag.objects.get(team=self.team_2, key=self.source_flag.key)
+ copied_schedule = ScheduledChange.objects.get(
+ record_id=str(copied_flag.id),
+ model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
+ team=self.team_2,
+ )
+ assert copied_schedule.change_request is not None
+ assert copied_schedule.change_request.state == ChangeRequestState.PENDING
+
+ def test_copy_enable_schedule_matching_multiple_policies_is_skipped(self, _mock_enabled):
+ # A copied schedule that matches more than one enabled policy on the target can't bind a
+ # single CR, so it's skipped (fail closed) rather than copied ungated. The flag copy itself
+ # still succeeds.
+ self._enable_policy(self.team_2) # team-level enable policy
+ self._enable_policy(None) # org-level enable policy also matches → conflict
+ ScheduledChange.objects.create(
+ record_id=str(self.source_flag.id),
+ model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
+ payload={"operation": "update_status", "value": True},
+ scheduled_at=timezone.now() + timedelta(days=1),
+ team=self.team_1,
+ created_by=self.user,
+ )
+
+ response = self._copy_with_schedule([self.team_2.id], disable=True)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ copied_flag = FeatureFlag.objects.get(team=self.team_2, key=self.source_flag.key)
+ assert not ScheduledChange.objects.filter(
+ record_id=str(copied_flag.id),
+ model_name=ScheduledChange.AllowedModels.FEATURE_FLAG,
+ team=self.team_2,
+ ).exists()
diff --git a/products/feature_flags/backend/migrations/0009_scheduledchange_change_request.py b/products/feature_flags/backend/migrations/0009_scheduledchange_change_request.py
new file mode 100644
index 000000000000..94fd247a9d51
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0009_scheduledchange_change_request.py
@@ -0,0 +1,23 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0008_team_feature_flags_config"),
+ ("approvals", "0001_migrate_approvals_models"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="scheduledchange",
+ name="change_request",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="scheduled_changes",
+ to="approvals.changerequest",
+ ),
+ ),
+ ]
diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txt
index 817cf71810e2..09d212f093b7 100644
--- a/products/feature_flags/backend/migrations/max_migration.txt
+++ b/products/feature_flags/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0008_team_feature_flags_config
+0009_scheduledchange_change_request
diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.py
index 776e9c293884..1ffe295dbeba 100644
--- a/products/feature_flags/backend/models/feature_flag.py
+++ b/products/feature_flags/backend/models/feature_flag.py
@@ -1,3 +1,4 @@
+import copy
import json
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Optional, cast
@@ -46,6 +47,61 @@ def default_filters() -> dict:
return {"groups": []}
+def build_scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """Shape a scheduled-change payload into the serializer data applying it would produce.
+
+ Single source of truth for both the creation-time approval gate
+ (``products.approvals.backend.scheduled_changes.scheduled_change_serializer_data``) and the
+ apply-time dispatcher (``FeatureFlag.scheduled_changes_dispatcher``), so the change the gate
+ evaluates is exactly the change the applier makes — previously two hand-kept-in-sync copies,
+ and the deep-copy-before-mutating fix had to be patched into both separately.
+
+ Returns ``{"active": ...}`` / ``{"filters": ...}`` for a recognized payload, or ``None`` when
+ the payload is malformed (missing ``operation``/``value``) or its operation is unrecognized.
+ Callers decide what ``None`` means: the gate declines to gate an uninterpretable change; the
+ dispatcher raises. Apply-time-only validation (variant rollout sums, payload-key matching)
+ stays in the dispatcher.
+ """
+ operation = payload.get("operation")
+ if operation is None or "value" not in payload:
+ return None
+ value = payload["value"]
+
+ if operation == "update_status":
+ return {"active": value}
+
+ current_filters = flag.get_filters()
+
+ if operation == "add_release_condition":
+ new_groups = value.get("groups", []) if isinstance(value, dict) else []
+ return {
+ "filters": {
+ **current_filters,
+ "groups": current_filters.get("groups", []) + new_groups,
+ }
+ }
+
+ if operation == "update_variants":
+ if not isinstance(value, dict):
+ return None
+ new_variants = value.get("variants", [])
+ new_payloads = value.get("payloads", {})
+ # Deep-copy before mutating: current_filters is flag.filters (a live reference), so assigning
+ # into its nested multivariate dict would mutate the flag's pre-change state in place and
+ # defeat the approval gate's old-vs-new comparison.
+ updated_multivariate = copy.deepcopy(current_filters.get("multivariate", {}))
+ updated_multivariate["variants"] = new_variants
+ return {
+ "filters": {
+ **current_filters,
+ "multivariate": updated_multivariate,
+ "payloads": new_payloads,
+ }
+ }
+
+ return None
+
+
class FeatureFlagManager(RootTeamManager):
def get_queryset(self):
return super().get_queryset().exclude(deleted=True)
@@ -516,33 +572,19 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
"project_id": self.team.project_id,
}
- serializer_data = {}
-
- if payload["operation"] == "add_release_condition":
- current_filters = self.get_filters()
- current_groups = current_filters.get("groups", [])
- new_groups = payload["value"].get("groups", [])
-
- serializer_data["filters"] = {
- **current_filters,
- "groups": current_groups + new_groups,
- }
- elif payload["operation"] == "update_status":
- serializer_data["active"] = payload["value"]
- elif payload["operation"] == "update_variants":
- current_filters = self.get_filters()
+ # Apply-time-only validation for variant changes, before shaping the payload. The gate skips
+ # these because an invalid change can't be approved into applying anyway; here they surface
+ # as errors at fire time.
+ if payload["operation"] == "update_variants":
variant_data = payload["value"]
-
new_variants = variant_data.get("variants", [])
new_payloads = variant_data.get("payloads", {})
- # Validate variant rollout percentages before proceeding
if new_variants:
total_rollout = sum(variant.get("rollout_percentage", 0) for variant in new_variants)
if total_rollout != 100:
raise ValueError(f"Invalid variant rollout percentages: sum is {total_rollout}, must be 100")
- # Validate payload keys match variant keys
variant_keys = {v.get("key") for v in new_variants}
payload_keys = set(new_payloads.keys()) if new_payloads else set()
@@ -552,15 +594,10 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
invalid_keys = payload_keys - variant_keys
raise ValueError(f"Payload keys {invalid_keys} don't match variant keys {variant_keys}")
- updated_multivariate = current_filters.get("multivariate", {})
- updated_multivariate["variants"] = new_variants
-
- serializer_data["filters"] = {
- **current_filters,
- "multivariate": updated_multivariate,
- "payloads": new_payloads,
- }
- else:
+ # Shape the payload through the shared builder the approval gate also uses, so the applied
+ # change is exactly the one the gate evaluated.
+ serializer_data = build_scheduled_change_serializer_data(self, payload)
+ if serializer_data is None:
raise Exception(f"Unrecognized operation: {payload['operation']}")
serializer = FeatureFlagSerializer(self, data=serializer_data, context=context, partial=True)
diff --git a/products/feature_flags/backend/models/scheduled_change.py b/products/feature_flags/backend/models/scheduled_change.py
index 2caaf97d7485..6e4b2c5fbfee 100644
--- a/products/feature_flags/backend/models/scheduled_change.py
+++ b/products/feature_flags/backend/models/scheduled_change.py
@@ -52,6 +52,17 @@ class ScheduledChange(RootTeamMixin, models.Model):
timezone = models.CharField(max_length=240, null=True, blank=True)
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ # When a scheduled change would flip a policy-gated field (e.g. enabling a flag), a pending
+ # ChangeRequest is created at scheduling time and bound here. The Celery applier only applies
+ # the change once that CR is approved; if the fire window passes while still pending, the CR
+ # is expired and the change is skipped. NULL for ungated schedules (no policy applies).
+ change_request = models.ForeignKey(
+ "approvals.ChangeRequest",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="scheduled_changes",
+ )
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 3e9622e8394f..b9028bc1876b 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -645,7 +645,6 @@ export interface PatchedApprovalPolicyApi {
/**
* * `valid` - Valid
* * `invalid` - Invalid
- * * `expired` - Expired
* * `stale` - Stale (resource changed)
*/
export type ValidationStatusEnumApi = (typeof ValidationStatusEnumApi)[keyof typeof ValidationStatusEnumApi]
@@ -653,7 +652,6 @@ export type ValidationStatusEnumApi = (typeof ValidationStatusEnumApi)[keyof typ
export const ValidationStatusEnumApi = {
Valid: 'valid',
Invalid: 'invalid',
- Expired: 'expired',
Stale: 'stale',
} as const
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e72778af8ad2..11262f71fd8e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12698,7 +12698,6 @@ export namespace Schemas {
/**
* * `valid` - Valid
* * `invalid` - Invalid
- * * `expired` - Expired
* * `stale` - Stale (resource changed)
*/
export type ValidationStatusEnum = typeof ValidationStatusEnum[keyof typeof ValidationStatusEnum];
@@ -12707,7 +12706,6 @@ export namespace Schemas {
export const ValidationStatusEnum = {
Valid: 'valid',
Invalid: 'invalid',
- Expired: 'expired',
Stale: 'stale',
} as const;
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 168b261d377a..69d7e1c5c3fc 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -7910,11 +7910,11 @@ export const ExperimentsCopyToProjectCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsDuplicateCreateParams = /* @__PURE__ */ zod.object({
id: zod.number().describe('A unique integer value identifying this experiment.'),
@@ -11597,11 +11597,11 @@ export const ExperimentsShipVariantCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsTimeseriesResultsRetrieveParams = /* @__PURE__ */ zod.object({
id: zod.number().describe('A unique integer value identifying this experiment.'),
@@ -11749,11 +11749,11 @@ export const ExperimentsCalculateRunningTimeCreateBody = /* @__PURE__ */ zod
.describe('Inputs for estimating the recommended sample size and running time of an experiment.')
/**
- * Mixin for ViewSets to handle ApprovalRequired exceptions from decorated serializers.
+ * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
*
- * This mixin intercepts ApprovalRequired exceptions raised by the @approval_gate decorator
- * on serializer methods and converts them into proper HTTP 409 Conflict responses with
- * change request details.
+ * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
+ * decorator on serializer methods and converts them into the same responses the viewset path
+ * produces (see decorators._result_to_response), so both paths share one contract.
*/
export const ExperimentsStatsRetrieveParams = /* @__PURE__ */ zod.object({
project_id: zod