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.

feat(approvals): sync feature flag policies to hidden experiment policies (#98957)

Yasen09c99ca942f0
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index f39122407475..f30b9cc65327 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -77,7 +77,11 @@ from posthog.utils import get_crontab, get_instance_region
from products.ai_training.backend.facade.api import privacy_enabled
from products.ai_training.backend.facade.tasks import process_ai_training_privacy_requests
-from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
+from products.approvals.backend.tasks import (
+ expire_old_change_requests,
+ sync_experiment_approval_policies,
+ validate_pending_change_requests,
+)
from products.canvas.backend.tasks import cleanup_canvas_builds, sweep_canvas_builds
from products.conversations.backend.tasks.email import flush_pending_email_replies
from products.conversations.backend.tasks.maintenance import wake_snoozed_tickets
@@ -1000,6 +1004,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="expire old change requests",
)
+ # TODO(experiment-approval-policies): temporary. See products/approvals/backend/experiment_policy_sync.py.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="15"),
+ sync_experiment_approval_policies.s(),
+ name="sync experiment approval policies",
+ )
+
# Deactivate endpoint materializations that haven't been used in 30+ days
sender.add_periodic_task(
crontab(hour="5", minute="0"),
diff --git a/products/approvals/backend/api.py b/products/approvals/backend/api.py
index 11535a9211ad..60d408d33efc 100644
--- a/products/approvals/backend/api.py
+++ b/products/approvals/backend/api.py
@@ -22,6 +22,7 @@ from posthog.permissions import (
)
from products.approvals.backend.exceptions import AlreadyVotedError, InvalidStateError, ReasonRequiredError
+from products.approvals.backend.experiment_policy_sync import SYNCED_ACTION_KEYS
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.approvals.backend.permissions import CanApprove, CanCancel
from products.approvals.backend.serializers import (
@@ -183,6 +184,9 @@ class ApprovalPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
premium_feature_on_cloud = AvailableFeature.APPROVALS
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ # TODO(experiment-approval-policies): temporary. Experiment policies are hidden mirrors of flag policies
+ # until they are enforced. See experiment_policy_sync.py.
+ queryset = queryset.exclude(action_key__in=SYNCED_ACTION_KEYS)
filters = self.request.query_params
if "action_key" in filters:
@@ -210,7 +214,10 @@ class ApprovalPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
action_key=action_key,
organization=self.organization,
team=self.team,
- ).exists()
+ )
+ # TODO(experiment-approval-policies): ignore hidden mirrors so this error cannot reveal them.
+ .exclude(action_key__in=SYNCED_ACTION_KEYS)
+ .exists()
):
raise exceptions.ValidationError(
"A policy for this action already exists. You can edit the existing policy instead."
diff --git a/products/approvals/backend/experiment_policy_sync.py b/products/approvals/backend/experiment_policy_sync.py
new file mode 100644
index 000000000000..1f6472bc037a
--- /dev/null
+++ b/products/approvals/backend/experiment_policy_sync.py
@@ -0,0 +1,118 @@
+"""TEMPORARY: mirror feature flag approval policies to experiment approval policies.
+
+This module exists only until experiment-owned flags leave `feature_flag.*` policy scope and the
+`experiment.*` policies are enforced. Delete it in the PR that ships that enforcement. The last sync
+run before that deploy is the final copy, so organizations keep the approvals they configured.
+
+Every part of the sync carries the tag `TODO(experiment-approval-policies)`. Remove all of them:
+- this module and `tests/test_experiment_policy_sync.py`
+- the `sync_experiment_approval_policies` task in `tasks.py`
+- its beat entry in `posthog/tasks/scheduled.py`
+- the `experiment.*` exclusions in `ApprovalPolicyViewSet`
+- the `experiment.*` rejection in `ApprovalPolicySerializer.validate_action_key`
+- the tests in `test_approvals_api.py` that create `experiment.*` rows to check they stay hidden
+
+No column marks a row as a mirror. This is on purpose, because the sync is short-lived. So the sync
+treats every `experiment.*` row as a mirror. It overwrites or deletes any `experiment.*` row that a
+person created before the API started to reject these keys.
+"""
+
+from uuid import UUID
+
+from django.db import connection, transaction
+
+from structlog import get_logger
+
+from products.approvals.backend.models import ApprovalPolicy
+
+logger = get_logger(__name__)
+
+# Each feature flag action and the experiment action that replaces it once experiment-owned flags
+# leave `feature_flag.*` scope. Until then nothing evaluates the experiment policies.
+ACTION_MAP = {
+ "feature_flag.enable": "experiment.launch",
+ "feature_flag.disable": "experiment.pause",
+ "feature_flag.update": "experiment.update",
+}
+
+SYNCED_ACTION_KEYS = frozenset(ACTION_MAP.values())
+
+MIRRORED_FIELDS = (
+ "conditions",
+ "approver_config",
+ "allow_self_approve",
+ "bypass_org_membership_levels",
+ "expires_after",
+ "enabled",
+ "created_by_id",
+)
+
+_SYNC_LOCK_KEY = "approvals:sync_experiment_policies"
+
+
+def sync_experiment_policies() -> None:
+ """Make the experiment policies an exact mirror of the feature flag policies.
+
+ Creates a mirror for each new flag policy, overwrites a mirror whose flag policy changed, and
+ deletes a mirror whose flag policy is gone. A one-off copy would drift in all three ways while
+ organizations keep editing flag policies before the experiment actions take effect.
+
+ Deleting orphans is safe because every row with a synced action key is a mirror: the API
+ rejects those keys, so no person can create one.
+
+ One run at a time holds a lock, and an overlapping run skips. The unique constraint cannot
+ stop two runs from each inserting an organization-level mirror, because `team_id` is NULL there.
+ """
+ with transaction.atomic():
+ if not _try_sync_lock():
+ logger.info("sync_experiment_policies.skipped", reason="another run holds the lock")
+ return
+
+ created = updated = 0
+ live: set[tuple[UUID, int | None, str]] = set()
+
+ sources = ApprovalPolicy.objects.filter(action_key__in=ACTION_MAP).prefetch_related("bypass_roles")
+ for source in sources:
+ target_action = ACTION_MAP[source.action_key]
+ live.add((source.organization_id, source.team_id, target_action))
+ fields = {field: getattr(source, field) for field in MIRRORED_FIELDS}
+ roles = {role.id for role in source.bypass_roles.all()}
+
+ mirror, was_created = ApprovalPolicy.objects.get_or_create(
+ organization_id=source.organization_id,
+ team_id=source.team_id,
+ action_key=target_action,
+ defaults=fields,
+ )
+ if was_created:
+ mirror.bypass_roles.set(roles)
+ created += 1
+ continue
+
+ stale = [field for field, value in fields.items() if getattr(mirror, field) != value]
+ roles_changed = set(mirror.bypass_roles.values_list("id", flat=True)) != roles
+ if not stale and not roles_changed:
+ continue
+
+ for field in stale:
+ setattr(mirror, field, fields[field])
+ mirror.save(update_fields=[*stale, "updated_at"])
+ if roles_changed:
+ mirror.bypass_roles.set(roles)
+ updated += 1
+
+ orphans = [
+ mirror
+ for mirror in ApprovalPolicy.objects.filter(action_key__in=SYNCED_ACTION_KEYS)
+ if (mirror.organization_id, mirror.team_id, mirror.action_key) not in live
+ ]
+ for orphan in orphans:
+ orphan.delete()
+
+ logger.info("sync_experiment_policies.complete", created=created, updated=updated, deleted=len(orphans))
+
+
+def _try_sync_lock() -> bool:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_try_advisory_xact_lock(hashtextextended(%s, 0))", [_SYNC_LOCK_KEY])
+ return cursor.fetchone()[0]
diff --git a/products/approvals/backend/serializers.py b/products/approvals/backend/serializers.py
index f0f0110e48a8..40076965a853 100644
--- a/products/approvals/backend/serializers.py
+++ b/products/approvals/backend/serializers.py
@@ -4,6 +4,7 @@ from rest_framework import serializers
from posthog.api.shared import UserBasicSerializer
from products.access_control.backend.models.role import Role
+from products.approvals.backend.experiment_policy_sync import SYNCED_ACTION_KEYS
from products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequest, ChangeRequestState
@@ -241,6 +242,13 @@ class ApprovalPolicySerializer(serializers.ModelSerializer):
]
read_only_fields = ["id", "created_by", "created_at", "updated_at"]
+ # TODO(experiment-approval-policies): temporary. Only the sync may write experiment policies.
+ # See experiment_policy_sync.py.
+ def validate_action_key(self, value: str) -> str:
+ if value in SYNCED_ACTION_KEYS:
+ raise serializers.ValidationError("This approval action isn't available yet.")
+ return value
+
def validate_approver_config(self, value):
quorum = value.get("quorum", 0)
if quorum < 1:
diff --git a/products/approvals/backend/tasks.py b/products/approvals/backend/tasks.py
index d3dbcfa318d1..3467757d4bb5 100644
--- a/products/approvals/backend/tasks.py
+++ b/products/approvals/backend/tasks.py
@@ -8,6 +8,7 @@ from structlog import get_logger
from posthog.scoping_audit import skip_team_scope_audit
+from products.approvals.backend.experiment_policy_sync import sync_experiment_policies
from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
from products.approvals.backend.notifications import send_approval_expired_notification
@@ -163,3 +164,10 @@ def expire_old_change_requests() -> dict[str, Any]:
logger.info("expire_old_change_requests.complete", **result)
return result
+
+
+# TODO(experiment-approval-policies): temporary. See experiment_policy_sync.py for what to remove.
+@shared_task(ignore_result=True)
+@skip_team_scope_audit
+def sync_experiment_approval_policies() -> None:
+ sync_experiment_policies()
diff --git a/products/approvals/backend/tests/test_approvals_api.py b/products/approvals/backend/tests/test_approvals_api.py
index acee54fd08a6..370c0a9a9fa5 100644
--- a/products/approvals/backend/tests/test_approvals_api.py
+++ b/products/approvals/backend/tests/test_approvals_api.py
@@ -425,12 +425,22 @@ class TestApprovalPolicyViewSet(APIBaseTest):
approver_config={"quorum": 1, "users": [self.user.id]},
created_by=self.user,
)
+ # TODO(experiment-approval-policies): remove the mirror row with the sync.
+ mirror = ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="experiment.launch",
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
response = self.client.get(f"/api/environments/{self.team.id}/approval_policies/")
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["results"]) == 1
assert response.json()["results"][0]["id"] == str(policy.id)
+ mirror_response = self.client.get(f"/api/environments/{self.team.id}/approval_policies/{mirror.id}/")
+ assert mirror_response.status_code == status.HTTP_404_NOT_FOUND
def test_create_policy(self):
response = self.client.post(
@@ -550,6 +560,26 @@ class TestApprovalPolicyViewSet(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "already exists" in response.json()["detail"]
+ # TODO(experiment-approval-policies): remove with the sync.
+ def test_create_experiment_policy_is_rejected(self):
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="experiment.launch",
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/approval_policies/",
+ {"action_key": "experiment.launch", "approver_config": {"quorum": 1, "users": [self.user.id]}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "action_key"
+ assert response.json()["detail"] == "This approval action isn't available yet."
+
@parameterized.expand(
[
("string_levels", ["8", "15"]),
diff --git a/products/approvals/backend/tests/test_experiment_policy_sync.py b/products/approvals/backend/tests/test_experiment_policy_sync.py
new file mode 100644
index 000000000000..16209b5ad44c
--- /dev/null
+++ b/products/approvals/backend/tests/test_experiment_policy_sync.py
@@ -0,0 +1,115 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.db import connection
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.access_control.backend.models.role import Role
+from products.approvals.backend.experiment_policy_sync import _SYNC_LOCK_KEY, sync_experiment_policies
+from products.approvals.backend.models import ApprovalPolicy
+
+
+class TestSyncExperimentPolicies(BaseTest):
+ def _flag_policy(self, action_key: str, **overrides) -> ApprovalPolicy:
+ fields = {
+ "organization": self.organization,
+ "team": self.team,
+ "action_key": action_key,
+ "approver_config": {"quorum": 1, "users": [self.user.id]},
+ "created_by": self.user,
+ **overrides,
+ }
+ return ApprovalPolicy.objects.create(**fields)
+
+ def _mirror(self, action_key: str, team: Team | None) -> ApprovalPolicy:
+ return ApprovalPolicy.objects.get(organization=self.organization, team=team, action_key=action_key)
+
+ @parameterized.expand(
+ [
+ ("feature_flag.enable", "experiment.launch"),
+ ("feature_flag.disable", "experiment.pause"),
+ ("feature_flag.update", "experiment.update"),
+ ]
+ )
+ def test_creates_mirror_with_mapped_action(self, source_action: str, mirror_action: str) -> None:
+ role = Role.objects.create(organization=self.organization, name="Release managers")
+ source = self._flag_policy(
+ source_action,
+ conditions={"rollout_percentage": {"gt": 50}},
+ approver_config={"quorum": 2, "users": [self.user.id], "roles": [str(role.id)]},
+ allow_self_approve=True,
+ bypass_org_membership_levels=[15],
+ expires_after=timedelta(days=3),
+ enabled=False,
+ )
+ source.bypass_roles.set([role])
+
+ sync_experiment_policies()
+
+ mirror = self._mirror(mirror_action, self.team)
+ assert mirror.conditions == source.conditions
+ assert mirror.approver_config == source.approver_config
+ assert mirror.allow_self_approve is True
+ assert mirror.bypass_org_membership_levels == [15]
+ assert mirror.expires_after == timedelta(days=3)
+ assert mirror.enabled is False
+ assert mirror.created_by_id == self.user.id
+ assert list(mirror.bypass_roles.all()) == [role]
+
+ def test_propagates_edits_without_duplicating(self) -> None:
+ kept_role = Role.objects.create(organization=self.organization, name="Kept")
+ dropped_role = Role.objects.create(organization=self.organization, name="Dropped")
+ source = self._flag_policy("feature_flag.update")
+ source.bypass_roles.set([dropped_role])
+ sync_experiment_policies()
+
+ source.bypass_roles.set([kept_role])
+ before_roles_sync = self._mirror("experiment.update", self.team).updated_at
+ sync_experiment_policies()
+ after_roles_sync = self._mirror("experiment.update", self.team).updated_at
+ assert before_roles_sync is not None and after_roles_sync is not None
+ assert after_roles_sync > before_roles_sync
+
+ source.approver_config = {"quorum": 3, "users": [self.user.id]}
+ source.enabled = False
+ source.save()
+ sync_experiment_policies()
+ sync_experiment_policies()
+
+ assert ApprovalPolicy.objects.filter(action_key="experiment.update").count() == 1
+ mirror = self._mirror("experiment.update", self.team)
+ assert mirror.approver_config == {"quorum": 3, "users": [self.user.id]}
+ assert mirror.enabled is False
+ assert list(mirror.bypass_roles.all()) == [kept_role]
+
+ def test_deletes_mirror_only_when_its_source_is_gone(self) -> None:
+ deleted_source = self._flag_policy("feature_flag.enable")
+ self._flag_policy("feature_flag.enable", team=None)
+ unrelated = self._flag_policy("feature_flag.delete")
+ sync_experiment_policies()
+
+ deleted_source.delete()
+ sync_experiment_policies()
+
+ assert not ApprovalPolicy.objects.filter(team=self.team, action_key="experiment.launch").exists()
+ assert self._mirror("experiment.launch", None)
+ assert ApprovalPolicy.objects.filter(id=unrelated.id).exists()
+ assert not ApprovalPolicy.objects.filter(action_key="experiment.delete").exists()
+
+ def test_skips_while_another_run_holds_the_lock(self) -> None:
+ self._flag_policy("feature_flag.enable", team=None)
+ other_run = connection.copy()
+ try:
+ with other_run.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_lock(hashtextextended(%s, 0))", [_SYNC_LOCK_KEY])
+ sync_experiment_policies()
+ finally:
+ other_run.close()
+
+ assert not ApprovalPolicy.objects.filter(action_key="experiment.launch").exists()
+ sync_experiment_policies()
+ assert self._mirror("experiment.launch", None)