:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): don't require control in flag variants (#70125)
Anders11b7d38aeeb2
diff --git a/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.tsx b/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.tsxindex a163a0034e51..94dc8362693c 100644--- a/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.tsx+++ b/frontend/src/scenes/experiments/ExperimentForm/SelectExistingFeatureFlagModal.tsx@@ -42,8 +42,8 @@ export const SelectExistingFeatureFlagModal = ({<LemonModal isOpen={isModalOpen} onClose={handleClose} title="Choose an existing feature flag" width="50%"><div className="deprecated-space-y-2"><div className="text-muted mb-2 max-w-xl">- Select an existing multivariate feature flag to use with this experiment. The feature flag must use- multiple variants with <code>'control'</code> as the first.+ Select an existing multivariate feature flag to use with this experiment. The variant keyed{' '}+ <code>'control'</code> is used as the analysis baseline, or the first variant if there is none.</div>{filtersSection}<LemonTablediff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsxindex 33c719fa0bec..7704497ec4d2 100644--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx@@ -103,6 +103,28 @@ describe('VariantsPanelCreateFeatureFlag', () => {expect(testInput).toBeInTheDocument()})+ it('allows renaming the control variant for product experiments', () => {+ renderComponent(defaultExperiment)++ const controlInput = screen.getByDisplayValue('control')+ expect(controlInput).toBeEnabled()++ fireEvent.change(controlInput, { target: { value: 'baseline' } })++ expect(mockOnChange).toHaveBeenCalledWith(+ expect.objectContaining({+ variants: [expect.objectContaining({ key: 'baseline' }), expect.objectContaining({ key: 'test' })],+ })+ )+ })++ it('locks the control variant key for web experiments', () => {+ renderComponent({ ...defaultExperiment, type: 'web' })++ expect(screen.getByDisplayValue('control')).toBeDisabled()+ expect(screen.getByDisplayValue('test')).toBeEnabled()+ })+it('renders variant split labels by default', () => {renderComponent(defaultExperiment)diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsxindex dc2d9beacb76..52cae490a005 100644--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.tsx@@ -237,8 +237,8 @@ export const VariantsPanelCreateFeatureFlag = ({disabledReason={disabled? 'Cannot edit feature flag in edit mode'- : variant.key === 'control'- ? 'Control variant cannot be changed'+ : experiment.type === 'web' && variant.key === 'control'+ ? "Web experiments require a variant with key 'control'": null}onChange={(value) =>diff --git a/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.test.ts b/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.test.tsnew file mode 100644index 000000000000..f16082b9ba16--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.test.ts@@ -0,0 +1,40 @@+import type { Experiment } from '~/types'++import { NEW_EXPERIMENT } from '../constants'+import { validateExperimentSubmission } from './experimentSubmissionValidation'++describe('validateExperimentSubmission', () => {+ const WEB_CONTROL_ERROR = "Web experiments require a variant with key 'control'"++ const experimentWith = (type: Experiment['type'], variantKeys: string[]): Experiment => ({+ ...NEW_EXPERIMENT,+ name: 'My experiment',+ feature_flag_key: 'my-experiment',+ type,+ feature_flag_config: {+ filters: {+ multivariate: {+ variants: variantKeys.map((key) => ({ key, rollout_percentage: 100 / variantKeys.length })),+ },+ },+ },+ })++ it.each([+ ['web', ['baseline', 'test'], true],+ ['web', ['control', 'test'], false],+ ['product', ['baseline', 'test'], false],+ ] as [Experiment['type'], string[], boolean][])(+ 'a %s experiment with variants %p requires control: %s',+ (type, variantKeys, expectError) => {+ const { errors } = validateExperimentSubmission({+ experiment: experimentWith(type, variantKeys),+ featureFlagKeyValidation: null,+ mode: 'create',+ experimentErrors: {},+ })++ expect(errors.includes(WEB_CONTROL_ERROR)).toBe(expectError)+ }+ )+})diff --git a/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.ts b/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.tsindex e2b8d38184a9..eaad03c52257 100644--- a/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/experimentSubmissionValidation.ts@@ -28,14 +28,20 @@ export const validateExperimentSubmission = ({}// Check variants+ const variants = getExperimentVariants(experiment)const variantErrors = getVariantValidationErrors({flagKey: experiment.feature_flag_key,- variants: getExperimentVariants(experiment),+ variants,featureFlagKeyValidation,mode,})errors.push(...variantErrors)+ // The toolbar editor hard-requires 'control', so the backend rejects web experiments without it+ if (experiment.type === 'web' && variants.length > 0 && !variants.some(({ key }) => key === 'control')) {+ errors.push("Web experiments require a variant with key 'control'")+ }+// Include any other experiment errorsObject.values(experimentErrors).forEach((error) => {if (error && !errors.includes(error)) {diff --git a/frontend/src/scenes/experiments/ExperimentTabContent.tsx b/frontend/src/scenes/experiments/ExperimentTabContent.tsxindex 7ae9510be834..e6f973658902 100644--- a/frontend/src/scenes/experiments/ExperimentTabContent.tsx+++ b/frontend/src/scenes/experiments/ExperimentTabContent.tsx@@ -7,7 +7,7 @@ import type { FeatureFlagType } from '~/types'import { CreateDraftExperimentCard } from './ExperimentTabContent/CreateDraftExperimentCard'import { RelatedExperimentsTable } from './ExperimentTabContent/RelatedExperimentsTable'import { experimentTabLogic } from './experimentTabLogic'-import { getFlagVariants } from './utils'+import { featureFlagEligibleForExperiment } from './utils'type ExperimentTabContentProps = {featureFlag: FeatureFlagType@@ -25,16 +25,20 @@ export const ExperimentTabContent = ({experimentTabLogic({ featureFlagId: featureFlag.id! }))- const variants = getFlagVariants(featureFlag)- const isValidMultivariateFlag = variants.length > 1 && variants.some((variant) => variant.key === 'control')+ let eligibilityError: string | null = null+ try {+ featureFlagEligibleForExperiment(featureFlag)+ } catch (error) {+ eligibilityError = (error as Error).message+ }- if (!isValidMultivariateFlag) {+ if (eligibilityError) {return (<div className="space-y-6"><LemonBanner type="warning"><div className="flex flex-col gap-3"><div>- Experiments require a multivariate flag with multiple variants and a control variant. + {eligibilityError} <Link to="https://posthog.com/docs/experiments/creating-an-experiment">Learn more in the docs</Link>diff --git a/frontend/src/scenes/experiments/ExperimentView/DistributionTable.tsx b/frontend/src/scenes/experiments/ExperimentView/DistributionTable.tsxindex 4306381a32d9..2d8d36d356a7 100644--- a/frontend/src/scenes/experiments/ExperimentView/DistributionTable.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/DistributionTable.tsx@@ -24,7 +24,7 @@ import {} from '~/scenes/experiments/ExperimentForm/VariantDistributionEditor'import { experimentLogic } from '~/scenes/experiments/experimentLogic'import { modalsLogic } from '~/scenes/experiments/modalsLogic'-import { getExperimentVariants } from '~/scenes/experiments/utils'+import { getBaselineVariantKey, getExperimentVariants } from '~/scenes/experiments/utils'import { MultivariateFlagVariant } from '~/types'import { HoldoutSelector } from './HoldoutSelector'@@ -113,11 +113,7 @@ export function DistributionTable(): JSX.Element {const excludedVariantsEnabled = useFeatureFlag('EXPERIMENTS_EXCLUDED_VARIANTS')- /**- * This is future-proofing to match the experiment query runner backend, that uses- * the baseline variant key to determine the baseline variant.- */- const baselineKey = experiment.stats_config?.baseline_variant_key || 'control'+ const baselineKey = getBaselineVariantKey(experiment)const variants = getExperimentVariants(experiment)/**diff --git a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsxindex 314c1e091c8f..fb62d3e0e9ae 100644--- a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx@@ -12,6 +12,7 @@ import { ExperimentStatsMethod, PropertyFilterType, PropertyOperator } from '~/timport { DEFAULT_LOOKBACK_DAYS } from '../constants'import { experimentLogic } from '../experimentLogic'import { modalsLogic } from '../modalsLogic'+import { getBaselineVariantKey } from '../utils'import { getCupedSelection, resolveCupedEnabled, resolveCupedLookbackDays } from './cuped'import { CupedModal } from './CupedModal'import { resolveSequentialEnabled } from './sequential'@@ -90,7 +91,7 @@ export function SettingsTab(): JSX.Element {<div><h2 className="font-semibold text-lg">Baseline variant</h2><LemonSelect- value={experiment.stats_config?.baseline_variant_key ?? 'control'}+ value={getBaselineVariantKey(experiment)}options={variants.map((v) => ({value: v.key,label: v.key,diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 260b9325e62c..d3828f917a5c 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -32,6 +32,7 @@ import {exposureConfigToFilter,featureFlagEligibleForExperiment,filterToExposureConfig,+ getBaselineVariantKey,getEventCountQuery,getOrderedMetricsWithResults,getViewRecordingFilters,@@ -566,55 +567,69 @@ describe('checkFeatureFlagEligibility', () => {evaluation_contexts: [],bucketing_identifier: FeatureFlagBucketingIdentifier.DISTINCT_ID,}- it('throws an error for a remote configuration feature flag', () => {+ const withVariants = (variantKeys: string[]): FeatureFlagType => ({+ ...baseFeatureFlag,+ filters: {+ ...baseFeatureFlag.filters,+ multivariate: {+ variants: variantKeys.map((key) => ({ key, rollout_percentage: 100 / variantKeys.length })),+ },+ },+ })++ it('throws an error for a remote configuration feature flag (no variants)', () => {const featureFlag = { ...baseFeatureFlag, is_remote_configuration: true }expect(() => featureFlagEligibleForExperiment(featureFlag)).toThrow(- 'Feature flag must use multiple variants with control as the first variant.'+ 'Feature flag must have at least 2 variants (a baseline and at least one test variant).')})- it('throws an error for a feature flag without control as the first variant', () => {- const featureFlag = {- ...baseFeatureFlag,- filters: {- ...baseFeatureFlag.filters,- multivariate: {- variants: [- { key: 'foobar', rollout_percentage: 50 },- { key: 'control', rollout_percentage: 50 },- ],- },- },- }- expect(() => featureFlagEligibleForExperiment(featureFlag)).toThrow(- 'Feature flag must have control as the first variant.'+ it('throws an error for a feature flag with only one variant', () => {+ expect(() => featureFlagEligibleForExperiment(withVariants(['test']))).toThrow(+ 'Feature flag must have at least 2 variants (a baseline and at least one test variant).')})- it('throws an error for a feature flag with only one variant', () => {- const featureFlag = {- ...baseFeatureFlag,- filters: {- ...baseFeatureFlag.filters,- multivariate: { variants: [{ key: 'test', rollout_percentage: 50 }] },- },- }- expect(() => featureFlagEligibleForExperiment(featureFlag)).toThrow(- 'Feature flag must use multiple variants with control as the first variant.'+ it('throws an error for a feature flag with more than 20 variants', () => {+ const manyVariants = Array.from({ length: 21 }, (_, i) => `variant-${i}`)+ expect(() => featureFlagEligibleForExperiment(withVariants(manyVariants))).toThrow(+ 'Feature flag must have at most 20 variants.')})+ it('returns true for a feature flag with exactly 20 variants', () => {+ const maxVariants = Array.from({ length: 20 }, (_, i) => `variant-${i}`)+ expect(featureFlagEligibleForExperiment(withVariants(maxVariants))).toEqual(true)+ })it('returns true for a feature flag with control and test variants', () => {- const featureFlag = {- ...baseFeatureFlag,- filters: {- ...baseFeatureFlag.filters,- multivariate: {- variants: [- { key: 'control', rollout_percentage: 50 },- { key: 'test', rollout_percentage: 50 },- ],+ expect(featureFlagEligibleForExperiment(withVariants(['control', 'test']))).toEqual(true)+ })+ it('returns true for a feature flag without a control variant', () => {+ expect(featureFlagEligibleForExperiment(withVariants(['foobar', 'test']))).toEqual(true)+ })+ it('returns true for a feature flag with control not as the first variant', () => {+ expect(featureFlagEligibleForExperiment(withVariants(['foobar', 'control']))).toEqual(true)+ })+})++describe('getBaselineVariantKey', () => {+ const experimentWith = (variantKeys: string[], baselineVariantKey?: string): Partial<Experiment> =>+ ({+ stats_config: baselineVariantKey ? { baseline_variant_key: baselineVariantKey } : {},+ feature_flag: {+ filters: {+ multivariate: { variants: variantKeys.map((key) => ({ key, rollout_percentage: 50 })) },},},- }- expect(featureFlagEligibleForExperiment(featureFlag)).toEqual(true)+ }) as unknown as Partial<Experiment>++ it.each([+ ['the configured baseline_variant_key', experimentWith(['variant-a', 'variant-b'], 'variant-b'), 'variant-b'],+ ['control when present and unconfigured', experimentWith(['variant-a', 'control']), 'control'],+ [+ 'the first variant when control-less and unconfigured',+ experimentWith(['variant-a', 'variant-b']),+ 'variant-a',+ ],+ ])('resolves %s', (_name, experiment, expected) => {+ expect(getBaselineVariantKey(experiment)).toEqual(expected)})})diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 5feaacdef6f5..9d8b83e3c76a 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -1,7 +1,7 @@import { match } from 'ts-pattern'import { getSeriesColor } from 'lib/colors'-import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout } from 'lib/constants'+import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout, MAX_EXPERIMENT_VARIANTS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { uuid } from 'lib/utils/dom'import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'@@ -112,6 +112,24 @@ export function getFlagVariants(return flag?.filters?.multivariate?.variants ?? []}+/**+ * The effective baseline variant, mirroring the backend rule (get_baseline_variant_key):+ * the configured stats_config.baseline_variant_key, else 'control' when the flag has one,+ * else the flag's first variant. A control-less draft can lack the configured key until+ * launch pins it, so callers must not assume 'control' exists.+ */+export function getBaselineVariantKey(experiment: Partial<Experiment> | null | undefined): string {+ const configured = experiment?.stats_config?.baseline_variant_key+ if (configured) {+ return configured+ }+ const variants = getExperimentVariants(experiment)+ if (variants.length === 0 || variants.some((variant) => variant.key === 'control')) {+ return 'control'+ }+ return variants[0].key+}+export function formatUnitByQuantity(value: number, unit: string): string {return value === 1 ? unit : unit + 's'}@@ -381,16 +399,16 @@ export function getViewRecordingFiltersLegacy(return filters}+// Mirrors the backend eligibility rule (experiment_eligibility_error): multivariate with 2-20 variantsexport function featureFlagEligibleForExperiment(featureFlag: FeatureFlagType): true {const variants = getFlagVariants(featureFlag)- if (variants.length > 1) {- if (variants[0].key !== 'control') {- throw new Error('Feature flag must have control as the first variant.')- }- return true+ if (variants.length < 2) {+ throw new Error('Feature flag must have at least 2 variants (a baseline and at least one test variant).')}-- throw new Error('Feature flag must use multiple variants with control as the first variant.')+ if (variants.length > MAX_EXPERIMENT_VARIANTS) {+ throw new Error(`Feature flag must have at most ${MAX_EXPERIMENT_VARIANTS} variants.`)+ }+ return true}/**diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 163fd037f9fc..2fb7b3dfa5a4 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -831,6 +831,7 @@'has_feature_enrollment','holdout','id',+ 'is_eligible_for_experiment','key_without_tombstone','last_called_at','last_modified_by_id',diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 21f3cd140e82..c5c41329aead 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -48,11 +48,14 @@ from posthog.models.person.util import get_person_ids_and_uuids_by_uuidsfrom posthog.models.signals import mute_selected_signalsfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Team+from posthog.models.user import User+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.utils import str_to_boolfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan+from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY, get_baseline_variant_keyfrom products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_mathfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.exposure_query_logic import (@@ -90,7 +93,7 @@ from products.feature_flags.backend.facade.api import (user_can_edit_flag,)from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext-from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_errorfrom products.notifications.backend.facade.api import (NotificationData,NotificationType,@@ -554,7 +557,8 @@ class ExperimentService:When ``variant_keys`` is provided, a ``baseline_variant_key`` set in``stats_config`` must be one of them. When ``variant_keys`` is None/empty,baseline validation is skipped (the caller couldn't supply the keys).- Absence of ``baseline_variant_key`` is always valid (defaults to control downstream).+ Absence of ``baseline_variant_key`` is always valid (downstream defaults to+ 'control' when present, else the first variant — see get_baseline_variant_key)."""if not stats_config:return@@ -570,6 +574,38 @@ class ExperimentService:f"Must be one of: {', '.join(sorted(variant_keys))}")+ @staticmethod+ def _materialize_baseline_variant_key(+ stats_config: dict | None, variant_keys: list[str], *, current_variant_keys: list[str] | None = None+ ) -> dict | None:+ """Pin the inferred baseline for control-less variant sets.++ Without 'control' among the variants the implicit default is the first variant,+ which is order-sensitive — a later reorder of the same keys would silently move+ the baseline under historical results. Persisting the key at write time makes+ the choice explicit and visible to API/frontend consumers. With 'control'+ present the default is order-independent, so absence is left as-is.++ ``current_variant_keys`` is the pre-update variant set: the pinned key is the+ baseline currently in effect (a [A, B] → [B, A] reorder keeps A), not the first+ key of the new order. When the current baseline does not survive into+ ``variant_keys``, nothing is pinned — the launch paths pin against the flag's+ final variant set instead.++ Contract: returns ``stats_config`` itself (the same object) when nothing is+ pinned, and a new dict only when a baseline was pinned. Callers rely on this+ identity (``result is not stats_config``) to detect a pin — every no-op branch+ must keep returning the input object, never an equal copy.+ """+ if (stats_config or {}).get("baseline_variant_key"):+ return stats_config+ if not variant_keys or CONTROL_VARIANT_KEY in variant_keys:+ return stats_config+ baseline = get_baseline_variant_key(stats_config, current_variant_keys or variant_keys)+ if baseline not in variant_keys:+ return stats_config+ return {**(stats_config or {}), "baseline_variant_key": baseline}+# 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@@ -920,11 +956,15 @@ class ExperimentService:used_variant_keys = self._variant_keys(used_variants)self.validate_stats_config(stats_config, used_variant_keys)+ self._assert_web_experiment_has_control(type, used_variant_keys)++ stats_config = self._materialize_baseline_variant_key(stats_config, used_variant_keys)+# Validate excluded_variants against the variants the flag actually ends up with,# mirroring the baseline check above. Resolving against the flag (not the request# payload) is what lets the excluded_variants path skip re-sending feature_flag_variants.if excluded_variants:- baseline_key = (stats_config or {}).get("baseline_variant_key", "control")+ baseline_key = get_baseline_variant_key(stats_config, used_variant_keys)self._validate_excluded_variant_keys(excluded_variants, used_variant_keys, baseline_key)team_config = self._get_team_experiments_config()@@ -1191,19 +1231,34 @@ class ExperimentService:def _validate_existing_flag(self, feature_flag: FeatureFlag) -> None:"""Validate that an existing feature flag is suitable for experiment use."""- variants = feature_flag.filters.get("multivariate", {}).get("variants", [])-- if len(variants) < 2:- raise ValidationError("Feature flag must have at least 2 variants (control and at least one test variant)")+ error = experiment_eligibility_error(feature_flag.variants)+ if error:+ raise ValidationError(error)- if "control" not in [variant["key"] for variant in variants]:- raise ValidationError("Feature flag must have a variant with key 'control'")+ @staticmethod+ def _assert_web_experiment_has_control(experiment_type: str | None, variant_keys: list[str]) -> None:+ """The toolbar editor and WebExperimentsAPISerializer hard-require a 'control'+ variant, so a control-less web experiment could never be edited or saved from+ the toolbar. Enforced on create, update, and launch."""+ if experiment_type == "web" and CONTROL_VARIANT_KEY not in variant_keys:+ raise ValidationError("Web experiments require a variant with key 'control'")def _assert_flag_not_deleted_for_launch(self, feature_flag: FeatureFlag) -> None:"""A deleted flag distributes no traffic, so an experiment can never go live on it."""if feature_flag.deleted:raise ValidationError("Experiment cannot be launched because its feature flag has been deleted.")+ def _validate_flag_for_launch(self, experiment: Experiment, feature_flag: FeatureFlag) -> None:+ """Flag guards shared by launch_experiment and the PATCH(start_date) launch path.++ The flag can drift after create (edited directly through the flags API), so launch+ re-checks everything create enforced: not deleted, experiment-eligible variants,+ and the web-only 'control' requirement.+ """+ self._assert_flag_not_deleted_for_launch(feature_flag)+ self._validate_existing_flag(feature_flag)+ self._assert_web_experiment_has_control(experiment.type, self._variant_keys(feature_flag.variants))+@staticmethoddef _assign_uuids_to_metrics(metrics: list[dict] | None,@@ -1503,8 +1558,21 @@ class ExperimentService:# Validate feature flag configurationfeature_flag = experiment.feature_flag- self._assert_flag_not_deleted_for_launch(feature_flag)- self._validate_existing_flag(feature_flag)+ self._validate_flag_for_launch(experiment, feature_flag)++ # The flag may have lost 'control' since create (out-of-band edit), so pin the+ # inferred baseline before it goes live — the fingerprints below and all later+ # results must not depend on variant order. A dangling configured baseline is+ # rejected rather than silently launched with uncomputable results.+ flag_variant_keys = self._variant_keys(feature_flag.variants)+ self.validate_stats_config(experiment.stats_config, flag_variant_keys)+ experiment.stats_config = self._materialize_baseline_variant_key(experiment.stats_config, flag_variant_keys)+ if experiment.excluded_variants:+ self._validate_excluded_variant_keys(+ experiment.excluded_variants,+ flag_variant_keys,+ get_baseline_variant_key(experiment.stats_config, flag_variant_keys),+ )# Activate the feature flag through the approval gate first. If approval is# required this raises ApprovalRequired (-> 409) before we touch the experiment,@@ -2799,22 +2867,59 @@ class ExperimentService:# Revalidate the baseline whenever either side of the constraint changes:# 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.+ # must not leave a dangling baseline_variant_key behind. Launching via PATCH+ # (start_date) also runs this so the flag's current variants get a pinned+ # baseline exactly like the dedicated launch action.update_variants = self._flag_config_variants(feature_flag_config)- if "stats_config" in update_data or update_variants is not None:+ stats_config_updated = "stats_config" in update_data+ launching = experiment.is_draft and update_data.get("start_date") is not None+ durable_baseline_pin: dict | None = None+ if stats_config_updated or update_variants is not None or launching:variant_keys = self._resolved_variant_keys(experiment, feature_flag_config)+ current_variant_keys = self._variant_keys(feature_flag.variants)effective_stats_config = update_data.get("stats_config", experiment.stats_config)self.validate_stats_config(effective_stats_config, variant_keys)+ # `type` is immutable on update (rejected by _validate_update_payload's+ # allowlist), so the persisted value is the effective one.+ if update_variants is not None:+ self._assert_web_experiment_has_control(experiment.type, variant_keys)++ # A variants update can leave an absent baseline pointing at an+ # order-sensitive default — pin the currently effective baseline, like on+ # create. When the flag write below is approval-gated, the approved change+ # request later applies flag-side only, so the pin must also be committed+ # independently of this update (durable_baseline_pin, persisted before the+ # flag write).+ materialized = self._materialize_baseline_variant_key(+ effective_stats_config, variant_keys, current_variant_keys=current_variant_keys+ )+ if materialized is not effective_stats_config:+ update_data["stats_config"] = materialized+ if update_variants is not None:+ pinned = self._materialize_baseline_variant_key(+ experiment.stats_config, variant_keys, current_variant_keys=current_variant_keys+ )+ if pinned is not experiment.stats_config:+ durable_baseline_pin = pinned+# Validate excluded_variants against the resolved flag variants — no- # feature_flag_variants resend required.- if "excluded_variants" in update_data:- new_excluded = update_data["excluded_variants"]- if new_excluded:+ # feature_flag_variants resend required. The stored list is revalidated too+ # whenever the variant set or baseline moves under it (e.g. a variants update+ # must not silently leave the baseline excluded, breaking result queries).+ if "excluded_variants" in update_data or stats_config_updated or update_variants is not None or launching:+ effective_excluded = (+ update_data["excluded_variants"] if "excluded_variants" in update_data else experiment.excluded_variants+ )+ if effective_excluded:+ # Not hoisted from the block above: the materialization there may have+ # replaced update_data["stats_config"] with a pinned baseline, which this+ # check must see. variant_keys is re-derived (same value) only because this+ # branch also runs for excluded_variants-only PATCHes that skip that block.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)+ baseline_key = get_baseline_variant_key(effective_stats_config, variant_keys)+ self._validate_excluded_variant_keys(effective_excluded, variant_keys, baseline_key)# Defense-in-depth: only validate the inline metric lists this update# is actually touching. Dedup-on-input has already made these lists@@ -2823,6 +2928,16 @@ class ExperimentService:if "metrics" in update_data or "metrics_secondary" in update_data:self.validate_no_duplicate_metric_uuids(update_data.get("metrics"), update_data.get("metrics_secondary"))+ # --- durable baseline pin (BEFORE the flag write) ---------------------+ # An approval-gated variants change raises ApprovalRequired below, aborting the+ # rest of this update, and the approved ChangeRequest later applies flag-side+ # only — it never re-enters this service. So the pin is committed on its own+ # first. It restates the currently effective baseline, which makes it a no-op+ # if the change request is rejected.+ if durable_baseline_pin is not None:+ experiment.stats_config = durable_baseline_pin+ experiment.save(update_fields=["stats_config", "updated_at"])+# --- feature flag sync (OUTSIDE the atomic block) ---------------------# The flag write goes through the FeatureFlagSerializer approval gate.# It runs before (and outside) the experiment-state transaction below so@@ -3121,10 +3236,9 @@ class ExperimentService:# Launching a draft via PATCH (start_date) is an alternate launch path, so it must# run the same flag guards as the dedicated launch_experiment action: flag not- # deleted, and a valid control/variant configuration.+ # deleted, and a valid variant configuration.if experiment.is_draft and update_data.get("start_date") is not None:- self._assert_flag_not_deleted_for_launch(feature_flag)- self._validate_existing_flag(feature_flag)+ self._validate_flag_for_launch(experiment, feature_flag)# Check for legacy metrics firstif experiment_has_legacy_metrics(experiment):@@ -3690,17 +3804,17 @@ class ExperimentService:evaluation_runtime: str | None,has_evaluation_contexts: str | bool | None,) -> QuerySet[FeatureFlag]:- queryset = FeatureFlag.objects.filter(team__project_id=self.team.project_id)-- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static SQL, no user input)- queryset = queryset.extra(- where=[- """- jsonb_array_length(filters->'multivariate'->'variants') >= 2- AND filters->'multivariate'->'variants'->0->>'key' = 'control'- """- ]- )+ queryset = FeatureFlag.objects.filter(team__project_id=self.team.project_id).eligible_for_experiment()++ # This action is experiment-scoped, so the flag resource's object-level access+ # controls are not applied by the viewset — filter here like the flag list+ # endpoint does, so private flags don't leak through the eligible-flags listing.+ if isinstance(self.user, User):+ queryset = UserAccessControl(user=self.user, team=self.team).filter_queryset_by_access_level(+ queryset, include_all_if_admin=True+ )+ else:+ queryset = queryset.none()if excluded_flag_ids:queryset = queryset.exclude(id__in=excluded_flag_ids)diff --git a/products/experiments/backend/hogql_queries/__init__.py b/products/experiments/backend/hogql_queries/__init__.pyindex 7399bfba48b4..2a2ca64d59a4 100644--- a/products/experiments/backend/hogql_queries/__init__.py+++ b/products/experiments/backend/hogql_queries/__init__.py@@ -1,6 +1,21 @@# The FF variant name for controlCONTROL_VARIANT_KEY = "control"++def get_baseline_variant_key(stats_config: dict | None, variant_keys: list[str]) -> str:+ """The effective baseline for an experiment: the configured baseline_variant_key,+ else 'control' when the flag has one, else the flag's first variant.++ The 'control'-when-present step keeps the baseline stable for pre-existing+ experiments whose flag has 'control' in a non-first position."""+ configured = (stats_config or {}).get("baseline_variant_key")+ if configured:+ return configured+ if not variant_keys or CONTROL_VARIANT_KEY in variant_keys:+ return CONTROL_VARIANT_KEY+ return variant_keys[0]++# The FF variant name for multiple variantsMULTIPLE_VARIANT_KEY = "$multiple"diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex d17d2b16a72f..2f380f880e4a 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -42,7 +42,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuensure_precomputed,parse_ttl_schedule,)-from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY, MULTIPLE_VARIANT_KEY+from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY, get_baseline_variant_keyfrom products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_endfrom products.experiments.backend.hogql_queries.cuped_config import get_cuped_configfrom products.experiments.backend.hogql_queries.error_handling import experiment_error_handler@@ -199,7 +199,7 @@ class ExperimentQueryRunner(QueryRunner):]stats_config = self.experiment.stats_config or {}- self.baseline_variant_key = stats_config.get("baseline_variant_key", CONTROL_VARIANT_KEY)+ self.baseline_variant_key = get_baseline_variant_key(stats_config, self.variants)self.date_range = experiment_window(self.experiment, self.team, self.as_of)self.date_range_query = QueryDateRange(diff --git a/products/experiments/backend/hogql_queries/test/test_stats_config.py b/products/experiments/backend/hogql_queries/test/test_stats_config.pyindex 2b93335f85a7..fae3d19e66fc 100644--- a/products/experiments/backend/hogql_queries/test/test_stats_config.py+++ b/products/experiments/backend/hogql_queries/test/test_stats_config.py@@ -361,12 +361,16 @@ class TestStatsConfig(APIBaseTest):@parameterized.expand([- ("stats_config_none", None, "control"),- ("stats_config_empty", {}, "control"),- ("stats_config_custom_baseline", {"baseline_variant_key": "test"}, "test"),+ ("stats_config_none", None, ["control", "test"], "control"),+ ("stats_config_empty", {}, ["control", "test"], "control"),+ ("stats_config_custom_baseline", {"baseline_variant_key": "test"}, ["control", "test"], "test"),+ ("no_control_falls_back_to_first_variant", None, ["variant_a", "variant_b"], "variant_a"),+ ("control_not_first_still_baseline", None, ["test", "control"], "control"),])- def test_experiment_query_runner_reads_baseline_from_stats_config(self, _name, stats_config, expected_baseline):+ def test_experiment_query_runner_reads_baseline_from_stats_config(+ self, _name, stats_config, variant_keys, expected_baseline+ ):feature_flag = FeatureFlag.objects.create(name="Test flag",key="test-flag",@@ -374,10 +378,7 @@ class TestStatsConfig(APIBaseTest):filters={"groups": [{"properties": [], "rollout_percentage": None}],"multivariate": {- "variants": [- {"key": "control", "name": "Control", "rollout_percentage": 50},- {"key": "test", "name": "Test", "rollout_percentage": 50},- ]+ "variants": [{"key": key, "name": key, "rollout_percentage": 50} for key in variant_keys]},},created_by=self.user,diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.pyindex 515b65da20d6..933c73c261c2 100644--- a/products/experiments/backend/max_tools.py+++ b/products/experiments/backend/max_tools.py@@ -18,7 +18,7 @@ from products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.experiment_summary_data_service import ExperimentSummaryDataServicefrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_methodfrom products.experiments.backend.models.experiment import Experiment-from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_errorfrom ee.hogai.context.experiment.context import ExperimentContextfrom ee.hogai.tool import MaxTool@@ -33,8 +33,8 @@ CREATE_EXPERIMENT_TOOL_DESCRIPTION = dedent("""# Prerequisites**IMPORTANT**: Before creating an experiment, you must first create a multivariate feature flag- using the `create_feature_flag` tool with at least two variants (control and test).- The first variant MUST be named "control".+ using the `create_feature_flag` tool with 2 to 20 variants (conventionally control and test).+ The baseline defaults to the variant named "control" when present, else the first variant.# Experiment Types- **product**: For backend/API changes, server-side experiments@@ -66,10 +66,11 @@ class CreateExperimentToolArgs(BaseModel):Requirements:- The flag must already exist (create it first with create_feature_flag)- The flag must have multivariate variants defined- - The flag must have at least 2 variants- - The first variant MUST be named "control"+ - The flag must have 2 to 20 variants- The flag cannot already be used by another experiment+ The baseline defaults to the variant keyed "control" when present, else the first variant.+Example: "pricing-page-experiment"""").strip())@@ -129,21 +130,11 @@ class CreateExperimentTool(MaxTool):except FeatureFlag.DoesNotExist:raise ValueError(f"Feature flag '{feature_flag_key}' does not exist")- multivariate = feature_flag.filters.get("multivariate")- if not multivariate or not multivariate.get("variants"):- raise ValueError(- f"Feature flag '{feature_flag_key}' must have multivariate variants to be used in an experiment. "- f"Create the flag with variants first using the create_feature_flag tool."- )-- variants = multivariate["variants"]- # Intentionally stricter than service validation for multi-variant flags:- # require control first for Max-created experiments.- # Single-variant flags are validated by the service with a clearer error.- if len(variants) >= 2 and variants[0].get("key") != "control":+ eligibility_error = experiment_eligibility_error(feature_flag.variants)+ if eligibility_error:raise ValueError(- f"Feature flag '{feature_flag_key}' must have 'control' as the first variant. "- f"Found '{variants[0].get('key')}' instead. Please update the feature flag variants."+ f"Feature flag '{feature_flag_key}' cannot back an experiment: {eligibility_error}. "+ f"Update the flag's variants, or create a new flag with the create_feature_flag tool.")existing_experiment_with_flag = Experiment.objects.filter(feature_flag=feature_flag, deleted=False).first()diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 8bed185ff080..65dd2b61248e 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -43,7 +43,7 @@ from products.experiments.backend.models.experiment import ()from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICESfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer-from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.feature_flag import FeatureFlag, experiment_eligibility_errorfrom ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializerfrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer@@ -76,8 +76,8 @@ 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+ # to lowercase 'control'. 'control' is the conventional baseline key (the default+ # baseline when present), and 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.@@ -556,28 +556,15 @@ class ExperimentSerializer(ExperimentBaseSerializer):@staticmethoddef _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."""+ """Variant rules on the validated (already normalized) config, raised as plain top-level+ errors so the messages surface directly to LLM/API callers. Absent or empty variants are+ allowed here — the service fills in the default control/test pair."""variants = ((config.get("filters") or {}).get("multivariate") or {}).get("variants")- if variants is None:+ if not variants: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'."- )+ error = experiment_eligibility_error(variants)+ if error:+ raise serializers.ValidationError(error)@staticmethoddef _is_feature_flag_config_input(feature_flag_input: Any) -> TypeGuard[dict]:@@ -795,7 +782,7 @@ 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)."+ help_text="Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant.")name = serializers.CharField(required=False,@@ -814,7 +801,7 @@ class ExperimentFlagMultivariateSerializer(_StrictFieldsMixin, serializers.Seriavariants = ExperimentFlagVariantSerializer(many=True,- help_text="Variant definitions. Exactly one variant key must be the literal string 'control'.",+ help_text="Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant.",)def to_internal_value(self, data: Any) -> Any:@@ -887,8 +874,9 @@ class ExperimentFeatureFlagInputSerializer(_StrictFieldsMixin, serializers.Seriafilters = ExperimentFeatureFlagFiltersSerializer(required=False,help_text=(- "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 "+ "Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to "+ "the variant keyed 'control' when present, else the first variant), "+ "`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/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 2fed3175b049..c86630afac5e 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -151,10 +151,10 @@ def list_is_legacy_annotation() -> Case:def _build_prompt_variants(versions: list[int]) -> list[dict[str, Any]]:"""Build N feature flag variants from an ordered list of prompt versions.- First variant is keyed "control" (required by ExperimentService._validate_existing_flag- when the experiment is later launched). For the standard 2-variant case the second is- keyed "test", matching the rest of the codebase's defaults. For N >= 3 the trailing- variants are keyed "test-1", "test-2", … so each key stays unique.+ First variant is keyed "control", matching the codebase's baseline convention (the+ baseline defaults to 'control' when present). For the standard 2-variant case the+ second is keyed "test", matching the rest of the codebase's defaults. For N >= 3 the+ trailing variants are keyed "test-1", "test-2", … so each key stays unique.The human-readable prompt version goes in the variant name so chart legends stay readable.Splits are integers summing to 100; the last variant absorbs any remainder."""@@ -416,7 +416,7 @@ class EnterpriseExperimentsViewSet(Validates the experiment is in draft state, activates its linked feature flag,sets start_date to the current server time, and transitions the experiment to running.Returns 400 if the experiment has already been launched or if the feature flag- configuration is invalid (e.g. missing "control" variant or fewer than 2 variants).+ configuration is invalid (e.g. fewer than 2 variants)."""experiment: Experiment = self.get_object()service = ExperimentService(team=self.team, user=request.user)@@ -879,8 +879,7 @@ class EnterpriseExperimentsViewSet(Returns a paginated list of feature flags eligible for use in experiments.Eligible flags must:- - Be multivariate with at least 2 variants- - Have "control" as the first variant key+ - Be multivariate with 2 to 20 variantsQuery parameters:- search: Filter by flag key or name (case insensitive)diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 65fc143ddc84..2dd7eb9559ad 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -393,7 +393,9 @@ class TestExperimentService(APIBaseTest):# Flag validation errors# ------------------------------------------------------------------- def test_existing_flag_without_control_raises(self):+ def test_existing_flag_without_control_pins_baseline_to_first_variant(self):+ # Without 'control' the default baseline is order-sensitive, so create+ # must persist the inferred key instead of leaving it implicit.self._create_flag(key="no-control",variants=[@@ -403,11 +405,210 @@ class TestExperimentService(APIBaseTest):)service = self._service()+ experiment = service.create_experiment(name="No Control", feature_flag_key="no-control")++ assert experiment.stats_config is not None+ assert experiment.stats_config["baseline_variant_key"] == "baseline"++ def test_existing_flag_with_control_leaves_baseline_unset(self):+ self._create_flag(key="with-control")+ service = self._service()++ experiment = service.create_experiment(name="With Control", feature_flag_key="with-control")++ assert "baseline_variant_key" not in (experiment.stats_config or {})++ def test_create_web_experiment_without_control_raises(self):+ # The toolbar editor and WebExperimentsAPISerializer hard-require 'control'.+ self._create_flag(+ key="no-control-web",+ variants=[+ {"key": "baseline", "name": "Baseline", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ],+ )+ service = self._service()+with self.assertRaises(ValidationError) as ctx:- service.create_experiment(name="Bad Flag", feature_flag_key="no-control")+ service.create_experiment(name="Bad Web", feature_flag_key="no-control-web", type="web")assert "control" in str(ctx.exception)+ def test_update_web_experiment_variants_dropping_control_raises(self):+ # Same guard as create/launch, on the update path: a web experiment must not+ # be PATCHable into a control-less variant set the toolbar can't edit.+ self._create_flag(key="web-update-flag")+ service = self._service()+ experiment = service.create_experiment(name="Web Update", feature_flag_key="web-update-flag", type="web")++ with self.assertRaises(ValidationError) as ctx:+ service.update_experiment(+ experiment,+ {},+ feature_flag_config={+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "variant-a", "name": "A", "rollout_percentage": 50},+ {"key": "variant-b", "name": "B", "rollout_percentage": 50},+ ]+ }+ }+ },+ )++ assert "control" in str(ctx.exception)++ def test_update_variants_dropping_control_defers_pin_to_launch(self):+ # Replacing 'control' changes the baseline's identity. Pinning the new order's+ # first key at update time would dangle if the flag write lands via a rejected+ # or pending change request, so the pin waits for launch (which reads the+ # flag's final state).+ experiment = self._create_draft_experiment()+ service = self._service()++ updated = service.update_experiment(+ experiment,+ {},+ feature_flag_config={+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "variant-a", "name": "A", "rollout_percentage": 50},+ {"key": "variant-b", "name": "B", "rollout_percentage": 50},+ ]+ }+ }+ },+ )++ assert "baseline_variant_key" not in (updated.stats_config or {})++ launched = service.launch_experiment(updated)++ assert launched.stats_config is not None+ assert launched.stats_config["baseline_variant_key"] == "variant-a"++ def test_update_variants_reorder_pins_currently_effective_baseline(self):+ # An unpinned control-less experiment implicitly uses the first variant; a+ # reorder must pin that same variant, not the new order's first.+ experiment = self._create_draft_experiment(flag_key="reorder-flag")+ flag = experiment.feature_flag+ flag.filters["multivariate"]["variants"] = [+ {"key": "variant-a", "rollout_percentage": 50},+ {"key": "variant-b", "rollout_percentage": 50},+ ]+ flag.save()+ experiment.feature_flag.refresh_from_db()+ service = self._service()++ updated = service.update_experiment(+ experiment,+ {},+ feature_flag_config={+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "variant-b", "rollout_percentage": 50},+ {"key": "variant-a", "rollout_percentage": 50},+ ]+ }+ }+ },+ )++ assert updated.stats_config is not None+ assert updated.stats_config["baseline_variant_key"] == "variant-a"++ def test_update_variants_baseline_pin_survives_approval_gate(self):+ # A gated variants change lands later via the approved change request, which+ # never re-enters the experiment service — the pin must already be committed+ # when ApprovalRequired aborts the update.+ experiment = self._create_draft_experiment(flag_key="approval-pin-flag")+ flag = experiment.feature_flag+ flag.filters["multivariate"]["variants"] = [+ {"key": "variant-a", "rollout_percentage": 50},+ {"key": "variant-b", "rollout_percentage": 50},+ ]+ flag.save()+ experiment.feature_flag.refresh_from_db()++ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.update",+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ # The gate detects rollout changes, so the reorder also shifts the split.+ with self.assertRaises(ApprovalRequired):+ self._service().update_experiment(+ experiment,+ {},+ feature_flag_config={+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "variant-b", "rollout_percentage": 60},+ {"key": "variant-a", "rollout_percentage": 40},+ ]+ }+ }+ },+ )++ experiment.refresh_from_db()+ assert experiment.stats_config is not None+ assert experiment.stats_config["baseline_variant_key"] == "variant-a"++ @parameterized.expand(+ [+ (+ "variants_update",+ {},+ {+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "variant-a", "rollout_percentage": 34},+ {"key": "variant-b", "rollout_percentage": 33},+ {"key": "variant-c", "rollout_percentage": 33},+ ]+ }+ }+ },+ ),+ ("baseline_update", {"stats_config": {"baseline_variant_key": "variant-a"}}, None),+ ]+ )+ def test_update_moving_baseline_onto_excluded_variant_raises(self, _name, update_data, feature_flag_config):+ # Stored exclusions must be revalidated when the variant set or baseline moves+ # under them — a variant both baseline and excluded breaks result queries.+ self._create_flag(+ key="excluded-baseline-flag",+ variants=[+ {"key": "control", "name": "Control", "rollout_percentage": 34},+ {"key": "variant-a", "name": "A", "rollout_percentage": 33},+ {"key": "variant-b", "name": "B", "rollout_percentage": 33},+ ],+ )+ service = self._service()+ experiment = service.create_experiment(+ name="Excluded Baseline",+ feature_flag_key="excluded-baseline-flag",+ excluded_variants=["variant-a"],+ )++ with self.assertRaises(ValidationError) as ctx:+ service.update_experiment(experiment, update_data, feature_flag_config=feature_flag_config)++ assert "baseline variant cannot be excluded" in str(ctx.exception)+def test_existing_flag_with_one_variant_raises(self):self._create_flag(key="one-variant",@@ -2427,12 +2628,54 @@ class TestExperimentService(APIBaseTest):assert groups[0]["properties"] == [{"key": "country", "value": "US", "type": "person"}]assert groups[0]["rollout_percentage"] == 50- def test_launch_experiment_flag_modified_to_invalid_raises(self):- """Flag modified after experiment creation to remove control variant. Launch should fail."""- flag = self._create_flag(key="will-break")- experiment = self._create_launchable_experiment(name="Will Break", feature_flag_key="will-break")+ def test_launch_experiment_flag_modified_to_control_less_launches(self):+ # A flag renamed away from 'control' out-of-band stays launchable, but the+ # inferred baseline must be pinned at launch — otherwise a later reorder+ # would silently move it under historical results.+ flag = self._create_flag(key="renamed-variants")+ experiment = self._create_launchable_experiment(name="Renamed Variants", feature_flag_key="renamed-variants")++ flag.filters["multivariate"]["variants"] = [+ {"key": "variant_a", "rollout_percentage": 50},+ {"key": "variant_b", "rollout_percentage": 50},+ ]+ flag.save()+ experiment.feature_flag.refresh_from_db()++ launched = self._service().launch_experiment(experiment)++ assert launched.start_date is not None+ experiment.refresh_from_db()+ assert experiment.stats_config is not None+ assert experiment.stats_config["baseline_variant_key"] == "variant_a"++ def test_launch_via_start_date_patch_pins_baseline_for_control_less_flag(self):+ # PATCHing start_date is an alternate launch path and must pin the inferred+ # baseline exactly like the dedicated launch action.+ flag = self._create_flag(key="patch-launch-flag")+ experiment = self._create_launchable_experiment(name="Patch Launch", feature_flag_key="patch-launch-flag")++ flag.filters["multivariate"]["variants"] = [+ {"key": "variant_a", "rollout_percentage": 50},+ {"key": "variant_b", "rollout_percentage": 50},+ ]+ flag.save()+ experiment.feature_flag.refresh_from_db()++ updated = self._service().update_experiment(experiment, {"start_date": timezone.now()})++ assert not updated.is_draft+ assert updated.stats_config is not None+ assert updated.stats_config["baseline_variant_key"] == "variant_a"++ def test_launch_web_experiment_flag_modified_to_control_less_raises(self):+ # The web guard on create can be bypassed by editing the flag out-of-band;+ # launch must re-check it, or the toolbar editor breaks on a live experiment.+ flag = self._create_flag(key="web-launch-flag")+ experiment = self._create_launchable_experiment(+ name="Web Launch", feature_flag_key="web-launch-flag", type="web"+ )- # Simulate someone modifying the flag to remove "control"flag.filters["multivariate"]["variants"] = [{"key": "variant_a", "rollout_percentage": 50},{"key": "variant_b", "rollout_percentage": 50},@@ -2443,7 +2686,7 @@ class TestExperimentService(APIBaseTest):with self.assertRaises(ValidationError) as ctx:self._service().launch_experiment(experiment)- assert "control" in str(ctx.exception).lower()+ assert "control" in str(ctx.exception)def test_launch_experiment_flag_reduced_to_single_variant_raises(self):"""Flag modified to have only 1 variant. Launch should fail."""@@ -4595,13 +4838,13 @@ class TestExperimentService(APIBaseTest):# Eligible feature flags# ------------------------------------------------------------------- def test_get_eligible_feature_flags_only_returns_control_first_multivariate_flags(self) -> None:+ def test_get_eligible_feature_flags_only_returns_multivariate_flags_within_variant_bounds(self) -> None:eligible_flag = self._create_flag(key="eligible-flag")- self._create_flag(- key="wrong-order-flag",+ no_control_flag = self._create_flag(+ key="no-control-flag",variants=[- {"key": "test", "name": "Test", "rollout_percentage": 50},- {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test-1", "name": "Test 1", "rollout_percentage": 50},+ {"key": "test-2", "name": "Test 2", "rollout_percentage": 50},],)self._create_flag(@@ -4611,8 +4854,8 @@ class TestExperimentService(APIBaseTest):result = self._service().get_eligible_feature_flags(order="key")- assert result["count"] == 1- assert [flag.key for flag in result["results"]] == [eligible_flag.key]+ assert result["count"] == 2+ assert [flag.key for flag in result["results"]] == [eligible_flag.key, no_control_flag.key]def test_get_eligible_feature_flags_applies_search_and_pagination(self) -> None:self._create_flag(key="search-alpha")@@ -4643,6 +4886,41 @@ class TestExperimentService(APIBaseTest):assert [flag.key for flag in flags_with_tags["results"]] == ["flag-with-tags"]assert [flag.key for flag in flags_without_tags["results"]] == ["flag-without-tags"]+ def test_get_eligible_feature_flags_excludes_flags_blocked_by_access_controls(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()++ self._create_flag(key="accessible-flag")+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ private_flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=other_user,+ key="private-flag",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ )+ AccessControl.objects.create(+ team=self.team, resource="feature_flag", resource_id=str(private_flag.id), access_level="none"+ )++ result = self._service().get_eligible_feature_flags(order="key")++ assert result["count"] == 1+ assert [flag.key for flag in result["results"]] == ["accessible-flag"]+# ------------------------------------------------------------------# Experiment list/querying# ------------------------------------------------------------------diff --git a/products/experiments/backend/test/test_max_tools.py b/products/experiments/backend/test/test_max_tools.pyindex 60b3dd833981..984e341065df 100644--- a/products/experiments/backend/test/test_max_tools.py+++ b/products/experiments/backend/test/test_max_tools.py@@ -250,7 +250,7 @@ class TestCreateExperimentTool(APIBaseTest):)assert "Failed to create" in result- assert "must have multivariate variants" in result+ assert "at least 2 variants" in resultassert artifact is not Noneassert artifact.get("error") is not None@@ -306,6 +306,7 @@ class TestCreateExperimentTool(APIBaseTest):assert variants[2]["key"] == "variant_c"async def test_create_experiment_flag_without_control_variant(self):+ # No 'control' variant is required; the baseline defaults to the first variant downstream.await self._create_multivariate_flag(key="no-control-flag",name="No Control Flag",@@ -322,11 +323,14 @@ class TestCreateExperimentTool(APIBaseTest):feature_flag_key="no-control-flag",)- assert "Failed to create" in result- assert "must have 'control' as the first variant" in result- assert "Found 'baseline' instead" in result- assert artifact is not None- assert artifact.get("error") is not None+ assert "Successfully created" in result++ experiment = await Experiment.objects.aget(name="Test Experiment", team=self.team)+ flag = await FeatureFlag.objects.aget(key="no-control-flag", team=self.team)+ assert experiment.feature_flag_id == flag.id+ assert [v["key"] for v in flag.variants] == ["baseline", "test"]+ assert experiment.stats_config is not None+ assert experiment.stats_config["baseline_variant_key"] == "baseline"class TestExperimentSummaryTool(APIBaseTest):diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 111a81578bad..0448824bac7f 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -207,8 +207,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):response = self.client.get(f"/api/projects/{self.team.id}/experiments/eligible_feature_flags/?order=key")self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 1)- self.assertEqual([flag["key"] for flag in response.json()["results"]], ["eligible-flag"])+ self.assertEqual(response.json()["count"], 2)+ self.assertEqual([flag["key"] for flag in response.json()["results"]], ["eligible-flag", "wrong-order-flag"])@parameterized.expand([@@ -2983,23 +2983,21 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertIsNotNone(get_data["feature_flag"])self.assertEqual(get_data["feature_flag"]["key"], "test-flag-serialization")- def test_creating_invalid_multivariate_experiment_no_control(self):+ def test_creating_multivariate_experiment_without_control_variant(self):+ # No 'control' variant is required; the baseline defaults to the first variant downstream.ff_key = "a-b-test"response = self.client.post(f"/api/projects/{self.team.id}/experiments/",{"name": "Test Experiment","description": "",- "start_date": "2021-12-01T10:23",- "end_date": None,"feature_flag_key": ff_key,"parameters": {"feature_flag_variants": [- # no control{"key": "test_0",- "name": "Control Group",- "rollout_percentage": 33,+ "name": "Baseline Group",+ "rollout_percentage": 34,},{"key": "test_1",@@ -3013,22 +3011,15 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):},]},- "filters": {- "events": [- {"order": 0, "id": "$pageview"},- {"order": 1, "id": "$pageleave"},- ],- "properties": [],- },},)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- detail = response.json()["detail"]- self.assertIn("must contain a variant with key 'control'", detail)- self.assertIn("'test_0'", detail)- self.assertIn("'test_1'", detail)- self.assertIn("'test_2'", detail)+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)+ flag = FeatureFlag.objects.get(key=ff_key)+ flag_keys = [v["key"] for v in flag.filters["multivariate"]["variants"]]+ self.assertEqual(flag_keys, ["test_0", "test_1", "test_2"])+ # The inferred baseline is pinned, not left implicit (order-sensitive).+ self.assertEqual(response.json()["stats_config"]["baseline_variant_key"], "test_0")@parameterized.expand([@@ -3071,9 +3062,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):# otherwise it would rewrite `Control` → `control` and produce two duplicate# entries. The downstream FeatureFlagSerializer may then accept (variants# preserved) or reject (duplicate-key error) — both prove the normalization- # path was skipped. The signal we actively check against: the response must- # not be the missing-control error, since that would only fire if our- # rewrite logic got confused.+ # path was skipped. A wrong rewrite would surface as duplicate `control` keys+ # in the 201 response, which the assertion below would catch.ff_key = "control-and-capital-control"response = self.client.post(f"/api/projects/{self.team.id}/experiments/",@@ -3096,11 +3086,6 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):if response.status_code == status.HTTP_201_CREATED:variants = response.json()["parameters"]["feature_flag_variants"]self.assertEqual([v["key"] for v in variants], ["control", "Control"])- else:- # 400 path: the error must NOT be the missing-control message,- # which would only fire if normalization had wrongly rewritten things.- detail = str(response.json())- self.assertNotIn("must contain a variant with key 'control'", detail)def test_creating_updating_experiment_with_group_aggregation(self):ff_key = "a-b-tests"@@ -3577,7 +3562,9 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertFalse(response.json()["only_count_matured_users"])- def test_create_experiment_with_feature_flag_missing_control(self):+ def test_create_experiment_with_feature_flag_without_control(self):+ # An existing flag without a 'control' variant is eligible; the baseline+ # defaults to the first variant downstream.feature_flag = FeatureFlag.objects.create(team=self.team,name="Beta feature",@@ -3602,8 +3589,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):},)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["detail"], "Feature flag must have a variant with key 'control'")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)+ self.assertEqual(response.json()["feature_flag"]["id"], feature_flag.id)def test_create_experiment_with_feature_flag_insufficient_variants(self):feature_flag = FeatureFlag.objects.create(@@ -3632,7 +3619,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["detail"],- "Feature flag must have at least 2 variants (control and at least one test variant)",+ "Feature flag must have at least 2 variants (a baseline and at least one test variant)",)def test_create_experiment_with_parameters_insufficient_variants(self):@@ -3652,7 +3639,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json()["detail"],- "Feature flag must have at least 2 variants (control and at least one test variant)",+ "Feature flag must have at least 2 variants (a baseline and at least one test variant)",)def test_create_experiment_with_valid_existing_feature_flag(self):diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 861363fa29f3..c73485176ce4 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -833,7 +833,7 @@ export interface ExperimentFlagRolloutGroupApi {* 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). */+ /** Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant. */key: string/** Human-readable variant name. */name?: string@@ -849,7 +849,7 @@ export interface ExperimentFlagVariantApi {* Multivariate config for the experiment's feature flag.*/export interface ExperimentFlagMultivariateApi {- /** Variant definitions. Exactly one variant key must be the literal string 'control'. */+ /** Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant. */variants: ExperimentFlagVariantApi[]}@@ -885,7 +885,7 @@ export interface ExperimentFeatureFlagFiltersApi {* 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. */+ /** Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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. */filters?: ExperimentFeatureFlagFiltersApi/*** Whether the flag persists variant assignment across authentication steps.diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 1be1e8c7256c..56502ec80b73 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -580,7 +580,7 @@ export const getExperimentsLaunchCreateUrl = (projectId: string, id: number) =>* Validates the experiment is in draft state, activates its linked feature flag,* sets start_date to the current server time, and transitions the experiment to running.* Returns 400 if the experiment has already been launched or if the feature flag- * configuration is invalid (e.g. missing "control" variant or fewer than 2 variants).+ * configuration is invalid (e.g. fewer than 2 variants).*/export const experimentsLaunchCreate = async (projectId: string,@@ -956,8 +956,7 @@ export const getExperimentsEligibleFeatureFlagsRetrieveUrl = (projectId: string)* Returns a paginated list of feature flags eligible for use in experiments.** Eligible flags must:- * - Be multivariate with at least 2 variants- * - Have "control" as the first variant key+ * - Be multivariate with 2 to 20 variants** Query parameters:* - search: Filter by flag key or name (case insensitive)diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex a9a8c0bec0f7..2ca40c26ec90 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -121,9 +121,12 @@ tools:the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flagmeans lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this,pass a feature_flag_key that does not already exist in the target project. If an existing target flag is- reused, it must have at least 2 variants including one with key "control", otherwise the call returns 400- ("Feature flag must have at least 2 variants (control and at least one test variant)" or "Feature flag must- have a variant with key 'control'").+ reused, it must be multivariate with 2 to 20 variants, otherwise the call returns 400 ("Feature flag must+ have at least 2 variants (a baseline and at least one test variant)" or "Feature flag must have at most 20+ variants"). No specific variant key is required — the analysis baseline defaults to the variant keyed+ "control" when present, else the first variant. Exception: copying a web experiment requires the reused+ target flag to have a variant keyed "control", otherwise the call returns 400 ("Web experiments require a+ variant with key 'control'").Returns 400 if the source experiment uses legacy metrics ("Copying is not supported for experiments using@@ -211,12 +214,12 @@ tools:to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected.- HARD REQUIREMENT — when you provide variants, exactly one variant's `key` must be the literal string- `control` (lowercase, no variations). It is the baseline used for analysis and the experiment- runtime treats it specially. If the user describes variants as "A/B", "old/new",- "original/redesign", or any other natural-language pair, map the baseline to `key: "control"` — not- "A", "Control", "old", "original", or "baseline". Other variants can use any key (`test`,- `variant_a`, etc.).+ No specific variant key is required. The analysis baseline defaults to the variant keyed `control`+ (lowercase) when present, else the first variant; override with stats_config.baseline_variant_key.+ Convention: when the user describes variants as "A/B", "old/new", "original/redesign", or any other+ natural-language pair without naming explicit keys, key the baseline `control` and keep their+ wording in the variant `name`. When the user asks for specific keys, use them as-is and put the+ baseline first.ui_app: experimentresponse:include:@@ -492,9 +495,9 @@ tools:user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.- Launch a draft experiment. Validates the feature flag has at least 2 multivariate variants with "control" as- the first variant. Activates the feature flag (sets active=true), sets start_date to the current server- time, recomputes metric fingerprints, and transitions status from draft to running.+ Launch a draft experiment. Validates the feature flag is multivariate with 2 to 20 variants. Activates the+ feature flag (sets active=true), sets start_date to the current server time, recomputes metric fingerprints,+ and transitions status from draft to running.Returns 400 if the experiment has already been launched ("Experiment has already been launched.") or if the@@ -990,8 +993,9 @@ tools:description: >Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, inthe flag's own filters shape. This is the canonical input for flag config. Set- filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100,- exactly one key must be the literal string 'control') to change the variant split. Set+ filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100;+ the analysis baseline defaults to the variant keyed 'control' when present, else the first variant —+ except web experiments, which must keep a variant keyed 'control') to change the variant split. Setfilters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to change theoverall rollout. Config this object omits is preserved from the flag's current state. On a runningexperiment this requires update_feature_flag_params=true (see rule 1: warn the user first).diff --git a/products/experiments/skills/configuring-experiment-rollout/SKILL.md b/products/experiments/skills/configuring-experiment-rollout/SKILL.mdindex e87530da1e99..e2a886ed20b1 100644--- a/products/experiments/skills/configuring-experiment-rollout/SKILL.md+++ b/products/experiments/skills/configuring-experiment-rollout/SKILL.md@@ -48,11 +48,11 @@ Both live on the linked feature flag, sent through the `feature_flag` object inHow users **inside** the experiment are distributed across variants.- Array of `{key, name, rollout_percentage}`, where the `rollout_percentage` values must sum to 100-- Exactly one variant key must be the literal string `"control"` (the baseline)- Minimum 2 variants, maximum 20+- No specific variant key is required — the analysis baseline defaults to the variant keyed `"control"` when present, else the first variant- Default: control 50% / test 50%-If the user says "A/B/C test", map the baseline to `"control"` and create additional variants for the others.+If the user says "A/B/C test" without naming keys, key the baseline `"control"` (the convention) and create additional variants for the others; if they ask for specific keys, use them as-is with the baseline first.### 2. Overall rollout (`feature_flag.filters.groups[0].rollout_percentage`)diff --git a/products/experiments/skills/creating-experiments/SKILL.md b/products/experiments/skills/creating-experiments/SKILL.mdindex d5f18157dcdc..6222b622f6e6 100644--- a/products/experiments/skills/creating-experiments/SKILL.md+++ b/products/experiments/skills/creating-experiments/SKILL.md@@ -86,7 +86,7 @@ Two different percentages live in there, do NOT mix them up:Key details:-- Exactly one variant key must be the literal string `"control"` (the baseline). Minimum 2, maximum 20 variants.+- Minimum 2, maximum 20 variants. No specific variant key is required — the analysis baseline defaults to the variant keyed `"control"` when present, else the first variant (override with `stats_config.baseline_variant_key`). Convention: key the baseline `"control"` unless the user asks for specific keys.- `filters.groups[0].rollout_percentage` defaults to 100 if omitted.- `ensure_experience_continuity` persists a user's variant across authentication steps; leave it `false` unless the flag is shown to both logged-out and logged-in users (see `configuring-experiment-rollout`).- Stats default to Bayesian. Only set `stats_config` if the user requests Frequentist.diff --git a/products/experiments/skills/managing-experiment-lifecycle/SKILL.md b/products/experiments/skills/managing-experiment-lifecycle/SKILL.mdindex 06e1d0b4d914..727c1490d5bd 100644--- a/products/experiments/skills/managing-experiment-lifecycle/SKILL.md+++ b/products/experiments/skills/managing-experiment-lifecycle/SKILL.md@@ -31,7 +31,7 @@ For each action, the two key questions:Transitions draft → running. Activates the feature flag and sets `start_date`.-- **Preconditions**: must be in draft, flag needs ≥2 variants with "control" first+- **Preconditions**: must be in draft, flag needs 2-20 multivariate variants (no specific key required; the baseline defaults to "control" when present, else the first variant)- **Pre-launch checklist**: has at least one metric? Variants correct? Flag implemented in code?- **Variants**: users start being bucketed into variants based on the configured split- **Analysis**: data collection begins from `start_date`@@ -129,7 +129,7 @@ Copies an experiment into a **different project in the same organization** as athe next point — so to be safe, pass an explicit key.)- **If the resolved key already exists as a flag in the target project**: the copy **shares** that existing flaginstead of creating one. Both experiments then point at the same flag, so lifecycle ops (ship, pause) on either- affect both. The existing flag must have ≥2 variants including one keyed `control`, otherwise the call returns 400.+ affect both. The existing flag must be multivariate with 2-20 variants, otherwise the call returns 400.- **If the resolved key does not exist in the target project**: a new, independent flag is created with that key.To guarantee independence, pass a `feature_flag_key` that doesn't already exist in the target.diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 9b8d770cf7e6..ae53424aa640 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -911,6 +911,10 @@ class FeatureFlagSerializer(queryset=Dashboard.objects.all(),)is_used_in_replay_settings = serializers.SerializerMethodField()+ is_eligible_for_experiment = serializers.BooleanField(+ read_only=True,+ help_text="Whether this flag can back an experiment: multivariate with 2 to 20 variants.",+ )name = serializers.CharField(required=False,@@ -968,6 +972,7 @@ class FeatureFlagSerializer("_create_in_folder","_should_create_usage_dashboard","is_used_in_replay_settings",+ "is_eligible_for_experiment",]def get_can_edit(self, feature_flag: FeatureFlag) -> bool:diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 36200f9710e9..d71b7fde30b4 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -466,6 +466,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "is_eligible_for_experiment": False,"team_id": target_project.id,"updated_existing": False,}@@ -563,6 +564,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "is_eligible_for_experiment": False,"team_id": target_project.id,"updated_existing": True,}@@ -705,6 +707,7 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "is_eligible_for_experiment": False,"team_id": target_project.id,# A soft-deleted flag doesn't count as existing: the copy replaces it with a fresh flag"updated_existing": False,diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 53fe65d4492a..aceed5ae95ad 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -8,7 +8,8 @@ from django.contrib.postgres.aggregates import ArrayAggfrom django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import DatabaseError, models, transaction-from django.db.models import Q, QuerySet+from django.db.models import Func, IntegerField, Q, QuerySet+from django.db.models.fields.json import KeyTransformfrom django.db.models.signals import post_delete, post_savefrom django.http import HttpRequestfrom django.utils import timezone@@ -25,7 +26,7 @@ from posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentationfrom posthog.models.property import GroupTypeIndexfrom posthog.models.signals import mutable_receiver-from posthog.models.utils import RootTeamManager, RootTeamMixin+from posthog.models.utils import RootTeamManager, RootTeamMixin, RootTeamQuerySetfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.experiments.backend.models.experiment import live_experiment_exists@@ -101,9 +102,43 @@ def build_scheduled_change_serializer_data(flag: "FeatureFlag", payload: dict[streturn None+# The single flag-side rule for "this flag can back an experiment": multivariate with+# 2-20 variants. No variant key is required — the baseline defaults to 'control' when+# present, else the first variant (see get_baseline_variant_key). Enforced in three+# matching shapes — experiment_eligibility_error (in-memory), FeatureFlagQuerySet.+# eligible_for_experiment (JSONB filter), and FeatureFlagSerializer.is_eligible_for_experiment+# (API field).+EXPERIMENT_MIN_VARIANTS = 2+EXPERIMENT_MAX_VARIANTS = 20+++def experiment_eligibility_error(variants: list[dict[str, Any]] | None) -> str | None:+ """Why these flag variants can't back an experiment, or None when they can."""+ if not variants or len(variants) < EXPERIMENT_MIN_VARIANTS:+ return "Feature flag must have at least 2 variants (a baseline and at least one test variant)"+ if len(variants) > EXPERIMENT_MAX_VARIANTS:+ return f"Feature flag must have at most {EXPERIMENT_MAX_VARIANTS} variants"+ return None+++class FeatureFlagQuerySet(RootTeamQuerySet):+ def eligible_for_experiment(self) -> "FeatureFlagQuerySet":+ """JSONB twin of experiment_eligibility_error: multivariate with 2-20 variants."""+ return self.annotate(+ _experiment_variant_count=Func(+ KeyTransform("variants", KeyTransform("multivariate", "filters")),+ function="jsonb_array_length",+ output_field=IntegerField(),+ )+ ).filter(+ _experiment_variant_count__gte=EXPERIMENT_MIN_VARIANTS,+ _experiment_variant_count__lte=EXPERIMENT_MAX_VARIANTS,+ )++class FeatureFlagManager(RootTeamManager):- def get_queryset(self):- return super().get_queryset().exclude(deleted=True)+ def get_queryset(self) -> FeatureFlagQuerySet:+ return FeatureFlagQuerySet(self.model, using=self._db).exclude(deleted=True)class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):@@ -319,6 +354,10 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsreturn variantsreturn []+ @property+ def is_eligible_for_experiment(self) -> bool:+ return experiment_eligibility_error(self.variants) is None+@propertydef usage_dashboard_has_enriched_insights(self) -> bool:if not self.usage_dashboard:diff --git a/products/feature_flags/backend/test/test_feature_flag_manager.py b/products/feature_flags/backend/test/test_feature_flag_manager.pyindex b3d6ffab9ed9..638f5c5ef1c0 100644--- a/products/feature_flags/backend/test/test_feature_flag_manager.py+++ b/products/feature_flags/backend/test/test_feature_flag_manager.py@@ -3,6 +3,38 @@ from posthog.test.base import BaseTestfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+def _variants(*keys: str) -> list[dict]:+ return [{"key": key, "rollout_percentage": 100 if len(keys) == 1 else 0} for key in keys]+++class TestExperimentEligibility(BaseTest):+ # (key, multivariate variants or None, eligible) — multivariate with 2-20 variants;+ # no 'control' variant is required (the baseline defaults downstream).+ CASES = [+ ("boolean-flag", None, False),+ ("single-variant", _variants("control"), False),+ ("control-first", _variants("control", "test"), True),+ ("control-not-first", _variants("test", "control"), True),+ ("control-missing", _variants("test-1", "test-2"), True),+ ("twenty-variants", _variants("control", *[f"test-{i}" for i in range(19)]), True),+ ("twenty-one-variants", _variants("control", *[f"test-{i}" for i in range(20)]), False),+ ]++ def test_queryset_and_predicate_agree_on_eligibility(self):+ for key, variants, _ in self.CASES:+ filters = {"groups": []} if variants is None else {"groups": [], "multivariate": {"variants": variants}}+ FeatureFlag.objects.create(team=self.team, key=key, created_by=self.user, filters=filters)++ eligible_keys = set(+ FeatureFlag.objects.filter(team=self.team).eligible_for_experiment().values_list("key", flat=True)+ )+ assert eligible_keys == {key for key, _, eligible in self.CASES if eligible}++ for key, _, eligible in self.CASES:+ flag = FeatureFlag.objects.get(team=self.team, key=key)+ assert flag.is_eligible_for_experiment is eligible, key++class TestFeatureFlagManager(BaseTest):def test_default_manager_excludes_soft_deleted_flags(self):FeatureFlag.objects.create(team=self.team, key="live", created_by=self.user)diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex cacf58351814..a06f0bb511c6 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -502,6 +502,8 @@ export interface FeatureFlagApi {_should_create_usage_dashboard?: boolean/** Check if this feature flag is used in any team's session recording linked flag setting. */readonly is_used_in_replay_settings: boolean+ /** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */+ readonly is_eligible_for_experiment: boolean}export interface PaginatedFeatureFlagListApi {diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 0df5236dfa2a..225c5a8585dc 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3076,7 +3076,7 @@}},"experiment-copy-to-project": {- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must have at least 2 variants including one with key \"control\", otherwise the call returns 400 (\"Feature flag must have at least 2 variants (control and at least one test variant)\" or \"Feature flag must have a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.",+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must be multivariate with 2 to 20 variants, otherwise the call returns 400 (\"Feature flag must have at least 2 variants (a baseline and at least one test variant)\" or \"Feature flag must have at most 20 variants\"). No specific variant key is required — the analysis baseline defaults to the variant keyed \"control\" when present, else the first variant. Exception: copying a web experiment requires the reused target flag to have a variant keyed \"control\", otherwise the call returns 400 (\"Web experiments require a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.","category": "Experiments","feature": "experiments","summary": "Copy experiment to another project",@@ -3230,7 +3230,7 @@}},"experiment-launch": {- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nLaunch a draft experiment. Validates the feature flag has at least 2 multivariate variants with \"control\" as the first variant. Activates the feature flag (sets active=true), sets start_date to the current server time, recomputes metric fingerprints, and transitions status from draft to running.\n\nReturns 400 if the experiment has already been launched (\"Experiment has already been launched.\") or if the flag configuration is invalid.\n\nNo request body needed.",+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nLaunch a draft experiment. Validates the feature flag is multivariate with 2 to 20 variants. Activates the feature flag (sets active=true), sets start_date to the current server time, recomputes metric fingerprints, and transitions status from draft to running.\n\nReturns 400 if the experiment has already been launched (\"Experiment has already been launched.\") or if the flag configuration is invalid.\n\nNo request body needed.","category": "Experiments","feature": "experiments","summary": "Launch experiment",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 300e9bce97cd..20a68534221e 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3245,7 +3245,7 @@}},"experiment-copy-to-project": {- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must have at least 2 variants including one with key \"control\", otherwise the call returns 400 (\"Feature flag must have at least 2 variants (control and at least one test variant)\" or \"Feature flag must have a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.",+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nREQUIRES EXPLICIT USER CONFIRMATION BEFORE CALLING. This writes a new experiment into a DIFFERENT project than the one the user is currently looking at. Resolve the target project from the user's wording to a concrete team id, then confirm the source experiment and the target project by name before invoking.\n\nCopies an experiment into another project in the SAME organization as a new draft. The target project must belong to the same organization — this CANNOT copy across organizations or regions. Use experiment-duplicate instead when the copy should land in the same project.\n\nWhat IS copied: name (defaults to \"Original Name (Copy)\", de-duplicated with a numeric suffix if that name already exists in the target), description, type, parameters (variant split, rollout), filters, primary and secondary metrics (each with freshly regenerated uuids and preserved ordering), stats config, scheduling config, exposure criteria, and the only_count_matured_users setting.\n\nWhat is NOT copied: saved-metric references (saved metrics are project-scoped, so they are dropped on a cross-project copy), holdout, exposure cohort, start/end dates, results, and conclusion. The copy always starts as a fresh draft.\n\nFeature flag: pass feature_flag_key to control the flag key created in the target project. If omitted, the source experiment's flag key is reused — and if a flag with that key already exists in the target project, the copy SHARES that existing flag (its variants are reused) rather than creating a new one. A shared flag means lifecycle operations on either experiment (shipping a variant, pausing) affect both. To avoid this, pass a feature_flag_key that does not already exist in the target project. If an existing target flag is reused, it must be multivariate with 2 to 20 variants, otherwise the call returns 400 (\"Feature flag must have at least 2 variants (a baseline and at least one test variant)\" or \"Feature flag must have at most 20 variants\"). No specific variant key is required — the analysis baseline defaults to the variant keyed \"control\" when present, else the first variant. Exception: copying a web experiment requires the reused target flag to have a variant keyed \"control\", otherwise the call returns 400 (\"Web experiments require a variant with key 'control'\").\n\nReturns 400 if the source experiment uses legacy metrics (\"Copying is not supported for experiments using legacy metrics.\"). Returns 404 if the target project is not found in the organization (\"Target team not found.\"). Returns 403 if you lack write access to the target project (\"You do not have write access to the target project.\").\n\nThe returned experiment (including its id) belongs to the TARGET project, not the source project.","category": "Experiments","feature": "experiments","summary": "Copy experiment to another project",@@ -3413,7 +3413,7 @@}},"experiment-launch": {- "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nLaunch a draft experiment. Validates the feature flag has at least 2 multivariate variants with \"control\" as the first variant. Activates the feature flag (sets active=true), sets start_date to the current server time, recomputes metric fingerprints, and transitions status from draft to running.\n\nReturns 400 if the experiment has already been launched (\"Experiment has already been launched.\") or if the flag configuration is invalid.\n\nNo request body needed.",+ "description": "Requires an experiment ID. If you don't have the ID, load the finding-experiments skill to resolve the user's reference first. Load the managing-experiment-lifecycle skill for preconditions and side effects.\n\nLaunch a draft experiment. Validates the feature flag is multivariate with 2 to 20 variants. Activates the feature flag (sets active=true), sets start_date to the current server time, recomputes metric fingerprints, and transitions status from draft to running.\n\nReturns 400 if the experiment has already been launched (\"Experiment has already been launched.\") or if the flag configuration is invalid.\n\nNo request body needed.","category": "Experiments","feature": "experiments","summary": "Launch experiment",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c178b477ec03..e5aa5e24ef84 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23950,7 +23950,7 @@ export namespace Schemas {* 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). */+ /** Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant. */key: string;/** Human-readable variant name. */name?: string;@@ -23966,7 +23966,7 @@ export namespace Schemas {* Multivariate config for the experiment's feature flag.*/export interface ExperimentFlagMultivariate {- /** Variant definitions. Exactly one variant key must be the literal string 'control'. */+ /** Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant. */variants: ExperimentFlagVariant[];}@@ -23997,7 +23997,7 @@ export namespace Schemas {* 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. */+ /** Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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. */filters?: ExperimentFeatureFlagFilters;/*** Whether the flag persists variant assignment across authentication steps.@@ -26630,6 +26630,8 @@ export namespace Schemas {_should_create_usage_dashboard?: boolean;/** Check if this feature flag is used in any team's session recording linked flag setting. */readonly is_used_in_replay_settings: boolean;+ /** Whether this flag can back an experiment: multivariate with 2 to 20 variants. */+ readonly is_eligible_for_experiment: boolean;}export interface FeatureFlagConditionPropertyAnalysis {diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 6c093c7d9122..d98fad844c88 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -902,7 +902,7 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zodkey: zod.string().describe(- "Unique variant key. Exactly one variant must use the key 'control' (the baseline)."+ "Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant."),name: zod.string()@@ -925,7 +925,7 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod)).describe(- "Variant definitions. Exactly one variant key must be the literal string 'control'."+ "Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant."),}).describe("Multivariate config for the experiment's feature flag."),@@ -947,7 +947,7 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod).optional().describe(- "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."+ "Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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."),ensure_experience_continuity: zod.boolean()@@ -4458,7 +4458,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zodkey: zod.string().describe(- "Unique variant key. Exactly one variant must use the key 'control' (the baseline)."+ "Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant."),name: zod.string()@@ -4481,7 +4481,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod)).describe(- "Variant definitions. Exactly one variant key must be the literal string 'control'."+ "Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant."),}).describe("Multivariate config for the experiment's feature flag."),@@ -4503,7 +4503,7 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod).optional().describe(- "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."+ "Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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."),ensure_experience_continuity: zod.boolean()@@ -11408,7 +11408,7 @@ export const ExperimentsEndCreateBody = /* @__PURE__ */ zod.object({* Validates the experiment is in draft state, activates its linked feature flag,* sets start_date to the current server time, and transitions the experiment to running.* Returns 400 if the experiment has already been launched or if the feature flag- * configuration is invalid (e.g. missing "control" variant or fewer than 2 variants).+ * configuration is invalid (e.g. fewer than 2 variants).*/export const ExperimentsLaunchCreateParams = /* @__PURE__ */ zod.object({id: zod.number().describe('A unique integer value identifying this experiment.'),diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 53b7a3c9abf6..b366ca21fb69 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -181,7 +181,7 @@ const ExperimentCreateSchema = ExperimentsCreateBody.omit({update_feature_flag_params: true,}).extend({feature_flag: ExperimentsCreateBody.shape['feature_flag'].describe(- 'Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag\'s own filters shape. This is the canonical input for flag config. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. HARD REQUIREMENT — when you provide variants, exactly one variant\'s `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as "A/B", "old/new", "original/redesign", or any other natural-language pair, map the baseline to `key: "control"` — not "A", "Control", "old", "original", or "baseline". Other variants can use any key (`test`, `variant_a`, etc.).'+ 'Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag\'s own filters shape. This is the canonical input for flag config. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. No specific variant key is required. The analysis baseline defaults to the variant keyed `control` (lowercase) when present, else the first variant; override with stats_config.baseline_variant_key. Convention: when the user describes variants as "A/B", "old/new", "original/redesign", or any other natural-language pair without naming explicit keys, key the baseline `control` and keep their wording in the variant `name`. When the user asks for specific keys, use them as-is and put the baseline first.'),})@@ -901,7 +901,7 @@ const ExperimentUpdateSchema = ExperimentsPartialUpdateParams.omit({ project_id:.extend({id: z.preprocess(castStringToInt, ExperimentsPartialUpdateParams.shape['id']),feature_flag: ExperimentsPartialUpdateBody.shape['feature_flag'].describe(- 'Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag\'s own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100, exactly one key must be the literal string \'control\') to change the variant split. Set filters.groups to a single group [{"properties": [], "rollout_percentage": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag\'s current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).'+ "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100; the analysis baseline defaults to the variant keyed 'control' when present, else the first variant — except web experiments, which must keep a variant keyed 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first)."),running_time_calculation: ExperimentsPartialUpdateBody.shape['running_time_calculation'].describe("Persist a running-time / sample-size plan onto the experiment (the planning target shown in the experiment's running-time panel). Object with optional keys: minimum_detectable_effect (percentage, e.g. 20 for a 20% lift), recommended_sample_size (total across all variants), recommended_running_time (days), and exposure_estimate_config."diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.jsonindex fb4c830be776..01a20f943dd3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json@@ -2071,7 +2071,7 @@"description": "Exposure configuration including filter test accounts and custom exposure events."},"feature_flag": {- "description": "Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag's own filters shape. This is the canonical input for flag config. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. HARD REQUIREMENT — when you provide variants, exactly one variant's `key` must be the literal string `control` (lowercase, no variations). It is the baseline used for analysis and the experiment runtime treats it specially. If the user describes variants as \"A/B\", \"old/new\", \"original/redesign\", or any other natural-language pair, map the baseline to `key: \"control\"` — not \"A\", \"Control\", \"old\", \"original\", or \"baseline\". Other variants can use any key (`test`, `variant_a`, etc.).",+ "description": "Variant split, rollout scope, payloads, and experience continuity for the auto-created feature flag, in the flag's own filters shape. This is the canonical input for flag config. If the user mentions a specific percentage, load the configuring-experiment-rollout skill and clarify before setting these values. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100) to customize the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to control the overall fraction of users entering the experiment. Default: 50/50 control/test, 100% rollout. Omit this parameter entirely when feature_flag_key refers to a pre-existing flag: the experiment links to that flag as-is and explicit config is rejected. No specific variant key is required. The analysis baseline defaults to the variant keyed `control` (lowercase) when present, else the first variant; override with stats_config.baseline_variant_key. Convention: when the user describes variants as \"A/B\", \"old/new\", \"original/redesign\", or any other natural-language pair without naming explicit keys, key the baseline `control` and keep their wording in the variant `name`. When the user asks for specific keys, use them as-is and put the baseline first.","properties": {"ensure_experience_continuity": {"anyOf": [@@ -2085,7 +2085,7 @@"description": "Whether the flag persists variant assignment across authentication steps."},"filters": {- "description": "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.",+ "description": "Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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.","properties": {"aggregation_group_type_index": {"anyOf": [@@ -2133,12 +2133,12 @@"description": "Multivariate config for the experiment's feature flag.","properties": {"variants": {- "description": "Variant definitions. Exactly one variant key must be the literal string 'control'.",+ "description": "Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant.","items": {"description": "A single multivariate variant. Extra per-variant keys are dropped.","properties": {"key": {- "description": "Unique variant key. Exactly one variant must use the key 'control' (the baseline).",+ "description": "Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant.","type": "string"},"name": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.jsonindex 8543ba3bfe08..e7c400099e0a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json@@ -2113,7 +2113,7 @@"description": "Exposure configuration including filter test accounts and custom exposure events."},"feature_flag": {- "description": "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100, exactly one key must be the literal string 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).",+ "description": "Variant split, rollout scope, payloads, and experience continuity for the linked feature flag, in the flag's own filters shape. This is the canonical input for flag config. Set filters.multivariate.variants (each with key and rollout_percentage; percentages must sum to 100; the analysis baseline defaults to the variant keyed 'control' when present, else the first variant — except web experiments, which must keep a variant keyed 'control') to change the variant split. Set filters.groups to a single group [{\"properties\": [], \"rollout_percentage\": N}] (0-100) to change the overall rollout. Config this object omits is preserved from the flag's current state. On a running experiment this requires update_feature_flag_params=true (see rule 1: warn the user first).","properties": {"ensure_experience_continuity": {"anyOf": [@@ -2127,7 +2127,7 @@"description": "Whether the flag persists variant assignment across authentication steps."},"filters": {- "description": "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.",+ "description": "Flag config to apply: `multivariate.variants` (2 to 20 variants; the baseline defaults to the variant keyed 'control' when present, else the first variant), `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.","properties": {"aggregation_group_type_index": {"anyOf": [@@ -2175,12 +2175,12 @@"description": "Multivariate config for the experiment's feature flag.","properties": {"variants": {- "description": "Variant definitions. Exactly one variant key must be the literal string 'control'.",+ "description": "Variant definitions (2 to 20). The baseline defaults to the variant keyed 'control' when present, else the first variant.","items": {"description": "A single multivariate variant. Extra per-variant keys are dropped.","properties": {"key": {- "description": "Unique variant key. Exactly one variant must use the key 'control' (the baseline).",+ "description": "Unique variant key. The baseline defaults to the variant keyed 'control' when present, else the first variant.","type": "string"},"name": {