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 winning-variant rollout transform behind the facade (#70122)

Anders423b77a50275
diff --git a/ee/hogai/eval/sandboxed/experiments/seeders.py b/ee/hogai/eval/sandboxed/experiments/seeders.py
index 177f0ddecded..7308f1e9e89f 100644
--- a/ee/hogai/eval/sandboxed/experiments/seeders.py
+++ b/ee/hogai/eval/sandboxed/experiments/seeders.py
@@ -49,8 +49,8 @@ ENDED_EXPERIMENT_NAME = "checkout cta v2"
# Verbatim string PostHog writes onto a feature flag's `properties[].description`
-# when an experiment is shipped, see _transform_filters_for_winning_variant in
-# ExperimentService
+# when an experiment is shipped, see the ship_flag_variant call in
+# products.experiments.backend.experiment_service
SHIP_VARIANT_FLIP_SIGNATURE = "Added automatically when the experiment was ended to keep only one variant."
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 3f839cad3473..21f3cd140e82 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -84,6 +84,7 @@ from products.feature_flags.backend.facade.api import (
create_flag,
flag_disable_requires_approval,
set_flag_active,
+ ship_variant as ship_flag_variant,
unarchive_flag,
update_flag,
user_can_edit_flag,
@@ -2593,27 +2594,28 @@ class ExperimentService:
if not flag:
raise ValidationError("Experiment does not have a linked feature flag.")
- # Validate variant_key exists on the flag
- variants = flag.filters.get("multivariate", {}).get("variants", [])
- if not any(v["key"] == variant_key for v in variants):
- raise ValidationError(f"Variant '{variant_key}' not found on feature flag.")
-
# A frozen experiment's release groups carry a machine-added snapshot-cohort condition.
# 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)
- new_filters = self._transform_filters_for_winning_variant(
- base_filters, variant_key, release_to_everyone=release_to_everyone
- )
-
# 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.
- update_flag(flag, {"filters": new_filters}, team=self.team, user=self.user, request=request)
+ # the user retries. base_filters folds the freeze-strip above into
+ # this same write: one approval-gate trip, one activity-log entry.
+ ship_flag_variant(
+ flag,
+ variant_key,
+ release_to_everyone=release_to_everyone,
+ release_condition_description="Added automatically when the experiment was ended to keep only one variant.",
+ base_filters=base_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.
@@ -2643,51 +2645,6 @@ class ExperimentService:
return experiment
- @staticmethod
- def _transform_filters_for_winning_variant(
- current_filters: dict,
- variant_key: str,
- *,
- release_to_everyone: bool = False,
- ) -> dict:
- """Rewrite flag filters so the selected variant gets 100% of the variant distribution.
-
- When ``release_to_everyone`` is False (default), existing release conditions on
- the flag are preserved untouched: the variant is served only to users who
- already match them, and any per-user variant overrides keep applying.
-
- When ``release_to_everyone`` is True, a catch-all release condition is prepended
- that rolls the variant out to 100% of users — note that under top-down
- first-match evaluation this overrides any existing release conditions and
- per-user variant overrides below it.
- """
- groups = list(current_filters.get("groups", []))
- if release_to_everyone:
- groups = [
- {
- "properties": [],
- "rollout_percentage": 100,
- "description": "Added automatically when the experiment was ended to keep only one variant.",
- },
- *groups,
- ]
-
- return {
- "aggregation_group_type_index": current_filters.get("aggregation_group_type_index"),
- "payloads": current_filters.get("payloads", {}),
- "multivariate": {
- "variants": [
- {
- "key": v["key"],
- "rollout_percentage": 100 if v["key"] == variant_key else 0,
- **({"name": v["name"]} if v.get("name") else {}),
- }
- for v in current_filters.get("multivariate", {}).get("variants", [])
- ],
- },
- "groups": groups,
- }
-
def _report_experiment_variant_shipped(
self,
experiment: Experiment,
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index e9d84ec6569a..65fc143ddc84 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -4141,7 +4141,7 @@ 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(
- "products.experiments.backend.experiment_service.update_flag",
+ "products.experiments.backend.experiment_service.ship_flag_variant",
side_effect=ValidationError("boom"),
):
with self.assertRaises(ValidationError):
@@ -4338,125 +4338,6 @@ class TestExperimentService(APIBaseTest):
assert "experiment completed" not in event_names
assert "experiment stopped" not in event_names
- # ------------------------------------------------------------------
- # Transform filters for winning variant
- # ------------------------------------------------------------------
-
- def test_transform_filters_default_preserves_groups(self):
- current_filters = {
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "payloads": {},
- "multivariate": {
- "variants": [
- {"key": "control", "name": "Control Group", "rollout_percentage": 50},
- {"key": "test", "name": "Test Variant", "rollout_percentage": 50},
- ]
- },
- "aggregation_group_type_index": None,
- }
-
- result = ExperimentService._transform_filters_for_winning_variant(current_filters, "test")
-
- # Variant distribution flipped
- assert result["multivariate"]["variants"] == [
- {"key": "control", "name": "Control Group", "rollout_percentage": 0},
- {"key": "test", "name": "Test Variant", "rollout_percentage": 100},
- ]
- # Groups preserved exactly — no catch-all prepended in default mode
- assert result["groups"] == current_filters["groups"]
- assert result["payloads"] == {}
- assert result["aggregation_group_type_index"] is None
-
- def test_transform_filters_release_to_everyone_prepends_catch_all(self):
- current_filters = {
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "payloads": {},
- "multivariate": {
- "variants": [
- {"key": "control", "name": "Control Group", "rollout_percentage": 50},
- {"key": "test", "name": "Test Variant", "rollout_percentage": 50},
- ]
- },
- "aggregation_group_type_index": None,
- }
-
- result = ExperimentService._transform_filters_for_winning_variant(
- current_filters, "test", release_to_everyone=True
- )
-
- assert result["multivariate"]["variants"] == [
- {"key": "control", "name": "Control Group", "rollout_percentage": 0},
- {"key": "test", "name": "Test Variant", "rollout_percentage": 100},
- ]
- assert result["groups"][0] == {
- "properties": [],
- "rollout_percentage": 100,
- "description": "Added automatically when the experiment was ended to keep only one variant.",
- }
- assert result["groups"][1:] == [{"properties": [], "rollout_percentage": 100}]
- assert result["payloads"] == {}
- assert result["aggregation_group_type_index"] is None
-
- def test_transform_filters_default_does_not_mutate_input(self):
- """Defensive: ensure the function returns a new groups list without mutating caller's filters."""
- original_groups = [{"properties": [], "rollout_percentage": 50}]
- current_filters = {
- "groups": original_groups,
- "multivariate": {
- "variants": [
- {"key": "control", "rollout_percentage": 50},
- {"key": "test", "rollout_percentage": 50},
- ]
- },
- }
-
- result = ExperimentService._transform_filters_for_winning_variant(current_filters, "test")
-
- # Caller's list reference is untouched
- assert current_filters["groups"] is original_groups
- # Result's groups equals original by value but is a distinct list object
- assert result["groups"] == original_groups
- assert result["groups"] is not original_groups
-
- def test_transform_filters_multiple_variants_with_payloads(self):
- current_filters = {
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "payloads": {
- "test_1": "{key: 'test_1'}",
- "test_2": "{key: 'test_2'}",
- "test_3": "{key: 'test_3'}",
- "control": "{key: 'control'}",
- },
- "multivariate": {
- "variants": [
- {"key": "control", "name": "This is control", "rollout_percentage": 25},
- {"key": "test_1", "name": "This is test_1", "rollout_percentage": 25},
- {"key": "test_2", "name": "This is test_2", "rollout_percentage": 25},
- {"key": "test_3", "name": "This is test_3", "rollout_percentage": 25},
- ]
- },
- "aggregation_group_type_index": 1,
- }
-
- result = ExperimentService._transform_filters_for_winning_variant(
- current_filters, "control", release_to_everyone=True
- )
-
- assert result["multivariate"]["variants"] == [
- {"key": "control", "name": "This is control", "rollout_percentage": 100},
- {"key": "test_1", "name": "This is test_1", "rollout_percentage": 0},
- {"key": "test_2", "name": "This is test_2", "rollout_percentage": 0},
- {"key": "test_3", "name": "This is test_3", "rollout_percentage": 0},
- ]
- assert result["groups"][0] == {
- "properties": [],
- "rollout_percentage": 100,
- "description": "Added automatically when the experiment was ended to keep only one variant.",
- }
- assert result["groups"][1:] == [{"properties": [], "rollout_percentage": 100}]
- assert result["payloads"] == current_filters["payloads"]
- assert result["aggregation_group_type_index"] == 1
-
# ------------------------------------------------------------------
# Exposure cohort
# ------------------------------------------------------------------
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
index 3110e7f83054..984507cd52ab 100644
--- a/products/feature_flags/backend/facade/api.py
+++ b/products/feature_flags/backend/facade/api.py
@@ -18,6 +18,8 @@ ChangeRequest. Run gated writes before/outside any transaction wrapping your own
from typing import Any
+from rest_framework.exceptions import ValidationError
+
from posthog.api.utils import ServiceRequest
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -116,6 +118,98 @@ def unarchive_flag(flag: FeatureFlag, *, team: Team, user: Any, request: Any | N
return update_flag(flag, {"archived": False}, team=team, user=user, request=request)
+def _roll_out_variant(
+ current_filters: dict,
+ variant_key: str,
+ *,
+ release_to_everyone: bool = False,
+ release_condition_description: str | None = None,
+) -> dict:
+ """Rewrite flag filters so the selected variant gets 100% of the variant distribution.
+
+ When ``release_to_everyone`` is False (default), existing release conditions on
+ the flag are preserved untouched: the variant is served only to users who
+ already match them, and any per-user variant overrides keep applying.
+
+ When ``release_to_everyone`` is True, a catch-all release condition is prepended
+ that rolls the variant out to 100% of users — note that under top-down
+ first-match evaluation this overrides any existing release conditions and
+ per-user variant overrides below it. ``release_condition_description`` is set as
+ the description of that catch-all condition, so callers can say why it was added;
+ it has no effect unless ``release_to_everyone`` is True.
+ """
+ groups = list(current_filters.get("groups", []))
+ if release_to_everyone:
+ catch_all: dict[str, Any] = {"properties": [], "rollout_percentage": 100}
+ if release_condition_description is not None:
+ catch_all["description"] = release_condition_description
+ groups = [catch_all, *groups]
+
+ return {
+ "aggregation_group_type_index": current_filters.get("aggregation_group_type_index"),
+ "payloads": current_filters.get("payloads", {}),
+ "multivariate": {
+ "variants": [
+ {
+ "key": v["key"],
+ "rollout_percentage": 100 if v["key"] == variant_key else 0,
+ **({"name": v["name"]} if v.get("name") else {}),
+ }
+ for v in current_filters.get("multivariate", {}).get("variants", [])
+ ],
+ },
+ "groups": groups,
+ }
+
+
+def ship_variant(
+ flag: FeatureFlag,
+ variant_key: str,
+ *,
+ team: Team,
+ user: Any,
+ request: Any | None = None,
+ release_to_everyone: bool = False,
+ release_condition_description: str | None = None,
+ base_filters: dict | None = None,
+) -> FeatureFlag:
+ """Roll ``variant_key`` out at 100% of the flag's variant distribution, through the gated write.
+
+ By default (``release_to_everyone=False``) existing release conditions on the flag
+ are preserved untouched — the variant is served only to users who already match
+ them. Pass ``release_to_everyone=True`` to also prepend a catch-all release
+ condition that rolls the variant out to 100% of users (overrides any existing
+ release conditions and per-user variant overrides), with
+ ``release_condition_description`` as its description — that parameter has no
+ effect unless ``release_to_everyone`` is True.
+
+ ``base_filters`` lets a caller fold companion adjustments it already computed from
+ the flag's current filters into the same gated write; defaults to the flag's
+ current filters. ``variant_key`` is validated against ``base_filters`` (not
+ ``flag.filters``), so its ``multivariate.variants`` must match the flag's own.
+ The parameter is transitional: it exists so the experiments-side freeze-strip
+ folds into a single gated write, and goes away once that strip moves flag-side.
+
+ Raises ValidationError when the variant doesn't exist on the flag, and
+ ApprovalRequired when a policy gates the write — the flag is left untouched
+ in both cases.
+ """
+ filters = base_filters if base_filters is not None else (flag.filters or {})
+
+ # Validate variant_key exists on the flag
+ variants = filters.get("multivariate", {}).get("variants", [])
+ if not any(v["key"] == variant_key for v in variants):
+ raise ValidationError(f"Variant '{variant_key}' not found on feature flag.")
+
+ new_filters = _roll_out_variant(
+ filters,
+ variant_key,
+ release_to_everyone=release_to_everyone,
+ release_condition_description=release_condition_description,
+ )
+ return update_flag(flag, {"filters": new_filters}, 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:
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index e93e4b39e7d9..14452c58cd47 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -7,18 +7,23 @@ 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.facade.api import (
+ _roll_out_variant,
+ archive_flag,
+ flag_disable_requires_approval,
+ ship_variant,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
class TestFeatureFlagFacadeGatedWrites(APIBaseTest):
- def _create_flag(self, *, active: bool = True) -> FeatureFlag:
+ def _create_flag(self, *, active: bool = True, filters: dict | None = None) -> FeatureFlag:
return FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
key="facade-gated-flag",
active=active,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ filters=filters if filters is not None else {"groups": [{"properties": [], "rollout_percentage": 100}]},
)
def test_archive_active_flag_with_disable_succeeds(self):
@@ -53,6 +58,28 @@ class TestFeatureFlagFacadeGatedWrites(APIBaseTest):
assert flag.archived is False
assert flag.active is True
+ def test_ship_variant_without_base_filters_uses_flag_filters(self):
+ flag = self._create_flag(
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ }
+ )
+
+ ship_variant(flag, "test", team=self.team, user=self.user)
+
+ flag.refresh_from_db()
+ variants = flag.filters["multivariate"]["variants"]
+ assert {v["key"]: v["rollout_percentage"] for v in variants} == {"control": 0, "test": 100}
+ # Default mode: no catch-all prepended, the existing release condition is preserved
+ assert len(flag.filters["groups"]) == 1
+ assert flag.filters["groups"][0]["rollout_percentage"] == 100
+
@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 = [
@@ -75,3 +102,118 @@ class TestFeatureFlagFacadeGatedWrites(APIBaseTest):
flag.refresh_from_db()
assert flag.archived is False
assert flag.active is True
+
+
+class TestRollOutVariant:
+ def test_transform_filters_default_preserves_groups(self):
+ current_filters = {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {},
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control Group", "rollout_percentage": 50},
+ {"key": "test", "name": "Test Variant", "rollout_percentage": 50},
+ ]
+ },
+ "aggregation_group_type_index": None,
+ }
+
+ result = _roll_out_variant(current_filters, "test")
+
+ # Variant distribution flipped
+ assert result["multivariate"]["variants"] == [
+ {"key": "control", "name": "Control Group", "rollout_percentage": 0},
+ {"key": "test", "name": "Test Variant", "rollout_percentage": 100},
+ ]
+ # Groups preserved exactly — no catch-all prepended in default mode
+ assert result["groups"] == current_filters["groups"]
+ assert result["payloads"] == {}
+ assert result["aggregation_group_type_index"] is None
+
+ def test_transform_filters_release_to_everyone_prepends_catch_all(self):
+ current_filters = {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {},
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control Group", "rollout_percentage": 50},
+ {"key": "test", "name": "Test Variant", "rollout_percentage": 50},
+ ]
+ },
+ "aggregation_group_type_index": None,
+ }
+
+ result = _roll_out_variant(
+ current_filters,
+ "test",
+ release_to_everyone=True,
+ release_condition_description="Rolled out by the caller.",
+ )
+
+ assert result["multivariate"]["variants"] == [
+ {"key": "control", "name": "Control Group", "rollout_percentage": 0},
+ {"key": "test", "name": "Test Variant", "rollout_percentage": 100},
+ ]
+ assert result["groups"][0] == {
+ "properties": [],
+ "rollout_percentage": 100,
+ "description": "Rolled out by the caller.",
+ }
+ assert result["groups"][1:] == [{"properties": [], "rollout_percentage": 100}]
+ assert result["payloads"] == {}
+ assert result["aggregation_group_type_index"] is None
+
+ def test_transform_filters_default_does_not_mutate_input(self):
+ """Defensive: ensure the function returns a new groups list without mutating caller's filters."""
+ original_groups = [{"properties": [], "rollout_percentage": 50}]
+ current_filters = {
+ "groups": original_groups,
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ }
+
+ result = _roll_out_variant(current_filters, "test")
+
+ # Caller's list reference is untouched
+ assert current_filters["groups"] is original_groups
+ # Result's groups equals original by value but is a distinct list object
+ assert result["groups"] == original_groups
+ assert result["groups"] is not original_groups
+
+ def test_transform_filters_multiple_variants_with_payloads(self):
+ current_filters = {
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {
+ "test_1": "{key: 'test_1'}",
+ "test_2": "{key: 'test_2'}",
+ "test_3": "{key: 'test_3'}",
+ "control": "{key: 'control'}",
+ },
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "This is control", "rollout_percentage": 25},
+ {"key": "test_1", "name": "This is test_1", "rollout_percentage": 25},
+ {"key": "test_2", "name": "This is test_2", "rollout_percentage": 25},
+ {"key": "test_3", "name": "This is test_3", "rollout_percentage": 25},
+ ]
+ },
+ "aggregation_group_type_index": 1,
+ }
+
+ result = _roll_out_variant(current_filters, "control", release_to_everyone=True)
+
+ assert result["multivariate"]["variants"] == [
+ {"key": "control", "name": "This is control", "rollout_percentage": 100},
+ {"key": "test_1", "name": "This is test_1", "rollout_percentage": 0},
+ {"key": "test_2", "name": "This is test_2", "rollout_percentage": 0},
+ {"key": "test_3", "name": "This is test_3", "rollout_percentage": 0},
+ ]
+ # No description on the catch-all when the caller doesn't pass one
+ assert result["groups"][0] == {"properties": [], "rollout_percentage": 100}
+ assert result["groups"][1:] == [{"properties": [], "rollout_percentage": 100}]
+ assert result["payloads"] == current_filters["payloads"]
+ assert result["aggregation_group_type_index"] == 1