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(experiments): gate a holdout change as one approval (#102305)

Yasend382a5f9b312
diff --git a/ee/clickhouse/views/experiment_holdouts.py b/ee/clickhouse/views/experiment_holdouts.py
index 0d5d5f1092e3..08db18901fd5 100644
--- a/ee/clickhouse/views/experiment_holdouts.py
+++ b/ee/clickhouse/views/experiment_holdouts.py
@@ -3,7 +3,7 @@ from typing import Any
from django.db import transaction
from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import serializers, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -13,10 +13,17 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.approvals.backend.decorators import approval_gate
+from products.approvals.backend.mixins import ApprovalHandlingMixin
from products.experiments.backend.models.experiment import ExperimentHoldout
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.facade.api import update_flag
from products.feature_flags.backend.facade.filters import set_holdout
+# A holdout change is gated as one operation, so the flag writes it fans out into must not
+# re-enter the flag gate: a second gate inside the transaction would roll its own change
+# request back. See products/approvals/backend/actions/experiment_holdouts.py.
+HOLDOUT_GATED_AT_OPERATION = {"approval_apply": True}
+
@extend_schema_field(FeatureFlagConditionGroupSchemaSerializer(many=True))
class HoldoutFiltersField(serializers.JSONField):
@@ -111,6 +118,7 @@ class ExperimentHoldoutSerializer(UserAccessControlSerializerMixin, serializers.
instance.save(skip_activity_log=True) # Skip activity logging for filters update
return instance
+ @approval_gate("experiment_holdout.update")
def update(self, instance: ExperimentHoldout, validated_data):
filters = validated_data.get("filters")
if filters and instance.filters != filters:
@@ -120,9 +128,9 @@ class ExperimentHoldoutSerializer(UserAccessControlSerializerMixin, serializers.
with transaction.atomic():
for experiment in instance.experiment_set.all():
flag = experiment.feature_flag
- existing_flag_serializer = FeatureFlagSerializer(
+ update_flag(
flag,
- data={
+ {
"filters": set_holdout(
flag.filters,
holdout_id=instance.id,
@@ -130,18 +138,42 @@ class ExperimentHoldoutSerializer(UserAccessControlSerializerMixin, serializers.
exclusion_percentage=new_filters[0]["rollout_percentage"],
),
},
- partial=True,
- context=self.context,
+ team=self.context["get_team"](),
+ user=self.context["request"].user,
+ request=self.context["request"],
+ serializer_context={**self.context, **HOLDOUT_GATED_AT_OPERATION},
)
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
return super().update(instance, validated_data)
return super().update(instance, validated_data)
+def delete_holdout_and_clear_flags(holdout: ExperimentHoldout, *, user: Any, request: Any = None) -> None:
+ """Delete a holdout and drop its exclusion from every linked experiment's flag.
+
+ Shared by the endpoint and by the apply path of an approved delete, so both write the same
+ rows in the same transaction.
+ """
+ with transaction.atomic():
+ for experiment in holdout.experiment_set.all():
+ flag = experiment.feature_flag
+ update_flag(
+ flag,
+ {"filters": set_holdout(flag.filters, holdout_id=None, exclusion_percentage=None)},
+ team=holdout.team,
+ user=user,
+ request=request,
+ serializer_context=HOLDOUT_GATED_AT_OPERATION,
+ )
+ holdout.delete()
+
+
@extend_schema(extensions={"x-swagger-tag": "experiment_holdouts", "x-product": "experiments"})
-class ExperimentHoldoutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+class ExperimentHoldoutViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """
+ Create, read, update and delete experiment holdouts.
+ """
+
# Deliberately NOT an AccessControlViewSetMixin: holdouts are shared project config that
# inherit experiment access, with no per-holdout grants. Exposing `/{id}/access_controls`
# would let an object-level holdout grant bypass resource-level experiment access.
@@ -150,21 +182,7 @@ class ExperimentHoldoutViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = ExperimentHoldoutSerializer
ordering = "-created_at"
+ @approval_gate("experiment_holdout.delete")
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- instance = self.get_object()
-
- with transaction.atomic():
- for experiment in instance.experiment_set.all():
- flag = experiment.feature_flag
- existing_flag_serializer = FeatureFlagSerializer(
- flag,
- data={
- "filters": set_holdout(flag.filters, holdout_id=None, exclusion_percentage=None),
- },
- partial=True,
- context={"request": request, "team": self.team, "team_id": self.team_id},
- )
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
-
- return super().destroy(request, *args, **kwargs)
+ delete_holdout_and_clear_flags(self.get_object(), user=request.user, request=request)
+ return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/ee/clickhouse/views/test/test_experiment_holdouts.py b/ee/clickhouse/views/test/test_experiment_holdouts.py
index 32ae21a46e6f..27408f6e62d2 100644
--- a/ee/clickhouse/views/test/test_experiment_holdouts.py
+++ b/ee/clickhouse/views/test/test_experiment_holdouts.py
@@ -1,3 +1,4 @@
+from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
@@ -331,3 +332,177 @@ class TestExperimentHoldoutAccessControl(APILicensedTest):
format="json",
)
self.assertEqual(put_res.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class TestExperimentHoldoutApprovals(APILicensedTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+
+ self.holdout = ExperimentHoldout.objects.create(
+ team=self.team,
+ name="Gated holdout",
+ filters=[{"properties": [], "rollout_percentage": 20, "variant": "holdout-1"}],
+ created_by=self.user,
+ )
+ self.holdout.filters = [{**self.holdout.filters[0], "variant": f"holdout-{self.holdout.id}"}]
+ self.holdout.save()
+
+ self.flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="experiment-in-holdout",
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "holdout": {"holdout_id": self.holdout.id, "exclusion_percentage": 20},
+ },
+ )
+ self.experiment = Experiment.objects.create(
+ team=self.team, name="Experiment in holdout", feature_flag=self.flag, holdout=self.holdout
+ )
+
+ def _create_policy(self, action_key: str, conditions: dict | None = None, approver_ids: list[int] | None = None):
+ from products.approvals.backend.models import ApprovalPolicy
+
+ return ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key=action_key,
+ conditions=conditions or {},
+ approver_config={"quorum": 1, "users": approver_ids or [self.user.id], "roles": []},
+ allow_self_approve=True,
+ created_by=self.user,
+ )
+
+ def _patch_exclusion(self, percentage: int, **extra):
+ return self.client.patch(
+ f"/api/projects/{self.team.id}/experiment_holdouts/{self.holdout.id}",
+ data={"filters": [{"properties": [], "rollout_percentage": percentage, "variant": "holdout"}], **extra},
+ format="json",
+ )
+
+ def _approve(self, change_request):
+ return self.client.post(
+ f"/api/environments/{self.team.id}/change_requests/{change_request.id}/approve/",
+ {"reason": "ok"},
+ )
+
+ def _change_request(self, action_key: str):
+ from products.approvals.backend.models import ChangeRequest
+
+ return ChangeRequest.objects.get(team=self.team, action_key=action_key)
+
+ def test_gated_update_writes_nothing_and_keeps_its_change_request(self):
+ self._create_policy("experiment_holdout.update")
+
+ response = self._patch_exclusion(40)
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ change_request = self._change_request("experiment_holdout.update")
+ assert response.json()["change_request_id"] == str(change_request.id)
+ assert change_request.intent["current_state"]["exclusion_percentage"] == 20
+ assert change_request.intent["gated_changes"]["exclusion_percentage"] == 40
+ assert [e["flag_key"] for e in change_request.intent["affected_experiments"]] == [self.flag.key]
+
+ self.holdout.refresh_from_db()
+ self.flag.refresh_from_db()
+ assert self.holdout.filters[0]["rollout_percentage"] == 20
+ assert self.flag.filters["holdout"]["exclusion_percentage"] == 20
+
+ def test_approving_an_update_rewrites_the_holdout_and_every_flag(self):
+ self._create_policy("experiment_holdout.update")
+ self._patch_exclusion(40, name="Renamed holdout")
+
+ response = self._approve(self._change_request("experiment_holdout.update"))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["status"] == "applied"
+ self.holdout.refresh_from_db()
+ self.flag.refresh_from_db()
+ assert self.holdout.name == "Renamed holdout"
+ assert self.holdout.filters[0]["rollout_percentage"] == 40
+ assert self.flag.filters["holdout"]["exclusion_percentage"] == 40
+
+ def test_update_is_stale_when_the_holdout_moved_after_the_request(self):
+ self._create_policy("experiment_holdout.update")
+ self._patch_exclusion(40)
+ change_request = self._change_request("experiment_holdout.update")
+
+ self.holdout.filters = [{**self.holdout.filters[0], "rollout_percentage": 35}]
+ self.holdout.save()
+ response = self._approve(change_request)
+
+ self.holdout.refresh_from_db()
+ assert self.holdout.filters[0]["rollout_percentage"] == 35
+ assert response.json().get("status") != "applied"
+
+ def test_update_is_stale_when_an_experiment_joined_the_holdout(self):
+ self._create_policy("experiment_holdout.update")
+ self._patch_exclusion(40)
+ change_request = self._change_request("experiment_holdout.update")
+
+ joined_flag = FeatureFlag.objects.create(team=self.team, key="joined-later", created_by=self.user)
+ Experiment.objects.create(team=self.team, name="Joined later", feature_flag=joined_flag, holdout=self.holdout)
+ response = self._approve(change_request)
+
+ self.holdout.refresh_from_db()
+ assert self.holdout.filters[0]["rollout_percentage"] == 20
+ assert response.json().get("status") != "applied"
+
+ def test_gated_delete_keeps_the_holdout_until_approval(self):
+ self._create_policy("experiment_holdout.delete")
+
+ response = self.client.delete(f"/api/projects/{self.team.id}/experiment_holdouts/{self.holdout.id}")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ change_request = self._change_request("experiment_holdout.delete")
+ assert ExperimentHoldout.objects.filter(id=self.holdout.id).exists()
+ self.flag.refresh_from_db()
+ assert self.flag.filters["holdout"]["exclusion_percentage"] == 20
+
+ approve = self._approve(change_request)
+
+ assert approve.status_code == status.HTTP_200_OK
+ assert not ExperimentHoldout.objects.filter(id=self.holdout.id).exists()
+ self.flag.refresh_from_db()
+ assert self.flag.filters.get("holdout") is None
+
+ @parameterized.expand(
+ [
+ ("update", "experiment_holdout.update", {}),
+ ("delete", "experiment_holdout.delete", {}),
+ (
+ "update_with_flag_field_condition",
+ "experiment_holdout.update",
+ {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 50},
+ ),
+ ]
+ )
+ def test_a_flag_policy_alone_still_gates_a_holdout_change(self, operation, action_key, conditions):
+ flag_policy = self._create_policy("feature_flag.update", conditions=conditions)
+
+ if operation == "delete":
+ response = self.client.delete(f"/api/projects/{self.team.id}/experiment_holdouts/{self.holdout.id}")
+ else:
+ response = self._patch_exclusion(40)
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ change_request = self._change_request(action_key)
+ assert change_request.get_policy() == flag_policy
+ self.flag.refresh_from_db()
+ assert self.flag.filters["holdout"]["exclusion_percentage"] == 20
+
+ def test_a_holdout_policy_takes_precedence_over_a_flag_policy(self):
+ other_approver = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._create_policy("feature_flag.update")
+ holdout_policy = self._create_policy("experiment_holdout.update", approver_ids=[other_approver.id])
+
+ response = self._patch_exclusion(40)
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ change_request = self._change_request("experiment_holdout.update")
+ assert change_request.get_policy() == holdout_policy
+ assert change_request.policy_snapshot["users"] == [other_approver.id]
diff --git a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
index fce958a4cfb0..db5791b8a020 100644
--- a/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
+++ b/posthog/test/repo_invariants/feature_flag_gated_writes_baseline.txt
@@ -1,6 +1,4 @@
# Generated by write_baseline() in test_feature_flag_gated_writes.py. Shrink it, never grow it.
-ee/clickhouse/views/experiment_holdouts.py::ExperimentHoldoutSerializer.update::FeatureFlagSerializer(flag)
-ee/clickhouse/views/experiment_holdouts.py::ExperimentHoldoutViewSet.destroy::FeatureFlagSerializer(flag)
posthog/api/file_system/registrations.py::_feature_flag_pre_delete::feature_flag.active =
posthog/api/file_system/registrations.py::_feature_flag_pre_restore::feature_flag.active =
posthog/management/commands/fix_invalid_flag_property_types.py::Command.handle::FeatureFlag.objects.bulk_update()
diff --git a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
index 84e1325980d1..bd13aaf37cd6 100644
--- a/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
+++ b/posthog/test/repo_invariants/test_feature_flag_gated_writes.py
@@ -23,7 +23,6 @@ GATED_PATH = {
# Shrink-only. Move a write to the facade, then regenerate the baseline and drop its entry here.
ALLOWED_REASONS: dict[str, str] = {
- "ee/clickhouse/views/experiment_holdouts.py": "holdout edit and delete",
"products/feature_flags/backend/api/organization_feature_flag.py": "copy a flag to other projects",
"products/surveys/backend/api/survey.py": "targeting flag writes and the start/stop mirror of active",
"posthog/api/file_system/registrations.py": "file-system trash and restore flip active",
diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.py
index 88a1bb4f3f9c..288ef6d9ddd8 100644
--- a/products/approvals/backend/actions/base.py
+++ b/products/approvals/backend/actions/base.py
@@ -24,6 +24,11 @@ class BaseAction(ABC):
intent_fields: Optional[list[str]] = None
+ # TODO(experiment-approval-policies): temporary. Action keys whose policy gates this action
+ # when it has no policy of its own, so a move to a new key leaves no window without approval.
+ # The fallback policy's conditions name the old action's fields, so they are not evaluated.
+ fallback_policy_action_keys: tuple[str, ...] = ()
+
@classmethod
def _get_instance(cls, view, *args, **kwargs):
if hasattr(view, "context") and "request" in view.context:
diff --git a/products/approvals/backend/actions/experiment_holdouts.py b/products/approvals/backend/actions/experiment_holdouts.py
new file mode 100644
index 000000000000..aa113b15789f
--- /dev/null
+++ b/products/approvals/backend/actions/experiment_holdouts.py
@@ -0,0 +1,230 @@
+from typing import Any, Optional
+
+from products.approvals.backend.actions.base import BaseAction
+from products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed
+
+
+def _exclusion_percentage(filters: Any) -> Optional[float]:
+ """Read the exclusion percentage a holdout's filters carry, or None when they carry none."""
+ if not isinstance(filters, list) or not filters:
+ return None
+ first = filters[0]
+ return first.get("rollout_percentage") if isinstance(first, dict) else None
+
+
+# The fields a holdout edit can write. An approved edit replays all of them, so a change
+# that also renames the holdout does not lose the rename on apply.
+HOLDOUT_WRITABLE_FIELDS = ("name", "description", "filters")
+
+
+def _affected_experiments(holdout) -> list[dict[str, Any]]:
+ """The experiments whose flag this holdout rewrites, as stable display data."""
+ return [
+ {"id": experiment.id, "name": experiment.name, "flag_key": experiment.feature_flag.key}
+ for experiment in holdout.experiment_set.select_related("feature_flag")
+ if experiment.feature_flag is not None
+ ]
+
+
+class ExperimentHoldoutActionBase(BaseAction):
+ """Gate a holdout change as one operation, rather than each flag write it fans out into.
+
+ A holdout edit rewrites the holdout block on every linked experiment's flag. Gating each of
+ those writes would raise ApprovalRequired inside the transaction that keeps the flags and the
+ holdout row consistent, and the rollback would take the pending change request with it. Gating
+ the operation means the only work before the gate is a read, so nothing rolls back and one
+ approval covers every flag the change touches.
+ """
+
+ resource_type = "experiment_holdout"
+ # TODO(experiment-approval-policies): until experiment-owned flags leave `feature_flag.*`
+ # scope, an organization's flag policy still gates the flag writes a holdout change makes.
+ fallback_policy_action_keys = ("feature_flag.update",)
+
+ @classmethod
+ def _holdout(cls, view, *args, **kwargs):
+ instance = cls._get_instance(view, *args, **kwargs)
+ return instance if instance is not None and hasattr(instance, "experiment_set") else None
+
+ @classmethod
+ def _load_holdout(cls, holdout_id, team_id):
+ # Imported from the holdout API module: approvals may depend on `ee`, not on the
+ # experiments product. See tach.toml.
+ from ee.clickhouse.views.experiment_holdouts import ExperimentHoldout
+
+ # nosemgrep: idor-lookup-without-team (team_id comes from the approved change request)
+ return ExperimentHoldout.objects.filter(id=holdout_id, team_id=team_id).first()
+
+ @classmethod
+ def _experiment_ids(cls, intent_data: dict[str, Any]) -> list[int]:
+ return sorted(experiment["id"] for experiment in intent_data.get("affected_experiments", []))
+
+ @classmethod
+ def check_staleness(cls, intent_data: dict[str, Any], context: Optional[dict[str, Any]] = None) -> bool:
+ holdout = context.get("instance") if context else None
+ if holdout is None:
+ return True
+ stored = intent_data.get("current_state", {}).get("exclusion_percentage")
+ if _exclusion_percentage(holdout.filters) != stored:
+ return True
+ # An experiment that joined or left the holdout changes which flags the approved change
+ # rewrites, so the approver saw a different blast radius than the one that would apply.
+ return sorted(e["id"] for e in _affected_experiments(holdout)) != cls._experiment_ids(intent_data)
+
+ @classmethod
+ def prepare_context(cls, change_request, base_context: dict[str, Any]) -> dict[str, Any]:
+ context = dict(base_context)
+ holdout_id = change_request.intent.get("holdout_id") or change_request.resource_id
+ context["instance"] = cls._load_holdout(holdout_id, change_request.team_id)
+ return context
+
+ @classmethod
+ def validate_intent(
+ cls, intent_data: dict[str, Any], context: Optional[dict[str, Any]] = None
+ ) -> tuple[bool, Optional[dict[str, Any]]]:
+ # The endpoint serializer validates a holdout's own fields; the stored intent holds the
+ # operation, not a serializer payload, so there is nothing to re-validate here.
+ return True, None
+
+
+class UpdateExperimentHoldoutAction(ExperimentHoldoutActionBase):
+ """Gate a change to a holdout's exclusion percentage."""
+
+ key = "experiment_holdout.update"
+ version = 1
+ description = "Change the exclusion percentage of an experiment holdout"
+
+ intent_fields = ["exclusion_percentage"]
+
+ @classmethod
+ def detect(cls, request, view, *args, **kwargs) -> bool:
+ holdout = cls._holdout(view, *args, **kwargs)
+ if holdout is None:
+ return False
+ change = args[1] if len(args) >= 2 and isinstance(args[1], dict) else getattr(request, "data", {}) or {}
+ desired = _exclusion_percentage(change.get("filters"))
+ return desired is not None and desired != _exclusion_percentage(holdout.filters)
+
+ @classmethod
+ def extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:
+ holdout = cls._holdout(view, *args, **kwargs)
+ change = args[1] if len(args) >= 2 and isinstance(args[1], dict) else getattr(request, "data", {}) or {}
+ return {
+ "holdout_id": holdout.id,
+ "holdout_name": holdout.name,
+ "current_state": {"exclusion_percentage": _exclusion_percentage(holdout.filters)},
+ "gated_changes": {"exclusion_percentage": _exclusion_percentage(change.get("filters"))},
+ "desired_filters": change.get("filters"),
+ "desired_changes": {field: change[field] for field in HOLDOUT_WRITABLE_FIELDS if field in change},
+ "affected_experiments": _affected_experiments(holdout),
+ }
+
+ @classmethod
+ def apply(cls, validated_intent: dict[str, Any], user, context: Optional[dict[str, Any]] = None) -> Any:
+ from ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializer
+
+ holdout = context.get("instance") if context else None
+ if holdout is None:
+ raise PreconditionFailed("The holdout no longer exists")
+
+ desired = _exclusion_percentage(validated_intent.get("desired_filters"))
+ if desired is None:
+ raise ApplyFailed("The change request carries no exclusion percentage")
+ desired_changes = validated_intent.get("desired_changes") or {"filters": validated_intent["desired_filters"]}
+ current = _exclusion_percentage(holdout.filters)
+ other_fields_applied = all(
+ getattr(holdout, field) == value for field, value in desired_changes.items() if field != "filters"
+ )
+ if current == desired and other_fields_applied:
+ # Idempotency: the holdout already carries the approved change.
+ return holdout
+ if current != validated_intent.get("current_state", {}).get("exclusion_percentage"):
+ raise PreconditionFailed("The holdout changed after this request was created")
+ if sorted(e["id"] for e in _affected_experiments(holdout)) != cls._experiment_ids(validated_intent):
+ raise PreconditionFailed("The experiments in this holdout changed after this request was created")
+
+ serializer = ExperimentHoldoutSerializer(context=cls._serializer_context(holdout, context))
+ try:
+ # update() rewrites every linked flag and the holdout row in one transaction.
+ return serializer.update(holdout, desired_changes)
+ except Exception as e:
+ raise ApplyFailed(f"Holdout update failed: {str(e)}")
+
+ @classmethod
+ def _serializer_context(cls, holdout, context: Optional[dict[str, Any]]) -> dict[str, Any]:
+ team = (context or {}).get("team") or holdout.team
+ serializer_context: dict[str, Any] = {
+ "team_id": team.id,
+ "project_id": team.project_id,
+ "get_team": lambda: team,
+ "get_organization": lambda: team.organization,
+ # Already approved — keep the gate from re-firing on the holdout write.
+ "approval_apply": True,
+ }
+ if context and "request" in context:
+ serializer_context["request"] = context["request"]
+ return serializer_context
+
+ @classmethod
+ def get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:
+ affected = intent_data.get("affected_experiments", [])
+ before = intent_data.get("current_state", {}).get("exclusion_percentage")
+ after = intent_data.get("gated_changes", {}).get("exclusion_percentage")
+ return {
+ "description": (
+ f"Change holdout '{intent_data.get('holdout_name', 'unknown')}' exclusion "
+ f"from {before}% to {after}%, affecting {len(affected)} experiments"
+ ),
+ "before": intent_data.get("current_state", {}),
+ "after": intent_data.get("gated_changes", {}),
+ }
+
+
+class DeleteExperimentHoldoutAction(ExperimentHoldoutActionBase):
+ """Gate deleting a holdout, which stops excluding its users from every linked experiment."""
+
+ key = "experiment_holdout.delete"
+ version = 1
+ description = "Delete an experiment holdout"
+
+ @classmethod
+ def detect(cls, request, view, *args, **kwargs) -> bool:
+ return cls._holdout(view, *args, **kwargs) is not None
+
+ @classmethod
+ def extract_intent(cls, request, view, *args, **kwargs) -> dict[str, Any]:
+ holdout = cls._holdout(view, *args, **kwargs)
+ return {
+ "holdout_id": holdout.id,
+ "holdout_name": holdout.name,
+ "current_state": {"exclusion_percentage": _exclusion_percentage(holdout.filters)},
+ "gated_changes": {"deleted": True},
+ "affected_experiments": _affected_experiments(holdout),
+ }
+
+ @classmethod
+ def apply(cls, validated_intent: dict[str, Any], user, context: Optional[dict[str, Any]] = None) -> Any:
+ from ee.clickhouse.views.experiment_holdouts import delete_holdout_and_clear_flags
+
+ holdout = context.get("instance") if context else None
+ if holdout is None:
+ # Idempotency: an already-applied delete leaves nothing to delete.
+ return None
+
+ try:
+ delete_holdout_and_clear_flags(holdout, user=user, request=(context or {}).get("request"))
+ except Exception as e:
+ raise ApplyFailed(f"Holdout delete failed: {str(e)}")
+ return None
+
+ @classmethod
+ def get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:
+ affected = intent_data.get("affected_experiments", [])
+ return {
+ "description": (
+ f"Delete holdout '{intent_data.get('holdout_name', 'unknown')}', "
+ f"releasing its users into {len(affected)} experiments"
+ ),
+ "before": intent_data.get("current_state", {}),
+ "after": intent_data.get("gated_changes", {}),
+ }
diff --git a/products/approvals/backend/actions/registry.py b/products/approvals/backend/actions/registry.py
index e5612a413df5..98ec50d4a387 100644
--- a/products/approvals/backend/actions/registry.py
+++ b/products/approvals/backend/actions/registry.py
@@ -6,6 +6,10 @@ ACTION_REGISTRY: dict[str, type[BaseAction]] = {}
def register_actions():
+ from products.approvals.backend.actions.experiment_holdouts import (
+ DeleteExperimentHoldoutAction,
+ UpdateExperimentHoldoutAction,
+ )
from products.approvals.backend.actions.feature_flags import (
DisableFeatureFlagAction,
EnableFeatureFlagAction,
@@ -15,6 +19,8 @@ def register_actions():
ACTION_REGISTRY[EnableFeatureFlagAction.key] = EnableFeatureFlagAction
ACTION_REGISTRY[DisableFeatureFlagAction.key] = DisableFeatureFlagAction
ACTION_REGISTRY[UpdateFeatureFlagAction.key] = UpdateFeatureFlagAction
+ ACTION_REGISTRY[UpdateExperimentHoldoutAction.key] = UpdateExperimentHoldoutAction
+ ACTION_REGISTRY[DeleteExperimentHoldoutAction.key] = DeleteExperimentHoldoutAction
def get_action(action_key: str) -> Optional[type[BaseAction]]:
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.py
index 945e0a0272b0..c053768c356a 100644
--- a/products/approvals/backend/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -77,11 +77,7 @@ def _is_approvals_enabled(organization) -> bool:
def _check_policy_for_action(action_class, team, organization) -> Optional[Any]:
"""Check if there's an enabled policy for this action."""
policy_engine = PolicyEngine()
- policy = policy_engine.get_policy(
- action_key=action_class.key,
- team=team,
- organization=organization,
- )
+ policy = policy_engine.get_policy_for_action(action_class, team, organization)
if policy and policy.enabled:
return policy
return None
@@ -290,6 +286,7 @@ def _evaluate_gate(
actor=request.user,
intent=intent_data,
context=context,
+ ignore_conditions=policy.action_key != action_class.key,
)
if decision.result == "ALLOW":
diff --git a/products/approvals/backend/experiment_policy_sync.py b/products/approvals/backend/experiment_policy_sync.py
index 1f6472bc037a..598b5288a501 100644
--- a/products/approvals/backend/experiment_policy_sync.py
+++ b/products/approvals/backend/experiment_policy_sync.py
@@ -11,6 +11,8 @@ Every part of the sync carries the tag `TODO(experiment-approval-policies)`. Rem
- 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
+- `fallback_policy_action_keys` on the experiment holdout actions, the fallback lookup in
+ `PolicyEngine.get_policy_for_action`, and `ignore_conditions` in `PolicyEngine.evaluate`
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
diff --git a/products/approvals/backend/models.py b/products/approvals/backend/models.py
index 200dc0f2812a..9f331d4ba656 100644
--- a/products/approvals/backend/models.py
+++ b/products/approvals/backend/models.py
@@ -88,6 +88,9 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
"""Get the matching approval policy for this change request."""
from products.approvals.backend.policies import PolicyEngine
+ action_class = self.get_action_class()
+ if action_class is not None:
+ return PolicyEngine().get_policy_for_action(action_class, self.team, self.organization)
return PolicyEngine().get_policy(self.action_key, self.team, self.organization)
def can_be_canceled_by(self, user_id: int) -> bool:
diff --git a/products/approvals/backend/policies.py b/products/approvals/backend/policies.py
index 650c1b6a3502..29bf83c07ea3 100644
--- a/products/approvals/backend/policies.py
+++ b/products/approvals/backend/policies.py
@@ -86,6 +86,14 @@ class PolicyEngine:
return policy
+ def get_policy_for_action(self, action_class, team, organization):
+ """Get the active policy for an action, falling back to its fallback action keys in order."""
+ for action_key in (action_class.key, *action_class.fallback_policy_action_keys):
+ policy = self.get_policy(action_key, team, organization)
+ if policy:
+ return policy
+ return None
+
def get_all_matching_policies(self, action_key: str, team, organization, intent: dict):
"""
Get all active policies for an action that match the given intent.
@@ -116,7 +124,7 @@ class PolicyEngine:
return policies
- def evaluate(self, policy, actor, intent: dict, context: dict) -> PolicyDecision:
+ def evaluate(self, policy, actor, intent: dict, context: dict, ignore_conditions: bool = False) -> PolicyDecision:
"""
Evaluate if an action requires approval.
@@ -136,7 +144,7 @@ class PolicyEngine:
policy_snapshot={},
)
- if not self._evaluate_conditions(policy.conditions, intent):
+ if not ignore_conditions and not self._evaluate_conditions(policy.conditions, intent):
return PolicyDecision(
result="ALLOW",
reason="Conditions not matched",
@@ -162,7 +170,7 @@ class PolicyEngine:
"users": approver_config.get("users", []),
"roles": approver_config.get("roles", []),
"allow_self_approve": policy.allow_self_approve,
- "conditions": policy.conditions or {},
+ "conditions": {} if ignore_conditions else (policy.conditions or {}),
"bypass_org_membership_levels": policy.bypass_org_membership_levels,
"bypass_roles": bypass_role_ids,
},
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 95a0bf62ed00..dda92bc6d4ab 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -86,6 +86,9 @@ export const getExperimentHoldoutsListUrl = (projectId: string, params?: Experim
: `/api/projects/${projectId}/experiment_holdouts/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsList = async (
projectId: string,
params?: ExperimentHoldoutsListParams,
@@ -101,6 +104,9 @@ export const getExperimentHoldoutsCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/experiment_holdouts/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsCreate = async (
projectId: string,
experimentHoldoutApi: NonReadonly<ExperimentHoldoutApi>,
@@ -118,6 +124,9 @@ export const getExperimentHoldoutsRetrieveUrl = (projectId: string, id: number)
return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsRetrieve = async (
projectId: string,
id: number,
@@ -133,6 +142,9 @@ export const getExperimentHoldoutsUpdateUrl = (projectId: string, id: number) =>
return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsUpdate = async (
projectId: string,
id: number,
@@ -151,6 +163,9 @@ export const getExperimentHoldoutsPartialUpdateUrl = (projectId: string, id: num
return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsPartialUpdate = async (
projectId: string,
id: number,
@@ -169,6 +184,9 @@ export const getExperimentHoldoutsDestroyUrl = (projectId: string, id: number) =
return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsDestroy = async (
projectId: string,
id: number,
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 6992c23bd95b..ad37ac7d3049 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -9,6 +9,9 @@
*/
import * as zod from 'zod'
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsCreateBodyNameMax = 400
export const experimentHoldoutsCreateBodyDescriptionMax = 400
@@ -285,6 +288,9 @@ export const ExperimentHoldoutsCreateBody = /* @__PURE__ */ zod
})
.describe('A holdout group — a stable slice of users excluded from experiment exposure.')
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsUpdateBodyNameMax = 400
export const experimentHoldoutsUpdateBodyDescriptionMax = 400
@@ -561,6 +567,9 @@ export const ExperimentHoldoutsUpdateBody = /* @__PURE__ */ zod
})
.describe('A holdout group — a stable slice of users excluded from experiment exposure.')
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const experimentHoldoutsPartialUpdateBodyNameMax = 400
export const experimentHoldoutsPartialUpdateBodyDescriptionMax = 400
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 26d094f7dbb8..262251aad056 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -8,6 +8,9 @@
*/
import * as zod from 'zod'
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const ExperimentHoldoutsListParams = () => zod.object({
project_id: zod
.string()
@@ -21,6 +24,9 @@ export const ExperimentHoldoutsListQueryParams = () => zod.object({
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const ExperimentHoldoutsCreateParams = () => zod.object({
project_id: zod
.string()
@@ -305,6 +311,9 @@ export const ExperimentHoldoutsCreateBody = () => zod
})
.describe('A holdout group — a stable slice of users excluded from experiment exposure.')
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const ExperimentHoldoutsRetrieveParams = () => zod.object({
id: zod.number().describe('A unique integer value identifying this experiment holdout.'),
project_id: zod
@@ -314,6 +323,9 @@ export const ExperimentHoldoutsRetrieveParams = () => zod.object({
),
})
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const ExperimentHoldoutsPartialUpdateParams = () => zod.object({
id: zod.number().describe('A unique integer value identifying this experiment holdout.'),
project_id: zod
@@ -600,6 +612,9 @@ export const ExperimentHoldoutsPartialUpdateBody = () => zod
})
.describe('A holdout group — a stable slice of users excluded from experiment exposure.')
+/**
+ * Create, read, update and delete experiment holdouts.
+ */
export const ExperimentHoldoutsDestroyParams = () => zod.object({
id: zod.number().describe('A unique integer value identifying this experiment holdout.'),
project_id: zod
diff --git a/tach.toml b/tach.toml
index 45e8821f19dd..9f167c9cdd90 100644
--- a/tach.toml
+++ b/tach.toml
@@ -45,6 +45,7 @@ depends_on = [
"posthog",
"products.access_control",
"products.actions",
+ "products.approvals",
"products.alerts",
"products.cdp",
"products.conversations",