:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(feature-flags): Block removing variants from a flag backing a running experiment (#84317)
Juraj Majerik4f9e36ddfcdc
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 553884e6ef74..945f9223c1d1 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1630,6 +1630,32 @@ class FeatureFlagSerializer(if early_exit and not previously_enabled and not self._is_early_exit_enabled():raise serializers.ValidationError("early_exit is not available for this organization.")+ # A running experiment reads its variants from this flag, so a save that drops any+ # of its variant keys (a rename counts: it's a drop plus an add) breaks the+ # experiment's exposure and results queries. Adding variants and changing rollout+ # percentages stay allowed — shipping a winner rolls out 100/0 without dropping+ # keys. Mirrors the deletion guard in update(): draft/stopped/completed experiments+ # don't block, so a flag can still be simplified once its experiment is over.+ # Checked on the merged state — partial updates that don't touch multivariate keep+ # the stored variants and pass through.+ if self.instance is not None:+ stored_keys = [+ v.get("key") for v in ((self.instance.filters or {}).get("multivariate") or {}).get("variants") or []+ ]+ merged_keys = {v.get("key") for v in (merged.get("multivariate") or {}).get("variants") or []}+ removed_keys = [k for k in stored_keys if k not in merged_keys]+ if removed_keys:+ running_experiments = [+ exp for exp in self.instance.experiment_set.filter(deleted=False) if exp.is_running+ ]+ if running_experiments:+ experiment_names = ", ".join(f'"{exp.name}" (ID: {exp.id})' for exp in running_experiments)+ removed = ", ".join(f"'{k}'" for k in removed_keys)+ raise serializers.ValidationError(+ f"Cannot remove variant(s) {removed} from a feature flag that is linked to running "+ f"experiment(s): {experiment_names}. Please stop the experiment(s) before removing variants."+ )+# The normalization and the two contextual checks below ran on every write before# enforcement, junk shapes and all, so they stay outside the structurally_valid gate:# a stored-violating flag in log-only mode must not slip a dependency cycle past themdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex abbdff7d74c1..4f2791a3941f 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -4061,6 +4061,120 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):assert flag.deleted is Trueassert flag.key == f"{_name}-exp-flag:deleted:{flag.id}"+ EXPERIMENT_FLAG_FILTERS = {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ }++ def test_remove_variants_blocked_with_running_experiment(self):+ flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="exp-variants-flag", filters=self.EXPERIMENT_FLAG_FILTERS+ )+ exp = Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=flag, name="My experiment", start_date=now()+ )+ # The flag editor serializes a boolean flag as "multivariate": null.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {**self.EXPERIMENT_FLAG_FILTERS, "multivariate": None}},+ )+ assert response.status_code == 400+ assert (+ response.json()["detail"]+ == f"Cannot remove variant(s) 'control', 'test' from a feature flag that is linked to running experiment(s): \"My experiment\" (ID: {exp.id}). Please stop the experiment(s) before removing variants."+ )+ flag.refresh_from_db()+ assert flag.filters["multivariate"] == self.EXPERIMENT_FLAG_FILTERS["multivariate"]++ def test_rename_variant_blocked_with_running_experiment(self):+ # A rename is a drop plus an add of a variant key, so it must be blocked too.+ flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="exp-rename-flag", filters=self.EXPERIMENT_FLAG_FILTERS+ )+ Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=flag, name="My experiment", start_date=now()+ )+ renamed = {+ **self.EXPERIMENT_FLAG_FILTERS,+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "treatment", "rollout_percentage": 50},+ ]+ },+ }+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"filters": renamed})+ assert response.status_code == 400+ assert "Cannot remove variant(s) 'test'" in response.json()["detail"]++ def test_add_variant_and_change_rollout_allowed_with_running_experiment(self):+ # Shipping a winner rewrites rollouts to 100/0 and keeps every key — additions+ # and rollout changes must pass.+ flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="exp-rollout-flag", filters=self.EXPERIMENT_FLAG_FILTERS+ )+ Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=flag, name="My experiment", start_date=now()+ )+ reshaped = {+ **self.EXPERIMENT_FLAG_FILTERS,+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 0},+ {"key": "test", "rollout_percentage": 100},+ {"key": "extra", "rollout_percentage": 0},+ ]+ },+ }+ response = self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"filters": reshaped})+ assert response.status_code == 200, response.content++ @parameterized.expand(+ [+ ("draft", None, None),+ ("stopped", now(), now()),+ ]+ )+ def test_remove_variants_allowed_with_non_running_experiment(self, _name, start_date, end_date):+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=f"{_name}-variants-flag",+ filters=self.EXPERIMENT_FLAG_FILTERS,+ )+ Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=flag, start_date=start_date, end_date=end_date+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {**self.EXPERIMENT_FLAG_FILTERS, "multivariate": None}},+ )+ assert response.status_code == 200, response.content+ flag.refresh_from_db()+ assert flag.filters.get("multivariate") is None++ def test_partial_update_keeps_variants_with_running_experiment(self):+ # Updates that don't touch multivariate merge the stored variants back in and+ # must pass — the experiments service flips flags through this serializer.+ flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="exp-partial-flag", filters=self.EXPERIMENT_FLAG_FILTERS+ )+ Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=flag, name="My experiment", start_date=now()+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}, "active": True},+ )+ assert response.status_code == 200, response.content+ flag.refresh_from_db()+ assert flag.filters["multivariate"] == self.EXPERIMENT_FLAG_FILTERS["multivariate"]+def test_soft_delete_flag_blocked_when_used_in_replay_settings(self):flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="replay-flag")# Set the flag as the session recording linked flag