Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): add replay context and variant lists to the facade (#108801)

Kim Svatos Dugan7e7cd9d7c53d
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 900f9dd383c1..15364cbf8722 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -50318,6 +50318,13 @@
"variant": {
"description": "Narrow to persons exposed to this variant. Defaults to all of the experiment's variants.",
"type": "string"
+ },
+ "variants": {
+ "description": "Narrow to persons exposed to any of these variants. Defaults to all of the experiment's variants. Do not combine with `variant`, the single-variant form that predates this field.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
}
},
"required": ["experiment_id"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 008875a78c0b..c44d2aa5f27d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -771,6 +771,11 @@ export interface RecordingsQueryExperimentExposureFilter {
experiment_id: integer
/** Narrow to persons exposed to this variant. Defaults to all of the experiment's variants. */
variant?: string
+ /**
+ * Narrow to persons exposed to any of these variants. Defaults to all of the experiment's variants.
+ * Do not combine with `variant`, the single-variant form that predates this field.
+ */
+ variants?: string[]
/**
* Only sessions carrying in-session exposure evidence: an event matching the experiment's exposure criteria
* inside the session (with the stamped `$feature/<flag_key>` property standing in when the exposure event was
diff --git a/posthog/schema.py b/posthog/schema.py
index 1a8a50cd7baa..f1702bfebb98 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -7079,6 +7079,14 @@ class RecordingsQueryExperimentExposureFilter(BaseModel):
default=None,
description=("Narrow to persons exposed to this variant. Defaults to all of the experiment's variants."),
)
+ variants: list[str] | None = Field(
+ default=None,
+ description=(
+ "Narrow to persons exposed to any of these variants. Defaults to all of the"
+ " experiment's variants. Do not combine with `variant`, the single-variant"
+ " form that predates this field."
+ ),
+ )
class ResultCustomization(RootModel[ResultCustomizationByValue | ResultCustomizationByPosition]):
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index 22818d7bd07e..f1a18cb69a56 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -388,6 +388,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._team,
experiment_id=self._query.experiment_exposure.experiment_id,
variant=self._query.experiment_exposure.variant,
+ variants=self._query.experiment_exposure.variants,
in_session=bool(self._query.experiment_exposure.in_session),
)
if self._experiment_exposure_linkage.population_filters_test_accounts:
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.py
index e9ba13a6c304..525c70c28a01 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -39,6 +39,50 @@ class TargetableExperiment:
variants: tuple[str, ...]
+@frozen
+class ExperimentVariantPromptContext:
+ """One variant, as an LLM prompt describes it."""
+
+ key: str
+ # The flag variant's display name, which the experiment UI treats as the variant's description.
+ description: str
+ rollout_percentage: float
+
+
+@frozen
+class ExperimentPromptContext:
+ """What an LLM prompt needs to describe an experiment and the change under test."""
+
+ id: int
+ name: str
+ # The experiment's description field, which carries the hypothesis and expected outcomes.
+ description: str
+ feature_flag_key: str
+ # Requestable variants only, excluded variants already removed.
+ variants: tuple[ExperimentVariantPromptContext, ...]
+ primary_metric_names: tuple[str, ...]
+
+
+@frozen
+class ExperimentStatus:
+ """The lifecycle facts a replay surface reads to decide whether an experiment is still worth watching."""
+
+ # Public status string: draft, running, paused, exposure_frozen, or stopped.
+ status: str
+ start_date: datetime | None
+ end_date: datetime | None
+ archived: bool
+ # The running-time calculator's recommended length in days, when one was set.
+ planned_duration_days: float | None
+
+ @property
+ def is_active(self) -> bool:
+ """True until the experiment ends or is archived. A paused experiment (its flag turned
+ off) stays active: it collects no exposures while paused, but it resumes without a
+ lifecycle change, so a watcher should keep watching."""
+ return self.start_date is not None and self.end_date is None and not self.archived
+
+
@dataclass(frozen=True)
class CreateExperimentInput:
"""
diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.py
index 925f58f2e8c4..4c7a60671909 100644
--- a/products/experiments/backend/facade/replay.py
+++ b/products/experiments/backend/facade/replay.py
@@ -1,5 +1,12 @@
"""Replay linkage capability, re-exported for callers outside the experiments product."""
+from products.experiments.backend.replay_context import (
+ accessible_experiment_ids,
+ experiment_prompt_context,
+ experiment_status,
+ session_variant,
+ variant_rollout_shares,
+)
from products.experiments.backend.replay_linkage import (
ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,
IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES,
@@ -18,10 +25,15 @@ __all__ = [
"IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES",
"ExperimentExposureLinkage",
"InSessionExposureSemantics",
+ "accessible_experiment_ids",
+ "experiment_prompt_context",
+ "experiment_status",
"exposed_distinct_ids_select",
"exposed_session_ids_select",
"resolve_exposure_linkage",
"resolve_in_session_exposure_semantics",
+ "session_variant",
"targetable_experiments",
"validate_experiment_exposure_access",
+ "variant_rollout_shares",
]
diff --git a/products/experiments/backend/replay_context.py b/products/experiments/backend/replay_context.py
new file mode 100644
index 000000000000..65e8ac944b6c
--- /dev/null
+++ b/products/experiments/backend/replay_context.py
@@ -0,0 +1,172 @@
+"""Experiment context for replay surfaces.
+
+The companion to :mod:`replay_linkage`: where the linkage resolves who is exposed, this module
+answers what a replay surface says and decides about the experiment itself. It carries the
+per-session variant lookup, the flag's rollout shares, the prompt-facing description of the
+experiment, and the lifecycle read. Everything here is reachable through
+``products.experiments.backend.facade.replay``, so consumers outside this product never import
+the Experiment model.
+"""
+
+from collections.abc import Collection
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.models.team.team import Team
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.experiments.backend.facade.contracts import (
+ ExperimentPromptContext,
+ ExperimentStatus,
+ ExperimentVariantPromptContext,
+)
+from products.experiments.backend.metric_utils import get_default_metric_title
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.replay_linkage import (
+ EXPERIMENT_HAS_NO_FLAG_MESSAGE,
+ ExperimentExposureLinkage,
+ _requestable_variant_keys,
+ exposed_persons_select,
+)
+
+
+def accessible_experiment_ids(
+ access: UserAccessControl | None, team_id: int, *, experiment_ids: Collection[int] | None = None
+) -> set[int]:
+ """The experiments the caller may view, filtered by object-level access (not just team).
+
+ With `experiment_ids`, the subset of those ids; with None, every experiment of the team.
+ `access` is None only outside request context, where there is no viewer to gate on, so
+ nothing is filtered out then. Soft-deleted experiments stay in: a deleted experiment's
+ historical data keeps the access level the experiment had, rather than opening up.
+ """
+ queryset = Experiment.objects.filter(team_id=team_id)
+ if experiment_ids is not None:
+ if not experiment_ids:
+ return set()
+ queryset = queryset.filter(id__in=experiment_ids)
+ if access is not None:
+ queryset = access.filter_queryset_by_access_level(queryset)
+ return set(queryset.values_list("id", flat=True))
+
+
+def _live_experiment(team: Team, experiment_id: int) -> Experiment | None:
+ return Experiment.objects.filter(id=experiment_id, team=team, deleted=False).select_related("feature_flag").first()
+
+
+def session_variant(linkage: ExperimentExposureLinkage, distinct_id: str) -> str | None:
+ """The variant the experiment's analysis attributes to this distinct id's person, or None.
+
+ None means the person is not cleanly exposed within the linkage's requested variants:
+ never exposed, exposed only to a variant outside the requested set, or set aside as
+ multiple-variant under "exclude" handling. The attribution follows the experiment's
+ ``multiple_variant_handling``, because it reads the same population the analysis buckets.
+
+ Runs a ClickHouse query, so call it from a run path, never while building an AST.
+ """
+ candidate = parse_select(
+ "SELECT {distinct_id} AS distinct_id",
+ placeholders={"distinct_id": ast.Constant(value=distinct_id)},
+ )
+ assert isinstance(candidate, ast.SelectQuery)
+ select = exposed_persons_select(linkage, include_multiple_variant=False, candidate_distinct_ids=candidate)
+ # Under a "break" timeout profile a timed-out scan returns partial rows, which would read as a
+ # complete attribution (or as "unexposed"); a timeout must fail the lookup instead.
+ settings = HogQLGlobalSettings(
+ timeout_overflow_mode="throw",
+ max_memory_usage=linkage.live_scan_max_memory_bytes,
+ )
+ response = execute_hogql_query(select, team=linkage.context.team, settings=settings)
+ rows = response.results or []
+ if not rows:
+ return None
+ columns = response.columns or []
+ variant = rows[0][columns.index("variant")]
+ return str(variant) if variant is not None else None
+
+
+def variant_rollout_shares(team: Team, *, experiment_id: int) -> dict[str, float]:
+ """Each requestable variant's share of the flag's rollout, as a 0..1 fraction.
+
+ Shares come from the flag's variant percentages, so together with any excluded variants
+ they sum to 1. Raises ValidationError, matching :func:`resolve_exposure_linkage`, for an
+ unknown or deleted experiment and for one with no flag.
+ """
+ experiment = _live_experiment(team, experiment_id)
+ if experiment is None:
+ raise ValidationError(f"Experiment {experiment_id} doesn't exist in this environment.")
+ flag = getattr(experiment, "feature_flag", None)
+ if flag is None:
+ raise ValidationError(EXPERIMENT_HAS_NO_FLAG_MESSAGE)
+ requestable = set(_requestable_variant_keys(experiment))
+ return {
+ definition["key"]: (definition.get("rollout_percentage") or 0) / 100
+ for definition in flag.variants
+ if definition.get("key") in requestable
+ }
+
+
+def experiment_prompt_context(team: Team, *, experiment_id: int) -> ExperimentPromptContext | None:
+ """The experiment as an LLM prompt describes it, or None for an unknown or deleted
+ experiment or one with no flag."""
+ experiment = _live_experiment(team, experiment_id)
+ if experiment is None:
+ return None
+ flag = getattr(experiment, "feature_flag", None)
+ if flag is None:
+ return None
+ requestable = set(_requestable_variant_keys(experiment))
+ variants = tuple(
+ ExperimentVariantPromptContext(
+ key=definition["key"],
+ description=definition.get("name") or "",
+ rollout_percentage=float(definition.get("rollout_percentage") or 0),
+ )
+ for definition in flag.variants
+ if definition.get("key") in requestable
+ )
+ # Saved metrics live on a junction table, classified primary/secondary by the link's
+ # metadata.type, so reading experiment.metrics alone would drop them from the prompt.
+ saved_primary_names = tuple(
+ link.saved_metric.name
+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all()
+ if (link.metadata or {}).get("type", "primary") == "primary"
+ )
+ primary_metric_names = (
+ tuple(
+ metric.get("name") or get_default_metric_title(metric)
+ for metric in experiment.metrics or []
+ if isinstance(metric, dict)
+ )
+ + saved_primary_names
+ )
+ return ExperimentPromptContext(
+ id=experiment.pk,
+ name=experiment.name,
+ description=experiment.description or "",
+ feature_flag_key=experiment.get_feature_flag_key(),
+ variants=variants,
+ primary_metric_names=primary_metric_names,
+ )
+
+
+def experiment_status(team: Team, *, experiment_id: int) -> ExperimentStatus | None:
+ """The experiment's lifecycle read, or None for an unknown or deleted experiment."""
+ experiment = _live_experiment(team, experiment_id)
+ if experiment is None:
+ return None
+ planned = (experiment.running_time_calculation or {}).get("recommended_running_time")
+ return ExperimentStatus(
+ status=experiment.status_label,
+ start_date=experiment.start_date,
+ end_date=experiment.end_date,
+ archived=experiment.archived,
+ planned_duration_days=(
+ float(planned) if isinstance(planned, int | float) and not isinstance(planned, bool) else None
+ ),
+ )
diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.py
index 2d0ae7c3dadf..e434a86a29e2 100644
--- a/products/experiments/backend/replay_linkage.py
+++ b/products/experiments/backend/replay_linkage.py
@@ -318,10 +318,19 @@ def targetable_experiments(team: Team, *, experiment_ids: Sequence[int]) -> list
def resolve_exposure_linkage(
- team: Team, *, experiment_id: int, variant: str | None, in_session: bool = False
+ team: Team,
+ *,
+ experiment_id: int,
+ variant: str | None = None,
+ variants: list[str] | None = None,
+ in_session: bool = False,
) -> ExperimentExposureLinkage:
"""Validate the experiment and resolve how its exposed population will be read.
+ ``variants`` narrows the population to any subset of the experiment's variants; ``variant``
+ is the single-variant form that predates it, kept for existing callers. Pass at most one of
+ the two. With neither, the population covers every requestable variant.
+
Raises ValidationError for experiments the linkage can't answer for: unknown or draft
experiments, group-aggregated ones (whose exposed entities are groups rather than
persons and so never match a recording's distinct id), unknown variants, and
@@ -348,12 +357,19 @@ def resolve_exposure_linkage(
variant_keys = _requestable_variant_keys(experiment)
if not variant_keys:
raise ValidationError("This experiment's feature flag defines no variants.")
- if variant is not None:
- if variant not in variant_keys:
- raise ValidationError(f"'{variant}' is not a variant of this experiment.")
- requested_variants = [variant]
- else:
+ if variant is not None and variants is not None:
+ raise ValidationError("Pass either 'variant' or 'variants', not both.")
+ if variants is not None and not variants:
+ raise ValidationError("'variants' must name at least one variant.")
+ requested = variants if variants is not None else ([variant] if variant is not None else None)
+ if requested is None:
requested_variants = variant_keys
+ else:
+ for requested_key in requested:
+ if requested_key not in variant_keys:
+ raise ValidationError(f"'{requested_key}' is not a variant of this experiment.")
+ # Keep the caller's order, drop duplicates, so the query's IN list stays minimal.
+ requested_variants = list(dict.fromkeys(requested))
session_exposure: SessionExposure | None = None
if in_session:
@@ -508,7 +524,12 @@ def exposed_distinct_ids_select(
)
-def exposed_persons_select(linkage: ExperimentExposureLinkage, *, include_multiple_variant: bool) -> ast.SelectQuery:
+def exposed_persons_select(
+ linkage: ExperimentExposureLinkage,
+ *,
+ include_multiple_variant: bool,
+ candidate_distinct_ids: ast.SelectQuery | None = None,
+) -> ast.SelectQuery:
"""One row per exposed distinct id, with the person and the attributed variant projected:
(distinct_id, person_id, variant, first_exposure_time).
@@ -518,12 +539,21 @@ def exposed_persons_select(linkage: ExperimentExposureLinkage, *, include_multip
"exclude" handling stay in, so a surface can count the people the analysis set aside; the
key never names a real variant, so callers comparing variants skip those rows naturally.
+ ``candidate_distinct_ids`` carries the same contract as on
+ :func:`exposed_distinct_ids_select`: a one-column ``distinct_id`` select that is a superset
+ of the distinct ids the caller joins on.
+
Pure AST construction, like :func:`exposed_distinct_ids_select`.
"""
variants = list(linkage.requested_variants)
if include_multiple_variant:
variants.append(MULTIPLE_VARIANT_KEY)
- return _exposed_population_select(linkage, project_attribution=True, variants=variants)
+ return _exposed_population_select(
+ linkage,
+ project_attribution=True,
+ variants=variants,
+ candidate_distinct_ids=candidate_distinct_ids,
+ )
def _distinct_ids_mapped_to_exposed_persons_select(linkage: ExperimentExposureLinkage) -> ast.SelectQuery:
diff --git a/products/experiments/backend/test/test_replay_context.py b/products/experiments/backend/test/test_replay_context.py
new file mode 100644
index 000000000000..cd995be2f892
--- /dev/null
+++ b/products/experiments/backend/test/test_replay_context.py
@@ -0,0 +1,143 @@
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.test.persons import create_person
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
+from products.experiments.backend.replay_context import (
+ experiment_prompt_context,
+ experiment_status,
+ session_variant,
+ variant_rollout_shares,
+)
+from products.experiments.backend.replay_linkage import resolve_exposure_linkage
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+FROZEN_NOW = "2026-01-10T20:00:00Z"
+BASE_TIME = datetime(2026, 1, 9, 10, 0, tzinfo=UTC)
+
+
+def _create_experiment(test: BaseTest, *, key: str = "checkout-cta", **kwargs) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=test.team,
+ key=key,
+ name=key,
+ created_by=test.user,
+ filters={
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Current checkout", "rollout_percentage": 50},
+ {"key": "test", "name": "One-click checkout", "rollout_percentage": 40},
+ {"key": "beta", "rollout_percentage": 10},
+ ]
+ }
+ },
+ )
+ defaults: dict = {
+ "team": test.team,
+ "name": "Checkout CTA copy",
+ "feature_flag": flag,
+ "created_by": test.user,
+ "start_date": BASE_TIME - timedelta(days=8),
+ "exposure_criteria": {},
+ }
+ return Experiment.objects.create(**{**defaults, **kwargs})
+
+
+# The facade reads Replay Vision builds its experiment scanner on: rollout shares feed
+# per-variant sampling, the prompt context feeds the scan prompt, and the status read
+# drives the sweep's lifecycle check.
+class TestExperimentReplayContext(BaseTest):
+ def test_rollout_shares_are_fractions_without_excluded_variants(self) -> None:
+ experiment = _create_experiment(self, excluded_variants=["beta"])
+
+ assert variant_rollout_shares(self.team, experiment_id=experiment.pk) == {"control": 0.5, "test": 0.4}
+
+ with self.assertRaises(ValidationError):
+ variant_rollout_shares(self.team, experiment_id=experiment.pk + 1)
+
+ def test_prompt_context_describes_the_experiment(self) -> None:
+ experiment = _create_experiment(
+ self,
+ description="One-click checkout raises purchase conversion.",
+ excluded_variants=["beta"],
+ metrics=[
+ {"kind": "ExperimentMetric", "metric_type": "mean", "name": "Purchases", "source": {}},
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "purchase"},
+ },
+ ],
+ )
+ for name, link_type in (("Checkout conversion", "primary"), ("Support tickets", "secondary")):
+ saved = ExperimentSavedMetric.objects.create(team=self.team, name=name, query={"kind": "ExperimentMetric"})
+ ExperimentToSavedMetric.objects.create(
+ experiment=experiment, saved_metric=saved, metadata={"type": link_type}
+ )
+
+ context = experiment_prompt_context(self.team, experiment_id=experiment.pk)
+
+ assert context is not None
+ assert context.name == "Checkout CTA copy"
+ assert context.description == "One-click checkout raises purchase conversion."
+ assert context.feature_flag_key == "checkout-cta"
+ assert [(v.key, v.description, v.rollout_percentage) for v in context.variants] == [
+ ("control", "Current checkout", 50.0),
+ ("test", "One-click checkout", 40.0),
+ ]
+ assert context.primary_metric_names == ("Purchases", "Mean purchase", "Checkout conversion")
+
+ experiment.deleted = True
+ experiment.save()
+ assert experiment_prompt_context(self.team, experiment_id=experiment.pk) is None
+
+ def test_status_reads_the_lifecycle(self) -> None:
+ experiment = _create_experiment(self, running_time_calculation={"recommended_running_time": 14})
+
+ status = experiment_status(self.team, experiment_id=experiment.pk)
+ assert status is not None
+ assert status.status == "running"
+ assert status.planned_duration_days == 14.0
+ assert status.is_active
+
+ experiment.end_date = BASE_TIME
+ experiment.save()
+ ended = experiment_status(self.team, experiment_id=experiment.pk)
+ assert ended is not None and not ended.is_active
+
+ experiment.deleted = True
+ experiment.save()
+ assert experiment_status(self.team, experiment_id=experiment.pk) is None
+
+
+@time_machine.travel(FROZEN_NOW, tick=False)
+class TestSessionVariant(ClickhouseTestMixin, BaseTest):
+ def _expose(self, distinct_id: str, variant: str) -> None:
+ create_person(team=self.team, distinct_ids=[distinct_id])
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id=distinct_id,
+ timestamp=BASE_TIME,
+ properties={"$feature_flag": "checkout-cta", "$feature_flag_response": variant},
+ )
+
+ def test_attributes_the_exposed_variant_within_the_requested_set(self) -> None:
+ experiment = _create_experiment(self)
+ self._expose("control-user", "control")
+ self._expose("test-user", "test")
+ create_person(team=self.team, distinct_ids=["unexposed-user"])
+ flush_persons_and_events()
+
+ all_variants = resolve_exposure_linkage(self.team, experiment_id=experiment.pk)
+ assert session_variant(all_variants, "test-user") == "test"
+ assert session_variant(all_variants, "control-user") == "control"
+ assert session_variant(all_variants, "unexposed-user") is None
+
+ narrowed = resolve_exposure_linkage(self.team, experiment_id=experiment.pk, variants=["test"])
+ assert session_variant(narrowed, "control-user") is None
diff --git a/products/experiments/backend/test/test_session_exposure.py b/products/experiments/backend/test/test_session_exposure.py
index bdd547e49075..a5a64334c9c9 100644
--- a/products/experiments/backend/test/test_session_exposure.py
+++ b/products/experiments/backend/test/test_session_exposure.py
@@ -5,6 +5,9 @@ from typing import Any
from posthog.test.base import BaseTest
from unittest.mock import patch
+from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
+
from posthog.hogql import ast
from posthog.models import EventProperty
@@ -267,3 +270,26 @@ class TestExposedPopulationSelects(BaseTest):
distinct_ids = exposed_distinct_ids_select(linkage)
assert _select_aliases(distinct_ids) == ["distinct_id", "first_exposure_time"]
assert _variant_filter(distinct_ids) == ["control", "test"]
+
+ def test_variants_narrow_the_population(self) -> None:
+ experiment = self._experiment()
+
+ single = resolve_exposure_linkage(self.team, experiment_id=experiment.pk, variant="test")
+ assert single.requested_variants == ["test"]
+
+ listed = resolve_exposure_linkage(self.team, experiment_id=experiment.pk, variants=["test", "control", "test"])
+ assert listed.requested_variants == ["test", "control"]
+ assert _variant_filter(exposed_distinct_ids_select(listed)) == ["test", "control"]
+
+ @parameterized.expand(
+ [
+ ("unknown_variant_in_list", {"variants": ["control", "unknown"]}),
+ ("empty_list", {"variants": []}),
+ ("both_forms", {"variant": "control", "variants": ["test"]}),
+ ]
+ )
+ def test_a_bad_variants_request_is_refused(self, _name: str, kwargs: dict) -> None:
+ experiment = self._experiment()
+
+ with self.assertRaises(ValidationError):
+ resolve_exposure_linkage(self.team, experiment_id=experiment.pk, **kwargs)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e42c2090593d..98c21a6c2210 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53156,6 +53156,8 @@ export namespace Schemas {
in_session?: boolean | null;
/** Narrow to persons exposed to this variant. Defaults to all of the experiment's variants. */
variant?: string | null;
+ /** Narrow to persons exposed to any of these variants. Defaults to all of the experiment's variants. Do not combine with `variant`, the single-variant form that predates this field. */
+ variants?: string[] | null;
}
export type RecordingOrder = typeof RecordingOrder[keyof typeof RecordingOrder];