: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(approvals): require approval for release condition changes (#113916)
Yasen03eb31365156
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.mdindex 941bbc3acfbb..a44eba8c55e5 100644--- a/docs/internal/feature-flags/django-api-endpoints.md+++ b/docs/internal/feature-flags/django-api-endpoints.md@@ -114,7 +114,7 @@ A flag already in the requested state is returned unchanged with no write at all`archive` matches the UI contract by disabling an enabled flag in the same write, because an archived flag must be disabled.`unarchive` leaves the flag disabled; enabling it is a separate call.-It is the one action that cannot return a 409: every gated action declines a change that sets neither `active` nor `filters`, so an `archived`-only write never opens a change request.+It is the one action that cannot return a 409: every gated action declines a change that sets none of `active`, `filters` and `bucketing_identifier`, so an `archived`-only write never opens a change request.### `create_static_cohort_for_flag`diff --git a/frontend/src/scenes/approvals/utils.ts b/frontend/src/scenes/approvals/utils.tsindex 2f178717d39e..9ca958415620 100644--- a/frontend/src/scenes/approvals/utils.ts+++ b/frontend/src/scenes/approvals/utils.ts@@ -28,7 +28,7 @@ export const APPROVAL_ACTIONS: Record<string, ApprovalActionConfig> = {},[ApprovalActionKey.FEATURE_FLAG_UPDATE]: {label: 'Update feature flag',- description: 'update feature flag fields',+ description: "change this feature flag's release conditions or rollout",contextDescriptions: { experiment: 'update this experiment' },},}diff --git a/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx b/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsxindex d5d56b765325..28310657dba0 100644--- a/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx+++ b/frontend/src/scenes/settings/organization/Approvals/ApprovalPolicies.tsx@@ -373,7 +373,9 @@ function ApprovalPolicyModal({ policy, onClose }: { policy?: ApprovalPolicy; onC)}<p className="text-xs text-secondary">- If no conditions are set, all changes to this action type will require approval.+ With no conditions, any change to a flag's rollout needs approval. So does any change to its+ release conditions, unless an experiment, survey, product tour or early access feature+ manages the flag.</p></div>)}diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.pyindex 52cb33210a49..2a563377f979 100644--- a/products/approvals/backend/actions/base.py+++ b/products/approvals/backend/actions/base.py@@ -1,6 +1,8 @@from abc import ABC, abstractmethodfrom typing import Any, Optional+from rest_framework.exceptions import APIException+from posthog.models import Team@@ -117,6 +119,14 @@ class BaseAction(ABC):"""return None+ @classmethod+ def refuse_change_request(cls, request, intent_data: dict[str, Any]) -> Optional[APIException]:+ """Return an error that refuses the write instead of opening a change request, or None.++ Called only when a policy requires approval for the change.+ """+ return None+@classmethoddef check_staleness(cls,diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex 59a7c234b942..fdd0b95a323d 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -1,3 +1,4 @@+import jsonfrom abc import abstractmethodfrom typing import Any, Optionalfrom uuid import UUID@@ -5,13 +6,24 @@ from uuid import UUIDfrom django.db import transactionfrom django.db.models import Model+from rest_framework.exceptions import APIException++from posthog.dataclasses import frozen+from posthog.exceptions import Conflict+from products.approvals.backend.actions.base import BaseActionfrom products.approvals.backend.exceptions import ApplyFailed, PreconditionFailedfrom products.approvals.backend.ownership import OWNER_KIND_UNOWNED, owner_kind_changed-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, flag_version_conflict_message+from products.feature_flags.backend.api.filters_schema import FEATURE_FLAG_OPERATOR_ALIASESfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.ownership import flag_owner_kind+# The property filter keys that flag evaluation reads. The API adds display keys such as+# `cohort_name` on read, and the flag editor sends them back on every save, so any other key is not+# a change to who gets the flag.+MATCHED_PROPERTY_KEYS = frozenset({"key", "value", "type", "operator", "negation", "group_type_index"})+def _to_wire_form(value: Any) -> Any:"""Convert deserialized related objects in a validated change back to primary keys.@@ -219,6 +231,144 @@ def _apply_create(validated_intent: dict[str, Any], context: Optional[dict[str,raise ApplyFailed(f"Serializer save failed: {str(e)}")+_OWNER_KIND_ATTR = "_approval_owner_kind"+++def _cached_owner_kind(flag: FeatureFlag) -> Optional[str]:+ """Return `flag_owner_kind(flag)`, read once per flag instance.++ Detection, the policy conditions check and the gate each read the owner for the same save, and+ each read runs up to six EXISTS queries.+ """+ if not hasattr(flag, _OWNER_KIND_ATTR):+ setattr(flag, _OWNER_KIND_ATTR, flag_owner_kind(flag))+ return getattr(flag, _OWNER_KIND_ATTR)+++def _comparable(value: Any) -> str:+ """Encode a release condition value so that values flag evaluation tells apart compare unequal.++ Python's `==` treats `True`, `1` and `1.0` as equal. The flag matcher compares an exact value by+ its string form, so `true`, `1` and `1.0` match different people and a change between them must+ count.+ """+ return json.dumps(value, sort_keys=True, default=str)+++def _canonical_property(prop: Any) -> Any:+ """Normalize a property filter, so a stored filter and the same filter sent back compare equal.++ Stored filters can predate the serializer's normalization, and the API adds display keys on+ read. Both differences appear on a save that changes nothing about who gets the flag.+ """+ if not isinstance(prop, dict):+ return prop++ canonical = {key: value for key, value in prop.items() if key in MATCHED_PROPERTY_KEYS and value is not None}++ operator = canonical.get("operator")+ if isinstance(operator, str):+ operator = FEATURE_FLAG_OPERATOR_ALIASES.get(operator, operator)+ canonical["operator"] = operator+ # A missing operator means an exact match.+ if operator == "exact":+ del canonical["operator"]++ if canonical.get("negation") is False:+ del canonical["negation"]++ key = canonical.get("key")+ if isinstance(key, int | float) and not isinstance(key, bool):+ canonical["key"] = str(key)++ return canonical+++def _canonical_bucketing(bucketing_identifier: Any) -> str:+ # A null identifier buckets by distinct ID, the same as the default.+ return "device_id" if bucketing_identifier == "device_id" else "distinct_id"+++def _release_conditions(filters: dict[str, Any], bucketing_identifier: Optional[str]) -> list[dict[str, Any]]:+ """Return what decides who gets the flag, as path and value pairs.++ These are the settings the flag editor shows under "Release conditions": "match by", each+ condition set's properties and variant override, and early exit. Rollout percentages are not+ here, because the rollout paths already compare them. `feature_enrollment` is not here either:+ the early access lifecycle sets it, and linking an existing flag to an early access feature sets+ it while the flag is still standalone.++ The flag-level `aggregation_group_type_index` is not compared. The serializer derives it from the+ condition sets, and each set's own value below already carries it.+ """+ results: list[dict[str, Any]] = [+ {"path": "bucketing_identifier", "value": _canonical_bucketing(bucketing_identifier)},+ {"path": "early_exit", "value": filters.get("early_exit") is True},+ ]++ groups = filters.get("groups")+ if not isinstance(groups, list):+ return results++ flag_aggregation = filters.get("aggregation_group_type_index")+ for index, group in enumerate(groups):+ if not isinstance(group, dict):+ continue++ raw_properties = group.get("properties") or []+ # The properties of a condition set must all match, so their order does not matter. A+ # malformed value is compared as stored, so that it cannot fail every save of the flag.+ properties = (+ sorted((_canonical_property(prop) for prop in raw_properties), key=_comparable)+ if isinstance(raw_properties, list)+ else raw_properties+ )+ results.append(+ {+ "path": f"groups[{index}]",+ "value": {+ "properties": properties,+ # The serializer copies the flag-level value into a set that has no key of its own.+ "aggregation_group_type_index": group.get("aggregation_group_type_index", flag_aggregation),+ # An empty override serves the normal variant split, the same as no override.+ "variant": group.get("variant") or None,+ },+ }+ )++ return results+++def _stale_editor_version(request, stored_version: Optional[int]) -> Optional[int]:+ """Return the version a stale editor loaded, or None when the write is not a stale editor save.++ The flag editor sends back every field it loaded, with `version` and `original_flag`. When that+ version is older than the stored one, the save resends release conditions that someone may have+ changed since, and FeatureFlagSerializer.update decides field by field which ones land. A version+ newer than the stored one is not stale here, because a concurrent write can make it current.+ """+ if getattr(request, "strict_version_precondition", False) is True:+ return None+ request_data = getattr(request, "data", None)+ if not isinstance(request_data, dict):+ return None+ version = request_data.get("version", -1)+ original_flag = request_data.get("original_flag")+ if not isinstance(version, int) or isinstance(version, bool) or version == -1:+ return None+ if version >= (stored_version or 0) or not isinstance(original_flag, dict) or not original_flag:+ return None+ return version+++@frozen+class _GatedValues:+ """The values of each gated field before and after a change, keyed by field name."""++ before: dict[str, list[dict[str, Any]]]+ after: dict[str, list[dict[str, Any]]]++class FeatureFlagActionBase(BaseAction):"""Base class for feature flag state change actions."""@@ -456,11 +606,16 @@ class DisableFeatureFlagAction(FeatureFlagActionBase):class UpdateFeatureFlagAction(BaseAction):- """Gate feature flag field-level updates based on policy conditions."""+ """Gate changes to a feature flag's rollout and release conditions.++ A rollout change is gated on every flag. A release condition change is gated on a standalone+ flag only. Product code rewrites the release conditions of a flag its product owns, for example+ when an experiment freezes its exposure, and those writes cannot wait for an approval.+ """key = "feature_flag.update"version = 1- description = "Update feature flag fields"+ description = "Change feature flag release conditions or rollout"resource_type = "feature_flag"endpoint_serializer_class = FeatureFlagSerializer@@ -481,6 +636,12 @@ class UpdateFeatureFlagAction(BaseAction):intent_fields = ["rollout_percentage"]+ # How the description names a release condition path other than a condition set.+ RELEASE_CONDITION_LABELS = {+ "bucketing_identifier": "match by",+ "early_exit": "early exit",+ }+@classmethoddef derive_owner_kind(cls,@@ -544,44 +705,57 @@ class UpdateFeatureFlagAction(BaseAction):return results- @classmethod- def _has_gateable_field_changes(cls, old_filters: dict[str, Any], new_filters: dict[str, Any]) -> bool:- """Check if any gateable field has changed between old and new filters."""- old_values = cls._extract_rollout_percentages(old_filters)- new_values = cls._extract_rollout_percentages(new_filters)+ @staticmethod+ def _changed_paths(+ old_values: list[dict[str, Any]], new_values: list[dict[str, Any]], *, strict: bool = False+ ) -> list[str]:+ """Return the paths whose value changed.+ Rollout values compare with `==`, so a stored `50.0` still equals a submitted `50`. Release+ condition values compare strictly, see `_comparable`.+ """old_by_path = {v["path"]: v["value"] for v in old_values}new_by_path = {v["path"]: v["value"] for v in new_values}-- all_paths = set(old_by_path.keys()) | set(new_by_path.keys())-- for path in all_paths:- old_val = old_by_path.get(path)- new_val = new_by_path.get(path)- if old_val != new_val:- return True-- return False+ paths = [*new_by_path, *(path for path in old_by_path if path not in new_by_path)]+ if strict:+ return [path for path in paths if _comparable(old_by_path.get(path)) != _comparable(new_by_path.get(path))]+ return [path for path in paths if old_by_path.get(path) != new_by_path.get(path)]@classmethod- def _get_triggered_paths(cls, old_filters: dict[str, Any], new_filters: dict[str, Any]) -> list[str]:- """Get list of field paths that have changed."""- old_values = cls._extract_rollout_percentages(old_filters)- new_values = cls._extract_rollout_percentages(new_filters)+ def _gated_values(cls, flag: Optional[FeatureFlag], change: dict[str, Any]) -> _GatedValues:+ """Return the values of each gated field before and after the change.- old_by_path = {v["path"]: v["value"] for v in old_values}- new_by_path = {v["path"]: v["value"] for v in new_values}+ `release_conditions` is present only when the release conditions of a standalone flag+ changed. A create compares its rollout against an empty baseline, so a flag born with any+ rollout trips an "any change / >0" policy, and its release conditions are not compared:+ a new flag serves nobody until it is enabled, and `feature_flag.enable` gates that.+ """+ old_filters = (flag.filters or {}) if flag is not None else {}+ new_filters = change["filters"] if "filters" in change else old_filters- all_paths = set(old_by_path.keys()) | set(new_by_path.keys())- triggered = []+ before = {"rollout_percentage": cls._extract_rollout_percentages(old_filters)}+ after = {"rollout_percentage": cls._extract_rollout_percentages(new_filters)}+ if flag is None:+ return _GatedValues(before=before, after=after)- for path in all_paths:- old_val = old_by_path.get(path)- new_val = new_by_path.get(path)- if old_val != new_val:- triggered.append(path)+ old_release = _release_conditions(old_filters, flag.bucketing_identifier)+ new_release = _release_conditions(new_filters, change.get("bucketing_identifier", flag.bucketing_identifier))+ # The owner lookup runs queries, so it runs only after the cheap comparison found a change.+ if cls._changed_paths(old_release, new_release, strict=True) and _cached_owner_kind(flag) is None:+ before["release_conditions"] = old_release+ after["release_conditions"] = new_release- return triggered+ return _GatedValues(before=before, after=after)++ @classmethod+ def _triggered_paths(cls, values: _GatedValues) -> list[str]:+ return [+ path+ for field in values.after+ for path in cls._changed_paths(+ values.before[field], values.after[field], strict=field == "release_conditions"+ )+ ]@classmethoddef detect(cls, request, view, *args, **kwargs) -> bool:@@ -592,22 +766,7 @@ class UpdateFeatureFlagAction(BaseAction):change = _get_validated_change(request, view, *args, **kwargs)- 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 = change.get("filters")- if not new_filters:- return False-- # 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):+ if not cls._triggered_paths(cls._gated_values(flag, change)):return Falseteam = cls._get_team(view)@@ -621,13 +780,7 @@ class UpdateFeatureFlagAction(BaseAction):flag = _get_flag_instance(view, *args, **kwargs)change = _get_validated_change(request, view, *args, **kwargs)- 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)-- triggered_paths = cls._get_triggered_paths(old_filters, new_filters)+ values = cls._gated_values(flag, change)# A caller exempt from the serializer's opportunistic filter cleanup stays exempt when# the approved change replays, the way the lifecycle base records it. Without this an@@ -637,13 +790,9 @@ class UpdateFeatureFlagAction(BaseAction):return {"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,- },- "gated_changes": {- "rollout_percentage": new_rollout_percentages,- },- "triggered_paths": triggered_paths,+ "current_state": values.before,+ "gated_changes": values.after,+ "triggered_paths": cls._triggered_paths(values),"full_request_data": dict(change),"preconditions": {"version": flag.version if flag is not None else None,@@ -652,6 +801,22 @@ class UpdateFeatureFlagAction(BaseAction):"skip_opportunistic_filter_cleanup": skip_cleanup,}+ @classmethod+ def refuse_change_request(cls, request, intent_data: dict[str, Any]) -> Optional[APIException]:+ """Refuse a stale editor's save that would change release conditions.++ The save may resend conditions that someone changed since the editor loaded the flag, and an+ approved change request replays the payload without the serializer's stale-write checks, so+ approving it would revert the newer edit. The editor reloads and saves again instead.+ """+ if "release_conditions" not in intent_data.get("gated_changes", {}):+ return None+ stored_version = intent_data.get("preconditions", {}).get("version")+ caller_version = _stale_editor_version(request, stored_version)+ if caller_version is None:+ return None+ return Conflict(flag_version_conflict_message(caller_version, stored_version or 0))+@classmethoddef validate_intent(cls,@@ -729,6 +894,18 @@ class UpdateFeatureFlagAction(BaseAction):return flag+ @classmethod+ def _release_condition_change(cls, path: str, before_paths: set[str], after_paths: set[str]) -> str:+ if not path.startswith("groups["):+ return cls.RELEASE_CONDITION_LABELS.get(path, path)++ label = f"condition set {int(path[len('groups[') : -1]) + 1}"+ if path not in before_paths:+ return f"{label} added"+ if path not in after_paths:+ return f"{label} removed"+ return label+@classmethoddef get_display_data(cls, intent_data: dict[str, Any]) -> dict[str, Any]:"""Generate human-readable diff showing before/after for gated fields."""@@ -737,22 +914,29 @@ class UpdateFeatureFlagAction(BaseAction):gated_changes = intent_data.get("gated_changes", {})triggered_paths = intent_data.get("triggered_paths", [])- changes_description = []- before_values = current_state.get("rollout_percentage", [])- after_values = gated_changes.get("rollout_percentage", [])-- before_by_path = {v["path"]: v["value"] for v in before_values}- after_by_path = {v["path"]: v["value"] for v in after_values}+ rollout_before = {v["path"]: v["value"] for v in current_state.get("rollout_percentage", [])}+ rollout_after = {v["path"]: v["value"] for v in gated_changes.get("rollout_percentage", [])}+ release_before = {v["path"] for v in current_state.get("release_conditions", [])}+ release_after = {v["path"] for v in gated_changes.get("release_conditions", [])}+ rollout_display_name = cls.GATEABLE_FIELDS["rollout_percentage"]["display_name"]+ release_changes: list[str] = []+ rollout_changes: list[str] = []for path in triggered_paths:- before_val = before_by_path.get(path, "N/A")- after_val = after_by_path.get(path, "N/A")- field_display_name = cls.GATEABLE_FIELDS["rollout_percentage"]["display_name"]- changes_description.append(f"{field_display_name} at {path}: {before_val}% -> {after_val}%")-- description = (- f"Update {cls.GATEABLE_FIELDS['rollout_percentage']['display_name']} for feature flag '{flag_key}'"- )+ if path in release_before or path in release_after:+ release_changes.append(cls._release_condition_change(path, release_before, release_after))+ else:+ before_val = rollout_before.get(path, "N/A")+ after_val = rollout_after.get(path, "N/A")+ rollout_changes.append(f"{rollout_display_name} at {path}: {before_val}% -> {after_val}%")++ changed_fields = [+ name+ for name, changes in (("release conditions", release_changes), (rollout_display_name, rollout_changes))+ if changes+ ] or [rollout_display_name]+ description = f"Update {' and '.join(changed_fields)} for feature flag '{flag_key}'"+ changes_description = [*release_changes, *rollout_changes]if changes_description:description = f"{description}: {'; '.join(changes_description)}"diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.pyindex 7731b34e760e..4224582be765 100644--- a/products/approvals/backend/decorators.py+++ b/products/approvals/backend/decorators.py@@ -101,6 +101,21 @@ def _check_policy_for_action(action_class, team, organization) -> Optional[Any]:return None+def _policy_conditions_match(action_class, policy, request, view_or_serializer, args: tuple, kwargs: dict) -> bool:+ """Whether the policy's conditions match this change, so the action needs approval at all.++ A change that more than one policy-backed action detects is rejected as a policy conflict. An+ action whose policy conditions do not match needs no approval, so it must not count toward that+ conflict. For example, enabling a flag and editing a property under a rollout-only update policy+ needs the enable approval only. A policy found through a fallback action key is evaluated with+ its conditions ignored, so it always matches.+ """+ if not policy.conditions or policy.action_key != action_class.key:+ return True+ intent = action_class.extract_intent(request, view_or_serializer, *args, **kwargs)+ return PolicyEngine().conditions_match(policy.conditions, intent)++def _check_for_duplicate(action_class, team, resource_id: Optional[str], intent_data: dict[str, Any]) -> Optional[ChangeRequest]:@@ -324,6 +339,10 @@ def _evaluate_gate(logger.warning("Policy denied request", extra={"action": action_class.key, "reason": decision.reason})return GateResult(action="deny", error_message=decision.reason)+ refusal = action_class.refuse_change_request(request, intent_data)+ if refusal is not None:+ raise refusal+# Step 5: REQUIRE_APPROVAL - check for duplicates and create change requestresource_id = _extract_resource_id(request, args, kwargs)@@ -553,8 +572,8 @@ def approval_gate(action_refs: Union[type, str, list]):if not _is_approvals_enabled(organization):return method(self, *args, **kwargs)- # 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+ # Collect every action that matches this change AND has an enabled policy whose conditions+ # match it — 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@@ -565,7 +584,7 @@ def approval_gate(action_refs: Union[type, str, list]):try:if action_class.detect(request, self, *args, **kwargs):policy = _check_policy_for_action(action_class, team, organization)- if policy:+ if policy and _policy_conditions_match(action_class, policy, request, self, args, kwargs):matches.append((action_class, policy))except Exception as e:logger.error(diff --git a/products/approvals/backend/policies.py b/products/approvals/backend/policies.pyindex 29bf83c07ea3..fc9bb007bab1 100644--- a/products/approvals/backend/policies.py+++ b/products/approvals/backend/policies.py@@ -176,6 +176,9 @@ class PolicyEngine:},)+ def conditions_match(self, conditions: dict[str, Any], intent: dict) -> bool:+ return self._evaluate_conditions(conditions, intent)+def _evaluate_conditions(self, conditions: dict[str, Any], intent: dict) -> bool:"""Evaluate policy conditions against the intent.@@ -221,6 +224,9 @@ class PolicyEngine:if not compare_fn:return True+ if not self._field_changed(field, intent):+ return False+gated_changes = intent.get("gated_changes", {})field_values = gated_changes.get(field, [])@@ -254,18 +260,13 @@ class PolicyEngine:if not compare_fn:return True- current_state = intent.get("current_state", {})- gated_changes = intent.get("gated_changes", {})-- before_values = current_state.get(field, [])- after_values = gated_changes.get(field, [])-- before_by_path = {v["path"]: v["value"] for v in before_values}- after_by_path = {v["path"]: v["value"] for v in after_values}+ if not self._field_changed(field, intent):+ return False- all_paths = set(before_by_path.keys()) | set(after_by_path.keys())+ before_by_path = self._values_by_path(intent, "current_state", field)+ after_by_path = self._values_by_path(intent, "gated_changes", field)- for path in all_paths:+ for path in before_by_path.keys() | after_by_path.keys():before_val = before_by_path.get(path)after_val = after_by_path.get(path)@@ -291,24 +292,30 @@ class PolicyEngine:if not field:return True- current_state = intent.get("current_state", {})- gated_changes = intent.get("gated_changes", {})-- before_values = current_state.get(field, [])- after_values = gated_changes.get(field, [])+ before_by_path = self._values_by_path(intent, "current_state", field)+ after_by_path = self._values_by_path(intent, "gated_changes", field)+ return any(+ before_by_path.get(path) != after_by_path.get(path) for path in before_by_path.keys() | after_by_path.keys()+ )- before_by_path = {v["path"]: v["value"] for v in before_values}- after_by_path = {v["path"]: v["value"] for v in after_values}+ def _field_changed(self, field: str, intent: dict) -> bool:+ """Whether the change touches the field that a condition names.- all_paths = set(before_by_path.keys()) | set(after_by_path.keys())+ `before_after` compares every value of the field, changed or not. Without this check, a+ "rollout > 50" policy would gate a release condition edit on a flag that some condition set+ already rolls out to more than 50%.+ """+ before_values = intent.get("current_state", {}).get(field)+ after_values = intent.get("gated_changes", {}).get(field)+ if not isinstance(before_values, list) or not isinstance(after_values, list):+ # Not the path and value shape this check reads, so the condition decides alone.+ return True- for path in all_paths:- before_val = before_by_path.get(path)- after_val = after_by_path.get(path)- if before_val != after_val:- return True+ return self._evaluate_any_change({"field": field}, intent)- return False+ @staticmethod+ def _values_by_path(intent: dict, side: str, field: str) -> dict[str, Any]:+ return {v["path"]: v["value"] for v in intent.get(side, {}).get(field, [])}def _has_bypass(self, actor, policy, bypass_role_ids: list[str], context: dict) -> bool:"""Check if user can bypass this policy based on org membership level or RBAC role."""diff --git a/products/approvals/backend/scheduled_changes.py b/products/approvals/backend/scheduled_changes.pyindex ff0d3ee63819..1fa9dfee885e 100644--- a/products/approvals/backend/scheduled_changes.py+++ b/products/approvals/backend/scheduled_changes.py@@ -115,7 +115,9 @@ def _detect_gated_action(flag: "FeatureFlag", payload: dict[str, Any], user) ->try:if action_class.detect(http_request, serializer, *gate_args):policy = decorators._check_policy_for_action(action_class, team, organization)- if policy:+ if policy and decorators._policy_conditions_match(+ action_class, policy, http_request, serializer, gate_args, {}+ ):return _GatedAction(action_class, policy, serializer, http_request, gate_args)except Exception as e:# Unknown means deny. A schedule saved here fires later with no approver watching, sodiff --git a/products/approvals/backend/tests/test_owner_operation_decision_table.py b/products/approvals/backend/tests/test_owner_operation_decision_table.pyindex ddd1e7126596..61c9f08b6387 100644--- a/products/approvals/backend/tests/test_owner_operation_decision_table.py+++ b/products/approvals/backend/tests/test_owner_operation_decision_table.py@@ -7,8 +7,9 @@ checked rather than described.Phase 3 proved every entry point behaves alike, so this varies owner and operation over oneentry point (the flag API) instead of multiplying by entry point.-Read DECISION_TABLE as the current, pre-narrowing state: `feature_flag.*` covers every owner.-Narrowing a family to an owner changes cells here, and that diff is the coverage change.+Read DECISION_TABLE as the current, pre-narrowing state: `feature_flag.*` covers every owner,+except that a release condition change is gated on an unowned flag only. Narrowing a family to an+owner changes cells here, and that diff is the coverage change."""from typing import Any, Optional@@ -48,7 +49,9 @@ OWNERS = ("session_recording_reference",)-OPERATIONS = ("create_active", "update_gated_field", "enable", "disable", "delete")+OPERATIONS = ("create_active", "update_gated_field", "update_release_condition", "enable", "disable", "delete")++RELEASE_CONDITION = {"key": "email", "type": "person", "operator": "icontains", "value": "@example.com"}def _row(*cells: Optional[str]) -> dict[str, Optional[str]]:@@ -84,15 +87,15 @@ NA = NOT_APPLICABLE# Narrowing a family to an owner changes cells here, and that diff is the coverage change.# fmt: offDECISION_TABLE: dict[str, dict[str, Optional[str]]] = {- # create update enable disable delete- "standalone": _row(ENABLE, UPDATE, ENABLE, DISABLE, UNGATED),- "experiment": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),- "survey_owned": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),- "survey_linked": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),- "tour_owned": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),- "tour_linked": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),- "early_access": _row(NA, UPDATE, ENABLE, DISABLE, REJECTED),- "session_recording_reference": _row(NA, UPDATE, ENABLE, DISABLE, REJECTED),+ # create update release enable disable delete+ "standalone": _row(ENABLE, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "experiment": _row(NA, UPDATE, UNGATED, ENABLE, DISABLE, UNGATED),+ "survey_owned": _row(NA, UPDATE, UNGATED, ENABLE, DISABLE, UNGATED),+ "survey_linked": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "tour_owned": _row(NA, UPDATE, UNGATED, ENABLE, DISABLE, UNGATED),+ "tour_linked": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, UNGATED),+ "early_access": _row(NA, UPDATE, UNGATED, ENABLE, DISABLE, REJECTED),+ "session_recording_reference": _row(NA, UPDATE, UPDATE, ENABLE, DISABLE, REJECTED),}# fmt: on@@ -154,6 +157,9 @@ class TestOwnerOperationDecisionTable(APIBaseTest):if operation == "update_gated_field":payload: dict[str, Any] = {"filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}}self.client.patch(f"{base}{flag.id}/", payload, format="json")+ elif operation == "update_release_condition":+ payload = {"filters": {"groups": [{"properties": [RELEASE_CONDITION], "rollout_percentage": 50}]}}+ self.client.patch(f"{base}{flag.id}/", payload, format="json")elif operation == "enable":self.client.patch(f"{base}{flag.id}/", {"active": True}, format="json")elif operation == "disable":@@ -165,6 +171,12 @@ class TestOwnerOperationDecisionTable(APIBaseTest):self, operation: str, flag: Optional[FeatureFlag], expected: Optional[str]) -> None:"""An ungated cell must prove the write landed, or "no change request" means nothing."""+ if operation == "update_release_condition":+ assert flag is not None+ properties = FeatureFlag.objects.get(id=flag.id).filters["groups"][0]["properties"]+ landed = [prop["key"] for prop in properties] == [RELEASE_CONDITION["key"]]+ assert landed is (expected is UNGATED), f"release edit landed={landed} but the table says {expected}"+ returnif operation != "delete":returnassert flag is not Nonediff --git a/products/approvals/backend/tests/test_scheduled_change_gating.py b/products/approvals/backend/tests/test_scheduled_change_gating.pyindex d8b8eb44feb1..557b7ade0474 100644--- a/products/approvals/backend/tests/test_scheduled_change_gating.py+++ b/products/approvals/backend/tests/test_scheduled_change_gating.py@@ -6,6 +6,8 @@ from unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterized+from posthog.models import Userfrom posthog.tasks.process_scheduled_changes import process_scheduled_changes@@ -14,6 +16,8 @@ from products.approvals.backend.services import ChangeRequestServicefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange+EMAIL_CONDITION = {"key": "email", "type": "person", "operator": "icontains", "value": "@example.com"}+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)class TestScheduledChangeGating(APIBaseTest):@@ -178,16 +182,35 @@ class TestScheduledChangeGating(APIBaseTest):# 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})+ @parameterized.expand(+ [+ (+ "rollout",+ {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0},+ {"properties": [], "rollout_percentage": 90},+ True,+ ),+ ("properties_only", {}, {"properties": [EMAIL_CONDITION]}, True),+ (+ "properties_only_under_a_rollout_policy",+ {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 0},+ {"properties": [EMAIL_CONDITION]},+ False,+ ),+ ]+ )+ def test_scheduled_added_condition_under_update_policy(+ self,+ _mock_enabled,+ _name: str,+ conditions: dict[str, Any],+ condition_fields: dict[str, Any],+ expected_gated: bool,+ ):+ self._update_policy(conditions)flag = self._disabled_flag(key="rollout-flag")- new_condition: dict[str, Any] = {- "variant": None,- "properties": [],- "rollout_percentage": 90,- "aggregation_group_type_index": None,- }+ new_condition: dict[str, Any] = {"variant": None, "aggregation_group_type_index": None, **condition_fields}scheduled = self._schedule(flag,{@@ -197,15 +220,22 @@ class TestScheduledChangeGating(APIBaseTest):timezone.now() - timedelta(seconds=30),)+ if not expected_gated:+ # The policy allows it when scheduled, so it must not be skipped when it fires.+ assert scheduled.change_request is None+ process_scheduled_changes()+ flag.refresh_from_db()+ assert len(flag.filters.get("groups", [])) == 2+ return+assert scheduled.change_request is not Noneassert scheduled.change_request.state == ChangeRequestState.PENDINGprocess_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+ # The new condition must not have been appended (change was gated, not applied).+ assert len(flag.filters.get("groups", [])) == 1scheduled.change_request.refresh_from_db()assert scheduled.change_request.state == ChangeRequestState.EXPIREDdiff --git a/products/approvals/backend/tests/test_update_feature_flag_action.py b/products/approvals/backend/tests/test_update_feature_flag_action.pyindex 2d572b6119cc..fe60786485cc 100644--- a/products/approvals/backend/tests/test_update_feature_flag_action.py+++ b/products/approvals/backend/tests/test_update_feature_flag_action.py@@ -19,12 +19,32 @@ from products.approvals.backend.actions.feature_flags import (from products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.approvals.backend.policies import PolicyEnginefrom products.approvals.backend.services import ChangeRequestService+from products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlagSINGLE_DICT_PATHS = {"holdout"}+GROUP_KEY_FILTER: dict[str, Any] = {+ "key": "$group_key",+ "type": "group",+ "operator": "exact",+ "value": ["acme"],+ "group_type_index": 0,+}+PROVIDER_FILTER: dict[str, Any] = {+ "key": "provider_id",+ "type": "group",+ "operator": "exact",+ "value": ["provider-1"],+ "group_type_index": 0,+}+++def _condition_set(*properties: dict[str, Any], **fields: Any) -> dict[str, Any]:+ return {"properties": list(properties), "rollout_percentage": 100, **fields}+def _build_filters_for_path(path_spec: tuple, rollout_percentage: int) -> dict[str, Any]:"""Build a filters dict with the rollout_percentage at the specified path."""@@ -111,6 +131,257 @@ class TestUpdateFeatureFlagActionDetect(APIBaseTest):assert result is False+ @parameterized.expand(+ [+ (+ "property_value_edited",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set({**GROUP_KEY_FILTER, "value": ["acme-2"]})],+ {},+ {},+ True,+ ),+ (+ "operator_edited",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set({**GROUP_KEY_FILTER, "operator": "is_not"})],+ {},+ {},+ True,+ ),+ (+ "property_added",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER, PROVIDER_FILTER)],+ {},+ {},+ True,+ ),+ (+ "property_removed",+ [_condition_set(GROUP_KEY_FILTER, PROVIDER_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {},+ True,+ ),+ (+ "negation_enabled",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set({**GROUP_KEY_FILTER, "negation": True})],+ {},+ {},+ True,+ ),+ (+ "property_type_changed",+ [_condition_set(PROVIDER_FILTER)],+ [_condition_set({**PROVIDER_FILTER, "type": "person"})],+ {},+ {},+ True,+ ),+ (+ "group_type_index_changed",+ [_condition_set(PROVIDER_FILTER)],+ [_condition_set({**PROVIDER_FILTER, "group_type_index": 1})],+ {},+ {},+ True,+ ),+ (+ "condition_set_removed",+ [_condition_set(GROUP_KEY_FILTER), _condition_set(PROVIDER_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {},+ True,+ ),+ (+ "condition_set_added",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER), _condition_set(PROVIDER_FILTER)],+ {},+ {},+ True,+ ),+ (+ "condition_sets_reordered",+ [_condition_set(GROUP_KEY_FILTER), _condition_set(PROVIDER_FILTER)],+ [_condition_set(PROVIDER_FILTER), _condition_set(GROUP_KEY_FILTER)],+ {},+ {},+ True,+ ),+ (+ "match_by_group_type_changed",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER, aggregation_group_type_index=1)],+ {},+ {},+ True,+ ),+ (+ "match_by_device",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {"bucketing_identifier": "device_id"},+ True,+ ),+ (+ "variant_override_set",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER, variant="test")],+ {},+ {},+ True,+ ),+ (+ "early_exit_enabled",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {"early_exit": True},+ {},+ True,+ ),+ (+ "feature_enrollment_enabled",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {"feature_enrollment": True},+ {},+ False,+ ),+ (+ "properties_reordered",+ [_condition_set(GROUP_KEY_FILTER, PROVIDER_FILTER)],+ [_condition_set(PROVIDER_FILTER, GROUP_KEY_FILTER)],+ {},+ {},+ False,+ ),+ (+ "display_only_keys_added",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set({**GROUP_KEY_FILTER, "label": "Acme", "group_key_names": {"acme": "Acme"}})],+ {},+ {},+ False,+ ),+ (+ "null_operator_is_exact",+ [_condition_set({**GROUP_KEY_FILTER, "operator": None})],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {},+ False,+ ),+ (+ "operator_alias",+ [_condition_set({**PROVIDER_FILTER, "operator": "min"})],+ [_condition_set({**PROVIDER_FILTER, "operator": "gte"})],+ {},+ {},+ False,+ ),+ (+ "negation_false_is_absent",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set({**GROUP_KEY_FILTER, "negation": False})],+ {},+ {},+ False,+ ),+ (+ "numeric_key_is_string",+ [_condition_set({**PROVIDER_FILTER, "key": 123})],+ [_condition_set({**PROVIDER_FILTER, "key": "123"})],+ {},+ {},+ False,+ ),+ (+ "set_inherits_flag_match_by",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER, aggregation_group_type_index=0)],+ {},+ {},+ False,+ ),+ (+ "empty_variant_is_none",+ [_condition_set(GROUP_KEY_FILTER, variant="")],+ [_condition_set(GROUP_KEY_FILTER, variant=None)],+ {},+ {},+ False,+ ),+ (+ "description_edited",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER, description="EU accounts")],+ {},+ {},+ False,+ ),+ (+ "boolean_value_replaces_number",+ [_condition_set({**PROVIDER_FILTER, "value": 1})],+ [_condition_set({**PROVIDER_FILTER, "value": True})],+ {},+ {},+ True,+ ),+ (+ "whole_float_value_replaces_integer",+ [_condition_set({**PROVIDER_FILTER, "value": [1.0]})],+ [_condition_set({**PROVIDER_FILTER, "value": [1]})],+ {},+ {},+ True,+ ),+ (+ "undeclared_property_key",+ [_condition_set({**GROUP_KEY_FILTER, "operator_type": "string"})],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {},+ False,+ ),+ (+ "malformed_stored_properties",+ [{"properties": 5, "rollout_percentage": 100}],+ [{"properties": 5, "rollout_percentage": 100}],+ {},+ {},+ False,+ ),+ (+ "null_bucketing_is_distinct_id",+ [_condition_set(GROUP_KEY_FILTER)],+ [_condition_set(GROUP_KEY_FILTER)],+ {},+ {"bucketing_identifier": None},+ False,+ ),+ ]+ )+ def test_detect_release_condition_changes(+ self,+ _name: str,+ old_groups: list[dict[str, Any]],+ new_groups: list[dict[str, Any]],+ new_filters_extra: dict[str, Any],+ new_flag_fields: dict[str, Any],+ expected: bool,+ ):+ flag = self._create_flag({"aggregation_group_type_index": 0, "groups": old_groups})+ new_filters = {"aggregation_group_type_index": 0, "groups": new_groups, **new_filters_extra}+ request = self._mock_request("PATCH", {"filters": new_filters, **new_flag_fields})++ assert UpdateFeatureFlagAction.detect(request, self._mock_view(flag)) is expected+class TestDetectFromValidatedData(APIBaseTest):"""The gate decorates FeatureFlagSerializer.update(self, instance, validated_data), so the@@ -306,20 +577,59 @@ class TestRelatedFieldsInIntent(APIBaseTest):class TestUpdateFeatureFlagActionDisplayData(APIBaseTest):- def test_get_display_data_generates_human_readable_diff(self):+ @parameterized.expand(+ [+ (+ "rollout",+ {"rollout_percentage": [{"path": "groups[0].rollout_percentage", "value": 50}]},+ {"rollout_percentage": [{"path": "groups[0].rollout_percentage", "value": 80}]},+ ["groups[0].rollout_percentage"],+ "Update rollout percentage for feature flag 'test-flag': "+ "rollout percentage at groups[0].rollout_percentage: 50% -> 80%",+ ),+ (+ "release_conditions",+ {+ "rollout_percentage": [],+ "release_conditions": [+ {"path": "bucketing_identifier", "value": "distinct_id"},+ {"path": "groups[0]", "value": {"properties": [GROUP_KEY_FILTER]}},+ ],+ },+ {+ "rollout_percentage": [],+ "release_conditions": [+ {"path": "bucketing_identifier", "value": "device_id"},+ {"path": "groups[0]", "value": {"properties": []}},+ {"path": "groups[1]", "value": {"properties": [PROVIDER_FILTER]}},+ ],+ },+ ["bucketing_identifier", "groups[0]", "groups[1]"],+ "Update release conditions for feature flag 'test-flag': "+ "match by; condition set 1; condition set 2 added",+ ),+ ]+ )+ def test_get_display_data_names_what_changed(+ self,+ _name: str,+ current_state: dict[str, Any],+ gated_changes: dict[str, Any],+ triggered_paths: list[str],+ expected_description: str,+ ):intent_data = {"flag_key": "test-flag",- "current_state": {"rollout_percentage": [{"path": "groups[0]", "value": 50}]},- "gated_changes": {"rollout_percentage": [{"path": "groups[0]", "value": 80}]},- "triggered_paths": ["groups[0].rollout_percentage"],+ "current_state": current_state,+ "gated_changes": gated_changes,+ "triggered_paths": triggered_paths,}display_data = UpdateFeatureFlagAction.get_display_data(intent_data)- assert "description" in display_data- assert "before" in display_data- assert "after" in display_data- assert "rollout percentage" in display_data["description"].lower()+ assert display_data["description"] == expected_description+ assert display_data["before"] == current_state+ assert display_data["after"] == gated_changesclass TestCheckStaleness(APIBaseTest):@@ -516,7 +826,7 @@ class TestPolicyConditionEvaluation(APIBaseTest):policy_engine = PolicyEngine()intent = {- "current_state": {"rollout_percentage": [{"path": "groups[0]", "value": 30}]},+ "current_state": {"rollout_percentage": [{"path": "groups[0]", "value": 10}]},"gated_changes": {"rollout_percentage": [{"path": "groups[0]", "value": after_value}]},}@@ -643,6 +953,268 @@ class TestMultiPolicyConflictDetection(APIBaseTest):assert "conflicting_policies" in data+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+class TestReleaseConditionGating(APIBaseTest):+ EMAIL_FILTER: dict[str, Any] = {"key": "email", "type": "person", "operator": "exact", "value": ["[email protected]"]}++ def _create_policies(self, policies: list[tuple[str, dict[str, Any]]]) -> None:+ for action_key, conditions in policies:+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key=action_key,+ conditions=conditions,+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ def _change_request_keys(self) -> list[str]:+ return sorted(ChangeRequest.objects.filter(team=self.team).values_list("action_key", flat=True))++ @parameterized.expand(+ [+ ("no_conditions_gates_it", [("feature_flag.update", {})], False, 409, ["feature_flag.update"]),+ (+ "rollout_change_condition_ignores_it",+ [("feature_flag.update", {"type": "any_change", "field": "rollout_percentage"})],+ False,+ 200,+ [],+ ),+ (+ "rollout_threshold_condition_ignores_it",+ [+ (+ "feature_flag.update",+ {"type": "before_after", "field": "rollout_percentage", "operator": ">", "value": 50},+ )+ ],+ False,+ 200,+ [],+ ),+ (+ "rollout_change_amount_condition_ignores_it",+ [+ (+ "feature_flag.update",+ {"type": "change_amount", "field": "rollout_percentage", "operator": "<", "value": 10},+ )+ ],+ False,+ 200,+ [],+ ),+ (+ "enabling_under_a_rollout_only_policy_needs_the_enable_approval_only",+ [+ ("feature_flag.enable", {}),+ ("feature_flag.update", {"type": "any_change", "field": "rollout_percentage"}),+ ],+ True,+ 409,+ ["feature_flag.enable"],+ ),+ (+ "enabling_in_the_same_save_conflicts",+ [("feature_flag.enable", {}), ("feature_flag.update", {})],+ True,+ 400,+ [],+ ),+ ]+ )+ def test_targeting_only_edit(+ self,+ _mock_enabled: MagicMock,+ _name: str,+ policies: list[tuple[str, dict[str, Any]]],+ also_enable: bool,+ expected_status: int,+ expected_change_requests: list[str],+ ):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="targeted-flag",+ active=not also_enable,+ filters={"groups": [{"properties": [self.EMAIL_FILTER], "rollout_percentage": 100}]},+ created_by=self.user,+ )+ self._create_policies(policies)+ edited_filter = {**self.EMAIL_FILTER, "value": ["[email protected]"]}+ body: dict[str, Any] = {"filters": {"groups": [{"properties": [edited_filter], "rollout_percentage": 100}]}}+ if also_enable:+ body["active"] = True++ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", body, format="json")++ assert response.status_code == expected_status, response.json()+ assert self._change_request_keys() == expected_change_requests+ flag.refresh_from_db()+ landed = flag.filters["groups"][0]["properties"][0]["value"] == ["[email protected]"]+ assert landed is (expected_status == 200)++ @parameterized.expand(+ [+ ("unchanged", False, 200, []),+ ("enabled_with_unchanged_targeting", True, 409, ["feature_flag.enable"]),+ ]+ )+ def test_saving_the_loaded_flag_back_does_not_gate_its_release_conditions(+ self,+ _mock_enabled: MagicMock,+ _name: str,+ enable: bool,+ expected_status: int,+ expected_change_requests: list[str],+ ):+ cohort = Cohort.objects.create(+ team=self.team,+ name="Paying customers",+ groups=[{"properties": [{"key": "plan", "value": "paid", "type": "person"}]}],+ )+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="loaded-flag",+ active=not enable,+ # Shapes an older write leaves behind: no per-set match by, an operator alias, and no operator.+ filters={+ "groups": [+ {"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}], "rollout_percentage": 100},+ {+ "properties": [+ {"key": "age", "type": "person", "operator": "min", "value": 18},+ {"key": "country", "type": "person", "value": ["US"]},+ ],+ "rollout_percentage": 30,+ },+ ]+ },+ created_by=self.user,+ )+ self._create_policies([("feature_flag.enable", {}), ("feature_flag.update", {})])+ url = f"/api/projects/{self.team.id}/feature_flags/{flag.id}/"+ loaded = self.client.get(url).json()+ if enable:+ loaded["active"] = True++ response = self.client.patch(url, loaded, format="json")++ assert response.status_code == expected_status, response.json()+ assert self._change_request_keys() == expected_change_requests++ def test_linking_a_standalone_flag_to_an_early_access_feature_is_not_gated(self, _mock_enabled: MagicMock):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="beta-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},+ created_by=self.user,+ )+ self._create_policies([("feature_flag.update", {})])++ response = self.client.post(+ f"/api/projects/{self.team.id}/early_access_feature/",+ {"name": "Beta", "stage": "beta", "feature_flag_id": flag.id},+ format="json",+ )++ assert response.status_code == 201, response.json()+ assert self._change_request_keys() == []++ @parameterized.expand(+ [+ ("someone_else_changed_targeting", 1, "a", "a", "b", {}, (409, "conflict"), [], "b"),+ ("caller_changed_targeting", 1, "a", "c", "a", {}, (409, "conflict"), [], "a"),+ ("both_changed_targeting", 1, "a", "c", "b", {}, (409, "conflict"), [], "b"),+ ("stale_caller_claims_the_edit_was_loaded", 1, "c", "c", "a", {}, (409, "conflict"), [], "a"),+ ("stale_claim_while_changing_rollout", 1, "c", "c", "a", {"rollout": 60}, (409, "conflict"), [], "a"),+ (+ "current_caller_claims_the_edit_was_loaded",+ 2,+ "c",+ "c",+ "a",+ {},+ (409, "approval_required"),+ ["feature_flag.update"],+ "a",+ ),+ ("stale_claim_while_enabling", 1, "c", "c", "a", {"active": True}, (400, "policy_conflict"), [], "a"),+ ("stale_save_without_a_release_condition_change", 1, "a", "a", "a", {}, (200, None), [], "a"),+ ]+ )+ def test_stale_editor_save_that_changes_release_conditions_is_refused(+ self,+ _mock_enabled: MagicMock,+ _name: str,+ caller_version: int,+ loaded: str,+ submitted: str,+ stored: str,+ also: dict[str, Any],+ expected_response: tuple[int, str | None],+ expected_change_requests: list[str],+ expected_stored: str,+ ):+ def filters(email: str, rollout: int = 100) -> dict[str, Any]:+ prop = {**self.EMAIL_FILTER, "value": [f"{email}@example.com"]}+ return {"groups": [{"properties": [prop], "rollout_percentage": rollout}]}++ enabling = also.get("active") is True+ flag = FeatureFlag.objects.create(+ team=self.team, key="stale-flag", filters=filters("a"), version=1, active=not enabling, created_by=self.user+ )+ FeatureFlag.objects.filter(pk=flag.pk).update(filters=filters(stored), version=2)+ self._create_policies([("feature_flag.update", {}), *([("feature_flag.enable", {})] if enabling else [])])+ body: dict[str, Any] = {+ "name": "renamed",+ "filters": filters(submitted, also.get("rollout", 100)),+ "version": caller_version,+ "original_flag": {"name": "", "filters": filters(loaded)},+ }+ if enabling:+ body["active"] = True++ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", body, format="json")++ expected_status, expected_code = expected_response+ assert response.status_code == expected_status, response.json()+ assert response.json().get("code") == expected_code+ assert self._change_request_keys() == expected_change_requests+ flag.refresh_from_db()+ assert flag.filters["groups"][0]["properties"][0]["value"] == [f"{expected_stored}@example.com"]+ assert flag.active is not enabling++ @parameterized.expand(+ [+ ("description_edit_with_a_python_equal_value", 1, 1, "edited"),+ ("python_equal_value_after_another_loaded_value", 2, 1, ""),+ ]+ )+ def test_stale_editor_save_of_a_typed_value_is_refused(+ self, _mock_enabled: MagicMock, _name: str, loaded: Any, submitted: Any, description: str+ ):+ def filters(value: Any, description: str = "") -> dict[str, Any]:+ prop = {"key": "beta", "type": "person", "operator": "exact", "value": [value]}+ return {"groups": [{"properties": [prop], "rollout_percentage": 100, "description": description}]}++ flag = FeatureFlag.objects.create(+ team=self.team, key="typed-flag", filters=filters(True), version=2, created_by=self.user+ )+ self._create_policies([("feature_flag.update", {})])++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": filters(submitted, description), "version": 1, "original_flag": {"filters": filters(loaded)}},+ format="json",+ )++ assert response.status_code == 409, response.json()+ assert self._change_request_keys() == []+ flag.refresh_from_db()+ assert flag.filters["groups"][0]["properties"][0]["value"] == [True]++class TestActionRegistrationAndIntegration(APIBaseTest):def test_update_feature_flag_action_registered_in_registry(self):from products.approvals.backend.actions.registry import ACTION_REGISTRY, register_actionsdiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 1fd3bb0b0369..a3a9ff41eda3 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -2188,15 +2188,16 @@ class ExperimentService:# 5. Persist the narrowed filters via the gated flag write.#- # Design note (approvals): FeatureFlagSerializer.update is decorated with @approval_gate,- # but flag approval policies are intentionally field-level and scoped to `active`- # (enable/disable) and `rollout_percentage` changes only — see GATEABLE_FIELDS in- # products/approvals/backend/actions/feature_flags.py and posthog.com/docs/settings/approvals.+ # Design note (approvals): FeatureFlagSerializer.update is decorated with @approval_gate.+ # The `feature_flag.update` policy gates release condition changes on standalone flags+ # only. An experiment owns this flag, so only `active` and `rollout_percentage` changes+ # are gated here (see UpdateFeatureFlagAction in+ # products/approvals/backend/actions/feature_flags.py).# Freezing exposure only AND-s a cohort condition into each group's `properties` and stamps# `description`; it changes neither `active` nor `rollout_percentage`, so the gate never# matches and no change request is raised. We therefore don't special-case ApprovalRequired- # here. If approvals ever grow to gate property/cohort changes, revisit this: the snapshot- # cohort would then need to outlive a pending change request rather than be cleaned up below.+ # here. If approvals ever gate property/cohort changes on experiment flags, revisit this: the+ # snapshot cohort would then need to outlive a pending change request rather than be cleaned up below.# Mark the write as freeze-driven so the flag's log entry does not read as# a manual targeting edit.locked_flag._activity_trigger = self._exposure_freeze_trigger(experiment, frozen=True)