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.

feat(experiments): consume flag config natively in the experiment service (#69485)

Anderscfc8061ed9f2
diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
index 2bdd1affefe8..33c719fa0bec 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
@@ -9,14 +9,14 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { Experiment } from '~/types'
-import type { FeatureFlagMultivariateVariantSchemaApi } from 'products/experiments/frontend/generated/api.schemas'
+import type { ExperimentFlagVariantApi } from 'products/experiments/frontend/generated/api.schemas'
import { NEW_EXPERIMENT } from '../constants'
import { VariantsPanelCreateFeatureFlag } from './VariantsPanelCreateFeatureFlag'
// Draft flag config in the flag's own input shape, the source the panel reads and writes.
const flagConfig = (
- variants: FeatureFlagMultivariateVariantSchemaApi[],
+ variants: ExperimentFlagVariantApi[],
rolloutPercentage?: number
): Experiment['feature_flag_config'] => ({
filters: {
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index edb11d9f4b28..8f15c4048186 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -213,75 +213,6 @@ class ExperimentService:
if start_date and end_date and start_date >= end_date:
raise ValidationError("End date must be after start date")
- @staticmethod
- def validate_variant_shapes(parameters: dict | None) -> None:
- """Validate that variant entries are well-formed dicts with required keys.
-
- This catches malformed input early before it reaches FeatureFlagSerializer,
- preventing unhandled KeyError/AttributeError 500s.
- """
- if not parameters:
- return
- variants = parameters.get("feature_flag_variants", [])
- for i, variant in enumerate(variants):
- if not isinstance(variant, dict):
- raise ValidationError(f"Feature flag variant at index {i} must be an object")
- if "key" not in variant:
- raise ValidationError(f"Feature flag variant at index {i} must have a 'key' field")
-
- @staticmethod
- def validate_variant_percentages(parameters: dict | None) -> None:
- """Each variant must carry split_percent (recommended) or rollout_percentage (deprecated).
-
- The API serializer translates split_percent to rollout_percentage before this runs, but we
- check for either field so direct service callers (facade, max_tools) are also covered.
- Once we fully migrate to split_percent, we can remove this validation and make split_percent
- required in the type system instead.
- """
- if not parameters:
- return
- for variant in parameters.get("feature_flag_variants", []) or []:
- if not isinstance(variant, dict):
- continue # validate_variant_shapes handles this
- if "split_percent" not in variant and "rollout_percentage" not in variant:
- raise ValidationError(
- "Each variant must include split_percent (recommended) or rollout_percentage (deprecated)."
- )
-
- @staticmethod
- def validate_experiment_parameters(parameters: dict | None) -> None:
- """Validate experiment parameters accepted by the API layer.
-
- Includes shape validation plus count/control checks.
- Called from the serializer where the full parameter set is available.
- """
- if not parameters:
- return
-
- ExperimentService.validate_variant_shapes(parameters)
- ExperimentService.validate_variant_percentages(parameters)
-
- variants = parameters.get("feature_flag_variants", [])
-
- if len(variants) >= 21:
- raise ValidationError("Feature flag variants must be less than 21")
- if len(variants) > 0:
- if len(variants) < 2:
- raise ValidationError(
- "Feature flag must have at least 2 variants (control and at least one test variant)"
- )
- keys = [variant["key"] for variant in variants]
- if "control" not in keys:
- # Surface the keys we did receive so LLM callers can self-correct without a
- # second roundtrip. Capitalized 'Control' is auto-normalized on the feature_flag
- # input path (_normalized_flag_variants), so anything reaching this branch
- # genuinely lacks a baseline variant.
- raise ValidationError(
- "Feature flag variants must contain a variant with key 'control' "
- f"(lowercase, exactly). Got keys: {keys}. Rename the baseline variant's "
- "'key' to 'control'."
- )
-
@staticmethod
def _validate_excluded_variant_keys(
excluded_variants: list[str], variant_keys: Iterable[str], baseline_key: str
@@ -610,10 +541,12 @@ class ExperimentService:
f"Must be one of: {', '.join(sorted(variant_keys))}"
)
- # Feature-flag config keys that belong on the linked FeatureFlag (the source of truth). They are
- # accepted as create/update input to build/sync the flag, projected back into the deprecated
- # `parameters` API field at read time (see ExperimentBaseSerializer), but never persisted into
- # the `parameters` column.
+ # Feature-flag config keys that historically lived on the deprecated `parameters` surface but
+ # belong on the linked FeatureFlag (the source of truth). A legacy caller still sending them in
+ # `parameters` input has them copied into the `feature_flag` config path (see
+ # ExperimentSerializer._deprecated_parameters_as_feature_flag_config) and stripped from the
+ # stored column; reads still project the flag's current config back into `parameters` for
+ # backward compatibility.
FEATURE_FLAG_CONFIG_KEYS = (
"feature_flag_variants",
"rollout_percentage",
@@ -631,6 +564,37 @@ class ExperimentService:
return parameters
return {k: v for k, v in parameters.items() if k not in cls.FEATURE_FLAG_CONFIG_KEYS}
+ @classmethod
+ def _feature_flag_config_from_parameters(cls, parameters: dict | None) -> dict | None:
+ """Translate deprecated ``parameters`` flag-config keys into a ``feature_flag`` config object
+ (the flag's native write shape), or ``None`` when ``parameters`` carries no flag config.
+
+ This is the reverse of the read projection. It lets a caller that hands the service deprecated
+ flag config through ``parameters`` — a direct service caller, or ExperimentSerializer's
+ deprecated-parameters copy-forward — flow through the single gated flag-write path. The
+ serializer strips these keys from ``parameters`` before calling ``update_experiment``, so on
+ the HTTP path this returns ``None`` and the explicit ``feature_flag`` config is used instead."""
+ if not parameters:
+ return None
+ flag_config = {key: parameters[key] for key in cls.FEATURE_FLAG_CONFIG_KEYS if key in parameters}
+ if not flag_config:
+ return None
+ filters: dict[str, Any] = {}
+ if "feature_flag_variants" in flag_config:
+ filters["multivariate"] = {"variants": flag_config["feature_flag_variants"]}
+ if flag_config.get("rollout_percentage") is not None:
+ filters["groups"] = [{"properties": [], "rollout_percentage": flag_config["rollout_percentage"]}]
+ if "aggregation_group_type_index" in flag_config:
+ filters["aggregation_group_type_index"] = flag_config["aggregation_group_type_index"]
+ if "feature_flag_payloads" in flag_config:
+ filters["payloads"] = flag_config["feature_flag_payloads"]
+ config: dict[str, Any] = {}
+ if filters:
+ config["filters"] = filters
+ if "ensure_experience_continuity" in flag_config:
+ config["ensure_experience_continuity"] = flag_config["ensure_experience_continuity"]
+ return config or None
+
@staticmethod
def _parameters_with_variant_detail(experiment: Experiment) -> dict[str, Any]:
"""Parameters for analytics events: the stored column carries no flag config, so attach
@@ -638,101 +602,16 @@ class ExperimentService:
return {**(experiment.parameters or {}), "feature_flag_variants": experiment.feature_flag.variants}
@staticmethod
- def feature_flag_config_to_parameters(
- feature_flag_input: dict, parameters: dict | None, flag: FeatureFlag | None = None
- ) -> dict:
- """Translate a ``feature_flag`` config object (the flag's native write shape:
- ``filters.multivariate.variants``, ``filters.groups``, ``filters.aggregation_group_type_index``,
- ``filters.payloads``, ``ensure_experience_continuity``) into the legacy ``parameters`` input
- keys the service still consumes to build/sync the flag.
-
- The explicit ``feature_flag`` object wins over any matching keys already in ``parameters``.
- This is the create/update write counterpart to the read projection (see
- ``ExperimentBaseSerializer``): callers send config through the flag object instead of
- ``parameters``, and this normalizes it while ``parameters`` remains the internal input shape.
- Returns a new dict, leaving the caller's input untouched.
-
- Pass ``flag`` (the experiment's linked flag, on update) to give the object PATCH semantics:
- config the input omits is backfilled from the flag's current state, because the downstream
- sync treats a missing variants key as "reset to defaults" and a missing aggregation key as
- "clear" — a partial object must not silently regress config it never mentioned.
+ def _flag_config_variants(feature_flag_config: dict | None) -> list | None:
+ """Variants carried by a ``feature_flag`` config object, or None when it omits them.
+
+ None means "not mentioned" (PATCH: preserve the flag's current variants); a list means the
+ caller is setting the variant set explicitly.
"""
- params = dict(parameters or {})
- # Reject unrecognized keys instead of silently dropping them: applying half an object
- # (e.g. taking filters but ignoring `active` or `super_groups`) would leave the flag in a
- # state the caller never asked for. `id` is allowed because clients serializing an optional
- # id as null still express write intent (a real echo carries a non-null id).
- unsupported = sorted(set(feature_flag_input) - {"id", "filters", "ensure_experience_continuity"})
- if unsupported:
- raise ValidationError(
- {
- "feature_flag": f"Unsupported keys: {', '.join(unsupported)}. The experiment feature_flag "
- "input accepts filters and ensure_experience_continuity; edit the feature flag "
- "directly for anything else."
- }
- )
- filters = feature_flag_input.get("filters")
- if filters is not None and not isinstance(filters, dict):
- raise ValidationError({"feature_flag": "filters must be an object."})
- filters = filters or {}
- unsupported_filters = sorted(
- set(filters) - {"multivariate", "groups", "aggregation_group_type_index", "payloads"}
- )
- if unsupported_filters:
- raise ValidationError(
- {
- "feature_flag": f"Unsupported filters keys: {', '.join(unsupported_filters)}. The experiment "
- "feature_flag input accepts filters.multivariate, filters.groups, "
- "filters.aggregation_group_type_index, and filters.payloads; edit the feature flag "
- "directly for anything else."
- }
- )
- multivariate = filters.get("multivariate")
- if multivariate is not None and not isinstance(multivariate, dict):
- raise ValidationError({"feature_flag": "filters.multivariate must be an object."})
- multivariate = multivariate or {}
- if "variants" in multivariate:
- if not isinstance(multivariate["variants"], list):
- raise ValidationError({"feature_flag": "filters.multivariate.variants must be a list."})
- params["feature_flag_variants"] = multivariate["variants"]
- groups = filters.get("groups")
- if groups is not None:
- if not isinstance(groups, list) or not all(isinstance(group, dict) for group in groups):
- raise ValidationError({"feature_flag": "filters.groups must be a list of objects."})
- # Only groups[0].rollout_percentage is applied; silently dropping release conditions
- # would leave the experiment exposed to a wider audience than the caller asked for.
- if len(groups) > 1 or (groups and groups[0].get("properties")):
- raise ValidationError(
- {
- "feature_flag": "Release conditions (multiple groups or group properties) are not "
- "supported via the experiment feature_flag input. Edit the feature flag directly."
- }
- )
- # Same rationale inside the group object: a `variant` override or per-group
- # aggregation would be silently ignored, not applied.
- unsupported_group_keys = sorted(set(groups[0]) - {"properties", "rollout_percentage"}) if groups else []
- if unsupported_group_keys:
- raise ValidationError(
- {
- "feature_flag": f"Unsupported keys in filters.groups[0]: {', '.join(unsupported_group_keys)}. "
- "Only rollout_percentage is applied here; edit the feature flag directly for anything else."
- }
- )
- if groups:
- rollout_percentage = groups[0].get("rollout_percentage")
- if rollout_percentage is not None:
- params["rollout_percentage"] = rollout_percentage
- if "aggregation_group_type_index" in filters:
- params["aggregation_group_type_index"] = filters["aggregation_group_type_index"]
- if "payloads" in filters:
- params["feature_flag_payloads"] = filters["payloads"]
- if "ensure_experience_continuity" in feature_flag_input:
- params["ensure_experience_continuity"] = feature_flag_input["ensure_experience_continuity"]
- if flag is not None:
- params.setdefault("feature_flag_variants", flag.variants)
- if "aggregation_group_type_index" not in params and flag.aggregation_group_type_index is not None:
- params["aggregation_group_type_index"] = flag.aggregation_group_type_index
- return params
+ multivariate = ((feature_flag_config or {}).get("filters") or {}).get("multivariate")
+ if isinstance(multivariate, dict) and "variants" in multivariate:
+ return multivariate["variants"]
+ return None
@staticmethod
def _variant_keys(variants: list | None) -> list[str]:
@@ -740,13 +619,13 @@ class ExperimentService:
return [variant["key"] for variant in (variants or []) if isinstance(variant, dict)]
@classmethod
- def _resolved_variant_keys(cls, experiment: Experiment, update_data: dict) -> list[str]:
+ def _resolved_variant_keys(cls, experiment: Experiment, feature_flag_config: dict | None) -> list[str]:
"""Variant keys the experiment will have after this update.
- Prefer the variants the PATCH sets; otherwise resolve from the linked flag,
+ Prefer the variants the feature_flag config sets; otherwise resolve from the linked flag,
which is the source of truth for variants.
"""
- update_variants = (update_data.get("parameters") or {}).get("feature_flag_variants")
+ update_variants = cls._flag_config_variants(feature_flag_config)
if update_variants is None:
update_variants = experiment.feature_flag.variants if experiment.feature_flag else []
return cls._variant_keys(update_variants)
@@ -934,6 +813,7 @@ class ExperimentService:
description: str = "",
type: str = "product",
parameters: dict | None = None,
+ feature_flag_config: dict | None = None,
running_time_calculation: dict | None = None,
excluded_variants: list[str] | None = None,
metrics: list[dict] | None = None,
@@ -972,8 +852,6 @@ class ExperimentService:
seen_metric_uuids: set[str] = self._collect_saved_metric_uuids(saved_metrics_ids)
metrics = self._assign_uuids_to_metrics(metrics, seen=seen_metric_uuids)
metrics_secondary = self._assign_uuids_to_metrics(metrics_secondary, seen=seen_metric_uuids)
- self.validate_variant_shapes(parameters)
- self.validate_variant_percentages(parameters)
self.validate_running_time_calculation(running_time_calculation)
self.validate_excluded_variants(excluded_variants)
running_time_calculation = running_time_calculation or {}
@@ -999,7 +877,7 @@ class ExperimentService:
feature_flag, used_variants = self._ensure_feature_flag(
feature_flag_key=feature_flag_key,
experiment_name=name,
- parameters=parameters,
+ feature_flag_config=feature_flag_config,
holdout=holdout,
is_draft=is_draft,
create_in_folder=create_in_folder,
@@ -1074,9 +952,9 @@ class ExperimentService:
"name": name,
"description": description,
"type": type,
- # Feature-flag config was already consumed by _ensure_feature_flag above; strip it so it
- # lives only on the flag, not mirrored into the deprecated `parameters` column.
- "parameters": self._strip_feature_flag_config(parameters),
+ # Flag config lives only on the flag (built by _ensure_feature_flag from
+ # feature_flag_config); `parameters` carries experiment-own keys only.
+ "parameters": parameters,
"running_time_calculation": running_time_calculation,
"excluded_variants": excluded_variants,
"metrics": metrics if metrics is not None else [],
@@ -1202,13 +1080,18 @@ class ExperimentService:
self,
feature_flag_key: str,
experiment_name: str,
- parameters: dict | None,
+ feature_flag_config: dict | None,
holdout: ExperimentHoldout | None,
is_draft: bool,
create_in_folder: str | None,
serializer_context: dict | None,
) -> tuple[FeatureFlag, list[dict]]:
- """Resolve existing flag or create a new one. Returns (flag, variants_used)."""
+ """Resolve existing flag or create a new one. Returns (flag, variants_used).
+
+ ``feature_flag_config`` is the flag's own write shape
+ (``{filters: {multivariate, groups, aggregation_group_type_index, payloads},
+ ensure_experience_continuity}``); a new flag is built from it plus defaults.
+ """
existing_flag = FeatureFlag.objects.filter(key=feature_flag_key, team_id=self.team.id).first()
if existing_flag:
@@ -1216,14 +1099,15 @@ class ExperimentService:
variants = existing_flag.filters.get("multivariate", {}).get("variants", list(DEFAULT_VARIANTS))
return existing_flag, variants
- variants = []
- aggregation_group_type_index = None
- if parameters:
- variants = parameters.get("feature_flag_variants", [])
- aggregation_group_type_index = parameters.get("aggregation_group_type_index")
+ config = feature_flag_config or {}
+ config_filters = config.get("filters") or {}
+ variants = self._flag_config_variants(config) or []
+ aggregation_group_type_index = config_filters.get("aggregation_group_type_index")
- params = parameters or {}
- experiment_rollout_percentage = params.get("rollout_percentage", DEFAULT_ROLLOUT_PERCENTAGE)
+ groups = config_filters.get("groups")
+ experiment_rollout_percentage = DEFAULT_ROLLOUT_PERCENTAGE
+ if groups and groups[0].get("rollout_percentage") is not None:
+ experiment_rollout_percentage = groups[0]["rollout_percentage"]
feature_flag_filters = {
"groups": [{"properties": [], "rollout_percentage": experiment_rollout_percentage}],
@@ -1235,7 +1119,7 @@ class ExperimentService:
# Per-variant payloads (variant_key -> JSON string). Callers pass this when they need to
# attach metadata that the SDK can read alongside the variant assignment, e.g. prompt
# experiments map each variant to {"prompt_name": ..., "prompt_version": ...}.
- feature_flag_payloads = params.get("feature_flag_payloads")
+ feature_flag_payloads = config_filters.get("payloads")
if feature_flag_payloads:
feature_flag_filters["payloads"] = feature_flag_payloads
@@ -1246,8 +1130,8 @@ class ExperimentService:
"active": not is_draft,
"creation_context": "experiments",
}
- if params.get("ensure_experience_continuity") is not None:
- feature_flag_data["ensure_experience_continuity"] = params["ensure_experience_continuity"]
+ if config.get("ensure_experience_continuity") is not None:
+ feature_flag_data["ensure_experience_continuity"] = config["ensure_experience_continuity"]
else:
feature_flag_data["ensure_experience_continuity"] = self.team.flags_persistence_default or False
if create_in_folder is not None:
@@ -2910,6 +2794,7 @@ class ExperimentService:
experiment: Experiment,
update_data: dict,
*,
+ feature_flag_config: dict | None = None,
serializer_context: dict | None = None,
allow_unknown_events: bool = False,
event_source: EventSource | None = None,
@@ -2920,6 +2805,9 @@ class ExperimentService:
``ExperimentSerializer``. The caller is responsible for DRF-level input
validation (field types, metric schema, etc.) before calling this method.
+ ``feature_flag_config`` is the flag's own write shape (``{filters, ensure_experience_continuity}``),
+ synced onto the linked flag with object-PATCH semantics (config it omits is preserved).
+
``event_source`` attributes the "experiment updated" event for non-HTTP callers,
mirroring ``create_experiment``.
"""
@@ -2994,7 +2882,15 @@ class ExperimentService:
context = serializer_context or self._build_serializer_context()
feature_flag = experiment.feature_flag
- self._validate_update_payload(experiment, update_data, feature_flag)
+ # Direct service callers (no serializer) may still send flag config through the deprecated
+ # `parameters` keys instead of `feature_flag_config`. Translate them here so the flag write
+ # below still runs through the approval gate — otherwise the write is skipped and the edit is
+ # silently dropped (and the gate bypassed). No double-write on the HTTP path: the serializer
+ # strips these keys from `parameters` and passes an explicit `feature_flag_config`.
+ if feature_flag_config is None:
+ feature_flag_config = self._feature_flag_config_from_parameters(update_data.get("parameters"))
+
+ self._validate_update_payload(experiment, update_data, feature_flag, feature_flag_config)
update_saved_metrics = "saved_metrics_ids" in update_data
saved_metrics_data: list[dict] = update_data.pop("saved_metrics_ids", []) or []
@@ -3011,9 +2907,9 @@ class ExperimentService:
# the stats_config itself, or the variant set it references. A variants-only
# PATCH (e.g. updateDistribution) that renames/removes the current baseline
# must not leave a dangling baseline_variant_key behind.
- update_variants = (update_data.get("parameters") or {}).get("feature_flag_variants")
+ update_variants = self._flag_config_variants(feature_flag_config)
if "stats_config" in update_data or update_variants is not None:
- variant_keys = self._resolved_variant_keys(experiment, update_data)
+ variant_keys = self._resolved_variant_keys(experiment, feature_flag_config)
effective_stats_config = update_data.get("stats_config", experiment.stats_config)
self.validate_stats_config(effective_stats_config, variant_keys)
@@ -3022,7 +2918,7 @@ class ExperimentService:
if "excluded_variants" in update_data:
new_excluded = update_data["excluded_variants"]
if new_excluded:
- variant_keys = self._resolved_variant_keys(experiment, update_data)
+ variant_keys = self._resolved_variant_keys(experiment, feature_flag_config)
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)
@@ -3043,7 +2939,9 @@ class ExperimentService:
# launch/pause/resume/ship_variant, which gate the flag write non-atomically
# for the same reason. The flag write does not depend on any of the
# experiment-state writes below, so hoisting it is safe.
- self._sync_feature_flag_on_update(experiment, update_data, feature_flag, context, update_feature_flag_params)
+ self._sync_feature_flag_on_update(
+ experiment, update_data, feature_flag, context, update_feature_flag_params, feature_flag_config
+ )
# --- feature flag activation on launch (OUTSIDE the atomic block) -----
# Setting a start_date on a draft launches it, which activates the linked
@@ -3175,14 +3073,15 @@ class ExperimentService:
feature_flag: FeatureFlag,
context: dict,
update_feature_flag_params: bool,
+ feature_flag_config: dict | None = None,
) -> None:
- """Sync experiment parameters/holdout to the linked flag THROUGH the approval gate.
+ """Sync the experiment's feature_flag config/holdout to the linked flag THROUGH the approval gate.
- Draft experiments always sync parameters to the linked feature flag.
+ Draft experiments always sync the feature_flag config to the linked flag.
Running experiments only sync when update_feature_flag_params=True, to prevent
- accidental side effects (e.g. overwrites when the frontend spreads stale
- parameters alongside unrelated updates, or an agent calls MCP with too many
- params).
+ accidental side effects (e.g. an agent calls MCP with too many params). Object-PATCH
+ semantics: config the object omits is preserved from the flag's current state, never
+ reset to defaults.
Routing the write through FeatureFlagSerializer honours the @approval_gate, so a
policy-gated variant/rollout change raises ApprovalRequired. This runs OUTSIDE
@@ -3196,16 +3095,21 @@ class ExperimentService:
if "holdout" in update_data:
holdout = update_data["holdout"]
- # Only resync the flag from ``parameters`` when it actually carries flag-config keys.
- # A read-modify-write PATCH that echoes non-flag params (e.g. variant_notes) alongside
- # a stripped parameters dict must not reset the flag's variants to DEFAULT_VARIANTS.
- params = update_data.get("parameters")
- if params and any(key in params for key in self.FEATURE_FLAG_CONFIG_KEYS):
- variants = update_data["parameters"].get("feature_flag_variants", [])
- aggregation_group_type_index = update_data["parameters"].get("aggregation_group_type_index")
+ if feature_flag_config:
+ config_filters = feature_flag_config.get("filters") or {}
+ existing_filters = feature_flag.filters or {}
+
+ config_variants = self._flag_config_variants(feature_flag_config)
+ variants = config_variants if config_variants is not None else feature_flag.variants
+
+ if "aggregation_group_type_index" in config_filters:
+ aggregation_group_type_index = config_filters["aggregation_group_type_index"]
+ else:
+ aggregation_group_type_index = existing_filters.get("aggregation_group_type_index")
- existing_groups = feature_flag.filters.get("groups", [])
- experiment_rollout_percentage = update_data["parameters"].get("rollout_percentage")
+ existing_groups = existing_filters.get("groups", [])
+ groups = config_filters.get("groups")
+ experiment_rollout_percentage = groups[0].get("rollout_percentage") if groups else None
if experiment_rollout_percentage is not None and existing_groups:
new_groups = [
{**existing_groups[0], "rollout_percentage": experiment_rollout_percentage},
@@ -3215,20 +3119,18 @@ class ExperimentService:
new_groups = list(existing_groups)
new_filters = {
- **feature_flag.filters,
+ **existing_filters,
"groups": new_groups,
"multivariate": {"variants": variants or list(DEFAULT_VARIANTS)},
"aggregation_group_type_index": aggregation_group_type_index,
**holdout_filters_for_flag(holdout.id if holdout else None, holdout.filters if holdout else None),
}
- if "feature_flag_payloads" in update_data["parameters"]:
- new_filters["payloads"] = update_data["parameters"]["feature_flag_payloads"]
+ if "payloads" in config_filters:
+ new_filters["payloads"] = config_filters["payloads"]
flag_update_data: dict[str, Any] = {"filters": new_filters}
- if "ensure_experience_continuity" in update_data["parameters"]:
- flag_update_data["ensure_experience_continuity"] = update_data["parameters"][
- "ensure_experience_continuity"
- ]
+ if "ensure_experience_continuity" in feature_flag_config:
+ flag_update_data["ensure_experience_continuity"] = feature_flag_config["ensure_experience_continuity"]
existing_flag_serializer = FeatureFlagSerializer(
feature_flag,
@@ -3307,7 +3209,13 @@ class ExperimentService:
request=request,
)
- def _validate_update_payload(self, experiment: Experiment, update_data: dict, feature_flag: FeatureFlag) -> None:
+ def _validate_update_payload(
+ self,
+ experiment: Experiment,
+ update_data: dict,
+ feature_flag: FeatureFlag,
+ feature_flag_config: dict | None = None,
+ ) -> None:
"""Validate update payload before any database mutations occur."""
# Prevent restoring a deleted experiment if the linked feature flag is also deleted
if experiment.deleted and update_data.get("deleted") is False and feature_flag.deleted:
@@ -3382,10 +3290,11 @@ class ExperimentService:
self.validate_excluded_variants(update_data.get("excluded_variants"))
if not experiment.is_draft:
- if "feature_flag_variants" in update_data.get("parameters", {}):
- if len(update_data["parameters"]["feature_flag_variants"]) != len(feature_flag.variants):
+ new_variants = self._flag_config_variants(feature_flag_config)
+ if new_variants is not None:
+ if len(new_variants) != len(feature_flag.variants):
raise ValidationError("Can't update feature_flag_variants on Experiment")
- for variant in update_data["parameters"]["feature_flag_variants"]:
+ for variant in new_variants:
if (
len([ff_variant for ff_variant in feature_flag.variants if ff_variant["key"] == variant["key"]])
!= 1
@@ -3423,21 +3332,13 @@ class ExperimentService:
if feature_flag_key is None:
feature_flag_key = source_experiment.feature_flag.key
+ # `parameters` carries only the source's experiment-own keys — flag config lives on the
+ # flag and is passed via feature_flag_config below.
parameters = deepcopy(source_experiment.parameters) or {}
- # Variants, payloads, and experience continuity come from the source experiment's feature
- # flag (the source of truth), not any stale copy denormalized into parameters.
- source_variants = source_experiment.feature_flag.variants
- if source_variants:
- parameters["feature_flag_variants"] = deepcopy(source_variants)
- source_payloads = source_experiment.feature_flag.get_filters().get("payloads")
- if source_payloads:
- parameters["feature_flag_payloads"] = deepcopy(source_payloads)
- else:
- parameters.pop("feature_flag_payloads", None)
- # bool() so a NULL continuity clones as off — the create path treats None as "unset" and
- # would substitute the target team's flags_persistence_default, changing SDK behavior.
- parameters["ensure_experience_continuity"] = bool(source_experiment.feature_flag.ensure_experience_continuity)
+ # Variants, payloads, group aggregation, and experience continuity come from the source
+ # experiment's feature flag (the source of truth), in the flag's own write shape.
+ clone_variants = deepcopy(source_experiment.feature_flag.variants)
# An existing flag in the target project wins — reuse its variants instead.
# For cross-project clones we always check the target; for same-project
@@ -3446,9 +3347,26 @@ class ExperimentService:
if should_check_existing:
existing_flag = FeatureFlag.objects.filter(key=feature_flag_key, team_id=target.id).first()
if existing_flag and existing_flag.variants:
- parameters["feature_flag_variants"] = deepcopy(existing_flag.variants)
+ clone_variants = deepcopy(existing_flag.variants)
+
+ clone_filters: dict[str, Any] = {}
+ if clone_variants:
+ clone_filters["multivariate"] = {"variants": clone_variants}
+ source_payloads = source_experiment.feature_flag.get_filters().get("payloads")
+ if source_payloads:
+ clone_filters["payloads"] = deepcopy(source_payloads)
+ # Group index 0 is valid, so guard on `is not None`; dropping it would silently convert a
+ # group-scoped experiment into a person-scoped one.
+ source_group_type_index = source_experiment.feature_flag.aggregation_group_type_index
+ if source_group_type_index is not None:
+ clone_filters["aggregation_group_type_index"] = source_group_type_index
+ feature_flag_config = {
+ "filters": clone_filters,
+ # bool() so a NULL continuity clones as off — the create path treats None as "unset" and
+ # would substitute the target team's flags_persistence_default, changing SDK behavior.
+ "ensure_experience_continuity": bool(source_experiment.feature_flag.ensure_experience_continuity),
+ }
- self.validate_experiment_parameters(parameters)
self.validate_experiment_exposure_criteria(source_experiment.exposure_criteria)
self.validate_experiment_metrics(source_experiment.metrics)
self.validate_experiment_metrics(source_experiment.metrics_secondary)
@@ -3491,6 +3409,7 @@ class ExperimentService:
description=source_experiment.description or "",
type=source_experiment.type or "product",
parameters=parameters,
+ feature_flag_config=feature_flag_config,
running_time_calculation=deepcopy(source_experiment.running_time_calculation),
filters=source_experiment.filters,
metrics=cloned_metrics,
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index aaaaf6124ea0..2292f81d79d4 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -58,6 +58,7 @@ def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInpu
description=input_dto.description,
type=input_dto.type,
parameters=input_dto.parameters,
+ feature_flag_config=input_dto.feature_flag_config,
running_time_calculation=input_dto.running_time_calculation,
excluded_variants=input_dto.excluded_variants,
metrics=input_dto.metrics,
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.py
index 13177a85a013..a6606eaa3fbe 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -27,10 +27,14 @@ class CreateExperimentInput:
description: str = ""
type: str = "product"
- # Experiment-own metadata (variant_notes, prompt_metadata, custom_exposure_filter).
- # NOT for flag config — send that through the experiment's feature_flag object.
+ # Experiment-own parameters (variant_notes, custom_exposure_filter, prompt_metadata, ...).
+ # Flag config is NOT accepted here — it goes through feature_flag_config below.
parameters: dict[str, Any] | None = None
+ # Feature flag configuration in the flag's own write shape:
+ # {filters: {multivariate, groups, aggregation_group_type_index, payloads}, ensure_experience_continuity}
+ feature_flag_config: dict[str, Any] | None = None
+
# Running-time calculator state (minimum_detectable_effect, recommended_running_time,
# recommended_sample_size, exposure_estimate_config)
running_time_calculation: dict[str, Any] | None = None
diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.py
index 6a30009be56a..515b65da20d6 100644
--- a/products/experiments/backend/max_tools.py
+++ b/products/experiments/backend/max_tools.py
@@ -152,6 +152,8 @@ class CreateExperimentTool(MaxTool):
f"Feature flag '{feature_flag_key}' is already used by experiment '{existing_experiment_with_flag.name}'"
)
+ # The flag already exists with valid variants, so the experiment links to it as-is —
+ # no flag config to send. (create_experiment reuses the existing flag unchanged.)
service = ExperimentService(team=self._team, user=self._user)
return service.create_experiment(
name=name,
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index e88a1b376fab..77e2875fc953 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -491,27 +491,23 @@ class ExperimentSerializer(ExperimentBaseSerializer):
return super().validate(data)
def _normalize_feature_flag_input(self, data: dict) -> dict:
- """Accept feature-flag config (variants/rollout/aggregation/payloads/continuity) via a
- ``feature_flag`` object on create/update, folding it into the internal ``parameters`` input
- the service still consumes to build/sync the flag. The explicit ``feature_flag`` object wins
- over the legacy ``parameters`` keys.
+ """Validate the ``feature_flag`` config object and stash it under ``data["feature_flag"]`` for
+ the service to consume in the flag's own write shape (``{filters, ensure_experience_continuity}``).
Read from ``initial_data`` because the serializer's ``feature_flag`` field is read-only output
- (the linked flag). This is its write counterpart during the window where ``parameters`` is
- still the internal input shape; callers can stop sending flag config under ``parameters``.
+ (the linked flag, as MinimalFeatureFlag); this is its write counterpart. Validation runs
+ through ``ExperimentFeatureFlagInputSerializer`` — the same serializer the OpenAPI request
+ schema advertises.
- The write contract is a config-only object (``filters``, ``ensure_experience_continuity``).
An object carrying a non-null ``id`` is the serialized linked flag echoed back by a
- read-modify-write client (the GET response's ``feature_flag``, which the frontend spreads
- into saves); treating that echo as intent would override the client's actual ``parameters``
- edits with the flag's pre-edit state, so it is ignored — the pre-existing behavior for the
- read-only field. An object with no config keys at all (e.g. a ``{"key": ...}`` stub) is
- likewise ignored rather than rejected, so clients that have always included such stubs in
- write bodies keep working.
+ read-modify-write client (the GET response's ``feature_flag``); treating that echo as intent
+ would reapply the flag's pre-edit state, so it is ignored. An object with no config keys at
+ all (e.g. a ``{"key": ...}`` stub) is likewise ignored rather than rejected, so clients that
+ have always included such stubs in write bodies keep working.
When no such object is present, a legacy caller may still be sending flag config through the
deprecated ``parameters`` keys. Rather than reject it, we copy it into the ``feature_flag``
- object shape here so it flows through this same build/sync path (see
+ object shape here so it flows through this same validate/stash path (see
``_deprecated_parameters_as_feature_flag_config``).
"""
feature_flag_input = (getattr(self, "initial_data", None) or {}).get("feature_flag")
@@ -540,27 +536,15 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"send update_feature_flag_params=true (or edit the feature flag directly)."
}
)
- # On a partial update that omits ``parameters``, DRF drops it from ``data``. Seed the merge
- # from the instance so non-flag params (minimum_detectable_effect, variant_notes, ...) survive.
- # Strip flag-config keys a legacy row may still have persisted in the column: patch semantics
- # must backfill omitted config from the linked flag's live state, never from stale mirrors.
- if "parameters" in data:
- base_parameters = data.get("parameters")
- elif self.instance is not None:
- base_parameters = ExperimentService._strip_feature_flag_config(self.instance.parameters)
- else:
- base_parameters = None
- merged = ExperimentService.feature_flag_config_to_parameters(
- feature_flag_input,
- base_parameters,
- flag=self.instance.feature_flag if self.instance is not None else None,
+ # ``id`` is the echo marker (handled above); a null id still expresses write intent, so drop
+ # it before validating the config-only shape.
+ config_serializer = ExperimentFeatureFlagInputSerializer(
+ data={key: value for key, value in feature_flag_input.items() if key != "id"}
)
- if isinstance(merged.get("feature_flag_variants"), list):
- # Same normalization the legacy ``parameters`` field applies (case-insensitive
- # 'control', split_percent translation) — both input surfaces must behave alike.
- merged["feature_flag_variants"] = _normalized_flag_variants(merged["feature_flag_variants"])
- ExperimentService.validate_experiment_parameters(merged)
- data["parameters"] = merged
+ config_serializer.is_valid(raise_exception=True)
+ config = dict(config_serializer.validated_data)
+ self._assert_flag_variants_valid(config)
+ data["feature_flag"] = config
return data
def validate_parameters(self, value):
@@ -568,9 +552,32 @@ class ExperimentSerializer(ExperimentBaseSerializer):
# (see ExperimentBaseSerializer._project_feature_flag_config). Strip any flag-config keys sent
# through `parameters` so they never reach the stored column; a legacy caller sending them is
# copied into the `feature_flag` path in _normalize_feature_flag_input instead of rejected.
- value = ExperimentService._strip_feature_flag_config(value)
- ExperimentService.validate_experiment_parameters(value)
- return value
+ return ExperimentService._strip_feature_flag_config(value)
+
+ @staticmethod
+ def _assert_flag_variants_valid(config: dict) -> None:
+ """Experiment-specific variant rules on the validated (already normalized) config. Raised as
+ plain top-level errors so the messages surface directly to LLM/API callers."""
+ variants = ((config.get("filters") or {}).get("multivariate") or {}).get("variants")
+ if variants is None:
+ return
+ if len(variants) >= 21:
+ raise serializers.ValidationError("Feature flag variants must be less than 21")
+ if len(variants) > 0:
+ if len(variants) < 2:
+ raise serializers.ValidationError(
+ "Feature flag must have at least 2 variants (control and at least one test variant)"
+ )
+ keys = [variant["key"] for variant in variants]
+ if "control" not in keys:
+ # Capitalized 'Control' is auto-normalized (ExperimentFlagMultivariateSerializer), so
+ # anything reaching this branch genuinely lacks a baseline variant. Surface the keys
+ # we did receive so LLM callers can self-correct without a second roundtrip.
+ raise serializers.ValidationError(
+ "Feature flag variants must contain a variant with key 'control' "
+ f"(lowercase, exactly). Got keys: {keys}. Rename the baseline variant's "
+ "'key' to 'control'."
+ )
@staticmethod
def _is_feature_flag_config_input(feature_flag_input: Any) -> TypeGuard[dict]:
@@ -613,28 +620,10 @@ class ExperimentSerializer(ExperimentBaseSerializer):
}
if not changed:
return None
- return self._feature_flag_config_object(changed) or None
-
- @staticmethod
- def _feature_flag_config_object(flag_config: dict[str, Any]) -> dict[str, Any]:
- """Assemble a ``feature_flag`` config object (the flag's native write shape) from deprecated
- ``parameters`` flag-config keys, so the shared feature_flag input path can consume them.
- Mirrors the read projection's translation in reverse."""
- filters: dict[str, Any] = {}
- if "feature_flag_variants" in flag_config:
- filters["multivariate"] = {"variants": flag_config["feature_flag_variants"]}
- if flag_config.get("rollout_percentage") is not None:
- filters["groups"] = [{"properties": [], "rollout_percentage": flag_config["rollout_percentage"]}]
- if "aggregation_group_type_index" in flag_config:
- filters["aggregation_group_type_index"] = flag_config["aggregation_group_type_index"]
- if "feature_flag_payloads" in flag_config:
- filters["payloads"] = flag_config["feature_flag_payloads"]
- feature_flag_input: dict[str, Any] = {}
- if filters:
- feature_flag_input["filters"] = filters
- if "ensure_experience_continuity" in flag_config:
- feature_flag_input["ensure_experience_continuity"] = flag_config["ensure_experience_continuity"]
- return feature_flag_input
+ # Assemble the flag's native write shape from the changed deprecated keys. The service owns
+ # this translation (it is the reverse of the read projection) so both the HTTP path and direct
+ # service callers build the config identically.
+ return ExperimentService._feature_flag_config_from_parameters(changed)
@staticmethod
def _flag_config_echo_matches(key: str, sent: Any, projected: Any) -> bool:
@@ -683,6 +672,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
description=self.validated_data.get("description", ""),
type=self.validated_data.get("type", "product"),
parameters=self.validated_data.get("parameters"),
+ feature_flag_config=self.validated_data.get("feature_flag"),
running_time_calculation=self.validated_data.get("running_time_calculation"),
excluded_variants=self.validated_data.get("excluded_variants"),
metrics=self.validated_data.get("metrics"),
@@ -722,6 +712,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"description",
"type",
"parameters",
+ "feature_flag",
"running_time_calculation",
"excluded_variants",
"metrics",
@@ -765,14 +756,72 @@ class ExperimentSerializer(ExperimentBaseSerializer):
def update(self, instance: Experiment, validated_data: dict, *args: Any, **kwargs: Any) -> Experiment:
allow_unknown_events = validated_data.pop("allow_unknown_events", False)
+ feature_flag_config = validated_data.pop("feature_flag", None)
team = Team.objects.get(id=self.context["team_id"])
service = ExperimentService(team=team, user=self.context["request"].user)
return service.update_experiment(
- instance, validated_data, serializer_context=self.context, allow_unknown_events=allow_unknown_events
+ instance,
+ validated_data,
+ feature_flag_config=feature_flag_config,
+ serializer_context=self.context,
+ allow_unknown_events=allow_unknown_events,
)
-class ExperimentFlagRolloutGroupSerializer(serializers.Serializer):
+class _StrictFieldsMixin:
+ """Reject unknown keys instead of silently dropping them (DRF's default).
+
+ Applying half a validated object (taking the keys we know, ignoring the rest) would leave the
+ flag in a state the caller never asked for, so the experiment feature_flag input rejects any
+ key it doesn't recognize.
+ """
+
+ fields: Any
+
+ def to_internal_value(self, data: Any) -> Any:
+ if isinstance(data, dict):
+ unknown = sorted(set(data) - set(self.fields))
+ if unknown:
+ raise ValidationError(dict.fromkeys(unknown, "Unsupported key for the experiment feature_flag input."))
+ return super().to_internal_value(data) # type: ignore[misc]
+
+
+class ExperimentFlagVariantSerializer(serializers.Serializer):
+ """A single multivariate variant. Extra per-variant keys are dropped."""
+
+ key = serializers.CharField(
+ help_text="Unique variant key. Exactly one variant must use the key 'control' (the baseline)."
+ )
+ name = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Human-readable variant name.",
+ )
+ rollout_percentage = serializers.IntegerField(
+ min_value=0,
+ max_value=100,
+ help_text="Variant rollout percentage (0-100). Across variants these must sum to 100.",
+ )
+
+
+class ExperimentFlagMultivariateSerializer(_StrictFieldsMixin, serializers.Serializer):
+ """Multivariate config for the experiment's feature flag."""
+
+ variants = ExperimentFlagVariantSerializer(
+ many=True,
+ help_text="Variant definitions. Exactly one variant key must be the literal string 'control'.",
+ )
+
+ def to_internal_value(self, data: Any) -> Any:
+ # Normalize before per-variant validation so the case-insensitive 'control' rewrite and the
+ # deprecated split_percent -> rollout_percentage translation happen before the strict child
+ # serializer sees the variants (the child accepts only rollout_percentage).
+ if isinstance(data, dict) and isinstance(data.get("variants"), list):
+ data = {**data, "variants": _normalized_flag_variants(data["variants"])}
+ return super().to_internal_value(data)
+
+
+class ExperimentFlagRolloutGroupSerializer(_StrictFieldsMixin, serializers.Serializer):
"""A single release-condition group carrying only the overall rollout percentage, the one
groups entry the experiment input applies."""
@@ -795,10 +844,9 @@ class ExperimentFlagRolloutGroupSerializer(serializers.Serializer):
# Subclassing the flag's canonical filters schema (rather than redeclaring the shape) keeps the
-# experiment write surface from drifting when the flag filters schema changes. Constraints the
-# schema can't express are enforced at runtime by
-# ExperimentService.feature_flag_config_to_parameters.
-class ExperimentFeatureFlagFiltersSerializer(FeatureFlagFiltersSchemaSerializer):
+# experiment write surface from drifting when the flag filters schema changes. Strict field
+# handling rejects filters keys experiments don't apply.
+class ExperimentFeatureFlagFiltersSerializer(_StrictFieldsMixin, FeatureFlagFiltersSchemaSerializer):
"""Feature-flag filters accepted by the experiment endpoints: the flag's own filters shape,
minus the keys experiments don't apply."""
@@ -815,13 +863,21 @@ class ExperimentFeatureFlagFiltersSerializer(FeatureFlagFiltersSchemaSerializer)
max_length=1,
help_text='Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}].',
)
+ multivariate = ExperimentFlagMultivariateSerializer( # type: ignore[assignment]
+ required=False,
+ allow_null=True,
+ help_text="Multivariate variant configuration.",
+ )
-# Schema-only: runtime consumes the raw feature_flag object from initial_data (see
-# ExperimentSerializer._normalize_feature_flag_input), so echoed read-only flag objects
-# (carrying a non-null id) keep being tolerated instead of failing this validation.
-class ExperimentFeatureFlagInputSerializer(serializers.Serializer):
- """Flag config for experiment create/update, sent through the linked feature flag's own shape."""
+class ExperimentFeatureFlagInputSerializer(_StrictFieldsMixin, serializers.Serializer):
+ """Flag config for experiment create/update, sent through the linked feature flag's own shape.
+
+ Validated both as the OpenAPI request field (via ``ExperimentWriteSerializer``) and at runtime
+ (``ExperimentSerializer._normalize_feature_flag_input`` runs it against the raw feature_flag
+ object). Echoed read-only flag objects (carrying a non-null id) are handled upstream and never
+ reach this validation.
+ """
filters = ExperimentFeatureFlagFiltersSerializer(
required=False,
@@ -840,10 +896,10 @@ class ExperimentFeatureFlagInputSerializer(serializers.Serializer):
)
-# Schema-only request serializer: advertises the writable feature_flag input in OpenAPI. Runtime
-# writes still validate through ExperimentSerializer (the viewset's serializer_class), which reads
-# feature_flag from initial_data. Referenced only via extend_schema(request=...) on the
-# create/update/partial_update methods.
+# Advertises the writable feature_flag input in the OpenAPI request schema. PostHog's drf-spectacular
+# config doesn't split request/response components, so feature_flag stays read-only (MinimalFeatureFlag)
+# on ExperimentSerializer for the response, and this subclass carries the writable input for the
+# request. Referenced via extend_schema(request=...) on the create/update/partial_update methods.
class ExperimentWriteSerializer(ExperimentSerializer):
"""Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input."""
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index d34d8491847b..4c50c93b2d01 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -751,15 +751,19 @@ class EnterpriseExperimentsViewSet(
feature_flag_key=feature_flag_key,
description=data.get("description", ""),
parameters={
- "feature_flag_variants": variants,
- "feature_flag_payloads": feature_flag_payloads,
- "rollout_percentage": 100,
"prompt_metadata": {
"name": prompt_name,
"templates": templates,
"versions": versions,
},
},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {"variants": variants},
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": feature_flag_payloads,
+ },
+ },
metrics=metrics,
serializer_context=self.get_serializer_context(),
allow_unknown_events=True,
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index e4df9f4993f2..86da9d02ccea 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -1006,14 +1006,20 @@ class TestExperimentService(APIBaseTest):
description="All optional fields set",
type="web",
parameters={
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 34},
- {"key": "variant-a", "name": "Variant A", "rollout_percentage": 33},
- {"key": "variant-b", "name": "Variant B", "rollout_percentage": 33},
- ],
- "rollout_percentage": 80,
"minimum_detectable_effect": 20,
},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 34},
+ {"key": "variant-a", "name": "Variant A", "rollout_percentage": 33},
+ {"key": "variant-b", "name": "Variant B", "rollout_percentage": 33},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 80}],
+ },
+ },
metrics=[
{
"kind": "ExperimentMetric",
@@ -1272,13 +1278,16 @@ class TestExperimentService(APIBaseTest):
with self.assertRaises(ValidationError) as ctx:
service.update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 34},
- {"key": "test", "name": "Test", "rollout_percentage": 33},
- {"key": "new_variant", "name": "New", "rollout_percentage": 33},
- ]
+ {},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 34},
+ {"key": "test", "name": "Test", "rollout_percentage": 33},
+ {"key": "new_variant", "name": "New", "rollout_percentage": 33},
+ ]
+ }
}
},
)
@@ -1322,12 +1331,15 @@ class TestExperimentService(APIBaseTest):
service = self._service()
service.update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 50},
- {"key": "test", "name": "Test", "rollout_percentage": 50},
- ],
+ {},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ]
+ },
},
},
)
@@ -1342,13 +1354,16 @@ class TestExperimentService(APIBaseTest):
service.update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 34},
- {"key": "test", "name": "Test", "rollout_percentage": 33},
- {"key": "variant-b", "name": "Variant B", "rollout_percentage": 33},
- ],
+ {},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 34},
+ {"key": "test", "name": "Test", "rollout_percentage": 33},
+ {"key": "variant-b", "name": "Variant B", "rollout_percentage": 33},
+ ]
+ },
}
},
)
@@ -1365,15 +1380,17 @@ class TestExperimentService(APIBaseTest):
self._service().update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 75},
- {"key": "test", "name": "Test", "rollout_percentage": 25},
- ],
- "rollout_percentage": 50,
+ {"update_feature_flag_params": True},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 75},
+ {"key": "test", "name": "Test", "rollout_percentage": 25},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 50}],
},
- "update_feature_flag_params": True,
},
)
@@ -1395,14 +1412,16 @@ class TestExperimentService(APIBaseTest):
self._service().update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 75},
- {"key": "test", "name": "Test", "rollout_percentage": 25},
- ],
+ {**extra},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 75},
+ {"key": "test", "name": "Test", "rollout_percentage": 25},
+ ]
+ },
},
- **extra,
},
)
@@ -1425,14 +1444,16 @@ class TestExperimentService(APIBaseTest):
self._service().update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 70},
- {"key": "test", "name": "Test", "rollout_percentage": 30},
- ],
+ {"update_feature_flag_params": True},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 70},
+ {"key": "test", "name": "Test", "rollout_percentage": 30},
+ ]
+ },
},
- "update_feature_flag_params": True,
},
)
@@ -1462,14 +1483,16 @@ class TestExperimentService(APIBaseTest):
self._service().update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 70},
- {"key": "test", "name": "Test", "rollout_percentage": 30},
- ],
+ {"update_feature_flag_params": True},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 70},
+ {"key": "test", "name": "Test", "rollout_percentage": 30},
+ ]
+ },
},
- "update_feature_flag_params": True,
},
)
@@ -1488,15 +1511,17 @@ class TestExperimentService(APIBaseTest):
with self.assertRaises(ValidationError) as ctx:
self._service().update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "name": "Control", "rollout_percentage": 34},
- {"key": "test", "name": "Test", "rollout_percentage": 33},
- {"key": "new_variant", "name": "New", "rollout_percentage": 33},
- ]
+ {"update_feature_flag_params": True},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 34},
+ {"key": "test", "name": "Test", "rollout_percentage": 33},
+ {"key": "new_variant", "name": "New", "rollout_percentage": 33},
+ ]
+ }
},
- "update_feature_flag_params": True,
},
)
@@ -2177,6 +2202,21 @@ class TestExperimentService(APIBaseTest):
assert len(links) == 1
assert links[0].saved_metric_id == sm.id
+ # index 0 is the truthiness edge case: a `if index:` guard would wrongly drop it.
+ @parameterized.expand([("index_zero", 0), ("index_one", 1)])
+ def test_duplicate_experiment_preserves_group_aggregation(self, _name: str, group_index: int):
+ flag = self._create_flag(key="dup-group-source")
+ flag.filters = {**flag.filters, "aggregation_group_type_index": group_index}
+ flag.save()
+ service = self._service()
+ source = service.create_experiment(name="Group Source", feature_flag_key="dup-group-source")
+
+ # New key forces a fresh flag through _ensure_feature_flag rather than reusing the source.
+ dup = service.duplicate_experiment(source, feature_flag_key="dup-group-target")
+
+ assert dup.feature_flag.id != source.feature_flag.id
+ assert dup.feature_flag.aggregation_group_type_index == group_index
+
# ------------------------------------------------------------------
# Launch experiment
# ------------------------------------------------------------------
@@ -5088,61 +5128,24 @@ class TestExperimentService(APIBaseTest):
# Validation hardening
# ------------------------------------------------------------------
- def test_variant_missing_key_raises_validation_error(self):
- """Variant without 'key' should return 400, not 500 KeyError."""
- service = self._service()
- with self.assertRaises(ValidationError):
- service.create_experiment(
- name="Bad Variants",
- feature_flag_key="bad-variant-flag",
- parameters={
- "feature_flag_variants": [
- {"name": "Control", "rollout_percentage": 50},
- {"key": "test", "name": "Test", "rollout_percentage": 50},
- ]
- },
- )
-
- def test_variant_not_a_dict_raises_validation_error(self):
- """Variant that is not a dict should return 400."""
- service = self._service()
- with self.assertRaises(ValidationError):
- service.create_experiment(
- name="Bad Variants",
- feature_flag_key="bad-variant-flag-2",
- parameters={"feature_flag_variants": ["control", "test"]},
- )
-
- def test_variant_missing_both_percentages_raises_validation_error(self):
- """Variant without split_percent or rollout_percentage should be rejected."""
- service = self._service()
- with self.assertRaises(ValidationError) as ctx:
- service.create_experiment(
- name="Missing Percentages",
- feature_flag_key="missing-pct-flag",
- parameters={
- "feature_flag_variants": [
- {"key": "control"},
- {"key": "test", "rollout_percentage": 50},
- ]
- },
- )
- assert "split_percent" in str(ctx.exception)
-
- def test_variant_with_only_rollout_percentage_succeeds(self):
- """Legacy clients sending only rollout_percentage must still work (deprecated but accepted)."""
+ def test_create_with_rollout_only_variants_succeeds(self):
+ """Variants carrying rollout_percentage (the flag's native shape) build the flag as-is."""
service = self._service()
experiment = service.create_experiment(
- name="Legacy rollout only",
- feature_flag_key="legacy-rollout-flag",
- parameters={
- "feature_flag_variants": [
- {"key": "control", "rollout_percentage": 50},
- {"key": "test", "rollout_percentage": 50},
- ]
+ name="Rollout only",
+ feature_flag_key="rollout-only-flag",
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ }
+ }
},
)
- assert experiment.id is not None
+ assert [v["key"] for v in experiment.feature_flag.variants] == ["control", "test"]
def test_duplicate_metric_uuids_within_list_are_regenerated(self):
"""Duplicate metric UUIDs within one list should be silently regenerated.
@@ -6364,12 +6367,15 @@ class TestExperimentService(APIBaseTest):
with self.assertRaises(ValidationError):
service.update_experiment(
experiment,
- {
- "parameters": {
- "feature_flag_variants": [
- {"key": "control", "rollout_percentage": 50},
- {"key": "variant-b", "rollout_percentage": 50},
- ]
+ {},
+ feature_flag_config={
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "variant-b", "rollout_percentage": 50},
+ ]
+ }
}
},
)
diff --git a/products/experiments/backend/test/test_experiment_service_approvals.py b/products/experiments/backend/test/test_experiment_service_approvals.py
index 6ec33eab1bb0..76d93f938ced 100644
--- a/products/experiments/backend/test/test_experiment_service_approvals.py
+++ b/products/experiments/backend/test/test_experiment_service_approvals.py
@@ -193,7 +193,8 @@ class TestExperimentServiceApprovals(APIBaseTest):
with self.assertRaises(ApprovalRequired):
self._service().update_experiment(
experiment,
- {"parameters": {"feature_flag_variants": new_variants}, "update_feature_flag_params": True},
+ {"update_feature_flag_params": True},
+ feature_flag_config={"filters": {"multivariate": {"variants": new_variants}}},
serializer_context=context,
)
@@ -227,11 +228,11 @@ class TestExperimentServiceApprovals(APIBaseTest):
self._service().update_experiment(
experiment,
{
- "parameters": {"feature_flag_variants": new_variants},
"update_feature_flag_params": True,
# baseline_variant_key references a variant that does not exist in the resolved set.
"stats_config": {"baseline_variant_key": "nonexistent"},
},
+ feature_flag_config={"filters": {"multivariate": {"variants": new_variants}}},
serializer_context=context,
)
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 72e0c0d20c29..8a0415937229 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -829,18 +829,28 @@ export interface ExperimentFlagRolloutGroupApi {
properties?: unknown[]
}
-export interface FeatureFlagMultivariateVariantSchemaApi {
- /** Unique key for this variant. */
+/**
+ * A single multivariate variant. Extra per-variant keys are dropped.
+ */
+export interface ExperimentFlagVariantApi {
+ /** Unique variant key. Exactly one variant must use the key 'control' (the baseline). */
key: string
- /** Human-readable name for this variant. */
+ /** Human-readable variant name. */
name?: string
- /** Variant rollout percentage. */
+ /**
+ * Variant rollout percentage (0-100). Across variants these must sum to 100.
+ * @minimum 0
+ * @maximum 100
+ */
rollout_percentage: number
}
-export interface FeatureFlagMultivariateSchemaApi {
- /** Variant definitions for multivariate feature flags. */
- variants: FeatureFlagMultivariateVariantSchemaApi[]
+/**
+ * Multivariate config for the experiment's feature flag.
+ */
+export interface ExperimentFlagMultivariateApi {
+ /** Variant definitions. Exactly one variant key must be the literal string 'control'. */
+ variants: ExperimentFlagVariantApi[]
}
/**
@@ -855,8 +865,8 @@ export type ExperimentFeatureFlagFiltersApiPayloads = { [key: string]: string }
export interface ExperimentFeatureFlagFiltersApi {
/** Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}]. */
groups?: ExperimentFlagRolloutGroupApi[]
- /** Multivariate configuration for variant-based rollouts. */
- multivariate?: FeatureFlagMultivariateSchemaApi | null
+ /** Multivariate variant configuration. */
+ multivariate?: ExperimentFlagMultivariateApi | null
/**
* Group type index for group-based feature flags.
* @nullable
@@ -868,6 +878,11 @@ export interface ExperimentFeatureFlagFiltersApi {
/**
* Flag config for experiment create/update, sent through the linked feature flag's own shape.
+ *
+ * Validated both as the OpenAPI request field (via ``ExperimentWriteSerializer``) and at runtime
+ * (``ExperimentSerializer._normalize_feature_flag_input`` runs it against the raw feature_flag
+ * object). Echoed read-only flag objects (carrying a non-null id) are handled upstream and never
+ * reach this validation.
*/
export interface ExperimentFeatureFlagInputApi {
/** Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1fbb65bf83d0..b6f8b4f47de6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22999,18 +22999,28 @@ export namespace Schemas {
properties?: unknown[];
}
- export interface FeatureFlagMultivariateVariantSchema {
- /** Unique key for this variant. */
+ /**
+ * A single multivariate variant. Extra per-variant keys are dropped.
+ */
+ export interface ExperimentFlagVariant {
+ /** Unique variant key. Exactly one variant must use the key 'control' (the baseline). */
key: string;
- /** Human-readable name for this variant. */
+ /** Human-readable variant name. */
name?: string;
- /** Variant rollout percentage. */
+ /**
+ * Variant rollout percentage (0-100). Across variants these must sum to 100.
+ * @minimum 0
+ * @maximum 100
+ */
rollout_percentage: number;
}
- export interface FeatureFlagMultivariateSchema {
- /** Variant definitions for multivariate feature flags. */
- variants: FeatureFlagMultivariateVariantSchema[];
+ /**
+ * Multivariate config for the experiment's feature flag.
+ */
+ export interface ExperimentFlagMultivariate {
+ /** Variant definitions. Exactly one variant key must be the literal string 'control'. */
+ variants: ExperimentFlagVariant[];
}
/**
@@ -23020,8 +23030,8 @@ export namespace Schemas {
export interface ExperimentFeatureFlagFilters {
/** Overall rollout as a single group: [{"properties": [], "rollout_percentage": N}]. */
groups?: ExperimentFlagRolloutGroup[];
- /** Multivariate configuration for variant-based rollouts. */
- multivariate?: FeatureFlagMultivariateSchema | null;
+ /** Multivariate variant configuration. */
+ multivariate?: ExperimentFlagMultivariate | null;
/**
* Group type index for group-based feature flags.
* @nullable
@@ -23033,6 +23043,11 @@ export namespace Schemas {
/**
* Flag config for experiment create/update, sent through the linked feature flag's own shape.
+ *
+ * Validated both as the OpenAPI request field (via ``ExperimentWriteSerializer``) and at runtime
+ * (``ExperimentSerializer._normalize_feature_flag_input`` runs it against the raw feature_flag
+ * object). Echoed read-only flag objects (carrying a non-null id) are handled upstream and never
+ * reach this validation.
*/
export interface ExperimentFeatureFlagInput {
/** Flag config to apply: `multivariate.variants` (exactly one variant key must be the literal string 'control'), `groups` (a single group with `rollout_percentage` only; release conditions are not supported here, edit the feature flag directly), `aggregation_group_type_index`, and `payloads` (JSON-encoded strings keyed by variant key). On update, config this object omits is preserved from the linked flag's current state. */
@@ -24800,6 +24815,20 @@ export namespace Schemas {
properties: FeatureFlagConditionPropertyAnalysis[];
}
+ export interface FeatureFlagMultivariateVariantSchema {
+ /** Unique key for this variant. */
+ key: string;
+ /** Human-readable name for this variant. */
+ name?: string;
+ /** Variant rollout percentage. */
+ rollout_percentage: number;
+ }
+
+ export interface FeatureFlagMultivariateSchema {
+ /** Variant definitions for multivariate feature flags. */
+ variants: FeatureFlagMultivariateVariantSchema[];
+ }
+
/**
* Optional payload values keyed by variant key.
*/
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 58b73ee14115..085044b6e13c 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -747,6 +747,9 @@ export const experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemRolloutPerce
export const experimentsCreateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax = 0
+export const experimentsCreateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMin = 0
+export const experimentsCreateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMax = 100
+
export const experimentsCreateBodyArchivedDefault = false
export const experimentsCreateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneOperatorDefault = `exact`
export const experimentsCreateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneTypeDefault = `event`
@@ -890,26 +893,46 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
),
multivariate: zod
.union([
- zod.object({
- variants: zod
- .array(
- zod.object({
- key: zod.string().describe('Unique key for this variant.'),
- name: zod
- .string()
- .optional()
- .describe('Human-readable name for this variant.'),
- rollout_percentage: zod
- .number()
- .describe('Variant rollout percentage.'),
- })
- )
- .describe('Variant definitions for multivariate feature flags.'),
- }),
+ zod
+ .object({
+ variants: zod
+ .array(
+ zod
+ .object({
+ key: zod
+ .string()
+ .describe(
+ "Unique variant key. Exactly one variant must use the key 'control' (the baseline)."
+ ),
+ name: zod
+ .string()
+ .optional()
+ .describe('Human-readable variant name.'),
+ rollout_percentage: zod
+ .number()
+ .min(
+ experimentsCreateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMin
+ )
+ .max(
+ experimentsCreateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMax
+ )
+ .describe(
+ 'Variant rollout percentage (0-100). Across variants these must sum to 100.'
+ ),
+ })
+ .describe(
+ 'A single multivariate variant. Extra per-variant keys are dropped.'
+ )
+ )
+ .describe(
+ "Variant definitions. Exactly one variant key must be the literal string 'control'."
+ ),
+ })
+ .describe("Multivariate config for the experiment's feature flag."),
zod.null(),
])
.optional()
- .describe('Multivariate configuration for variant-based rollouts.'),
+ .describe('Multivariate variant configuration.'),
aggregation_group_type_index: zod
.number()
.nullish()
@@ -931,7 +954,9 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
.nullish()
.describe('Whether the flag persists variant assignment across authentication steps.'),
})
- .describe("Flag config for experiment create/update, sent through the linked feature flag's own shape.")
+ .describe(
+ "Flag config for experiment create/update, sent through the linked feature flag's own shape.\n\nValidated both as the OpenAPI request field (via ``ExperimentWriteSerializer``) and at runtime\n(``ExperimentSerializer._normalize_feature_flag_input`` runs it against the raw feature_flag\nobject). Echoed read-only flag objects (carrying a non-null id) are handled upstream and never\nreach this validation."
+ )
.optional()
.describe(
"Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is)."
@@ -4279,6 +4304,9 @@ export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemRollo
export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneGroupsItemPropertiesMax = 0
+export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMin = 0
+export const experimentsPartialUpdateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMax = 100
+
export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneOperatorDefault = `exact`
export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemOneTypeDefault = `event`
export const experimentsPartialUpdateBodyExposureCriteriaOneExposureConfigOnePropertiesItemTwoTypeDefault = `person`
@@ -4421,26 +4449,46 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
),
multivariate: zod
.union([
- zod.object({
- variants: zod
- .array(
- zod.object({
- key: zod.string().describe('Unique key for this variant.'),
- name: zod
- .string()
- .optional()
- .describe('Human-readable name for this variant.'),
- rollout_percentage: zod
- .number()
- .describe('Variant rollout percentage.'),
- })
- )
- .describe('Variant definitions for multivariate feature flags.'),
- }),
+ zod
+ .object({
+ variants: zod
+ .array(
+ zod
+ .object({
+ key: zod
+ .string()
+ .describe(
+ "Unique variant key. Exactly one variant must use the key 'control' (the baseline)."
+ ),
+ name: zod
+ .string()
+ .optional()
+ .describe('Human-readable variant name.'),
+ rollout_percentage: zod
+ .number()
+ .min(
+ experimentsPartialUpdateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMin
+ )
+ .max(
+ experimentsPartialUpdateBodyFeatureFlagOneFiltersOneMultivariateOneVariantsItemRolloutPercentageMax
+ )
+ .describe(
+ 'Variant rollout percentage (0-100). Across variants these must sum to 100.'
+ ),
+ })
+ .describe(
+ 'A single multivariate variant. Extra per-variant keys are dropped.'
+ )
+ )
+ .describe(
+ "Variant definitions. Exactly one variant key must be the literal string 'control'."
+ ),
+ })
+ .describe("Multivariate config for the experiment's feature flag."),
zod.null(),
])
.optional()
- .describe('Multivariate configuration for variant-based rollouts.'),
+ .describe('Multivariate variant configuration.'),
aggregation_group_type_index: zod
.number()
.nullish()
@@ -4462,7 +4510,9 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
.nullish()
.describe('Whether the flag persists variant assignment across authentication steps.'),
})
- .describe("Flag config for experiment create/update, sent through the linked feature flag's own shape.")
+ .describe(
+ "Flag config for experiment create/update, sent through the linked feature flag's own shape.\n\nValidated both as the OpenAPI request field (via ``ExperimentWriteSerializer``) and at runtime\n(``ExperimentSerializer._normalize_feature_flag_input`` runs it against the raw feature_flag\nobject). Echoed read-only flag objects (carrying a non-null id) are handled upstream and never\nreach this validation."
+ )
.optional()
.describe(
"Feature-flag config for the experiment, in the flag's own filters shape. The linked flag is the source of truth for variants, rollout, aggregation, payloads, and experience continuity: send config here instead of the deprecated `parameters` keys. On a running experiment, also send `update_feature_flag_params=true`. Cannot be combined with the key of a pre-existing feature flag on create (the experiment links to it as-is)."
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json
index 5c245ff15a5f..fb4c830be776 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json
@@ -2130,21 +2130,25 @@
"multivariate": {
"anyOf": [
{
+ "description": "Multivariate config for the experiment's feature flag.",
"properties": {
"variants": {
- "description": "Variant definitions for multivariate feature flags.",
+ "description": "Variant definitions. Exactly one variant key must be the literal string 'control'.",
"items": {
+ "description": "A single multivariate variant. Extra per-variant keys are dropped.",
"properties": {
"key": {
- "description": "Unique key for this variant.",
+ "description": "Unique variant key. Exactly one variant must use the key 'control' (the baseline).",
"type": "string"
},
"name": {
- "description": "Human-readable name for this variant.",
+ "description": "Human-readable variant name.",
"type": "string"
},
"rollout_percentage": {
- "description": "Variant rollout percentage.",
+ "description": "Variant rollout percentage (0-100). Across variants these must sum to 100.",
+ "maximum": 100,
+ "minimum": 0,
"type": "number"
}
},
@@ -2161,7 +2165,7 @@
"type": "null"
}
],
- "description": "Multivariate configuration for variant-based rollouts."
+ "description": "Multivariate variant configuration."
},
"payloads": {
"additionalProperties": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
index 0e1603a520b7..8543ba3bfe08 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
@@ -2172,21 +2172,25 @@
"multivariate": {
"anyOf": [
{
+ "description": "Multivariate config for the experiment's feature flag.",
"properties": {
"variants": {
- "description": "Variant definitions for multivariate feature flags.",
+ "description": "Variant definitions. Exactly one variant key must be the literal string 'control'.",
"items": {
+ "description": "A single multivariate variant. Extra per-variant keys are dropped.",
"properties": {
"key": {
- "description": "Unique key for this variant.",
+ "description": "Unique variant key. Exactly one variant must use the key 'control' (the baseline).",
"type": "string"
},
"name": {
- "description": "Human-readable name for this variant.",
+ "description": "Human-readable variant name.",
"type": "string"
},
"rollout_percentage": {
- "description": "Variant rollout percentage.",
+ "description": "Variant rollout percentage (0-100). Across variants these must sum to 100.",
+ "maximum": 100,
+ "minimum": 0,
"type": "number"
}
},
@@ -2203,7 +2207,7 @@
"type": "null"
}
],
- "description": "Multivariate configuration for variant-based rollouts."
+ "description": "Multivariate variant configuration."
},
"payloads": {
"additionalProperties": {