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): accept flag config via the feature_flag object (#66669)

Andersdfd5999b6c32
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 3173a29da81d..25681ea0d26b 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -388,7 +388,9 @@ experiments: PostgresTable = PostgresTable(
name="filters", description="JSON definition of the experiment's goal metric filters."
),
"parameters": StringJSONDatabaseField(
- name="parameters", description="JSON experiment parameters (variants, exposure, etc.)."
+ name="parameters",
+ description="JSON experiment parameters (e.g. sample size settings). Flag config such as "
+ "variants lives on the linked feature flag's filters, not in this column.",
),
"start_date": DateTimeDatabaseField(
name="start_date", description="When the experiment was launched; NULL if not started."
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index afa0722178cd..a254874cd58e 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -528,7 +528,13 @@ class ExperimentService:
# 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 = ("feature_flag_variants", "rollout_percentage", "aggregation_group_type_index")
+ FEATURE_FLAG_CONFIG_KEYS = (
+ "feature_flag_variants",
+ "rollout_percentage",
+ "aggregation_group_type_index",
+ "feature_flag_payloads",
+ "ensure_experience_continuity",
+ )
@classmethod
def _strip_feature_flag_config(cls, parameters: dict | None) -> dict | None:
@@ -539,6 +545,99 @@ class ExperimentService:
return parameters
return {k: v for k, v in parameters.items() if k not in cls.FEATURE_FLAG_CONFIG_KEYS}
+ @staticmethod
+ def _parameters_with_variant_detail(experiment: Experiment) -> dict[str, Any]:
+ """Parameters for analytics events: the stored column carries no flag config, so attach
+ the variant detail event consumers expect from the linked flag."""
+ 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.
+ """
+ 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."
+ }
+ )
+ 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
+
@staticmethod
def _variant_keys(variants: list | None) -> list[str]:
"""Extract variant keys from a feature_flag_variants list, skipping malformed entries."""
@@ -1801,7 +1900,7 @@ class ExperimentService:
completed_metadata = experiment.get_analytics_metadata()
completed_metadata["end_date"] = experiment.end_date.isoformat() if experiment.end_date else None
- completed_metadata["parameters"] = experiment.parameters
+ completed_metadata["parameters"] = self._parameters_with_variant_detail(experiment)
completed_metadata["stats_method"] = (experiment.stats_config or {}).get("method", "bayesian")
if experiment.start_date and experiment.end_date:
completed_metadata["duration"] = int((experiment.end_date - experiment.start_date).total_seconds())
@@ -2084,7 +2183,7 @@ class ExperimentService:
metadata = experiment.get_analytics_metadata()
metadata["variant_key"] = variant_key
metadata["release_to_everyone"] = release_to_everyone
- metadata["parameters"] = experiment.parameters
+ metadata["parameters"] = self._parameters_with_variant_detail(experiment)
report_user_action(
self.user,
@@ -2274,10 +2373,18 @@ class ExperimentService:
"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"]
+
+ 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"
+ ]
existing_flag_serializer = FeatureFlagSerializer(
feature_flag,
- data={"filters": new_filters},
+ data=flag_update_data,
partial=True,
context=context,
)
@@ -2559,11 +2666,19 @@ class ExperimentService:
parameters = deepcopy(source_experiment.parameters) or {}
- # Variants come from the source experiment's feature flag (the source of truth),
- # not the stale copy denormalized into parameters.
+ # 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)
# An existing flag in the target project wins — reuse its variants instead.
# For cross-project clones we always check the target; for same-project
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 9ecdce68dc8c..2c0d93a49127 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -61,47 +61,53 @@ class ExperimentMetricsField(serializers.JSONField):
pass
+def _with_split_percent(variants: list) -> list:
+ # Add split_percent to outside representation for each variant to simplify frontend logic. The internal representation only uses rollout_percentage to avoid redundancy, but the frontend needs split_percent to display the variant splits in the UI and to support editing the splits in a user-friendly way (editing rollout_percentage directly would be more complex since it's not variant-specific and needs to be inferred from the variants' split_percent values).
+ return [
+ {**variant, "split_percent": variant["rollout_percentage"]}
+ if isinstance(variant, dict) and "rollout_percentage" in variant
+ else variant
+ for variant in variants
+ ]
+
+
+def _normalized_flag_variants(variants: list) -> list:
+ """Returns a new list, leaving the caller's input (e.g. request.data) untouched."""
+ variants = deepcopy(variants)
+ # Normalize a case-insensitive 'control' key (e.g. 'Control', 'CONTROL') down
+ # to lowercase 'control'. The downstream validator and runtime treat 'control'
+ # as a special key, so a typo in casing was the leading cause of the
+ # "Feature flag variants must contain a control variant" error in MCP traces —
+ # most often from LLM-generated payloads. Only rewrite when no exact 'control'
+ # match already exists, so we never collapse two distinct keys into a duplicate.
+ existing_keys = {v.get("key") for v in variants if isinstance(v, dict)}
+ if "control" not in existing_keys:
+ for variant in variants:
+ if not isinstance(variant, dict):
+ continue
+ key = variant.get("key")
+ if isinstance(key, str) and key != "control" and key.lower() == "control":
+ variant["key"] = "control"
+ break
+ for variant in variants:
+ if isinstance(variant, dict) and "split_percent" in variant:
+ # split_percent wins in case both keys present, as rollout_percentage deprecated
+ variant["rollout_percentage"] = variant.pop("split_percent")
+ return variants
+
+
@extend_schema_field(ExperimentParameters) # type: ignore[arg-type]
class ExperimentParametersField(serializers.JSONField):
def to_representation(self, value: Any) -> Any:
- from copy import deepcopy
-
- # Add split_percent to outside representation for each variant to simplify frontend logic. The internal representation only uses rollout_percentage to avoid redundancy, but the frontend needs split_percent to display the variant splits in the UI and to support editing the splits in a user-friendly way (editing rollout_percentage directly would be more complex since it's not variant-specific and needs to be inferred from the variants' split_percent values).
- # Deep copy to avoid mutating the model instance's in-memory parameters dict
- data: Any = deepcopy(super().to_representation(value))
- if isinstance(data, dict) and "feature_flag_variants" in data:
- for variant in data["feature_flag_variants"]:
- if isinstance(variant, dict) and "rollout_percentage" in variant:
- variant["split_percent"] = variant["rollout_percentage"]
+ data: Any = super().to_representation(value)
+ if isinstance(data, dict) and isinstance(data.get("feature_flag_variants"), list):
+ # New dicts throughout, to avoid mutating the model instance's in-memory parameters
+ data = {**data, "feature_flag_variants": _with_split_percent(data["feature_flag_variants"])}
return data
def to_internal_value(self, data: Any) -> Any:
- from copy import deepcopy
-
- # Deep copy to avoid mutating the caller's dict (e.g. serializer.initial_data / request.data)
- if isinstance(data, dict) and "feature_flag_variants" in data:
- data = deepcopy(data)
- variants = data["feature_flag_variants"]
- if isinstance(variants, list):
- # Normalize a case-insensitive 'control' key (e.g. 'Control', 'CONTROL') down
- # to lowercase 'control'. The downstream validator and runtime treat 'control'
- # as a special key, so a typo in casing was the leading cause of the
- # "Feature flag variants must contain a control variant" error in MCP traces —
- # most often from LLM-generated payloads. Only rewrite when no exact 'control'
- # match already exists, so we never collapse two distinct keys into a duplicate.
- existing_keys = {v.get("key") for v in variants if isinstance(v, dict)}
- if "control" not in existing_keys:
- for variant in variants:
- if not isinstance(variant, dict):
- continue
- key = variant.get("key")
- if isinstance(key, str) and key != "control" and key.lower() == "control":
- variant["key"] = "control"
- break
- for variant in variants:
- if isinstance(variant, dict) and "split_percent" in variant:
- # split_percent wins in case both keys present, as rollout_percentage deprecated
- variant["rollout_percentage"] = variant.pop("split_percent")
+ if isinstance(data, dict) and isinstance(data.get("feature_flag_variants"), list):
+ data = {**data, "feature_flag_variants": _normalized_flag_variants(data["feature_flag_variants"])}
return super().to_internal_value(data)
@@ -152,9 +158,11 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Mod
allow_null=True,
help_text=(
"Experiment parameters JSON. Supported keys include "
- "`feature_flag_variants`, `rollout_percentage`, "
- "`custom_exposure_filter`, and `variant_notes` "
+ "`custom_exposure_filter` and `variant_notes` "
"(free-text notes per variant, keyed by variant key). "
+ "Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated "
+ "input surface kept for compatibility — the linked feature flag is the source of "
+ "truth, and reads project its current config into this field. "
"Excluded variants live on the top-level `excluded_variants` field, not here."
),
)
@@ -244,27 +252,24 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Mod
def _project_feature_flag_config(data: dict[str, Any], flag: FeatureFlag | None) -> None:
"""Source feature-flag config in the deprecated `parameters` projection from the linked flag.
- The flag is the source of truth for variants/rollout/aggregation group type — `parameters`
+ The flag is the source of truth for every key in ``FEATURE_FLAG_CONFIG_KEYS`` — `parameters`
is a deprecated compatibility surface (see the experiment model's `parameters` comment).
Reading these keys from the flag instead of the stored column lets us stop persisting the
- `parameters` mirror without changing the API response. The linked flag is already serialized
- into `data["feature_flag"]`, so this adds no queries.
+ `parameters` mirror without changing the API response. It also keeps read-modify-write
+ echoes safe: legacy rows still carry stale copies in the column until the backfill strips
+ them, and a client that spreads a GET response into a save must echo the flag's live
+ config, not stale values the update path would then sync onto the flag. The linked flag is
+ already serialized into `data["feature_flag"]`, so this adds no queries.
"""
if flag is None:
return
parameters = dict(data.get("parameters") or {})
- variants = deepcopy(flag.variants)
- for variant in variants:
- # Mirror ExperimentParametersField.to_representation: the UI edits splits via split_percent.
- if isinstance(variant, dict) and "rollout_percentage" in variant:
- variant["split_percent"] = variant["rollout_percentage"]
- parameters["feature_flag_variants"] = variants
+ parameters["feature_flag_variants"] = _with_split_percent(flag.variants)
filters = flag.get_filters()
- aggregation_group_type_index = filters.get("aggregation_group_type_index")
- if aggregation_group_type_index is not None:
- parameters["aggregation_group_type_index"] = aggregation_group_type_index
+ if flag.aggregation_group_type_index is not None:
+ parameters["aggregation_group_type_index"] = flag.aggregation_group_type_index
else:
parameters.pop("aggregation_group_type_index", None)
@@ -274,6 +279,17 @@ class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.Mod
else:
parameters.pop("rollout_percentage", None)
+ payloads = filters.get("payloads")
+ if payloads:
+ parameters["feature_flag_payloads"] = payloads
+ else:
+ parameters.pop("feature_flag_payloads", None)
+
+ if flag.ensure_experience_continuity is not None:
+ parameters["ensure_experience_continuity"] = flag.ensure_experience_continuity
+ else:
+ parameters.pop("ensure_experience_continuity", None)
+
data["parameters"] = parameters
@@ -472,8 +488,77 @@ class ExperimentSerializer(ExperimentBaseSerializer):
def validate(self, data):
ExperimentService.validate_experiment_date_range(data.get("start_date"), data.get("end_date"))
+ data = self._normalize_feature_flag_input(data)
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.
+
+ 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 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.
+ """
+ feature_flag_input = (getattr(self, "initial_data", None) or {}).get("feature_flag")
+ if not isinstance(feature_flag_input, dict) or feature_flag_input.get("id") is not None:
+ return data
+ if not any(key in feature_flag_input for key in ("filters", "ensure_experience_continuity")):
+ return data
+ if self.instance is None:
+ # The service links an existing flag as-is (it may already serve traffic), so explicit
+ # config here would be applied nowhere — reject instead of silently dropping it.
+ flag_key = data.get("get_feature_flag_key")
+ if flag_key and FeatureFlag.objects.filter(key=flag_key, team_id=self.context["team_id"]).exists():
+ raise serializers.ValidationError(
+ {
+ "feature_flag": f"A feature flag with key '{flag_key}' already exists; the experiment "
+ "links to it as-is, so its config cannot be set here. Omit feature_flag to reuse "
+ "the existing flag, or edit the flag directly."
+ }
+ )
+ # On a running experiment the service only syncs flag config when the caller opts in;
+ # without the opt-in the config would be applied nowhere and silently dropped.
+ if self.instance is not None and not self.instance.is_draft and not data.get("update_feature_flag_params"):
+ raise serializers.ValidationError(
+ {
+ "feature_flag": "This experiment is running. To change its flag config, "
+ "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,
+ )
+ 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
+ return data
+
def validate_parameters(self, value):
ExperimentService.validate_experiment_parameters(value)
return value
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 0933f30b3185..164890daa93b 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -2310,6 +2310,561 @@ class TestExperimentCRUD(APILicensedTest):
self.assertNotIn("feature_flag_variants", experiment.parameters)
self.assertEqual(experiment.parameters["variant_notes"], {"control": "still baseline"})
+ def test_create_experiment_with_feature_flag_config_object(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF object create",
+ "feature_flag_key": "ff-object-create",
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 80}],
+ },
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+
+ flag = FeatureFlag.objects.get(key="ff-object-create", team_id=self.team.id)
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test"])
+ self.assertEqual(flag.filters["groups"][0]["rollout_percentage"], 80)
+
+ experiment = Experiment.objects.get(id=response.json()["id"])
+ self.assertNotIn("feature_flag_variants", experiment.parameters or {})
+ self.assertEqual(
+ [v["key"] for v in response.json()["parameters"]["feature_flag_variants"]],
+ ["control", "test"],
+ )
+
+ def test_update_draft_experiment_with_feature_flag_config_object(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF object update",
+ "feature_flag_key": "ff-object-update",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ],
+ "minimum_detectable_effect": 30,
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 34},
+ {"key": "test", "rollout_percentage": 33},
+ {"key": "test_2", "rollout_percentage": 33},
+ ]
+ }
+ }
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag = FeatureFlag.objects.get(key="ff-object-update", team_id=self.team.id)
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test", "test_2"])
+
+ # A feature_flag-only PATCH must not clobber unrelated parameters.
+ experiment = Experiment.objects.get(id=experiment_id)
+ self.assertEqual((experiment.parameters or {})["minimum_detectable_effect"], 30)
+
+ def test_feature_flag_object_takes_precedence_over_parameters(self):
+ # When both inputs are sent, the explicit feature_flag object wins over the legacy
+ # parameters.feature_flag_variants.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF precedence",
+ "feature_flag_key": "ff-precedence",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "ignored", "rollout_percentage": 50},
+ ]
+ },
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "winner", "rollout_percentage": 50},
+ ]
+ }
+ }
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ flag = FeatureFlag.objects.get(key="ff-precedence", team_id=self.team.id)
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "winner"])
+
+ def test_echoed_feature_flag_object_is_ignored_on_round_trip(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF echo",
+ "feature_flag_key": "ff-echo",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+
+ # Read-modify-write client: the frontend spreads the whole GET response into the save,
+ # including the serialized read-only flag (which carries `id`). The stale echo must not
+ # override the edited `parameters` variants.
+ echoed_flag = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}").json()[
+ "feature_flag"
+ ]
+ self.assertIn("id", echoed_flag)
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 60},
+ {"key": "test", "rollout_percentage": 40},
+ ]
+ },
+ "feature_flag": echoed_flag,
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag = FeatureFlag.objects.get(key="ff-echo", team_id=self.team.id)
+ self.assertEqual([v["rollout_percentage"] for v in flag.variants], [60, 40])
+
+ def test_partial_feature_flag_object_preserves_omitted_flag_config(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF partial",
+ "feature_flag_key": "ff-partial",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 34},
+ {"key": "red", "rollout_percentage": 33},
+ {"key": "blue", "rollout_percentage": 33},
+ ],
+ "aggregation_group_type_index": 1,
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+ flag = FeatureFlag.objects.get(key="ff-partial", team_id=self.team.id)
+ self.assertEqual(flag.filters["aggregation_group_type_index"], 1)
+
+ # A rollout-only config object must not reset the flag's variants to defaults or clear
+ # its aggregation group type — omitted config keeps the flag's current state.
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {"feature_flag": {"filters": {"groups": [{"properties": [], "rollout_percentage": 30}]}}},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag.refresh_from_db()
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "red", "blue"])
+ self.assertEqual(flag.filters["aggregation_group_type_index"], 1)
+ self.assertEqual(flag.filters["groups"][0]["rollout_percentage"], 30)
+
+ @parameterized.expand(
+ [
+ ("filters_not_object", {"filters": "oops"}),
+ ("multivariate_not_object", {"filters": {"multivariate": [1]}}),
+ ("group_not_object", {"filters": {"groups": ["x"]}}),
+ (
+ "group_properties_unsupported",
+ {"filters": {"groups": [{"properties": [{"key": "email", "value": "a"}], "rollout_percentage": 50}]}},
+ ),
+ (
+ "multiple_groups_unsupported",
+ {"filters": {"groups": [{"rollout_percentage": 50}, {"rollout_percentage": 100}]}},
+ ),
+ (
+ "unknown_top_level_key",
+ {"active": False, "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}},
+ ),
+ ("unknown_filters_key", {"filters": {"super_groups": []}}),
+ ]
+ )
+ def test_invalid_feature_flag_object_returns_400(self, _name, feature_flag_input):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {"name": "FF invalid", "feature_flag_key": "ff-invalid", "feature_flag": feature_flag_input},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+ self.assertFalse(FeatureFlag.objects.filter(key="ff-invalid", team_id=self.team.id).exists())
+
+ def test_feature_flag_object_normalizes_control_variant_key(self):
+ # Same normalization as the legacy parameters path — LLM/MCP payloads often send 'Control'.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF control case",
+ "feature_flag_key": "ff-control-case",
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "Control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ }
+ }
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ flag = FeatureFlag.objects.get(key="ff-control-case", team_id=self.team.id)
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test"])
+
+ def test_feature_flag_object_on_running_experiment_requires_opt_in(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF running",
+ "feature_flag_key": "ff-running",
+ "start_date": "2021-12-01T10:23",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+ new_variants_input = {
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 60},
+ {"key": "test", "rollout_percentage": 40},
+ ]
+ }
+ }
+ }
+ }
+
+ # Without the opt-in the service would sync nothing — reject loudly instead.
+ response = self.client.patch(f"/api/projects/{self.team.id}/experiments/{experiment_id}", new_variants_input)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("update_feature_flag_params", str(response.json()))
+ flag = FeatureFlag.objects.get(key="ff-running", team_id=self.team.id)
+ self.assertEqual([v["rollout_percentage"] for v in flag.variants], [50, 50])
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {**new_variants_input, "update_feature_flag_params": True},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag.refresh_from_db()
+ self.assertEqual([v["rollout_percentage"] for v in flag.variants], [60, 40])
+
+ def test_feature_flag_object_payloads_and_continuity_live_on_the_flag(self):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF payloads",
+ "feature_flag_key": "ff-payloads",
+ "feature_flag": {
+ "ensure_experience_continuity": True,
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ "payloads": {"test": '"v1"'},
+ },
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ experiment_id = response.json()["id"]
+
+ flag = FeatureFlag.objects.get(key="ff-payloads", team_id=self.team.id)
+ self.assertEqual(flag.filters["payloads"], {"test": '"v1"'})
+ self.assertTrue(flag.ensure_experience_continuity)
+ experiment = Experiment.objects.get(id=experiment_id)
+ self.assertNotIn("feature_flag_payloads", experiment.parameters or {})
+ self.assertNotIn("ensure_experience_continuity", experiment.parameters or {})
+
+ # A draft update through the object syncs payloads to the flag too.
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {"feature_flag": {"filters": {"payloads": {"test": '"v2"'}}}},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag.refresh_from_db()
+ self.assertEqual(flag.filters["payloads"], {"test": '"v2"'})
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test"])
+
+ def test_duplicate_experiment_carries_flag_payloads_and_continuity(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF clone source",
+ "feature_flag_key": "ff-clone-src",
+ "feature_flag": {
+ "ensure_experience_continuity": True,
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ "payloads": {"test": '"v1"'},
+ },
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+
+ # The stored column carries no flag config, so the duplicate's new flag must inherit
+ # payloads and continuity from the source flag, not lose them.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{create.json()['id']}/duplicate",
+ {"feature_flag_key": "ff-clone-dst"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ new_flag = FeatureFlag.objects.get(key="ff-clone-dst", team_id=self.team.id)
+ self.assertEqual(new_flag.filters["payloads"], {"test": '"v1"'})
+ self.assertTrue(new_flag.ensure_experience_continuity)
+
+ def test_stale_persisted_flag_config_is_not_echoed_back_onto_the_flag(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF stale echo",
+ "feature_flag_key": "ff-stale-echo",
+ "feature_flag": {
+ "ensure_experience_continuity": True,
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ "payloads": {"test": '"live"'},
+ },
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+
+ # Legacy rows still carry flag config in the column until the backfill strips it.
+ Experiment.objects.filter(id=experiment_id).update(
+ parameters={
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 90},
+ {"key": "test", "rollout_percentage": 10},
+ ],
+ "feature_flag_payloads": {"test": '"stale"'},
+ "ensure_experience_continuity": False,
+ }
+ )
+
+ # Reads must project the flag's live config so a read-modify-write client echoes live
+ # values — not the stale column — into its next save.
+ get_parameters = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}").json()[
+ "parameters"
+ ]
+ self.assertEqual(get_parameters["feature_flag_payloads"], {"test": '"live"'})
+ self.assertTrue(get_parameters["ensure_experience_continuity"])
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {"name": "FF stale echo renamed", "parameters": get_parameters},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag = FeatureFlag.objects.get(key="ff-stale-echo", team_id=self.team.id)
+ self.assertEqual(flag.filters["payloads"], {"test": '"live"'})
+ self.assertTrue(flag.ensure_experience_continuity)
+ self.assertEqual([v["rollout_percentage"] for v in flag.variants], [50, 50])
+
+ def test_partial_feature_flag_object_ignores_stale_column_config(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF stale column",
+ "feature_flag_key": "ff-stale-column",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ experiment_id = create.json()["id"]
+
+ # Legacy rows still carry stale flag config in the column until the backfill strips it;
+ # patch semantics must backfill omitted config from the flag's live state, not the column.
+ Experiment.objects.filter(id=experiment_id).update(
+ parameters={
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 90},
+ {"key": "stale", "rollout_percentage": 10},
+ ],
+ "rollout_percentage": 5,
+ }
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment_id}",
+ {"feature_flag": {"filters": {"payloads": {"test": '"v1"'}}}},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ flag = FeatureFlag.objects.get(key="ff-stale-column", team_id=self.team.id)
+ self.assertEqual(flag.filters["payloads"], {"test": '"v1"'})
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test"])
+ self.assertEqual(flag.filters["groups"][0]["rollout_percentage"], 100)
+
+ def test_feature_flag_object_with_null_id_is_write_intent(self):
+ # Typed clients may serialize an optional id as null; only a non-null id marks an echo.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF null id",
+ "feature_flag_key": "ff-null-id",
+ "feature_flag": {
+ "id": None,
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 34},
+ {"key": "test_a", "rollout_percentage": 33},
+ {"key": "test_b", "rollout_percentage": 33},
+ ]
+ }
+ },
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ flag = FeatureFlag.objects.get(key="ff-null-id", team_id=self.team.id)
+ self.assertEqual([v["key"] for v in flag.variants], ["control", "test_a", "test_b"])
+
+ def test_create_with_existing_flag_and_feature_flag_config_returns_400(self):
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="ff-preexisting",
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ # The service links an existing flag as-is, so explicit config would be silently dropped.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF preexisting",
+ "feature_flag_key": "ff-preexisting",
+ "feature_flag": {
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 60},
+ {"key": "test", "rollout_percentage": 40},
+ ]
+ }
+ }
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("already exists", str(response.json()))
+
+ def test_config_free_feature_flag_stub_is_ignored(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF stub",
+ "feature_flag_key": "ff-stub",
+ "start_date": "2021-12-01T10:23",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+
+ # An object with no config keys carries no write intent — clients that include such stubs
+ # in write bodies must keep working, even on running experiments.
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{create.json()['id']}",
+ {"name": "FF stub renamed", "feature_flag": {"key": "ff-stub", "active": True}},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(response.json()["name"], "FF stub renamed")
+
+ def test_duplicate_experiment_with_null_flag_continuity_stays_off(self):
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/",
+ {
+ "name": "FF null continuity",
+ "feature_flag_key": "ff-null-continuity",
+ "parameters": {
+ "feature_flag_variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ self.assertEqual(create.status_code, status.HTTP_201_CREATED, create.json())
+ FeatureFlag.objects.filter(key="ff-null-continuity", team_id=self.team.id).update(
+ ensure_experience_continuity=None
+ )
+ # A NULL continuity behaves as off; the clone must not pick up the team default instead.
+ self.team.flags_persistence_default = True
+ self.team.save()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiments/{create.json()['id']}/duplicate",
+ {"feature_flag_key": "ff-null-continuity-copy"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ new_flag = FeatureFlag.objects.get(key="ff-null-continuity-copy", team_id=self.team.id)
+ self.assertFalse(new_flag.ensure_experience_continuity)
+
def test_experiment_response_includes_feature_flag(self):
"""Test that experiment responses include the feature_flag field correctly serialized."""
response = self.client.post(
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 167b97ef501e..2805a86a1474 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -768,7 +768,7 @@ export interface ExperimentBasicApi {
readonly holdout: ExperimentHoldoutApi
/** @nullable */
readonly exposure_cohort: number | null
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParametersApi | null
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculationApi | null
@@ -1310,7 +1310,7 @@ export interface ExperimentApi {
holdout_id?: number | null
/** @nullable */
readonly exposure_cohort: number | null
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParametersApi | null
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculationApi | null
@@ -1416,7 +1416,7 @@ export interface PatchedExperimentApi {
holdout_id?: number | null
/** @nullable */
readonly exposure_cohort?: number | null
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParametersApi | null
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculationApi | null
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 56cc83c473b4..55084d19ab20 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1962,9 +1962,8 @@ class FeatureFlagSerializer(
# nosemgrep: idor-lookup-without-team -- dashboard objects validated via get_fields() queryset restriction
FeatureFlagDashboards.objects.get_or_create(dashboard=dashboard, feature_flag=instance)
- # The linked feature flag is the source of truth for variants and aggregation group type.
- # Experiment reads derive these from the flag (see ExperimentBaseSerializer), so there is no
- # longer a `parameters` mirror to keep in sync here.
+ # The linked feature flag is the source of truth for variants and aggregation group type;
+ # experiment reads derive these from the flag (see ExperimentBaseSerializer).
if old_key != instance.key:
_update_feature_flag_dashboard(instance, old_key)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bc5cc4597332..7046f4bdcee8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -22020,7 +22020,7 @@ export namespace Schemas {
holdout_id?: number | null;
/** @nullable */
readonly exposure_cohort: number | null;
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParameters | null;
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculation | null;
@@ -22129,7 +22129,7 @@ export namespace Schemas {
readonly holdout: ExperimentHoldout;
/** @nullable */
readonly exposure_cohort: number | null;
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParameters | null;
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculation | null;
@@ -38026,7 +38026,7 @@ export namespace Schemas {
holdout_id?: number | null;
/** @nullable */
readonly exposure_cohort?: number | null;
- /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here. */
+ /** Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here. */
parameters?: ExperimentParameters | null;
/** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`. */
running_time_calculation?: ExperimentRunningTimeCalculation | null;
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 0f23d5d3adaa..b04424097079 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -903,7 +903,7 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here.'
+ 'Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here.'
),
running_time_calculation: zod
.union([
@@ -4324,7 +4324,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here.'
+ 'Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here.'
),
running_time_calculation: zod
.union([
@@ -7804,7 +7804,7 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- 'Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here.'
+ 'Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here.'
),
running_time_calculation: zod
.union([
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 2232a6627050..290499df5d17 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
@@ -5438,7 +5438,7 @@
"type": "null"
}
],
- "description": "Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `custom_exposure_filter`, and `variant_notes` (free-text notes per variant, keyed by variant key). Excluded variants live on the top-level `excluded_variants` field, not here."
+ "description": "Experiment parameters JSON. Supported keys include `custom_exposure_filter` and `variant_notes` (free-text notes per variant, keyed by variant key). Flag config keys (`feature_flag_variants`, `rollout_percentage`) are a deprecated input surface kept for compatibility — the linked feature flag is the source of truth, and reads project its current config into this field. Excluded variants live on the top-level `excluded_variants` field, not here."
},
"running_time_calculation": {
"anyOf": [