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): move enrollment-freeze filter transforms behind the facade (#70123)

Andersb332bcc18db7
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 0bd46a0640d6..a8c3386ff01c 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -685,6 +685,7 @@
'__str__',
'_meta',
'archived',
+ 'can_freeze_exposure',
'computed_status',
'conclusion',
'conclusion_comment',
@@ -698,6 +699,7 @@
'experimenttosavedmetric_set',
'exposure_cohort_id',
'feature_flag_id',
+ 'freeze_exposure_blocker',
'get_analytics_metadata',
'get_conclusion_display',
'get_feature_flag_key',
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index c5c41329aead..0e9d6af2317c 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -6,7 +6,7 @@ from collections.abc import Iterable, Mapping
from copy import deepcopy
from datetime import date, datetime, timedelta
from enum import Enum
-from typing import Any, Literal
+from typing import Any, Literal, get_args
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -75,6 +75,7 @@ from products.experiments.backend.models.experiment import (
ExperimentSavedMetric,
ExperimentTimeseriesRecalculation,
ExperimentToSavedMetric,
+ ExposureFreezeBlocker,
experiment_has_legacy_metrics,
holdout_filters_for_flag,
)
@@ -92,6 +93,7 @@ from products.feature_flags.backend.facade.api import (
update_flag,
user_can_edit_flag,
)
+from products.feature_flags.backend.facade.filters import restrict_groups_to_cohort, strip_group_cohort_restriction
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_error
from products.notifications.backend.facade.api import (
@@ -214,6 +216,57 @@ def _deprecated_fields_in_request(request: Any) -> dict[str, Any]:
return props
+# The user-facing validation message for each freeze-exposure blocker the model can report.
+_FREEZE_EXPOSURE_BLOCKER_MESSAGES: dict[ExposureFreezeBlocker, str] = {
+ "draft": "Experiment has not been launched yet.",
+ "stopped": "Experiment has already ended.",
+ "paused": "Cannot freeze a paused experiment. Resume it first.",
+ "already_frozen": "Experiment exposure is already frozen.",
+ "no_flag": "Experiment does not have a feature flag linked.",
+ "flag_deleted": "Experiment's feature flag has been deleted.",
+ "group_aggregation": "Group-aggregated experiments cannot have their exposure frozen.",
+ "holdout": (
+ "Experiments in a holdout cannot have their exposure frozen: holdout assignment is "
+ "evaluated before release conditions, so new users would keep entering the holdout."
+ ),
+ "super_groups": (
+ "This experiment's feature flag has early access conditions, which are evaluated "
+ "before release conditions, so freezing cannot stop new enrollment."
+ ),
+ "no_groups": "Experiment's feature flag has no release conditions to freeze.",
+}
+
+# Dict literals keyed by a Literal union aren't exhaustiveness-checked, and the union's
+# variants span two modules — fail at import rather than 500 on a missing message.
+_expected_blockers = {variant for literal in get_args(ExposureFreezeBlocker) for variant in get_args(literal)}
+assert set(_FREEZE_EXPOSURE_BLOCKER_MESSAGES) == _expected_blockers, (
+ f"_FREEZE_EXPOSURE_BLOCKER_MESSAGES out of sync with ExposureFreezeBlocker: "
+ f"{_expected_blockers ^ set(_FREEZE_EXPOSURE_BLOCKER_MESSAGES)}"
+)
+
+
+def _restrict_filters_to_frozen_cohort(filters: dict, cohort_id: int) -> dict:
+ """The facade's generic cohort restriction, bound to the experiments freeze marker."""
+ return restrict_groups_to_cohort(
+ filters,
+ cohort_id,
+ marker_key=EXPOSURE_FROZEN_GROUP_KEY,
+ cohort_key=EXPOSURE_FROZEN_COHORT_KEY,
+ marker_note=EXPOSURE_FROZEN_GROUP_MARKER,
+ )
+
+
+def _strip_frozen_exposure(filters: dict) -> tuple[dict, list[int]]:
+ """Inverse of _restrict_filters_to_frozen_cohort: strip the freeze marker and its cohort
+ conditions, returning the stripped filters plus the snapshot cohort ids for cleanup."""
+ return strip_group_cohort_restriction(
+ filters,
+ marker_key=EXPOSURE_FROZEN_GROUP_KEY,
+ cohort_key=EXPOSURE_FROZEN_COHORT_KEY,
+ marker_note=EXPOSURE_FROZEN_GROUP_MARKER,
+ )
+
+
class ExperimentQueryStatus(str, Enum):
"""
Filter values for the experiment list endpoint.
@@ -1951,7 +2004,7 @@ class ExperimentService:
# return the flag's default for everyone. This is the standard behavior of any static-cohort flag,
# not specific to freezing — it just means a frozen experiment is evaluated server-side via /decide
# rather than locally.
- new_filters = self._transform_filters_for_frozen_exposure(locked_flag.filters, exposure_snapshot.id)
+ new_filters = _restrict_filters_to_frozen_cohort(locked_flag.filters, exposure_snapshot.id)
# 5. Persist the narrowed filters via the gated flag write.
#
@@ -2003,46 +2056,12 @@ class ExperimentService:
def _validate_freeze_exposure_state(self, experiment: Experiment) -> None:
"""Guards for freeze_exposure, run twice: unlocked before the expensive snapshot build to
- fail fast, and again under the flag lock to fail closed against whatever landed mid-build."""
- if experiment.is_draft:
- raise ValidationError("Experiment has not been launched yet.")
- if experiment.is_stopped:
- raise ValidationError("Experiment has already ended.")
- if experiment.is_paused:
- # A paused flag serves no one, so there is no live enrollment to freeze; freezing anyway
- # would mislabel the (inactive) experiment as "exposure_frozen". Resume first.
- raise ValidationError("Cannot freeze a paused experiment. Resume it first.")
- if experiment.is_exposure_frozen:
- raise ValidationError("Experiment exposure is already frozen.")
-
- # Guard on the id, not the relation: feature_flag is a non-nullable FK, so accessing
- # experiment.feature_flag when it's unset raises RelatedObjectDoesNotExist rather than
- # returning None.
- if experiment.feature_flag_id is None:
- raise ValidationError("Experiment does not have a feature flag linked.")
- flag = experiment.feature_flag
- if flag.deleted:
- raise ValidationError("Experiment's feature flag has been deleted.")
- if flag.aggregation_group_type_index is not None:
- raise ValidationError("Group-aggregated experiments cannot have their exposure frozen.")
- # Holdout assignment and early-access enrollment (super_groups) are evaluated by the flag
- # matcher before release conditions, so narrowing the release groups to a cohort cannot stop
- # new users from entering through those paths. Fail closed rather than freeze partially.
- flag_filters = flag.filters or {}
- if experiment.holdout_id is not None or flag_filters.get("holdout") or flag_filters.get("holdout_groups"):
- raise ValidationError(
- "Experiments in a holdout cannot have their exposure frozen: holdout assignment is "
- "evaluated before release conditions, so new users would keep entering the holdout."
- )
- if flag_filters.get("super_groups"):
- raise ValidationError(
- "This experiment's feature flag has early access conditions, which are evaluated "
- "before release conditions, so freezing cannot stop new enrollment."
- )
- # Without release conditions there is nothing to narrow: the transform would be a no-op and
- # the frozen state (derived from the per-group key) could never be detected.
- if not flag_filters.get("groups"):
- raise ValidationError("Experiment's feature flag has no release conditions to freeze.")
+ fail fast, and again under the flag lock to fail closed against whatever landed mid-build.
+ The preconditions live on the model (Experiment.freeze_exposure_blocker) so the serializer's
+ can_freeze_exposure gate and this validator can't drift apart."""
+ blocker = experiment.freeze_exposure_blocker
+ if blocker is not None:
+ raise ValidationError(_FREEZE_EXPOSURE_BLOCKER_MESSAGES[blocker])
def _fetch_exposed_person_uuids(self, experiment: Experiment) -> list[str]:
"""Return the UUIDs of persons already exposed to the experiment, bounded by time and count.
@@ -2200,78 +2219,6 @@ class ExperimentService:
raise
return cohort
- @staticmethod
- def _transform_filters_for_frozen_exposure(current_filters: dict, cohort_id: int) -> dict:
- """AND a static-cohort condition into every release group and stamp the freeze key.
-
- AND (not a new group): groups are OR'd, so a separate group would *widen* access.
- AND (not replace): the original per-group ``properties``/``rollout_percentage`` are
- preserved so a future unfreeze or manual revert strips back to exactly the original.
- The frozen state lives in the structured EXPOSURE_FROZEN_GROUP_KEY on each group;
- the marker is merely prepended to the (preserved) ``description`` as a human-readable
- note. Everything else (``multivariate``, ``payloads``, aggregation index) is left
- byte-for-byte.
- """
- cohort_condition = {"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}
-
- new_groups = []
- for group in current_filters.get("groups", []):
- # One deepcopy per group so the new filters never alias the original flag's dicts.
- new_group = deepcopy(group)
- new_group["properties"] = [*new_group.get("properties", []), cohort_condition]
- new_group[EXPOSURE_FROZEN_GROUP_KEY] = True
- new_group[EXPOSURE_FROZEN_COHORT_KEY] = cohort_id
- existing_description = new_group.get("description")
- new_group["description"] = (
- f"{EXPOSURE_FROZEN_GROUP_MARKER} {existing_description}"
- if existing_description
- else EXPOSURE_FROZEN_GROUP_MARKER
- )
- new_groups.append(new_group)
- return {**current_filters, "groups": new_groups}
-
- @staticmethod
- def _strip_frozen_exposure_from_filters(current_filters: dict) -> tuple[dict, list[int]]:
- """Inverse of _transform_filters_for_frozen_exposure: remove the freeze stamps from every
- release group — the AND'd snapshot-cohort condition (identified via the per-group
- EXPOSURE_FROZEN_COHORT_KEY, so user-added cohort conditions survive), the two structured
- keys, and the description marker note. Groups without the freeze key pass through untouched.
-
- Returns the stripped filters plus the snapshot cohort ids that were referenced, so callers
- can clean up the then-orphaned cohorts once the stripped filters are persisted — and only
- then: deleting earlier would yank the cohort from under a still-frozen flag if the save fails.
- """
- new_groups = []
- cohort_ids: list[int] = []
- for group in current_filters.get("groups", []):
- new_group = deepcopy(group)
- if new_group.get(EXPOSURE_FROZEN_GROUP_KEY) is not True:
- new_groups.append(new_group)
- continue
- new_group.pop(EXPOSURE_FROZEN_GROUP_KEY, None)
- cohort_id = new_group.pop(EXPOSURE_FROZEN_COHORT_KEY, None)
- if cohort_id is not None:
- cohort_ids.append(cohort_id)
- new_group["properties"] = [
- condition
- for condition in new_group.get("properties", [])
- if not (
- condition.get("type") == "cohort"
- and condition.get("key") == "id"
- and condition.get("value") == cohort_id
- )
- ]
- description = new_group.get("description")
- if isinstance(description, str) and EXPOSURE_FROZEN_GROUP_MARKER in description:
- stripped_description = description.replace(EXPOSURE_FROZEN_GROUP_MARKER, "").strip()
- if stripped_description:
- new_group["description"] = stripped_description
- else:
- # The freeze added the description outright — restore its absence.
- del new_group["description"]
- new_groups.append(new_group)
- return {**current_filters, "groups": new_groups}, list(dict.fromkeys(cohort_ids))
-
def _delete_orphaned_snapshot_cohorts(self, cohort_ids: list[int]) -> None:
"""Soft-delete freeze snapshot cohorts whose flag reference was just removed.
@@ -2324,7 +2271,7 @@ class ExperimentService:
raise ValidationError("Experiment exposure is not frozen.")
flag = experiment.feature_flag
- new_filters, cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters or {})
+ new_filters, cohort_ids = _strip_frozen_exposure(flag.filters or {})
update_flag(flag, {"filters": new_filters}, team=self.team, user=self.user, request=request)
@@ -2596,7 +2543,7 @@ class ExperimentService:
)
if flag is None or flag.deleted:
return
- stripped_filters, cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters or {})
+ stripped_filters, cohort_ids = _strip_frozen_exposure(flag.filters or {})
if stripped_filters == (flag.filters or {}):
return
@@ -2666,7 +2613,7 @@ class ExperimentService:
# Shipping a winner ends the enrollment freeze by definition, so strip it in the same flag
# write: preserved, it would lock the shipped variant to the stale snapshot forever in the
# default mode, and linger as dead weight below the catch-all in release_to_everyone mode.
- base_filters, frozen_cohort_ids = self._strip_frozen_exposure_from_filters(flag.filters)
+ base_filters, frozen_cohort_ids = _strip_frozen_exposure(flag.filters)
# Update the flag through the gated write to preserve the approval
# workflow. If change-request approval is required, this raises
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 1c1e184410f9..1edd10be458b 100644
--- a/products/experiments/backend/models/experiment.py
+++ b/products/experiments/backend/models/experiment.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Literal
from django.contrib.postgres.fields import ArrayField
from django.db import models
@@ -12,6 +12,12 @@ from posthog.models.file_system.file_system_representation import FileSystemRepr
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import RootTeamMixin, UUIDModel
+from products.feature_flags.backend.facade.filters import (
+ CohortRestrictionBlocker,
+ group_cohort_restriction_blocker,
+ groups_carry_restriction_marker,
+)
+
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -31,6 +37,12 @@ EXPOSURE_FROZEN_COHORT_KEY = "exposure_frozen_cohort"
# informational — the description stays user-editable prose and carries no state.
EXPOSURE_FROZEN_GROUP_MARKER = "Added automatically when the experiment exposure was frozen to stop new enrollment."
+# Why an experiment's exposure can't be frozen right now. Experiment-state reasons plus the
+# flag-shape reasons computed flag-side by group_cohort_restriction_blocker.
+ExposureFreezeBlocker = (
+ Literal["draft", "stopped", "paused", "already_frozen", "no_flag", "flag_deleted"] | CohortRestrictionBlocker
+)
+
class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):
class ExperimentType(models.TextChoices):
@@ -174,8 +186,46 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.
return False
# Enrollment is closed only when EVERY release group is stamped, so that add/edit groups
# surfaces as the experiment reverting to "running".
- groups = (self.feature_flag.filters or {}).get("groups", [])
- return bool(groups) and all(group.get(EXPOSURE_FROZEN_GROUP_KEY) is True for group in groups)
+ return groups_carry_restriction_marker(self.feature_flag.filters or {}, marker_key=EXPOSURE_FROZEN_GROUP_KEY)
+
+ @property
+ def freeze_exposure_blocker(self) -> ExposureFreezeBlocker | None:
+ """Why exposure can't be frozen right now, or None. Single source for the freeze
+ validator's preconditions and the serializer's can_freeze_exposure gate — the service
+ maps each blocker to its user-facing validation message, so the UI gate can't drift
+ from what the validator enforces."""
+ if self.is_draft:
+ return "draft"
+ if self.is_stopped:
+ return "stopped"
+ if self.is_paused:
+ # A paused flag serves no one, so there is no live enrollment to freeze; freezing anyway
+ # would mislabel the (inactive) experiment as "exposure_frozen". Resume first.
+ return "paused"
+ if self.is_exposure_frozen:
+ return "already_frozen"
+ # Guard on the id, not the relation: feature_flag is a non-nullable FK, so accessing
+ # self.feature_flag when it's unset raises RelatedObjectDoesNotExist rather than
+ # returning None. Widened to Optional because django-stubs types the id as int, but an
+ # unsaved in-memory instance can still carry None.
+ feature_flag_id: int | None = self.feature_flag_id
+ if feature_flag_id is None:
+ return "no_flag"
+ if self.feature_flag.deleted:
+ return "flag_deleted"
+ # The flag-shape preconditions (group aggregation, evaluation order, empty groups) live
+ # flag-side in group_cohort_restriction_blocker. Fail closed rather than freeze partially.
+ flag_blocker = group_cohort_restriction_blocker(self.feature_flag.filters or {})
+ if flag_blocker == "group_aggregation":
+ return flag_blocker
+ # An experiment-level holdout blocks freezing even before the flag filters carry holdout keys.
+ if self.holdout_id is not None or flag_blocker == "holdout":
+ return "holdout"
+ return flag_blocker
+
+ @property
+ def can_freeze_exposure(self) -> bool:
+ return self.freeze_exposure_blocker is None
@property
def computed_status(self) -> "Experiment.Status":
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 65dd2b61248e..1fd5dbeedd58 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -361,6 +361,14 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"without this flag is rejected."
),
)
+ can_freeze_exposure = serializers.SerializerMethodField(
+ help_text=(
+ "Whether enrollment can be frozen right now: the experiment must be running (not draft, "
+ "paused, stopped, or already frozen) and its feature flag must have release conditions "
+ "that a person cohort can narrow (no group aggregation, no holdout, no early access "
+ "conditions)."
+ ),
+ )
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
class Meta:
@@ -404,6 +412,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"update_feature_flag_params",
"status",
"is_legacy",
+ "can_freeze_exposure",
"user_access_level",
]
read_only_fields = [
@@ -416,6 +425,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"holdout",
"saved_metrics",
"status",
+ "can_freeze_exposure",
"user_access_level",
]
@@ -428,6 +438,10 @@ class ExperimentSerializer(ExperimentBaseSerializer):
fields["holdout_id"].queryset = ExperimentHoldout.objects.none() # type: ignore[attr-defined]
return fields
+ @extend_schema_field(serializers.BooleanField())
+ def get_can_freeze_exposure(self, obj: Experiment) -> bool:
+ return obj.can_freeze_exposure
+
@tracer.start_as_current_span("ExperimentSerializer.to_representation")
def to_representation(self, instance):
data = super().to_representation(instance)
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 2dd7eb9559ad..eab66dd2c5e3 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -3537,6 +3537,50 @@ class TestExperimentService(APIBaseTest):
experiment.refresh_from_db()
assert experiment.is_exposure_frozen is expected
+ @parameterized.expand(
+ [
+ ("running", "running", None, True),
+ ("draft", "draft", None, False),
+ ("stopped", "stopped", None, False),
+ ("paused", "paused", None, False),
+ ("frozen", "frozen", None, False),
+ ("holdout_linked", "holdout_linked", None, False),
+ ("group_aggregated", "running", {"aggregation_group_type_index": 0}, False),
+ ("flag_super_groups", "running", {"super_groups": [{"properties": [], "rollout_percentage": 100}]}, False),
+ ("no_groups", "running", {"groups": []}, False),
+ ]
+ )
+ def test_can_freeze_exposure_property(self, _name: str, state: str, extra_filters: dict | None, expected: bool):
+ if state == "draft":
+ experiment = self._create_launchable_experiment(name="CF Draft", feature_flag_key=f"cf-{_name}")
+ elif state == "stopped":
+ experiment = self._create_ended_experiment(name="CF Stopped", feature_flag_key=f"cf-{_name}")
+ else:
+ experiment = self._create_running_experiment(name="CF Running", feature_flag_key=f"cf-{_name}")
+
+ if state == "paused":
+ flag = experiment.feature_flag
+ flag.active = False
+ flag.save()
+ elif state == "frozen":
+ self._stamp_exposure_frozen_marker(experiment.feature_flag)
+ elif state == "holdout_linked":
+ holdout = ExperimentHoldout.objects.create(
+ team=self.team,
+ name="CF Holdout",
+ filters=[{"properties": [], "rollout_percentage": 10, "variant": "holdout"}],
+ created_by=self.user,
+ )
+ experiment.holdout = holdout
+ experiment.save()
+ if extra_filters:
+ flag = experiment.feature_flag
+ flag.filters = {**flag.filters, **extra_filters}
+ flag.save()
+
+ experiment.refresh_from_db()
+ assert experiment.can_freeze_exposure is expected
+
def test_freeze_exposure_success(self):
experiment = self._create_running_experiment(name="Freeze Exposure", feature_flag_key="freeze-exposure-flag")
original_variants = deepcopy(experiment.feature_flag.filters["multivariate"])
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 0448824bac7f..f398e77e3428 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -4925,6 +4925,9 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()["status"], "draft")
+ # False counterpart to the wiring guard in test_launching_experiment_sets_status_running,
+ # proving the field tracks the property value rather than being hardcoded truthy.
+ self.assertFalse(response.json()["can_freeze_exposure"])
def test_launching_experiment_sets_status_running(self):
response = self.client.post(
@@ -4938,6 +4941,9 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()["status"], "running")
+ # Wiring guard for the serializer-computed field; the case matrix lives on the
+ # model property test (test_can_freeze_exposure_property).
+ self.assertTrue(response.json()["can_freeze_exposure"])
def test_ending_experiment_sets_status_stopped(self):
response = self.client.post(
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index c73485176ce4..bc9d5f50b82f 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1449,6 +1449,8 @@ export interface ExperimentWriteApi {
readonly status: ExperimentStatusEnumApi
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy: boolean
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure: boolean
/**
* The effective access level the user has for this object
* @nullable
@@ -1555,6 +1557,8 @@ export interface ExperimentApi {
readonly status: ExperimentStatusEnumApi
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy: boolean
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure: boolean
/**
* The effective access level the user has for this object
* @nullable
@@ -1657,6 +1661,8 @@ export interface PatchedExperimentWriteApi {
readonly status?: ExperimentStatusEnumApi
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy?: boolean
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure?: boolean
/**
* The effective access level the user has for this object
* @nullable
diff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.py
new file mode 100644
index 000000000000..af62ee74afe3
--- /dev/null
+++ b/products/feature_flags/backend/facade/filters.py
@@ -0,0 +1,140 @@
+"""Pure transforms over feature flag ``filters`` dicts, exposed via the facade.
+
+These own the flag-schema knowledge (groups are OR'd, conditions AND within a group,
+evaluation is top-down first-match, holdout/super groups are evaluated before release
+conditions) so consumers don't have to. The marker keys and notes are opaque values
+passed in by the caller — e.g. experiments' enrollment freeze — so the flag product
+learns no consumer concepts.
+
+Deliberately free of Django/DRF imports: consumer model modules import these predicates
+at module level, and routing them through ``facade.api`` (which imports the flag
+serializer, whose module imports back into consumers) would create an import cycle.
+"""
+
+from copy import deepcopy
+from typing import Literal
+
+CohortRestrictionBlocker = Literal["group_aggregation", "holdout", "super_groups", "no_groups"]
+
+
+def restrict_groups_to_cohort(
+ current_filters: dict,
+ cohort_id: int,
+ *,
+ marker_key: str,
+ cohort_key: str,
+ marker_note: str,
+) -> dict:
+ """AND a static-cohort condition into every release group and stamp the marker key.
+
+ AND (not a new group): groups are OR'd, so a separate group would *widen* access.
+ AND (not replace): the original per-group ``properties``/``rollout_percentage`` are
+ preserved so a future strip or manual revert restores exactly the original.
+ The restricted state lives in the structured ``marker_key`` on each group and
+ ``cohort_key`` records which cohort was AND'd in; ``marker_note`` is merely prepended
+ to the (preserved) ``description`` as a human-readable note. Everything else
+ (``multivariate``, ``payloads``, aggregation index) is left byte-for-byte.
+ """
+ cohort_condition = {"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}
+
+ new_groups = []
+ for group in current_filters.get("groups", []):
+ # One deepcopy per group so the new filters never alias the original flag's dicts.
+ new_group = deepcopy(group)
+ new_group["properties"] = [*new_group.get("properties", []), cohort_condition]
+ new_group[marker_key] = True
+ new_group[cohort_key] = cohort_id
+ existing_description = new_group.get("description")
+ new_group["description"] = f"{marker_note} {existing_description}" if existing_description else marker_note
+ new_groups.append(new_group)
+ return {**current_filters, "groups": new_groups}
+
+
+def strip_group_cohort_restriction(
+ current_filters: dict,
+ *,
+ marker_key: str,
+ cohort_key: str,
+ marker_note: str,
+) -> tuple[dict, list[int]]:
+ """Inverse of restrict_groups_to_cohort: remove the restriction stamps from every
+ release group — the AND'd cohort condition (identified via the per-group
+ ``cohort_key``, so user-added cohort conditions survive), the two structured keys,
+ and the description note. Groups without the marker key pass through untouched.
+
+ Returns the stripped filters plus the cohort ids that were referenced, so callers
+ can clean up the then-orphaned cohorts once the stripped filters are persisted — and only
+ then: deleting earlier would yank the cohort from under a still-restricted flag if the
+ save fails.
+ """
+ new_groups = []
+ cohort_ids: list[int] = []
+ for group in current_filters.get("groups", []):
+ new_group = deepcopy(group)
+ if new_group.get(marker_key) is not True:
+ new_groups.append(new_group)
+ continue
+ new_group.pop(marker_key, None)
+ cohort_id = new_group.pop(cohort_key, None)
+ if cohort_id is not None:
+ cohort_ids.append(cohort_id)
+ new_group["properties"] = [
+ condition
+ for condition in new_group.get("properties", [])
+ if not (
+ condition.get("type") == "cohort"
+ and condition.get("key") == "id"
+ and condition.get("value") == cohort_id
+ )
+ ]
+ description = new_group.get("description")
+ if isinstance(description, str) and marker_note in description:
+ stripped_description = description.replace(marker_note, "").strip()
+ if stripped_description:
+ new_group["description"] = stripped_description
+ else:
+ # The restriction added the description outright — restore its absence.
+ del new_group["description"]
+ new_groups.append(new_group)
+ return {**current_filters, "groups": new_groups}, list(dict.fromkeys(cohort_ids))
+
+
+def groups_carry_restriction_marker(current_filters: dict, *, marker_key: str) -> bool:
+ """Whether EVERY release group carries the ``marker_key`` restriction stamp.
+
+ Checks only the stamp, not the AND'd cohort condition itself — a manually edited group
+ could keep the stamp after losing the condition.
+
+ All-groups (not any-group) so that adding or editing an unstamped group reads as the
+ restriction being lifted; an empty ``groups`` list is not restricted (there is nothing
+ holding anyone back).
+ """
+ groups = current_filters.get("groups", [])
+ return bool(groups) and all(group.get(marker_key) is True for group in groups)
+
+
+def group_cohort_restriction_blocker(current_filters: dict) -> CohortRestrictionBlocker | None:
+ """Why the flag's release groups can't be reversibly narrowed to a person cohort, or None.
+
+ Encodes flag-matcher evaluation-order knowledge so consumers don't recompute it:
+
+ - ``group_aggregation``: the flag aggregates by groups, not persons, so a person cohort
+ cannot narrow who it serves.
+ - ``holdout``: holdout assignment is evaluated before release conditions, so narrowing
+ the groups cannot stop entry through the holdout.
+ - ``super_groups``: early-access enrollment (super groups) is evaluated before release
+ conditions too.
+ - ``no_groups``: without release conditions there is nothing to narrow — the restriction
+ would be a no-op and could never be detected from the group stamps.
+
+ Checked in that order; the first blocker wins.
+ """
+ if current_filters.get("aggregation_group_type_index") is not None:
+ return "group_aggregation"
+ if current_filters.get("holdout") or current_filters.get("holdout_groups"):
+ return "holdout"
+ if current_filters.get("super_groups"):
+ return "super_groups"
+ if not current_filters.get("groups"):
+ return "no_groups"
+ return None
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index 14452c58cd47..2a592a17458d 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -1,6 +1,9 @@
+from copy import deepcopy
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.constants import AvailableFeature
@@ -13,6 +16,12 @@ from products.feature_flags.backend.facade.api import (
flag_disable_requires_approval,
ship_variant,
)
+from products.feature_flags.backend.facade.filters import (
+ group_cohort_restriction_blocker,
+ groups_carry_restriction_marker,
+ restrict_groups_to_cohort,
+ strip_group_cohort_restriction,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -217,3 +226,76 @@ class TestRollOutVariant:
assert result["groups"][1:] == [{"properties": [], "rollout_percentage": 100}]
assert result["payloads"] == current_filters["payloads"]
assert result["aggregation_group_type_index"] == 1
+
+
+MARKER_KWARGS = {"marker_key": "restricted", "cohort_key": "restricted_cohort", "marker_note": "Restricted."}
+
+
+class TestFilterTransforms:
+ def test_restrict_then_strip_round_trips(self):
+ original = {
+ "groups": [
+ {"properties": [{"key": "email", "type": "person", "value": "@posthog.com"}], "rollout_percentage": 50},
+ {"properties": [], "rollout_percentage": 100, "description": "User prose"},
+ ],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ }
+ pristine = deepcopy(original)
+
+ restricted = restrict_groups_to_cohort(original, 42, **MARKER_KWARGS)
+
+ assert all(group["restricted"] is True for group in restricted["groups"])
+ assert all(group["restricted_cohort"] == 42 for group in restricted["groups"])
+ assert all(group["properties"][-1]["value"] == 42 for group in restricted["groups"])
+ assert restricted["groups"][0]["description"] == "Restricted."
+ assert restricted["groups"][1]["description"] == "Restricted. User prose"
+ assert original == pristine
+
+ stripped, cohort_ids = strip_group_cohort_restriction(restricted, **MARKER_KWARGS)
+
+ # Exact round-trip, including restored absence of the added description key —
+ # and the shared cohort id reported once, not per group.
+ assert stripped == pristine
+ assert cohort_ids == [42]
+
+ def test_strip_leaves_unstamped_groups_and_user_cohort_conditions_untouched(self):
+ user_cohort = {"key": "id", "type": "cohort", "value": 7, "operator": "in"}
+ filters = {
+ "groups": [
+ {
+ "properties": [user_cohort, {"key": "id", "type": "cohort", "value": 42, "operator": "in"}],
+ "restricted": True,
+ "restricted_cohort": 42,
+ "description": "Restricted.",
+ },
+ {"properties": [user_cohort], "rollout_percentage": 100},
+ ]
+ }
+
+ stripped, cohort_ids = strip_group_cohort_restriction(filters, **MARKER_KWARGS)
+
+ assert cohort_ids == [42]
+ assert stripped["groups"][0] == {"properties": [user_cohort]}
+ assert stripped["groups"][1] == filters["groups"][1]
+
+ @parameterized.expand(
+ [
+ ("all_stamped", [{"restricted": True}, {"restricted": True}], True),
+ ("one_unstamped", [{"restricted": True}, {}], False),
+ ("empty_groups", [], False),
+ ]
+ )
+ def test_groups_carry_restriction_marker(self, _name: str, groups: list[dict], expected: bool):
+ assert groups_carry_restriction_marker({"groups": groups}, marker_key="restricted") is expected
+
+ @parameterized.expand(
+ [
+ ("group_aggregation_wins", {"aggregation_group_type_index": 1, "holdout": {"id": 1}}, "group_aggregation"),
+ ("holdout", {"holdout_groups": [{}], "groups": [{}]}, "holdout"),
+ ("super_groups", {"super_groups": [{}], "groups": [{}]}, "super_groups"),
+ ("no_groups", {"groups": []}, "no_groups"),
+ ("plain_groups_ok", {"groups": [{"properties": []}]}, None),
+ ]
+ )
+ def test_group_cohort_restriction_blocker(self, _name: str, filters: dict, expected: str | None):
+ assert group_cohort_restriction_blocker(filters) == expected
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d933877c4b45..a7c5b571d42d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24373,6 +24373,8 @@ export namespace Schemas {
readonly status: ExperimentStatusEnum;
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy: boolean;
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure: boolean;
/**
* The effective access level the user has for this object
* @nullable
@@ -25018,6 +25020,8 @@ export namespace Schemas {
readonly status: ExperimentStatusEnum;
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy: boolean;
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure: boolean;
/**
* The effective access level the user has for this object
* @nullable
@@ -43177,6 +43181,8 @@ export namespace Schemas {
readonly status?: ExperimentStatusEnum;
/** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
readonly is_legacy?: boolean;
+ /** Whether enrollment can be frozen right now: the experiment must be running (not draft, paused, stopped, or already frozen) and its feature flag must have release conditions that a person cohort can narrow (no group aggregation, no holdout, no early access conditions). */
+ readonly can_freeze_exposure?: boolean;
/**
* The effective access level the user has for this object
* @nullable