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.

refactor(flags): add facade with gated flag writes (#70121)

Andersc891362b4bb8
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index 6fc7e640233b..b1ee0395ae2c 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -56,6 +56,24 @@ class PaginationMode(Enum):
previous = auto()
+class ServiceRequest:
+ """Minimal request-like object for DRF serializers used from a service layer.
+
+ Provides the subset of the DRF Request interface that serializers actually
+ use (request.user and friends), without DRF's authentication machinery.
+ """
+
+ def __init__(self, user: Any):
+ self.user = user
+ self.method = "POST"
+ self.path = "/"
+ self.data: dict = {}
+ self.GET: dict = {}
+ self.META: dict = {}
+ self.headers: dict = {}
+ self.session: dict = {}
+
+
# This overrides a change in DRF 3.15 that alters our behavior. If the user passes an empty argument,
# the new version keeps it as null vs coalescing it to the default.
# Don't add this to new classes
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index ebdc91aed4c9..806c22a93a0d 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -34,6 +34,7 @@ from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.query import execute_hogql_query
from posthog.api.cohort import CohortSerializer, get_active_flags_using_cohort
+from posthog.api.utils import ServiceRequest
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.event_usage import EventSource, report_user_action
from posthog.exceptions import (
@@ -47,12 +48,9 @@ from posthog.models.person.util import get_person_ids_and_uuids_by_uuids
from posthog.models.signals import mute_selected_signals
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
-from posthog.models.user import User
-from posthog.rbac.user_access_control import UserAccessControl
from posthog.utils import str_to_bool
from products.actions.backend.models.action import Action
-from products.approvals.backend.policies import PolicyEngine
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan
from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
@@ -80,10 +78,15 @@ from products.experiments.backend.models.experiment import (
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.result_serialization import strip_step_sessions
from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_access
-from products.feature_flags.backend.api.feature_flag import (
- FeatureFlagSerializer,
- parse_created_by_ids,
- raise_if_flag_has_dependents,
+from products.feature_flags.backend.api.feature_flag import parse_created_by_ids
+from products.feature_flags.backend.facade.api import (
+ archive_flag,
+ create_flag,
+ flag_disable_requires_approval,
+ set_flag_active,
+ unarchive_flag,
+ update_flag,
+ user_can_edit_flag,
)
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -1135,27 +1138,28 @@ class ExperimentService:
config = feature_flag_config or {}
config_filters = config.get("filters") or {}
variants = self._flag_config_variants(config) or []
- aggregation_group_type_index = config_filters.get("aggregation_group_type_index")
groups = config_filters.get("groups")
experiment_rollout_percentage = DEFAULT_ROLLOUT_PERCENTAGE
if groups and groups[0].get("rollout_percentage") is not None:
experiment_rollout_percentage = groups[0]["rollout_percentage"]
+ # `groups` and `multivariate` are normalized (the experiment input surface restricts
+ # groups to a single rollout-only entry, and an experiment flag always has variants).
+ # `aggregation_group_type_index` is seeded to None so person-level aggregation stays
+ # the default when the config omits it; the spread overrides the seed when present.
+ # Every other validated filters key — payloads (variant_key -> JSON string, e.g.
+ # prompt experiments map each variant to {"prompt_name": ..., "prompt_version": ...})
+ # and any future key — is applied as-is so nothing the serializer accepted is
+ # silently dropped.
feature_flag_filters = {
+ "aggregation_group_type_index": None,
+ **{k: v for k, v in config_filters.items() if k not in ("groups", "multivariate")},
"groups": [{"properties": [], "rollout_percentage": experiment_rollout_percentage}],
"multivariate": {"variants": variants or list(DEFAULT_VARIANTS)},
- "aggregation_group_type_index": aggregation_group_type_index,
**holdout_filters_for_flag(holdout.id if holdout else None, holdout.filters if holdout else None),
}
- # Per-variant payloads (variant_key -> JSON string). Callers pass this when they need to
- # attach metadata that the SDK can read alongside the variant assignment, e.g. prompt
- # experiments map each variant to {"prompt_name": ..., "prompt_version": ...}.
- feature_flag_payloads = config_filters.get("payloads")
- if feature_flag_payloads:
- feature_flag_filters["payloads"] = feature_flag_payloads
-
feature_flag_data: dict[str, Any] = {
"key": feature_flag_key,
"name": f"Feature Flag for Experiment {experiment_name}",
@@ -1170,13 +1174,12 @@ class ExperimentService:
if create_in_folder is not None:
feature_flag_data["_create_in_folder"] = create_in_folder
- context = serializer_context or self._build_serializer_context()
- feature_flag_serializer = FeatureFlagSerializer(
- data=feature_flag_data,
- context=context,
+ feature_flag = create_flag(
+ feature_flag_data,
+ team=self.team,
+ user=self.user,
+ request=(serializer_context or {}).get("request"),
)
- feature_flag_serializer.is_valid(raise_exception=True)
- feature_flag = feature_flag_serializer.save()
return feature_flag, variants or list(DEFAULT_VARIANTS)
@@ -1482,40 +1485,6 @@ class ExperimentService:
# Launch
# ------------------------------------------------------------------
- def _set_flag_active_gated(self, feature_flag: FeatureFlag, active: bool, request: Any) -> None:
- """Flip a flag's active state THROUGH the approval gate.
-
- Routing the flip through FeatureFlagSerializer.update() honours the
- @approval_gate so the feature_flag.enable/disable policies apply. Raises
- ApprovalRequired (which surfaces as a 409 + change_request_id) when a
- policy requires approval; in that case the flag is left untouched.
-
- The gate's detect()/extract_intent() read the serializer's validated_data
- (the actual change being saved), so the incoming experiment launch/pause/
- resume request is passed straight through — no synthetic PATCH request is
- needed.
-
- Pass BOTH get_team and get_organization so the gate resolves the policy
- from context rather than falling back to instance derivation.
- """
- # Internal callers may omit a request; FeatureFlagSerializer.update() needs
- # request.user, so fall back to the service's user via a minimal request.
- flag_request = request if getattr(request, "user", None) is not None else _ServiceRequest(self.user)
- serializer = FeatureFlagSerializer(
- instance=feature_flag,
- data={"active": active},
- partial=True,
- context={
- "request": flag_request,
- "get_team": lambda: self.team,
- "get_organization": lambda: self.team.organization,
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- serializer.is_valid(raise_exception=True)
- serializer.save()
-
# Not @transaction.atomic: the flag flip goes through the FeatureFlagSerializer
# approval workflow, which conflicts with atomic (an ApprovalRequired propagating
# out of an atomic block would roll back the just-created ChangeRequest). The flag
@@ -1534,7 +1503,7 @@ class ExperimentService:
# Activate the feature flag through the approval gate first. If approval is
# required this raises ApprovalRequired (-> 409) before we touch the experiment,
# so start_date stays None and the experiment is not launched.
- self._set_flag_active_gated(feature_flag, True, request)
+ set_flag_active(feature_flag, True, team=self.team, user=self.user, request=request)
# Set start_date
experiment.start_date = timezone.now()
@@ -1593,29 +1562,23 @@ class ExperimentService:
experiment.save()
self._archive_linked_feature_flag(
- experiment, disable_if_active=disable_feature_flag, can_write_feature_flag=can_write_feature_flag
+ experiment,
+ disable_if_active=disable_feature_flag,
+ can_write_feature_flag=can_write_feature_flag,
+ request=request,
)
self._report_lifecycle_event(experiment, "experiment archived", request=request)
return experiment
- def _user_can_edit_flag(self, feature_flag: FeatureFlag) -> bool:
- """Whether self.user has editor access to this flag — the same check the feature flag API enforces."""
- user = self.user
- if not isinstance(user, User) or user.is_anonymous:
- return False
- return UserAccessControl(user=user, team=self.team).check_access_level_for_object(feature_flag, "editor")
-
- def _flag_disable_requires_approval(self) -> bool:
- """Whether an enabled approval policy gates disabling a flag for this team/org."""
- policy = PolicyEngine().get_policy(
- action_key="feature_flag.disable", team=self.team, organization=self.team.organization
- )
- return policy is not None
-
def _archive_linked_feature_flag(
- self, experiment: Experiment, *, disable_if_active: bool = False, can_write_feature_flag: bool = True
+ self,
+ experiment: Experiment,
+ *,
+ disable_if_active: bool = False,
+ can_write_feature_flag: bool = True,
+ request: Any | None = None,
) -> None:
"""Archive the experiment's flag along with it, so it stops cluttering the flag list.
@@ -1643,7 +1606,7 @@ class ExperimentService:
if feature_flag.experiment_set.filter(deleted=False, archived=False).exclude(id=experiment.id).exists():
return
- can_edit = self._user_can_edit_flag(feature_flag)
+ can_edit = user_can_edit_flag(feature_flag, team=self.team, user=self.user)
if feature_flag.active:
if not disable_if_active:
@@ -1658,21 +1621,28 @@ class ExperimentService:
"You don't have editor access to this experiment's feature flag, so it can't be disabled. "
"Archive the experiment without disabling the flag, or ask someone with flag access."
)
- if self._flag_disable_requires_approval():
+ # A side-effect mutation can't be routed through the change-request flow (this runs
+ # inside archive_experiment's transaction, so an ApprovalRequired would roll back the
+ # just-created ChangeRequest) — refuse up front instead of letting the gate fire.
+ if flag_disable_requires_approval(self.team):
raise PermissionDenied(
"Disabling this feature flag requires approval. Disable it from the feature flag page "
"to go through the approval flow, then archive the experiment."
)
- # Mirror the feature flag API's check: don't disable a flag other active flags depend on.
- raise_if_flag_has_dependents(feature_flag)
- feature_flag.active = False
elif not can_edit or not can_write_feature_flag:
# Implicit cleanup of an already-disabled flag — skip silently when the caller
# lacks flag editor access or feature_flag:write scope; the experiment still archives.
return
- feature_flag.archived = True
- feature_flag.save(update_fields=["archived", "active"])
+ # Gated write: disabling applies the flag API's dependents guard
+ # (raise_if_flag_has_dependents) inside the serializer.
+ archive_flag(
+ feature_flag,
+ team=self.team,
+ user=self.user,
+ request=request,
+ disable_if_active=disable_if_active,
+ )
# Sync the cached relation so the serialized response reflects the flag we just
# mutated — experiment.feature_flag is a separately-loaded instance otherwise.
@@ -1702,13 +1672,15 @@ class ExperimentService:
experiment.archived = False
experiment.save()
- self._unarchive_linked_feature_flag(experiment, can_write_feature_flag=can_write_feature_flag)
+ self._unarchive_linked_feature_flag(experiment, can_write_feature_flag=can_write_feature_flag, request=request)
self._report_lifecycle_event(experiment, "experiment unarchived", request=request)
return experiment
- def _unarchive_linked_feature_flag(self, experiment: Experiment, *, can_write_feature_flag: bool = True) -> None:
+ def _unarchive_linked_feature_flag(
+ self, experiment: Experiment, *, can_write_feature_flag: bool = True, request: Any | None = None
+ ) -> None:
"""Mirror of _archive_linked_feature_flag: bring the flag back with the experiment.
Only undoes an archive this experiment performed — a flag the user archived
@@ -1731,11 +1703,14 @@ class ExperimentService:
experiment.save(update_fields=["feature_flag_auto_archived"])
return
- if not can_write_feature_flag or not self._user_can_edit_flag(feature_flag):
+ if not can_write_feature_flag or not user_can_edit_flag(feature_flag, team=self.team, user=self.user):
return
- feature_flag.archived = False
- feature_flag.save(update_fields=["archived"])
+ # Gated write inside unarchive_experiment's transaction: safe because an
+ # archived-only payload matches no approval action (enable/disable detect on
+ # `active`, update on `filters`), so the gate can't raise ApprovalRequired here
+ # and roll back a just-created change request.
+ unarchive_flag(feature_flag, team=self.team, user=self.user, request=request)
experiment.feature_flag_auto_archived = False
experiment.save(update_fields=["feature_flag_auto_archived"])
@@ -1745,7 +1720,7 @@ class ExperimentService:
# ------------------------------------------------------------------
# Not @transaction.atomic — the flag flip goes through the FeatureFlagSerializer
- # approval workflow, which conflicts with atomic (see _set_flag_active_gated).
+ # approval workflow, which conflicts with atomic (see the flag facade's set_flag_active).
def pause_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
"""Pause a running experiment: deactivate its feature flag so it is no longer served by /decide."""
if experiment.is_draft:
@@ -1761,7 +1736,7 @@ class ExperimentService:
# Deactivate through the approval gate. An ApprovalRequired (-> 409) aborts the
# pause before we report it, leaving the flag active.
- self._set_flag_active_gated(feature_flag, False, request)
+ set_flag_active(feature_flag, False, team=self.team, user=self.user, request=request)
# Re-fetch so the serializer sees the updated flag
experiment.feature_flag = feature_flag
@@ -1771,7 +1746,7 @@ class ExperimentService:
return experiment
# Not @transaction.atomic — the flag flip goes through the FeatureFlagSerializer
- # approval workflow, which conflicts with atomic (see _set_flag_active_gated).
+ # approval workflow, which conflicts with atomic (see the flag facade's set_flag_active).
def resume_experiment(self, experiment: Experiment, *, request: Any | None = None) -> Experiment:
"""Resume a paused experiment: reactivate its feature flag so /decide serves variants again."""
if experiment.is_draft:
@@ -1787,7 +1762,7 @@ class ExperimentService:
# Reactivate through the approval gate. An ApprovalRequired (-> 409) aborts the
# resume before we report it, leaving the flag paused.
- self._set_flag_active_gated(feature_flag, True, request)
+ set_flag_active(feature_flag, True, team=self.team, user=self.user, request=request)
# Re-fetch so the serializer sees the updated flag
experiment.feature_flag = feature_flag
@@ -1904,7 +1879,7 @@ class ExperimentService:
# rather than locally.
new_filters = self._transform_filters_for_frozen_exposure(locked_flag.filters, exposure_snapshot.id)
- # 5. Persist the narrowed filters via FeatureFlagSerializer.
+ # 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`
@@ -1915,18 +1890,13 @@ class ExperimentService:
# 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.
- flag_serializer = FeatureFlagSerializer(
+ update_flag(
locked_flag,
- data={"filters": new_filters},
- partial=True,
- context={
- "request": request,
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
+ {"filters": new_filters},
+ team=self.team,
+ user=self.user,
+ request=request,
)
- flag_serializer.is_valid(raise_exception=True)
- flag_serializer.save()
except Exception:
exposure_snapshot.delete()
raise
@@ -2277,18 +2247,7 @@ class ExperimentService:
flag = experiment.feature_flag
new_filters, cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters or {})
- flag_serializer = FeatureFlagSerializer(
- flag,
- data={"filters": new_filters},
- partial=True,
- context={
- "request": request,
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- flag_serializer.is_valid(raise_exception=True)
- flag_serializer.save()
+ update_flag(flag, {"filters": new_filters}, team=self.team, user=self.user, request=request)
# Refresh so the experiment's nested flag reflects the restored filters when serialized.
flag.refresh_from_db()
@@ -2563,18 +2522,7 @@ class ExperimentService:
return
if request is not None:
- flag_serializer = FeatureFlagSerializer(
- flag,
- data={"filters": stripped_filters},
- partial=True,
- context={
- "request": request,
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- flag_serializer.is_valid(raise_exception=True)
- flag_serializer.save()
+ update_flag(flag, {"filters": stripped_filters}, team=self.team, user=self.user, request=request)
else:
# FeatureFlagSerializer needs a real request for its context; for non-HTTP callers
# write directly — flag caches still refresh via model save signals, only the flag's
@@ -2650,25 +2598,12 @@ class ExperimentService:
base_filters, variant_key, release_to_everyone=release_to_everyone
)
- # Update the flag through the serializer to preserve the approval
+ # Update the flag through the gated write to preserve the approval
# workflow. If change-request approval is required, this raises
# ApprovalRequired which surfaces as a 409 to the caller. The
# experiment is NOT ended until the change request is approved and
# the user retries.
- flag_serializer = FeatureFlagSerializer(
- flag,
- data={"filters": new_filters},
- partial=True,
- context={
- "request": request,
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- "get_team": lambda: self.team,
- "get_organization": lambda: self.team.organization,
- },
- )
- flag_serializer.is_valid(raise_exception=True)
- flag_serializer.save()
+ update_flag(flag, {"filters": new_filters}, team=self.team, user=self.user, request=request)
# Refresh the flag instance so the experiment's nested flag reflects
# the updated filters when serialized in the response.
@@ -2942,7 +2877,7 @@ class ExperimentService:
# as the sync above: an ApprovalRequired must leave the pending
# ChangeRequest intact rather than roll it back.
if experiment.is_draft and update_data.get("start_date") is not None:
- self._set_flag_active_gated(feature_flag, True, context.get("request"))
+ set_flag_active(feature_flag, True, team=self.team, user=self.user, request=context.get("request"))
with transaction.atomic():
# --- saved metrics sync (update-in-place) -----------
@@ -3096,11 +3031,6 @@ class ExperimentService:
config_variants = self._flag_config_variants(feature_flag_config)
variants = config_variants if config_variants is not None else feature_flag.variants
- if "aggregation_group_type_index" in config_filters:
- aggregation_group_type_index = config_filters["aggregation_group_type_index"]
- else:
- aggregation_group_type_index = existing_filters.get("aggregation_group_type_index")
-
existing_groups = existing_filters.get("groups", [])
groups = config_filters.get("groups")
experiment_rollout_percentage = groups[0].get("rollout_percentage") if groups else None
@@ -3112,32 +3042,27 @@ class ExperimentService:
else:
new_groups = list(existing_groups)
+ # `groups` and `multivariate` are normalized (only groups[0].rollout_percentage is
+ # merged, and variants always resolve against the flag); every other validated filters
+ # key is merged as-is over the flag's current filters, so nothing the serializer
+ # accepted is silently dropped.
new_filters = {
**existing_filters,
+ **{k: v for k, v in config_filters.items() if k not in ("groups", "multivariate")},
"groups": new_groups,
"multivariate": {"variants": variants or list(DEFAULT_VARIANTS)},
- "aggregation_group_type_index": aggregation_group_type_index,
**holdout_filters_for_flag(holdout.id if holdout else None, holdout.filters if holdout else None),
}
- if "payloads" in config_filters:
- new_filters["payloads"] = config_filters["payloads"]
flag_update_data: dict[str, Any] = {"filters": new_filters}
if "ensure_experience_continuity" in feature_flag_config:
flag_update_data["ensure_experience_continuity"] = feature_flag_config["ensure_experience_continuity"]
- existing_flag_serializer = FeatureFlagSerializer(
- feature_flag,
- data=flag_update_data,
- partial=True,
- context=context,
- )
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
+ update_flag(feature_flag, flag_update_data, team=self.team, user=self.user, request=context.get("request"))
elif "holdout" in update_data:
- existing_flag_serializer = FeatureFlagSerializer(
+ update_flag(
feature_flag,
- data={
+ {
"filters": {
**feature_flag.filters,
**holdout_filters_for_flag(
@@ -3145,11 +3070,10 @@ class ExperimentService:
),
}
},
- partial=True,
- context=context,
+ team=self.team,
+ user=self.user,
+ request=context.get("request"),
)
- existing_flag_serializer.is_valid(raise_exception=True)
- existing_flag_serializer.save()
def _compute_changed_fields(
self,
@@ -4236,27 +4160,9 @@ class ExperimentService:
def _build_serializer_context(self) -> dict:
"""Build minimal DRF serializer context for internal service use."""
return {
- "request": _ServiceRequest(self.user),
+ "request": ServiceRequest(self.user),
"team_id": self.team.id,
"project_id": self.team.project_id,
"get_team": lambda: self.team,
"get_organization": lambda: self.team.organization,
}
-
-
-class _ServiceRequest:
- """Minimal request-like object for DRF serializers used from the service layer.
-
- Provides the subset of the DRF Request interface that FeatureFlagSerializer
- and other serializers actually use, without DRF's authentication machinery.
- """
-
- def __init__(self, user: Any):
- self.user = user
- self.method = "POST"
- self.path = "/"
- self.data: dict = {}
- self.GET: dict = {}
- self.META: dict = {}
- self.headers: dict = {}
- self.session: dict = {}
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 0abaf0ceefc2..2fed3175b049 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -86,7 +86,7 @@ from products.experiments.backend.session_context import get_session_experiment_
from products.experiments.backend.temporal.models import (
ExperimentMetricsRecalculationWorkflowInputs as MetricsRecalcInputs,
)
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.facade.api import serialize_flags
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_tours.backend.models import ProductTour
@@ -918,16 +918,15 @@ class EnterpriseExperimentsViewSet(
has_evaluation_contexts=request.query_params.get("has_evaluation_contexts"),
)
- # Serialize using the standard FeatureFlagSerializer
- serializer = FeatureFlagSerializer(
+ # Serialize using the flag API's standard representation
+ results = serialize_flags(
eligible_feature_flags["results"],
- many=True,
context=self.get_serializer_context(),
)
return Response(
{
- "results": serializer.data,
+ "results": results,
"count": eligible_feature_flags["count"],
}
)
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 634d11b7eef7..8a60d5ae7542 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -31,6 +31,7 @@ from posthog.models import OrganizationMembership, Team, User
from posthog.models.team.extensions import get_or_create_team_extension
from products.actions.backend.models.action import Action
+from products.approvals.backend.exceptions import ApprovalRequired
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.event_definition import EventDefinition
@@ -50,7 +51,7 @@ from products.experiments.backend.models.experiment import (
ExperimentTimeseriesRecalculation,
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.facade.api import set_flag_active, update_flag
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
@@ -2511,7 +2512,7 @@ class TestExperimentService(APIBaseTest):
experiment = self._create_ended_experiment(name="No Flag Access", feature_flag_key="no-flag-access")
service = self._service()
- with patch.object(service, "_user_can_edit_flag", return_value=False):
+ with patch("products.experiments.backend.experiment_service.user_can_edit_flag", return_value=False):
with self.assertRaises(PermissionDenied):
service.archive_experiment(experiment, disable_feature_flag=True)
@@ -2522,7 +2523,7 @@ class TestExperimentService(APIBaseTest):
assert flag.archived is False
def test_archive_experiment_denies_disabling_flag_for_user_without_real_access(self):
- # Exercises the real _user_can_edit_flag check (no patching): a user with no access to
+ # Exercises the real user_can_edit_flag check (no patching): a user with no access to
# the flag is refused, so an inverted/broken access check would fail this test.
experiment = self._create_ended_experiment(name="Real No Access", feature_flag_key="real-no-access-flag")
outsider = User.objects.create_user("[email protected]", None, "Outsider")
@@ -2590,8 +2591,8 @@ class TestExperimentService(APIBaseTest):
service = self._service()
with (
- patch.object(service, "_user_can_edit_flag", return_value=True),
- patch.object(service, "_flag_disable_requires_approval", return_value=True),
+ patch("products.experiments.backend.experiment_service.user_can_edit_flag", return_value=True),
+ patch("products.experiments.backend.experiment_service.flag_disable_requires_approval", return_value=True),
):
with self.assertRaises(PermissionDenied):
service.archive_experiment(experiment, disable_feature_flag=True)
@@ -2632,7 +2633,7 @@ class TestExperimentService(APIBaseTest):
experiment.feature_flag.save()
service = self._service()
- with patch.object(service, "_user_can_edit_flag", return_value=False):
+ with patch("products.experiments.backend.experiment_service.user_can_edit_flag", return_value=False):
service.archive_experiment(experiment)
experiment.refresh_from_db()
@@ -2709,6 +2710,41 @@ class TestExperimentService(APIBaseTest):
# The flag stays disabled — re-enabling is an explicit user decision
assert flag.active is False
+ def test_unarchive_experiment_flag_unarchive_not_blocked_by_approval_policies(self):
+ # unarchive_experiment runs inside transaction.atomic, so its gated flag write must
+ # never trip an approval policy — an ApprovalRequired escaping the block would roll
+ # back the just-created change request. Archived-only payloads match no flag action
+ # today; this pins that invariant against detect() being broadened.
+ experiment = self._create_ended_experiment(name="Unarchive Policy", feature_flag_key="unarchive-policy-flag")
+ experiment.feature_flag.active = False
+ experiment.feature_flag.save()
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+ for action_key in ["feature_flag.enable", "feature_flag.disable", "feature_flag.update"]:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key=action_key,
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ service = self._service()
+ service.archive_experiment(experiment)
+ service.unarchive_experiment(experiment)
+
+ assert ChangeRequest.objects.filter(team=self.team).count() == 0
+ experiment.feature_flag.refresh_from_db()
+ assert experiment.feature_flag.archived is False
+
+ # Positive control: the gate is live in this harness — a payload a policy does
+ # match must trip it, or the zero-change-request assertion above proves nothing.
+ with self.assertRaises(ApprovalRequired):
+ set_flag_active(experiment.feature_flag, True, team=self.team, user=self.user)
+
def test_unarchive_experiment_keeps_manually_archived_flag(self):
# The user archived the flag themselves, so unarchiving the experiment must not undo it.
experiment = self._create_ended_experiment(name="Manual Archive", feature_flag_key="manually-archived-flag")
@@ -3205,14 +3241,7 @@ class TestExperimentService(APIBaseTest):
flag.save()
def _update_flag_filters(self, flag: FeatureFlag, filters: dict) -> None:
- serializer = FeatureFlagSerializer(
- flag,
- data={"filters": filters},
- partial=True,
- context={"request": self._make_request(), "team_id": self.team.id, "project_id": self.team.project_id},
- )
- serializer.is_valid(raise_exception=True)
- serializer.save()
+ update_flag(flag, {"filters": filters}, team=self.team, user=self.user, request=self._make_request())
flag.refresh_from_db()
@contextmanager
@@ -3513,7 +3542,10 @@ class TestExperimentService(APIBaseTest):
# Any failure persisting the narrowed flag must not leave the snapshot cohort behind.
with self._stub_freeze_population():
- with patch.object(FeatureFlagSerializer, "save", side_effect=ValidationError("boom")):
+ with patch(
+ "products.experiments.backend.experiment_service.update_flag",
+ side_effect=ValidationError("boom"),
+ ):
with self.assertRaises(ValidationError):
self._service().freeze_exposure(experiment, request=self._make_request())
@@ -4100,7 +4132,10 @@ class TestExperimentService(APIBaseTest):
# If persisting the shipped flag fails (e.g. ApprovalRequired surfacing as a 409), the flag
# is still frozen and serving from the snapshot — the cohort must not be deleted from under it.
- with patch.object(FeatureFlagSerializer, "save", side_effect=ValidationError("boom")):
+ with patch(
+ "products.experiments.backend.experiment_service.update_flag",
+ side_effect=ValidationError("boom"),
+ ):
with self.assertRaises(ValidationError):
self._service().ship_variant(frozen, variant_key="test", request=self._make_request())
@@ -4120,18 +4155,7 @@ class TestExperimentService(APIBaseTest):
"rollout_percentage": 100,
}
updated_filters = {**flag.filters, "groups": [scoped_group]}
- serializer = FeatureFlagSerializer(
- flag,
- data={"filters": updated_filters},
- partial=True,
- context={
- "request": self._make_request(),
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- serializer.is_valid(raise_exception=True)
- serializer.save()
+ update_flag(flag, {"filters": updated_filters}, team=self.team, user=self.user, request=self._make_request())
flag.refresh_from_db()
original_groups = flag.filters["groups"]
@@ -4153,18 +4177,7 @@ class TestExperimentService(APIBaseTest):
}
existing_groups = flag.filters.get("groups", [])
updated_filters = {**flag.filters, "groups": [override_group, *existing_groups]}
- serializer = FeatureFlagSerializer(
- flag,
- data={"filters": updated_filters},
- partial=True,
- context={
- "request": self._make_request(),
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- serializer.is_valid(raise_exception=True)
- serializer.save()
+ update_flag(flag, {"filters": updated_filters}, team=self.team, user=self.user, request=self._make_request())
flag.refresh_from_db()
original_groups = flag.filters["groups"]
@@ -4237,18 +4250,7 @@ class TestExperimentService(APIBaseTest):
"aggregation_group_type_index": 1,
"groups": [{**g, "aggregation_group_type_index": 1} for g in flag.filters.get("groups", [])],
}
- flag_serializer = FeatureFlagSerializer(
- flag,
- data={"filters": updated_filters},
- partial=True,
- context={
- "request": self._make_request(),
- "team_id": self.team.id,
- "project_id": self.team.project_id,
- },
- )
- flag_serializer.is_valid(raise_exception=True)
- flag_serializer.save()
+ update_flag(flag, {"filters": updated_filters}, team=self.team, user=self.user, request=self._make_request())
flag.refresh_from_db()
shipped = self._service().ship_variant(experiment, variant_key="test", request=self._make_request())
diff --git a/products/feature_flags/backend/facade/__init__.py b/products/feature_flags/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
new file mode 100644
index 000000000000..3110e7f83054
--- /dev/null
+++ b/products/feature_flags/backend/facade/api.py
@@ -0,0 +1,139 @@
+"""Feature flag facade: gated flag writes and read helpers for other products.
+
+Every write routes through ``FeatureFlagSerializer`` — the only path that honors
+``@approval_gate``, validation, and activity logging. Consumers (currently experiments)
+call these functions instead of driving the serializer and its DRF context by hand.
+The read helpers (``user_can_edit_flag``, ``flag_disable_requires_approval``,
+``serialize_flags``) expose the flag API's access-control, approval-policy, and
+representation logic behind the same boundary.
+
+Writes do not enforce access control — that lives at the viewset layer. A caller
+acting on behalf of an end user must pre-check ``user_can_edit_flag`` first.
+
+Approval-gate ordering constraint for callers: a gated write can raise ``ApprovalRequired``
+(surfacing as a 409 + change_request_id), which conflicts with ``transaction.atomic`` — the
+exception propagating out of an atomic block would roll back the just-created pending
+ChangeRequest. Run gated writes before/outside any transaction wrapping your own state.
+"""
+
+from typing import Any
+
+from posthog.api.utils import ServiceRequest
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.rbac.user_access_control import UserAccessControl
+
+from products.approvals.backend.policies import PolicyEngine
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+def _serializer_context(team: Team, user: Any, request: Any | None) -> dict:
+ """Build the DRF serializer context for a gated flag write.
+
+ Callers without a real request (internal service paths) fall back to a minimal
+ request shim carrying the acting user — FeatureFlagSerializer needs request.user.
+
+ Pass BOTH get_team and get_organization so the approval gate resolves the policy
+ from context rather than falling back to instance derivation.
+ """
+ flag_request = request if getattr(request, "user", None) is not None else ServiceRequest(user)
+ return {
+ "request": flag_request,
+ "team_id": team.id,
+ "project_id": team.project_id,
+ "get_team": lambda: team,
+ "get_organization": lambda: team.organization,
+ }
+
+
+def create_flag(data: dict, *, team: Team, user: Any, request: Any | None = None) -> FeatureFlag:
+ """Gated create: routes through FeatureFlagSerializer so @approval_gate, validation,
+ and activity logging apply. ``data`` is the flag's own write shape (key, name, filters,
+ active, ...) and is applied as-is — nothing is silently dropped. Raises ApprovalRequired
+ when a policy requires approval."""
+ serializer = FeatureFlagSerializer(data=data, context=_serializer_context(team, user, request))
+ serializer.is_valid(raise_exception=True)
+ return serializer.save()
+
+
+def update_flag(flag: FeatureFlag, data: dict, *, team: Team, user: Any, request: Any | None = None) -> FeatureFlag:
+ """Gated partial update: routes through FeatureFlagSerializer so @approval_gate,
+ validation, and activity logging apply. ``data`` is a partial flag write payload
+ (fields it omits are untouched) applied as-is — nothing is silently dropped.
+ Raises ApprovalRequired when a policy requires approval; the flag is left untouched."""
+ serializer = FeatureFlagSerializer(flag, data=data, partial=True, context=_serializer_context(team, user, request))
+ serializer.is_valid(raise_exception=True)
+ return serializer.save()
+
+
+def set_flag_active(
+ flag: FeatureFlag, active: bool, *, team: Team, user: Any, request: Any | None = None
+) -> FeatureFlag:
+ """Flip a flag's active state THROUGH the approval gate.
+
+ Routing the flip through FeatureFlagSerializer.update() honours the
+ @approval_gate so the feature_flag.enable/disable policies apply. Raises
+ ApprovalRequired (which surfaces as a 409 + change_request_id) when a
+ policy requires approval; in that case the flag is left untouched.
+
+ The gate's detect()/extract_intent() read the serializer's validated_data
+ (the actual change being saved), so an incoming HTTP request that triggered
+ the flip is passed straight through — no synthetic PATCH request is needed.
+ """
+ return update_flag(flag, {"active": active}, team=team, user=user, request=request)
+
+
+def archive_flag(
+ flag: FeatureFlag,
+ *,
+ team: Team,
+ user: Any,
+ request: Any | None = None,
+ disable_if_active: bool = False,
+) -> FeatureFlag:
+ """Archive a flag through the gated serializer path.
+
+ An archived flag must be disabled (the serializer enforces it); pass
+ ``disable_if_active`` to disable an active flag in the same write. Disabling
+ applies the dependents guard (``raise_if_flag_has_dependents``) inside the
+ serializer, and trips the feature_flag.disable approval policy if one is
+ enabled — check ``flag_disable_requires_approval`` first when the caller
+ cannot surface a change request.
+ """
+ data: dict[str, Any] = {"archived": True}
+ if disable_if_active and flag.active:
+ data["active"] = False
+ return update_flag(flag, data, team=team, user=user, request=request)
+
+
+def unarchive_flag(flag: FeatureFlag, *, team: Team, user: Any, request: Any | None = None) -> FeatureFlag:
+ """Unarchive a flag through the gated serializer path.
+
+ The flag stays disabled; re-enabling it is a separate, explicit write
+ (``set_flag_active``).
+ """
+ return update_flag(flag, {"archived": False}, team=team, user=user, request=request)
+
+
+def user_can_edit_flag(flag: FeatureFlag, *, team: Team, user: Any) -> bool:
+ """Whether ``user`` has editor access to this flag — the same check the feature flag API enforces."""
+ if not isinstance(user, User) or user.is_anonymous:
+ return False
+ return UserAccessControl(user=user, team=team).check_access_level_for_object(flag, "editor")
+
+
+def flag_disable_requires_approval(team: Team) -> bool:
+ """Whether an enabled approval policy gates disabling a flag for this team/org."""
+ policy = PolicyEngine().get_policy(action_key="feature_flag.disable", team=team, organization=team.organization)
+ return policy is not None
+
+
+def serialize_flags(flags: Any, *, context: dict) -> Any:
+ """The flag API's full list representation for the given flags.
+
+ ``context`` is the caller's DRF serializer context (a viewset's
+ ``get_serializer_context()``): the representation includes request- and
+ access-control-derived fields, so it can only be built for a real request.
+ """
+ return FeatureFlagSerializer(flags, many=True, context=context).data
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
new file mode 100644
index 000000000000..e93e4b39e7d9
--- /dev/null
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -0,0 +1,77 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.constants import AvailableFeature
+
+from products.approvals.backend.exceptions import ApprovalRequired
+from products.approvals.backend.models import ApprovalPolicy
+from products.feature_flags.backend.facade.api import archive_flag, flag_disable_requires_approval
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestFeatureFlagFacadeGatedWrites(APIBaseTest):
+ def _create_flag(self, *, active: bool = True) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="facade-gated-flag",
+ active=active,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+
+ def test_archive_active_flag_with_disable_succeeds(self):
+ flag = self._create_flag(active=True)
+
+ archive_flag(flag, team=self.team, user=self.user, disable_if_active=True)
+
+ flag.refresh_from_db()
+ assert flag.archived is True
+ assert flag.active is False
+
+ def test_flag_disable_requires_approval_reflects_policy(self):
+ assert flag_disable_requires_approval(self.team) is False
+
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.disable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ assert flag_disable_requires_approval(self.team) is True
+
+ def test_archive_active_flag_without_disable_is_rejected(self):
+ flag = self._create_flag(active=True)
+
+ with self.assertRaises(ValidationError):
+ archive_flag(flag, team=self.team, user=self.user)
+
+ flag.refresh_from_db()
+ assert flag.archived is False
+ assert flag.active is True
+
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+ def test_archive_with_disable_honors_disable_approval_policy(self, _mock_enabled):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.disable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ flag = self._create_flag(active=True)
+
+ with self.assertRaises(ApprovalRequired):
+ archive_flag(flag, team=self.team, user=self.user, disable_if_active=True)
+
+ flag.refresh_from_db()
+ assert flag.archived is False
+ assert flag.active is True