:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): add excluded_variants column, dual-write from parameters (#65123)
Anders5c58b607e4ac
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.ambrindex e7ad8d2b923d..0c66d2d51d2b 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@@ -205,6 +205,7 @@# name: TestVisitorFieldSnapshots.test_primitive_fields_Experimentlist(['description',+ 'excluded_variants','exposure_criteria','feature_flag_auto_archived','filters',diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambrindex ddbf210004fa..8cdf1c146cdd 100644--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr@@ -339,6 +339,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",@@ -1089,6 +1090,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex f6ec446d1e3d..e17d7dd858b5 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -1,7 +1,7 @@"""Experiment service — single source of truth for experiment business logic."""from collections import defaultdict-from collections.abc import Mapping+from collections.abc import Iterable, Mappingfrom copy import deepcopyfrom datetime import date, datetime, timedeltafrom enum import Enum@@ -52,6 +52,7 @@ from products.experiments.backend.models.experiment import (ExperimentTimeseriesRecalculation,ExperimentToSavedMetric,experiment_has_legacy_metrics,+ get_excluded_variants,holdout_filters_for_flag,)from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig@@ -208,6 +209,21 @@ class ExperimentService:variant_keys = {v["key"] for v in variants}baseline_key = (parameters.get("stats_config") or {}).get("baseline_variant_key", "control")+ ExperimentService._validate_excluded_variant_keys(excluded_variants, variant_keys, baseline_key)++ @staticmethod+ def _validate_excluded_variant_keys(+ excluded_variants: list[str], variant_keys: Iterable[str], baseline_key: str+ ) -> None:+ """Semantic checks for excluded variants against an already-resolved variant set.++ Variant keys come from the linked feature flag (the source of truth), so the canonical+ `excluded_variants` path validates without re-sending `feature_flag_variants`.+ """+ if not excluded_variants:+ return++ variant_key_set = set(variant_keys)holdout_excluded = {k for k in excluded_variants if k.startswith("holdout-")}if holdout_excluded:@@ -216,13 +232,36 @@ class ExperimentService:if baseline_key in excluded_variants:raise ValidationError(f"baseline variant cannot be excluded ('{baseline_key}')")- unknown = set(excluded_variants) - variant_keys+ unknown = set(excluded_variants) - variant_key_setif unknown:raise ValidationError(f"unknown variants for this experiment: {sorted(unknown)}")- if not variant_keys - set(excluded_variants) - {baseline_key}:+ if not variant_key_set - set(excluded_variants) - {baseline_key}:raise ValidationError("at least one test variant must remain in analysis")+ @staticmethod+ def validate_excluded_variants(value: list[str] | None) -> None:+ """Shape check for the canonical excluded_variants list (the serializer also enforces+ this via ListField, but direct service callers don't go through it).++ Semantic checks (holdout/baseline/unknown/at-least-one-remains) run in create/update+ against the resolved feature-flag variants — see ``_validate_excluded_variant_keys``.+ """+ if value is None:+ return+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):+ raise ValidationError("excluded_variants must be a list of strings")++ @staticmethod+ def _merge_excluded_variants_into_parameters(parameters: dict | None, excluded_variants: list[str] | None) -> dict:+ """Mirror the canonical excluded_variants into the legacy `parameters` blob."""+ merged = dict(parameters or {})+ if excluded_variants is None:+ merged.pop("excluded_variants", None)+ else:+ merged["excluded_variants"] = list(excluded_variants)+ return merged+RUNNING_TIME_CALCULATION_KEYS = ("minimum_detectable_effect","recommended_running_time",@@ -730,6 +769,7 @@ class ExperimentService:type: str = "product",parameters: dict | None = None,running_time_calculation: dict | None = None,+ excluded_variants: list[str] | None = None,metrics: list[dict] | None = None,metrics_secondary: list[dict] | None = None,secondary_metrics: list[dict] | None = None,@@ -769,12 +809,19 @@ class ExperimentService:self.validate_variant_shapes(parameters)self.validate_variant_percentages(parameters)self.validate_running_time_calculation(running_time_calculation)+ self.validate_excluded_variants(excluded_variants)# Dual-write during the parameters deprecation window: running_time_calculation is# canonical, but the legacy calculator keys in `parameters` stay in sync for old readers.if running_time_calculation is not None:parameters = self._merge_running_time_calculation_into_parameters(parameters, running_time_calculation)else:running_time_calculation = self._running_time_calculation_from_parameters(parameters)+ # Same dual-write for excluded_variants: the canonical column wins over legacy+ # `parameters` when supplied; otherwise derive the column from `parameters`.+ if excluded_variants is not None:+ parameters = self._merge_excluded_variants_into_parameters(parameters, excluded_variants)+ else:+ excluded_variants = (parameters or {}).get("excluded_variants")self.validate_experiment_metrics(metrics)self.validate_experiment_metrics(metrics_secondary)self.validate_metric_action_ids(metrics, self.team.id)@@ -802,6 +849,13 @@ class ExperimentService:used_variant_keys = self._variant_keys(used_variants)self.validate_stats_config(stats_config, used_variant_keys)+ # Validate excluded_variants against the variants the flag actually ends up with,+ # mirroring the baseline check above. Resolving against the flag (not the request+ # payload) is what lets the excluded_variants path skip re-sending feature_flag_variants.+ if excluded_variants:+ baseline_key = (stats_config or {}).get("baseline_variant_key", "control")+ self._validate_excluded_variant_keys(excluded_variants, used_variant_keys, baseline_key)+team_config = self._get_team_experiments_config()stats_config = self._apply_stats_config_defaults(stats_config, team_config)exposure_criteria = self._apply_exposure_criteria_defaults(exposure_criteria)@@ -818,7 +872,7 @@ class ExperimentService:stats_method,exposure_criteria,only_count_matured_users=only_count_matured_users,- excluded_variants=(parameters or {}).get("excluded_variants"),+ excluded_variants=excluded_variants,)if metrics_secondary is not None:for metric in metrics_secondary:@@ -828,7 +882,7 @@ class ExperimentService:stats_method,exposure_criteria,only_count_matured_users=only_count_matured_users,- excluded_variants=(parameters or {}).get("excluded_variants"),+ excluded_variants=excluded_variants,)self.validate_no_duplicate_metric_uuids(metrics, metrics_secondary)@@ -858,6 +912,7 @@ class ExperimentService:"type": type,"parameters": parameters,"running_time_calculation": running_time_calculation,+ "excluded_variants": excluded_variants,"metrics": metrics if metrics is not None else [],"metrics_secondary": metrics_secondary if metrics_secondary is not None else [],"secondary_metrics": secondary_metrics if secondary_metrics is not None else [],@@ -1314,7 +1369,7 @@ class ExperimentService:experiment.start_date,experiment.stats_config,experiment.exposure_criteria,- excluded_variants=(experiment.parameters or {}).get("excluded_variants"),+ excluded_variants=get_excluded_variants(experiment),),)@@ -2155,6 +2210,17 @@ class ExperimentService:effective_stats_config = update_data.get("stats_config", experiment.stats_config)self.validate_stats_config(effective_stats_config, variant_keys)+ # Validate excluded_variants on the canonical column path against the resolved flag+ # variants — no feature_flag_variants resend required (the legacy+ # `parameters.excluded_variants` path is still validated in the serializer).+ if "excluded_variants" in update_data:+ new_excluded = update_data["excluded_variants"]+ if new_excluded:+ variant_keys = self._resolved_variant_keys(experiment, update_data)+ effective_stats_config = update_data.get("stats_config", experiment.stats_config)+ baseline_key = (effective_stats_config or {}).get("baseline_variant_key", "control")+ self._validate_excluded_variant_keys(new_excluded, variant_keys, baseline_key)+# Defense-in-depth: only validate the inline metric lists this update# is actually touching. Dedup-on-input has already made these lists# unique; validating the stored arrays would block a soft-delete (or any@@ -2167,8 +2233,16 @@ class ExperimentService:stats_config = update_data.get("stats_config", experiment.stats_config)exposure_criteria = update_data.get("exposure_criteria", experiment.exposure_criteria)only_count_matured_users = update_data.get("only_count_matured_users", experiment.only_count_matured_users)- new_parameters = update_data.get("parameters", experiment.parameters)- excluded_variants = (new_parameters or {}).get("excluded_variants")+ # Canonical excluded_variants for fingerprints: prefer an explicit column update, then+ # legacy parameters in the payload, then the stored canonical value. Computed here+ # (before the dual-write below) so a new client PATCHing only excluded_variants still+ # fingerprints with the new exclusions.+ if "excluded_variants" in update_data:+ excluded_variants = update_data["excluded_variants"]+ elif "parameters" in update_data:+ excluded_variants = (update_data["parameters"] or {}).get("excluded_variants")+ else:+ excluded_variants = get_excluded_variants(experiment)for metric_field in ["metrics", "metrics_secondary"]:metrics = update_data.get(metric_field, getattr(experiment, metric_field, None))@@ -2213,6 +2287,18 @@ class ExperimentService:update_data["parameters"])+ # --- excluded_variants dual-write -----------------------------------+ # Mirror the canonical excluded_variants column into legacy `parameters`. Runs after the+ # running-time block so it reads the already-merged `parameters` (they touch disjoint+ # keys). The column wins when both are sent.+ if "excluded_variants" in update_data:+ update_data["parameters"] = self._merge_excluded_variants_into_parameters(+ update_data.get("parameters", experiment.parameters),+ update_data["excluded_variants"],+ )+ elif "parameters" in update_data:+ update_data["excluded_variants"] = (update_data["parameters"] or {}).get("excluded_variants")+# --- apply changes and save ----------------------------------------for attr, value in update_data.items():setattr(experiment, attr, value)@@ -2266,6 +2352,7 @@ class ExperimentService:"filters","parameters","running_time_calculation",+ "excluded_variants","archived","deleted","secondary_metrics",@@ -2291,6 +2378,7 @@ class ExperimentService:raise ValidationError(f"Can't update keys: {', '.join(sorted(extra_keys))} on Experiment")self.validate_running_time_calculation(update_data.get("running_time_calculation"))+ self.validate_excluded_variants(update_data.get("excluded_variants"))if not experiment.is_draft:if "feature_flag_variants" in update_data.get("parameters", {}):diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.pyindex b57eda56b2d4..aaaaf6124ea0 100644--- a/products/experiments/backend/facade/api.py+++ b/products/experiments/backend/facade/api.py@@ -59,6 +59,7 @@ def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInputype=input_dto.type,parameters=input_dto.parameters,running_time_calculation=input_dto.running_time_calculation,+ excluded_variants=input_dto.excluded_variants,metrics=input_dto.metrics,metrics_secondary=input_dto.metrics_secondary,secondary_metrics=input_dto.secondary_metrics,diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex e28918b18c53..829002e7f790 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -34,6 +34,9 @@ class CreateExperimentInput:# recommended_sample_size, exposure_estimate_config)running_time_calculation: dict[str, Any] | None = None+ # Variant keys dropped from statistical analysis+ excluded_variants: list[str] | None = None+# Metrics configurationmetrics: list[dict] | None = Nonemetrics_secondary: list[dict] | None = Nonediff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.pyindex 3412c3a454e3..b5e38de6f18d 100644--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py@@ -44,7 +44,7 @@ from products.experiments.backend.hogql_queries.experiment_query_runner import (experiment_has_min_runtime_for_precomputation,)from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import Experiment, get_excluded_variantsfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfiglogger = structlog.get_logger(__name__)@@ -75,7 +75,7 @@ class ExperimentExposuresQueryRunner(QueryRunner):# Holdout is intentionally not appended: holdout users were never exposed to# the experiment, so they don't belong in the exposure chart. self.query.holdout# is still consulted by _calculate_srm for the holdout-adjusted rollout math.- self.excluded_variants = set((self.experiment.parameters or {}).get("excluded_variants") or [])+ self.excluded_variants = set(get_excluded_variants(self.experiment))multivariate_data = self.query.feature_flag.get("filters", {}).get("multivariate", {})self.variants = [variant.get("key")diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex 80711e89b8b1..3b1612b1fa0e 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -62,7 +62,7 @@ from products.experiments.backend.hogql_queries.utils import (split_baseline_and_test_variants,)from products.experiments.backend.metric_utils import get_default_metric_title-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import Experiment, get_excluded_variantsfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfiglogger = structlog.get_logger(__name__)@@ -152,7 +152,7 @@ class ExperimentQueryRunner(QueryRunner):# the experiment, so they don't belong in the metric scorecard.# self.experiment.holdout is still readable for code paths that need it# (e.g. the Distribution table on the Variants tab).- excluded_variants = set((self.experiment.parameters or {}).get("excluded_variants") or [])+ excluded_variants = set(get_excluded_variants(self.experiment))self.variants = [variant["key"] for variant in self.feature_flag.variants if variant["key"] not in excluded_variants]diff --git a/products/experiments/backend/migrations/0023_experiment_excluded_variants.py b/products/experiments/backend/migrations/0023_experiment_excluded_variants.pynew file mode 100644index 000000000000..8476e9c933f6--- /dev/null+++ b/products/experiments/backend/migrations/0023_experiment_excluded_variants.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.14 on 2026-06-22 11:42++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0022_experiment_feature_flag_auto_archived"),+ ]++ operations = [+ migrations.AddField(+ model_name="experiment",+ name="excluded_variants",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.TextField(), blank=True, null=True, size=None+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/0024_backfill_excluded_variants.py b/products/experiments/backend/migrations/0024_backfill_excluded_variants.pynew file mode 100644index 000000000000..868c82e85979--- /dev/null+++ b/products/experiments/backend/migrations/0024_backfill_excluded_variants.py@@ -0,0 +1,38 @@+from django.db import migrations+from django.db.models import Q++BATCH_SIZE = 1000+++def backfill_excluded_variants(apps, schema_editor):+ Experiment = apps.get_model("experiments", "Experiment")++ # AddField defaults existing rows to [], so copy the legacy parameters.excluded_variants+ # into the new column for rows that actually have exclusions. Re-running is a no-op:+ # once a row's column is populated it no longer matches the empty/null guard.+ base_queryset = Experiment.objects.filter(parameters__has_key="excluded_variants").filter(+ Q(excluded_variants__isnull=True) | Q(excluded_variants=[])+ )+ experiment_ids = list(base_queryset.values_list("id", flat=True).order_by("id"))++ for start in range(0, len(experiment_ids), BATCH_SIZE):+ batch_ids = experiment_ids[start : start + BATCH_SIZE]+ to_update = []+ for experiment in Experiment.objects.filter(id__in=batch_ids).only("id", "parameters", "excluded_variants"):+ value = (experiment.parameters or {}).get("excluded_variants")+ if not value: # legacy empty/None — the column default [] already matches+ continue+ experiment.excluded_variants = list(value)+ to_update.append(experiment)+ if to_update:+ Experiment.objects.bulk_update(to_update, ["excluded_variants"], batch_size=BATCH_SIZE)+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0023_experiment_excluded_variants"),+ ]++ operations = [+ migrations.RunPython(backfill_excluded_variants, migrations.RunPython.noop),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex e733f13a713a..1debd9fba141 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0022_experiment_feature_flag_auto_archived+0024_backfill_excluded_variantsdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 4cd016842585..21fd04847670 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any+from django.contrib.postgres.fields import ArrayFieldfrom django.db import modelsfrom django.db.models import QuerySetfrom django.utils import timezone@@ -78,6 +79,12 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.# which historically lived in `parameters`.running_time_calculation = models.JSONField(default=dict, null=True, blank=True)+ # Variant keys dropped from statistical analysis. Canonical home for what historically+ # lived in `parameters.excluded_variants`. No default on purpose: `null` means "never set"+ # (fall back to the legacy `parameters` mirror during the deprecation window), while `[]`+ # means an explicit "no exclusions". A `list` default would shadow the fallback.+ excluded_variants = ArrayField(models.TextField(), null=True, blank=True)+only_count_matured_users = models.BooleanField(default=False)status = models.CharField(@@ -208,6 +215,18 @@ def holdout_filters_for_flag(holdout_id: int | None, filters: list | None) -> di}+def get_excluded_variants(experiment: "Experiment") -> list[str]:+ """Variant keys dropped from statistical analysis.++ Canonical home is the `excluded_variants` column; falls back to the legacy+ `parameters` mirror during the deprecation window. A `None` column means "never set"+ (use the fallback); an explicit empty list is honored as "no exclusions".+ """+ if experiment.excluded_variants is not None:+ return list(experiment.excluded_variants)+ return list((experiment.parameters or {}).get("excluded_variants") or [])++LEGACY_METRIC_KINDS: frozenset[str] = frozenset({"ExperimentTrendsQuery", "ExperimentFunnelsQuery"})diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex f9f05c0911ce..24ccb6eb6879 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -38,6 +38,7 @@ from products.experiments.backend.models.experiment import (ExperimentHoldout,ExperimentMetricsRecalculation,experiment_has_legacy_metrics,+ get_excluded_variants,)from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICESfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer@@ -172,6 +173,17 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Mod"during the deprecation window."),)+ excluded_variants = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_null=True,+ help_text=(+ "Variant keys to exclude from metric result calculations. Excluded variants are still "+ "served to users but omitted from statistical analysis. The baseline variant and holdout "+ "pseudo-variants cannot be excluded. Canonical home for what historically lived in "+ "`parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window."+ ),+ )conclusion = serializers.ChoiceField(choices=["won", "lost", "inconclusive", "stopped_early", "invalid"],required=False,@@ -316,6 +328,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):"exposure_cohort","parameters","running_time_calculation",+ "excluded_variants","secondary_metrics","saved_metrics","saved_metrics_ids",@@ -413,7 +426,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):get_experiment_stats_method(instance),instance.exposure_criteria,only_count_matured_users=instance.only_count_matured_users,- excluded_variants=(instance.parameters or {}).get("excluded_variants"),+ excluded_variants=get_excluded_variants(instance),)return data@@ -434,6 +447,10 @@ class ExperimentSerializer(ExperimentBaseSerializer):ExperimentService.validate_running_time_calculation(value)return value+ def validate_excluded_variants(self, value):+ ExperimentService.validate_excluded_variants(value)+ return value+def validate_exposure_criteria(self, exposure_criteria: dict | None):ExperimentService.validate_experiment_exposure_criteria(exposure_criteria)return exposure_criteria@@ -466,6 +483,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):type=self.validated_data.get("type", "product"),parameters=self.validated_data.get("parameters"),running_time_calculation=self.validated_data.get("running_time_calculation"),+ excluded_variants=self.validated_data.get("excluded_variants"),metrics=self.validated_data.get("metrics"),metrics_secondary=self.validated_data.get("metrics_secondary"),secondary_metrics=self.validated_data.get("secondary_metrics"),@@ -504,6 +522,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):"type","parameters","running_time_calculation",+ "excluded_variants","metrics","metrics_secondary","secondary_metrics",@@ -583,6 +602,7 @@ class ExperimentBasicSerializer(ExperimentBaseSerializer):"exposure_cohort","parameters","running_time_calculation",+ "excluded_variants","archived","deleted","created_by",diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 306f7fb0f3c9..138489b86cfe 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -31,6 +31,7 @@ from products.experiments.backend.models.experiment import (ExperimentMetricResult,ExperimentSavedMetric,ExperimentTimeseriesRecalculation,+ get_excluded_variants,)from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer@@ -5396,3 +5397,46 @@ class TestValidateExperimentParametersExcludedVariants:def test_excluded_variants_without_feature_flag_variants_raises(self):with pytest.raises(ValidationError, match="requires feature_flag_variants in the same request"):ExperimentService.validate_experiment_parameters({"excluded_variants": ["test-1"]})+++class TestGetExcludedVariants:+ @pytest.mark.parametrize(+ "column,parameters,expected",+ [+ (None, None, []),+ (None, {}, []),+ # the column is canonical, including an explicit empty list+ (["test-2"], {"excluded_variants": ["legacy"]}, ["test-2"]),+ ([], {"excluded_variants": ["legacy"]}, []),+ # falls back to legacy parameters only when the column is None (never set)+ (None, {"excluded_variants": ["legacy"]}, ["legacy"]),+ ],+ )+ def test_precedence(self, column, parameters, expected):+ experiment = Experiment(excluded_variants=column, parameters=parameters)+ assert get_excluded_variants(experiment) == expected+++class TestValidateExcludedVariants:+ @pytest.mark.parametrize(+ "value",+ [+ None,+ [],+ ["test-2"],+ ["test-1", "test-2"],+ ],+ )+ def test_valid(self, value):+ ExperimentService.validate_excluded_variants(value)++ @pytest.mark.parametrize(+ "value",+ [+ "test-2",+ [123],+ ],+ )+ def test_invalid_raises(self, value):+ with pytest.raises(ValidationError, match="must be a list of strings"):+ ExperimentService.validate_excluded_variants(value)diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex e6ac698ca3fb..7546298d2cbf 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -7261,6 +7261,152 @@ class TestExperimentRunningTimeCalculation(APILicensedTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+class TestExperimentExcludedVariants(APILicensedTest):+ THREE_VARIANTS = [+ {"key": "control", "rollout_percentage": 34},+ {"key": "test-1", "rollout_percentage": 33},+ {"key": "test-2", "rollout_percentage": 33},+ ]++ def _create_experiment(self, **overrides: Any) -> dict:+ payload: dict[str, Any] = {+ "name": "Excluded variants experiment",+ "feature_flag_key": "excluded-variants-flag",+ "filters": {"events": [{"order": 0, "id": "$pageview"}], "properties": []},+ **overrides,+ }+ response = self.client.post(f"/api/projects/{self.team.id}/experiments/", payload)+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ return response.json()++ def test_create_with_legacy_parameters_populates_column(self):+ created = self._create_experiment(+ parameters={"feature_flag_variants": self.THREE_VARIANTS, "excluded_variants": ["test-2"]}+ )++ self.assertEqual(created["excluded_variants"], ["test-2"])++ experiment = Experiment.objects.get(pk=created["id"])+ self.assertEqual(experiment.excluded_variants, ["test-2"])+ assert experiment.parameters is not None+ self.assertEqual(experiment.parameters["excluded_variants"], ["test-2"])++ def test_create_with_excluded_variants_mirrors_into_parameters(self):+ created = self._create_experiment(+ parameters={"feature_flag_variants": self.THREE_VARIANTS},+ excluded_variants=["test-2"],+ )++ self.assertEqual(created["excluded_variants"], ["test-2"])++ experiment = Experiment.objects.get(pk=created["id"])+ assert experiment.parameters is not None+ self.assertEqual(experiment.parameters["excluded_variants"], ["test-2"])++ def test_update_excluded_variants_does_not_require_feature_flag_variants(self):+ """The headline of the parameters split: excluding a variant no longer requires+ re-sending feature_flag_variants, because validation resolves against the flag."""+ created = self._create_experiment(parameters={"feature_flag_variants": self.THREE_VARIANTS})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {"excluded_variants": ["test-2"]},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ experiment = Experiment.objects.get(pk=created["id"])+ self.assertEqual(experiment.excluded_variants, ["test-2"])+ # Legacy mirror updated, and the variants stored in parameters survive the merge+ assert experiment.parameters is not None+ self.assertEqual(experiment.parameters["excluded_variants"], ["test-2"])+ self.assertEqual(len(experiment.parameters["feature_flag_variants"]), 3)++ def test_update_excluded_variants_does_not_touch_feature_flag(self):+ created = self._create_experiment(parameters={"feature_flag_variants": self.THREE_VARIANTS})+ flag = FeatureFlag.objects.get(key="excluded-variants-flag")+ self.assertEqual(len(flag.filters["multivariate"]["variants"]), 3)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {"excluded_variants": ["test-2"]},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ flag.refresh_from_db()+ self.assertEqual(len(flag.filters["multivariate"]["variants"]), 3)++ def test_update_parameters_derives_column(self):+ created = self._create_experiment(parameters={"feature_flag_variants": self.THREE_VARIANTS})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {"parameters": {"feature_flag_variants": self.THREE_VARIANTS, "excluded_variants": ["test-2"]}},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ experiment = Experiment.objects.get(pk=created["id"])+ self.assertEqual(experiment.excluded_variants, ["test-2"])++ # parameters replaces wholesale, so dropping the key clears the canonical column too+ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {"parameters": {"feature_flag_variants": self.THREE_VARIANTS}},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ experiment.refresh_from_db()+ self.assertIsNone(experiment.excluded_variants)++ def test_excluded_variants_wins_when_both_sent(self):+ created = self._create_experiment(parameters={"feature_flag_variants": self.THREE_VARIANTS})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {+ "parameters": {"feature_flag_variants": self.THREE_VARIANTS, "excluded_variants": ["test-1"]},+ "excluded_variants": ["test-2"],+ },+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ experiment = Experiment.objects.get(pk=created["id"])+ self.assertEqual(experiment.excluded_variants, ["test-2"])+ assert experiment.parameters is not None+ self.assertEqual(experiment.parameters["excluded_variants"], ["test-2"])++ @parameterized.expand(+ [+ ("unknown_variant", ["does-not-exist"]),+ ("baseline_excluded", ["control"]),+ ("all_test_variants_excluded", ["test-1", "test-2"]),+ ]+ )+ def test_update_excluded_variants_validates_against_flag_variants(self, _name: str, excluded_variants: list):+ created = self._create_experiment(parameters={"feature_flag_variants": self.THREE_VARIANTS})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/experiments/{created['id']}/",+ {"excluded_variants": excluded_variants},+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())++ @parameterized.expand(+ [+ ("non_list", "test-2"),+ ("non_string_element", [123]),+ ]+ )+ def test_invalid_excluded_variants_rejected(self, _name: str, value):+ response = self.client.post(+ f"/api/projects/{self.team.id}/experiments/",+ {+ "name": "Invalid excluded variants",+ "feature_flag_key": "invalid-excluded-variants-flag",+ "excluded_variants": value,+ },+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++class TestCalculateRunningTimeEndpoint(APILicensedTest):def _calculate(self, payload: dict[str, Any]):return self.client.post(diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex fe6f11c03a29..67e7d9b47cc4 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -370,6 +370,11 @@ export interface ExperimentBasicApi {parameters?: ExperimentParametersApi | null/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculationApi | null+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | null/** Whether the experiment is archived. */archived?: boolean/** @nullable */@@ -675,6 +680,11 @@ export interface ExperimentApi {parameters?: ExperimentParametersApi | null/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculationApi | null+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | nullsecondary_metrics?: unknownreadonly saved_metrics: readonly ExperimentToSavedMetricApi[]/**@@ -776,6 +786,11 @@ export interface PatchedExperimentApi {parameters?: ExperimentParametersApi | null/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculationApi | null+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | nullsecondary_metrics?: unknownreadonly saved_metrics?: readonly ExperimentToSavedMetricApi[]/**diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex a3c3c639b124..3663f13ad5c9 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -1353,6 +1353,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",@@ -1768,6 +1769,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 8c534df8d3e1..201abb0ae7d0 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -3929,6 +3929,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",@@ -3968,6 +3969,7 @@"posthog_experiment"."stats_config","posthog_experiment"."scheduling_config","posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants","posthog_experiment"."only_count_matured_users","posthog_experiment"."status","posthog_experiment"."conclusion",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8ba7b675137e..da88c85102ab 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20675,6 +20675,11 @@ export namespace Schemas {parameters?: ExperimentParameters | null;/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculation | null;+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | null;secondary_metrics?: unknown;readonly saved_metrics: readonly ExperimentToSavedMetric[];/**@@ -20779,6 +20784,11 @@ export namespace Schemas {parameters?: ExperimentParameters | null;/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculation | null;+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | null;/** Whether the experiment is archived. */archived?: boolean;/** @nullable */@@ -35717,6 +35727,11 @@ export namespace Schemas {parameters?: ExperimentParameters | null;/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */running_time_calculation?: ExperimentRunningTimeCalculation | null;+ /**+ * Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.+ * @nullable+ */+ excluded_variants?: string[] | null;secondary_metrics?: unknown;readonly saved_metrics?: readonly ExperimentToSavedMetric[];/**diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 1c27c9f3b1e4..6978105ea7a5 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -376,6 +376,12 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.describe('Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window.'),+ excluded_variants: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.'+ ),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zod.array(zod.unknown())@@ -2758,6 +2764,12 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.describe('Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window.'),+ excluded_variants: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.'+ ),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zod.array(zod.unknown())@@ -5199,6 +5211,12 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod.describe('Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window.'),+ excluded_variants: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window.'+ ),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zod.array(zod.unknown())diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 2a0cebf73958..74fef3b820df 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -155,6 +155,7 @@ const ExperimentCreateSchema = ExperimentsCreateBody.omit({start_date: true,end_date: true,running_time_calculation: true,+ excluded_variants: true,secondary_metrics: true,saved_metrics_ids: true,filters: true,@@ -287,6 +288,9 @@ const experimentDuplicate = (): ToolBase<typeof ExperimentDuplicateSchema, unknoif (params.running_time_calculation !== undefined) {body['running_time_calculation'] = params.running_time_calculation}+ if (params.excluded_variants !== undefined) {+ body['excluded_variants'] = params.excluded_variants+ }if (params.secondary_metrics !== undefined) {body['secondary_metrics'] = params.secondary_metrics}@@ -777,6 +781,7 @@ const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id:start_date: true,end_date: true,feature_flag_key: true,+ excluded_variants: true,secondary_metrics: true,saved_metrics_ids: true,filters: true,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.jsonindex c10e9d3d38c8..a117fdafad63 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json@@ -70,6 +70,20 @@}]},+ "excluded_variants": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Variant keys to exclude from metric result calculations. Excluded variants are still served to users but omitted from statistical analysis. The baseline variant and holdout pseudo-variants cannot be excluded. Canonical home for what historically lived in `parameters.excluded_variants`; kept in sync with `parameters` during the deprecation window."+ },"exposure_criteria": {"anyOf": [{