: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): update experiment serializer and service to handle excluded variants (#60005)
Rodrigo Ilorod1a851ba3736
diff --git a/posthog/hogql_queries/experiments/experiment_metric_fingerprint.py b/posthog/hogql_queries/experiments/experiment_metric_fingerprint.pyindex a44c99245f4b..02941cae8cd9 100644--- a/posthog/hogql_queries/experiments/experiment_metric_fingerprint.py+++ b/posthog/hogql_queries/experiments/experiment_metric_fingerprint.py@@ -28,6 +28,7 @@ def compute_metric_fingerprint(stats_method: str | None = None,exposure_criteria: dict | None = None,only_count_matured_users: bool = False,+ excluded_variants: list[str] | None = None,) -> str:"""Compute fingerprint for a metric.@@ -37,6 +38,9 @@ def compute_metric_fingerprint(start_date: Experiment start datestats_methodexposure_criteria+ only_count_matured_users+ excluded_variants: Variant keys excluded from analysis — changing the set+ invalidates cached results since it alters which data is computedReturns:SHA256 hash string representing the metric fingerprint@@ -67,6 +71,9 @@ def compute_metric_fingerprint(if only_count_matured_users:fingerprint_data["only_count_matured_users"] = True+ if excluded_variants:+ fingerprint_data["excluded_variants"] = sorted(set(excluded_variants))+# Create deterministic JSON string with sorted keys at all levelsjson_str = json.dumps(fingerprint_data, sort_keys=True, separators=(",", ":"))diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 08f2648b6d89..afb43e44298f 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -190,6 +190,44 @@ class ExperimentService:"'key' to 'control'.")+ excluded_variants = parameters.get("excluded_variants")+ if excluded_variants is None:+ return++ if not isinstance(excluded_variants, list) or not all(isinstance(v, str) for v in excluded_variants):+ raise ValidationError("excluded_variants must be a list of strings")++ if not excluded_variants:+ return++ # `parameters` is replaced wholesale on update (see update_experiment:+ # `update_data.get("parameters", experiment.parameters)`), not merged — so a+ # PATCH that sets `excluded_variants` must also resend `feature_flag_variants`,+ # otherwise the stored object would have no variants at all. Surface that+ # explicitly rather than letting every key fall through to "unknown variants".+ if not variants:+ raise ValidationError(+ "excluded_variants requires feature_flag_variants in the same request — "+ "parameters are replaced as a whole on update, so send the full parameters object"+ )++ variant_keys = {v["key"] for v in variants}+ baseline_key = (parameters.get("stats_config") or {}).get("baseline_variant_key", "control")++ holdout_excluded = {k for k in excluded_variants if k.startswith("holdout-")}+ if holdout_excluded:+ raise ValidationError(f"cannot exclude holdout pseudo-variants: {sorted(holdout_excluded)}")++ if baseline_key in excluded_variants:+ raise ValidationError(f"baseline variant cannot be excluded ('{baseline_key}')")++ unknown = set(excluded_variants) - variant_keys+ if unknown:+ raise ValidationError(f"unknown variants for this experiment: {sorted(unknown)}")++ if not variant_keys - set(excluded_variants) - {baseline_key}:+ raise ValidationError("at least one test variant must remain in analysis")+EXPOSURE_CONFIG_KINDS = ("ExperimentEventExposureConfig", "ActionsNode")EXPOSURE_CONFIG_HINT = (@@ -672,6 +710,7 @@ class ExperimentService:stats_method,exposure_criteria,only_count_matured_users=only_count_matured_users,+ excluded_variants=(parameters or {}).get("excluded_variants"),)if metrics_secondary is not None:for metric in metrics_secondary:@@ -681,6 +720,7 @@ class ExperimentService:stats_method,exposure_criteria,only_count_matured_users=only_count_matured_users,+ excluded_variants=(parameters or {}).get("excluded_variants"),)self.validate_no_duplicate_metric_uuids(metrics, metrics_secondary)@@ -964,6 +1004,7 @@ class ExperimentService:stats_config: dict | None,exposure_criteria: dict | None,only_count_matured_users: bool = False,+ excluded_variants: list[str] | None = None,) -> list[dict]:"""Recompute fingerprints for a list of metrics. Returns a new list with updated fingerprints."""stats_method = "bayesian" if stats_config is None else stats_config.get("method", "bayesian")@@ -976,6 +1017,7 @@ class ExperimentService:stats_method,exposure_criteria,only_count_matured_users=only_count_matured_users,+ excluded_variants=excluded_variants,)updated.append(metric_copy)return updated@@ -1155,7 +1197,11 @@ class ExperimentService:experiment,metric_field,self._recompute_fingerprints(- metrics, experiment.start_date, experiment.stats_config, experiment.exposure_criteria+ metrics,+ experiment.start_date,+ experiment.stats_config,+ experiment.exposure_criteria,+ excluded_variants=(experiment.parameters or {}).get("excluded_variants"),),)@@ -1861,6 +1907,8 @@ 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")for metric_field in ["metrics", "metrics_secondary"]:metrics = update_data.get(metric_field, getattr(experiment, metric_field, None))@@ -1871,6 +1919,7 @@ class ExperimentService:stats_config,exposure_criteria,only_count_matured_users=only_count_matured_users,+ excluded_variants=excluded_variants,)# --- metric ordering sync + validation -----------------------------diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 801cadfc103c..682789bfad0b 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -148,11 +148,12 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSerequired=False,allow_null=True,help_text=(- "Variant definitions and rollout configuration. "- "Set feature_flag_variants to customize the split (default: 50/50 control/test). "- "Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. "- "Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. "- "Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ "Experiment parameters JSON. Supported keys include "+ "`feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, "+ "`recommended_running_time`, `recommended_sample_size`, "+ "`custom_exposure_filter`, and `excluded_variants` "+ "(list of variant keys to drop from statistical analysis; "+ "the baseline variant and holdout pseudo-variants cannot be excluded)."),)metrics = ExperimentMetricsField(@@ -335,6 +336,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSeget_experiment_stats_method(instance),instance.exposure_criteria,only_count_matured_users=instance.only_count_matured_users,+ excluded_variants=(instance.parameters or {}).get("excluded_variants"),)return datadiff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 9ed8c4a49b1b..7f7c0827870a 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -4,6 +4,7 @@ from decimal import Decimalfrom typing import Anyfrom uuid import UUID+import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -4897,3 +4898,49 @@ class TestExperimentService(APIBaseTest):],},)+++class TestValidateExperimentParametersExcludedVariants:+ def _base_params(self) -> dict[str, Any]:+ return {+ "feature_flag_variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test-1", "rollout_percentage": 25},+ {"key": "test-2", "rollout_percentage": 25},+ ]+ }++ @pytest.mark.parametrize(+ "extra_params",+ [+ {},+ {"excluded_variants": []},+ {"excluded_variants": ["test-2"]},+ {"excluded_variants": ["test-2", "test-2"]},+ ],+ )+ def test_valid_excluded_variants(self, extra_params: dict[str, Any]):+ ExperimentService.validate_experiment_parameters({**self._base_params(), **extra_params})++ @pytest.mark.parametrize(+ "extra_params,match",+ [+ ({"excluded_variants": ["does-not-exist"]}, "unknown variants"),+ ({"excluded_variants": ["control"]}, "baseline variant cannot be excluded"),+ ({"excluded_variants": ["holdout-42"]}, "cannot exclude holdout"),+ ({"excluded_variants": ["test-1", "test-2"]}, "at least one test variant"),+ ({"excluded_variants": "test-2"}, "must be a list of strings"),+ ({"excluded_variants": [123]}, "must be a list of strings"),+ (+ {"stats_config": {"baseline_variant_key": "test-1"}, "excluded_variants": ["test-1"]},+ "baseline variant cannot be excluded",+ ),+ ],+ )+ def test_invalid_excluded_variants_raises(self, extra_params: dict[str, Any], match: str):+ with pytest.raises(ValidationError, match=match):+ ExperimentService.validate_experiment_parameters({**self._base_params(), **extra_params})++ 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"]})diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 9c26f9f33465..66b3dcc01e7b 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -466,7 +466,7 @@ export interface ExperimentApi {holdout_id?: number | null/** @nullable */readonly exposure_cohort: number | null- /** Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power. */+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). */parameters?: ExperimentParametersApi | nullsecondary_metrics?: unknownreadonly saved_metrics: readonly ExperimentToSavedMetricApi[]@@ -568,7 +568,7 @@ export interface PatchedExperimentApi {holdout_id?: number | null/** @nullable */readonly exposure_cohort?: number | null- /** Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power. */+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). */parameters?: ExperimentParametersApi | nullsecondary_metrics?: unknownreadonly saved_metrics?: readonly ExperimentToSavedMetricApi[]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e0589503e2fa..b80d2d9ce93b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16509,7 +16509,7 @@ export namespace Schemas {holdout_id?: number | null;/** @nullable */readonly exposure_cohort: number | null;- /** Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power. */+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). */parameters?: ExperimentParameters | null;secondary_metrics?: unknown;readonly saved_metrics: readonly ExperimentToSavedMetric[];@@ -28180,7 +28180,7 @@ export namespace Schemas {holdout_id?: number | null;/** @nullable */readonly exposure_cohort?: number | null;- /** Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power. */+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). */parameters?: ExperimentParameters | 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 48b898b9ce79..554442876f3e 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -475,7 +475,7 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod]).optional().describe(- "Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded).'),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zod@@ -3171,7 +3171,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- "Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded).'),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zod@@ -5950,7 +5950,7 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod]).optional().describe(- "Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded).'),secondary_metrics: zod.unknown().optional(),saved_metrics_ids: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-duplicate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-duplicate.jsonindex f69405926162..dbefac4a8da2 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-duplicate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-duplicate.json@@ -3795,7 +3795,7 @@"type": "null"}],- "description": "Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ "description": "Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded)."},"primary_metrics_ordered_uuids": {},"saved_metrics_ids": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-update.jsonindex 029a9103f8c3..92c2de0865ae 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/experiment-update.json@@ -3606,7 +3606,7 @@"type": "null"}],- "description": "Variant definitions and rollout configuration. Set feature_flag_variants to customize the split (default: 50/50 control/test). Each variant needs a key and split_percent (the variant's share of traffic); percentages must sum to 100. Set rollout_percentage (0-100, default 100) to limit what fraction of users enter the experiment. Set minimum_detectable_effect (percentage, suggest 20-30) to control statistical power."+ "description": "Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded)."},"stats_config": {},"update_feature_flag_params": {