: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(replay-vision): let a goal draft target the experiment it names (#96787)
Kim Svatos Dugan21a68cea86f8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex eb9c4256386b..5cb4dbdcd930 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8596,10 +8596,14 @@ snapshots:hash: v1.k794b7964.4ef60f727ace235099b7180e0b8e6e96a81e3626ce2ccae46f74c29508f85c15.Mp6FnYUKmqMQBB2sni9IukHvqlxQSXt5l1F91H6F8Zgscenes-app-replay-vision--scanner-editor-goal-overview--light:hash: v1.k794b7964.2820672a63528051df5cbb805e984c645eaf35a5f3437b59eaa70e90f1a5f118.S63d60T6vwVkop1Z_-KvK0rTZiRymODAiDvjaaJD7Do+ scenes-app-replay-vision--scanner-editor-goal-overview-experiment--dark:+ hash: v1.k794b7964.bb23ed20fa34a412db9228dba2790feb2f2f4ea9a39353c5cf86db21e853746b.0kjhA7cqYlnGm1XT6TDODIphKatHsAykS0i3PVy7s4I+ scenes-app-replay-vision--scanner-editor-goal-overview-experiment--light:+ hash: v1.k794b7964.6eaedf34e715312cbca9d79b2d6e634630338edd3c75e54410f41f4ea633b1bd.vVF1dO7E1KQN60xV05xwLEBhM2_mwDB6rfPNDFLzPA4scenes-app-replay-vision--scanner-editor-goal-overview-loading--dark:- hash: v1.k794b7964.fe62cd969ce6bd55970c1e9cf78fe6de964c46ec4fc544b7a7bcf40aa4b16011.sh_jB5tLnqum3YbI99V6GH8nWno2Ll-Mkram9K8qHLk+ hash: v1.k794b7964.a94f2025953ab7473f0483ea7f6cdd85de331d729b117eecd0b2d95ec0158ca5.Bvp5Vh_dIzetAM4rH8iV6SGeAN1R9dmqEl7v5e5PJUUscenes-app-replay-vision--scanner-editor-goal-overview-loading--light:- hash: v1.k794b7964.cb882e5afca7dc0bf22f4d9341d7979f06500f25120c5020a1f797f6fa578486.davCiLjyEwLLRw5kh0JjVAtrghRONwHitTruNrTpoZ8+ hash: v1.k794b7964.08677286d79894d0b435378a498bf343806adc41dfe5688ab95836bd9f25262c.5ZUh6xUU-lD1BhpTkRRBz-sPx6g5EqcTb80fUAhThSEscenes-app-replay-vision--scanner-editor-triggers--dark:hash: v1.k794b7964.5bc5dc77d7346163d92585657a949d38938bdbabf11a2a0341bc3a6b9c980c80.AL7y75QUTSwtUvG6XKJvD4CPhbEXC4TmNPkxG_57CQ4scenes-app-replay-vision--scanner-editor-triggers--light:diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex 414e53a2f139..e9ba13a6c304 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -28,6 +28,17 @@ class ExperimentSummaryData:omitted_metric_count: int+@frozen+class TargetableExperiment:+ """A launched experiment whose exposed sessions a replay surface can narrow to."""++ id: int+ name: str+ description: str+ # The variant keys a caller may ask for, excluded variants already removed.+ variants: tuple[str, ...]++@dataclass(frozen=True)class CreateExperimentInput:"""diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.pyindex b5b29a8b57e4..925f58f2e8c4 100644--- a/products/experiments/backend/facade/replay.py+++ b/products/experiments/backend/facade/replay.py@@ -9,6 +9,7 @@ from products.experiments.backend.replay_linkage import (exposed_session_ids_select,resolve_exposure_linkage,resolve_in_session_exposure_semantics,+ targetable_experiments,validate_experiment_exposure_access,)@@ -21,5 +22,6 @@ __all__ = ["exposed_session_ids_select","resolve_exposure_linkage","resolve_in_session_exposure_semantics",+ "targetable_experiments","validate_experiment_exposure_access",]diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.pyindex 5e6ad5bd9515..a3bd22b15c4c 100644--- a/products/experiments/backend/replay_linkage.py+++ b/products/experiments/backend/replay_linkage.py@@ -40,6 +40,7 @@ stamped-property fallback flavor (the read with no event name to prune on) is reprecomputing teams rather than left to time out."""+from collections.abc import Sequencefrom dataclasses import dataclassfrom datetime import UTC, datetime@@ -66,6 +67,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuLazyComputationTable,ensure_precomputed,)+from products.experiments.backend.facade.contracts import TargetableExperimentfrom products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_endfrom products.experiments.backend.hogql_queries.cuped_config import CupedQueryConfigfrom products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder@@ -266,6 +268,52 @@ def resolve_in_session_exposure_semantics(team: Team, experiment: Experiment) ->return InSessionExposureSemantics(session_exposure=session_exposure, unavailable_reason=None)+def _requestable_variant_keys(experiment: Experiment) -> list[str]:+ """The variant keys a caller may narrow an exposed population to, in the flag's own order."""+ excluded_variants = set(experiment.excluded_variants or [])+ return [+ variant_definition["key"]+ for variant_definition in experiment.feature_flag.variants or []+ if variant_definition.get("key") and variant_definition["key"] not in excluded_variants+ ]+++def targetable_experiments(team: Team, *, experiment_ids: Sequence[int]) -> list[TargetableExperiment]:+ """The experiments among `experiment_ids` a replay surface can narrow to, each with its variants.++ For a surface that offers experiments to pick from before it has a query to run: Postgres reads+ only, and it applies the same refusals `resolve_exposure_linkage` raises on — deleted, no flag,+ not launched, group-aggregated, no variants — so an experiment listed here is one the exposure+ filter will accept rather than a ValidationError once a query runs.++ Object-level access is the caller's job: pass ids the principal may already read.+ """+ if not experiment_ids:+ return []+ experiments = Experiment.objects.filter(id__in=experiment_ids, team=team, deleted=False).select_related(+ "feature_flag"+ )+ targetable = []+ for experiment in experiments:+ flag = getattr(experiment, "feature_flag", None)+ if flag is None or experiment.start_date is None:+ continue+ if (flag.filters or {}).get("aggregation_group_type_index") is not None:+ continue+ variants = _requestable_variant_keys(experiment)+ if not variants:+ continue+ targetable.append(+ TargetableExperiment(+ id=experiment.id,+ name=experiment.name,+ description=experiment.description or "",+ variants=tuple(variants),+ )+ )+ return targetable++def resolve_exposure_linkage(team: Team, *, experiment_id: int, variant: str | None, in_session: bool = False) -> ExperimentExposureLinkage:@@ -294,12 +342,7 @@ def resolve_exposure_linkage("This experiment aggregates by group, so its exposures can't be matched to persons' recordings.")- excluded_variants = set(experiment.excluded_variants or [])- variant_keys = [- variant_definition["key"]- for variant_definition in flag.variants or []- if variant_definition.get("key") and variant_definition["key"] not in excluded_variants- ]+ 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:diff --git a/products/experiments/backend/test/test_replay_linkage.py b/products/experiments/backend/test/test_replay_linkage.pynew file mode 100644index 000000000000..95d76dc32ab3--- /dev/null+++ b/products/experiments/backend/test/test_replay_linkage.py@@ -0,0 +1,99 @@+from datetime import UTC, datetime++from posthog.test.base import BaseTest++from posthog.models.team import Team++from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.replay_linkage import targetable_experiments+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++# The read a surface uses to offer experiments before it has a query to run. It has to refuse+# exactly what `resolve_exposure_linkage` refuses, or a surface offers a target whose exposure+# filter fails the moment a query resolves it.+class TestTargetableExperiments(BaseTest):+ def _flag(self, key: str, *, variants: list[dict] | None = None, group_index: int | None = None) -> FeatureFlag:+ filters: dict = {}+ if variants is not None:+ filters["multivariate"] = {"variants": variants}+ if group_index is not None:+ filters["aggregation_group_type_index"] = group_index+ return FeatureFlag.objects.create(team=self.team, key=key, name=key, created_by=self.user, filters=filters)++ def _experiment(self, name: str, *, flag: FeatureFlag, launched: bool = True, **kwargs) -> Experiment:+ return Experiment.objects.create(+ team=self.team,+ name=name,+ feature_flag=flag,+ created_by=self.user,+ start_date=datetime(2026, 1, 1, tzinfo=UTC) if launched else None,+ exposure_criteria={},+ **kwargs,+ )++ def _default_variants(self) -> list[dict]:+ return [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]++ def test_a_launched_experiment_comes_back_with_its_variants(self):+ experiment = self._experiment(+ "Checkout CTA copy", flag=self._flag("checkout-cta", variants=self._default_variants())+ )++ targetable = targetable_experiments(self.team, experiment_ids=[experiment.id])++ assert [(t.id, t.name, t.variants) for t in targetable] == [+ (experiment.id, "Checkout CTA copy", ("control", "test"))+ ]++ def test_an_excluded_variant_is_not_offered(self):+ # Asking for an excluded variant is refused when the exposure filter resolves, so it must+ # not be one of the keys a caller can pick.+ experiment = self._experiment(+ "Checkout CTA copy",+ flag=self._flag("checkout-cta", variants=self._default_variants()),+ excluded_variants=["control"],+ )++ assert targetable_experiments(self.team, experiment_ids=[experiment.id])[0].variants == ("test",)++ def test_an_experiment_the_exposure_filter_would_refuse_is_left_out(self):+ # Each of these raises in `resolve_exposure_linkage`, so offering it would hand a caller+ # targeting that only fails later.+ draft = self._experiment(+ "Not launched", flag=self._flag("not-launched", variants=self._default_variants()), launched=False+ )+ grouped = self._experiment(+ "Group aggregated", flag=self._flag("grouped", variants=self._default_variants(), group_index=0)+ )+ boolean = self._experiment("Boolean flag", flag=self._flag("boolean-flag"))+ deleted = self._experiment(+ "Deleted", flag=self._flag("deleted-exp", variants=self._default_variants()), deleted=True+ )++ targetable = targetable_experiments(self.team, experiment_ids=[draft.id, grouped.id, boolean.id, deleted.id])++ assert targetable == []++ def test_an_experiment_in_another_team_is_left_out(self):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ flag = FeatureFlag.objects.create(+ team=other_team,+ key="checkout-cta",+ name="checkout-cta",+ created_by=self.user,+ filters={"multivariate": {"variants": self._default_variants()}},+ )+ foreign = Experiment.objects.create(+ team=other_team,+ name="Checkout CTA copy",+ feature_flag=flag,+ created_by=self.user,+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ exposure_criteria={},+ )++ assert targetable_experiments(self.team, experiment_ids=[foreign.id]) == []diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 9dceb93c1c38..e23d800f4c31 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1466,6 +1466,14 @@ class DraftScannerResponseSerializer(serializers.Serializer):"mis-estimate stops the scanner at the credits the user agreed to. Null on the legacy flow."),)+ experiment_targeting = ScannerExperimentTargetingField(+ allow_null=True,+ help_text=(+ "Goal-based flow only: the experiment whose participants the draft watches, when the goal "+ "named one of the project's launched experiments. Null when it named none. Carried "+ "separately from `query`, which never holds an exposure filter."+ ),+ )estimated_monthly_observations = serializers.IntegerField(allow_null=True,help_text=(@@ -2338,7 +2346,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi}# Scoped tokens must not receive data their scopes exclude. Core memory is INTERNAL# (session-only), so any scoped token loses it; the goal-based entity grounding (surveys,- # actions) is gated per resource against these scopes inside the drafter.+ # actions, experiments) is gated per resource against these scopes inside the drafter.allowed_scopes = get_authenticator_scopes(request.successful_authenticator)include_business_context = allowed_scopes is None@@ -2391,6 +2399,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"scanner_type": drafted.scanner_type,# Whether the goal mapped to a real filter or fell back to no targeting."has_query": bool(drafted.query),+ # Whether the goal named an experiment, so the scan watches its participants rather+ # than everyone who reached the same pages.+ "has_experiment_targeting": drafted.experiment_targeting is not None,"sampling_mode": drafted.sampling_mode,"sampling_rate": drafted.sampling_rate,"model": drafted.model,@@ -2414,6 +2425,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"sampling_rate": drafted.sampling_rate,"model": drafted.model,"credit_limit": drafted.credit_limit,+ "experiment_targeting": drafted.experiment_targeting,"estimated_monthly_observations": drafted.estimated_monthly_observations,}).datadiff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex e1bf229125da..a240bd9357fb 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -38,8 +38,15 @@ from posthog.models.user import Userfrom posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.experiments.backend.facade.replay import targetable_experimentsfrom products.replay_vision.backend.billing import observation_credits_for_model-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingMode, ScannerModel, ScannerType+from products.replay_vision.backend.models.replay_scanner import (+ ReplayScanner,+ SamplingMode,+ ScannerModel,+ ScannerType,+ apply_experiment_targeting,+)from products.replay_vision.backend.queries.action_volume import recent_action_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import MIN_SAMPLING_RATE, SAMPLE_RATE_PRECISIONfrom products.replay_vision.backend.queries.scanner_volume_estimate import (@@ -112,6 +119,9 @@ _MAX_MATCHED_SURVEYS = 10# an event filter plus this property, which is why the draft needs property filters at all._SURVEY_EVENTS = ("survey sent", "survey shown", "survey dismissed")_SURVEY_ID_PROPERTY = "$survey_id"+# Launched experiments whose names match the goal, shown with their variants so the draft can watch+# one variant's participants instead of everyone who reached the same pages.+_MAX_MATCHED_EXPERIMENTS = 5# Actions whose names match the goal, shown so the draft can filter on a curated behavior._MAX_MATCHED_ACTIONS = 10# Actions AND with the other filters like events do, so the same small ceiling applies.@@ -285,6 +295,11 @@ class ScannerDraft:# budget so a mis-estimate cannot overspend it. None on the legacy path.model: str | None = Nonecredit_limit: int | None = None+ # Shape: ScannerExperimentTargetingSerializer. Set by the goal-based path when the goal named one+ # of the team's experiments, so the scan watches that experiment's participants. It stays out of+ # `query`, which is where the API refuses an exposure filter, and rides to the wizard as its own+ # field the way a saved scanner carries it.+ experiment_targeting: dict[str, Any] | None = None@dataclass(frozen=True, kw_only=True)@@ -314,6 +329,16 @@ class _MatchedCohort:cohort_id: int+@dataclass(frozen=True, kw_only=True)+class _MatchedExperiment:+ """One of the team's launched experiments whose name matches the goal, with the variants a+ filter can name. Already checked to be one the exposure filter accepts."""++ name: str+ experiment_id: int+ variants: tuple[str, ...]++@dataclass(frozen=True, kw_only=True)class _GoalEntityMatches:"""The named objects a goal can target, each resolved to the ID a filter needs. Empty lists@@ -322,6 +347,7 @@ class _GoalEntityMatches:surveys: list[_MatchedSurvey]actions: list[_MatchedAction]cohorts: list[_MatchedCohort]+ experiments: list[_MatchedExperiment]class _SearchView:@@ -787,6 +813,17 @@ class _LlmDraftV2(BaseModel):"matching-cohorts list. Use when the goal is about a specific audience ('what do power users do'); a ""cohort scopes to those people. Usually just one; leave empty when the goal is not about who the user is.",)+ filter_experiment: str = Field(+ default="",+ description="An experiment whose participants the scan is limited to, copied verbatim from "+ "the briefing's matching-experiments list. Use when the goal is about an experiment or "+ "about a feature that shipped behind one; empty otherwise.",+ )+ filter_experiment_variant: str = Field(+ default="",+ description="The one variant of `filter_experiment` whose experience the goal is about, "+ "copied verbatim from that experiment's variant list. Empty means every variant.",+ )filter_event_properties: list[_LlmEventPropertyFilter] = Field(default_factory=list,description="Narrows an event in `filter_events` to one thing, for goals that name a specific survey "@@ -873,6 +910,19 @@ Pick the single type that best fits the goal, then draft the scanner:other filter, so the one strongest action usually stands alone. Each action shows the sessions itfired in recently: when several fit the goal, pick the busier one, and prefer an event or a page overan action that barely fires.+- filter_experiment: the briefing may list the team's launched experiments matching the goal. Use+ one whenever the goal is about an experiment, a variant, or a feature that shipped behind one+ ("the new flow we're testing", "people who see the new entrypoint", "our pricing test"). It+ limits the scan to the people that experiment exposed, which no page or event filter can+ express: a page filter scans everyone who visited the page, so the control group's sessions land+ in the results too and the observations describe the old experience and the new one at once.+ Copy the name exactly; anything not in the list is discarded.+ - filter_experiment_variant: the variant whose experience the goal is about, copied exactly from+ that experiment's variants. A goal about the new thing means the variant that has it, not+ control. Leave empty only when the goal compares the variants or names none.+ - Pick filter_pages too when the goal also names a surface: the experiment says WHO is watched+ and the pages say WHERE, so both together is what "friction in the new flow" asks for. The+ experiment filter is the one that must be there, so keep the pages to the flow itself.- filter_cohorts: the briefing may list the team's cohorts matching the goal. A cohort is a savedaudience, so use one when the goal is about WHO the user is ('what do power users struggle with')rather than what they did. Copy the name exactly; anything not in the list is discarded. Usually@@ -923,6 +973,7 @@ def _build_user_content_v2(surveys: Sequence[_MatchedSurvey] = (),actions: Sequence[_MatchedAction] = (),cohorts: Sequence[_MatchedCohort] = (),+ experiments: Sequence[_MatchedExperiment] = (),business_context: str = "",company: str = "",) -> str:@@ -992,6 +1043,20 @@ def _build_user_content_v2(),))+ if experiments:+ lines.append(+ "\n"+ + as_untrusted_data(+ "matching-experiments",+ [f'"{e.name}" -> variants: {", ".join(e.variants)}' for e in experiments],+ source=(+ "the team's launched experiments whose names match the goal, each with the "+ "variants it runs. Copy a name into filter_experiment to scan only the sessions "+ "of people that experiment exposed, and one of its variants into "+ "filter_experiment_variant to scan only the people who got that variant"+ ),+ )+ )if cohorts:lines.append("\n"@@ -1079,14 +1144,16 @@ def _goal_entity_matches(user_access_control: UserAccessControl,allowed_scopes: list[str] | None = None,) -> _GoalEntityMatches:- """Surveys, actions, and cohorts the caller can read whose names match the goal's words.+ """Surveys, actions, cohorts, and experiments the caller can read whose names match the goal.A goal that names a survey ("people who answered the pricing survey") cannot be filtered fromevents alone: every survey shares the same `survey sent` event, and the one the user means isidentified by `$survey_id`. Reading the survey by name gives that ID exactly, where sampling theproperty's values would return a list of UUIDs with nothing to choose between them. Actions andcohorts are the team's own curated definitions of a behavior and an audience, so a goal naming- one is the sharpest filter available.+ one is the sharpest filter available. An experiment is who a change was shown to, which nothing+ in the taxonomy can stand in for: its participants are resolved from exposure, not from anything+ a page or event filter can match, so a goal about a variant needs the experiment by id.Matching goes through `search_entities`, the ranked full-text search behind the app's search bar,one bounded call per goal term because its query grammar ANDs every word of its input.@@ -1094,21 +1161,22 @@ def _goal_entity_matches(Access control has two gates, and RBAC differs by kind. RBAC: `search_entities` applies thequeryset filter, but that filter passes everything through when the caller has neither resourceaccess nor object grants, and this helper has no viewset permission check behind it, so each- resource in `ACCESS_CONTROL_RESOURCES` (`survey`, `action`) needs the resource-level gate here.+ resource in `ACCESS_CONTROL_RESOURCES` (`survey`, `action`, `experiment`) needs the+ resource-level gate here.`cohort` is not an access-controlled resource, so it has no resource gate to apply (gating itwould always deny). Scope: a scoped token must not receive any resource its scopes exclude, sincethis path has no viewset to enforce `required_scopes`, so every kind is also scope-gated."""terms = _goal_terms(goal)if not terms:- return _GoalEntityMatches(surveys=[], actions=[], cohorts=[])+ return _GoalEntityMatches(surveys=[], actions=[], cohorts=[], experiments=[])def _readable(resource: APIScopeObject) -> bool:return user_access_control.check_access_level_for_resource(resource, required_level="viewer") or user_access_control.has_any_specific_access_for_resource(resource, required_level="viewer")- acl_kinds: tuple[APIScopeObject, ...] = ("survey", "action")+ acl_kinds: tuple[APIScopeObject, ...] = ("survey", "action", "experiment")kinds: set[str] = {kind for kind in acl_kinds if _readable(kind) and _scopes_allow_read(allowed_scopes, kind)}# Cohorts are team-scoped only, not in ACCESS_CONTROL_RESOURCES, so they get no resource gate,# but a scoped token still must hold cohort:read to receive them.@@ -1118,11 +1186,12 @@ def _goal_entity_matches(# those querysets annotate. With no kind it orders an empty base queryset by a column that was# never added, which raises.if not kinds:- return _GoalEntityMatches(surveys=[], actions=[], cohorts=[])+ return _GoalEntityMatches(surveys=[], actions=[], cohorts=[], experiments=[])surveys: dict[str, _MatchedSurvey] = {}actions: dict[str, _MatchedAction] = {}cohorts: dict[str, _MatchedCohort] = {}+ experiment_ids: list[int] = []view = _SearchView(user_access_control)try:for term in terms:@@ -1146,14 +1215,42 @@ def _goal_entity_matches(actions.setdefault(result_id, _MatchedAction(name=name, action_id=int(result_id)))elif kind == "cohort" and len(cohorts) < _MAX_MATCHED_COHORTS:cohorts.setdefault(result_id, _MatchedCohort(name=name, cohort_id=int(result_id)))+ elif kind == "experiment" and len(experiment_ids) < _MAX_MATCHED_EXPERIMENTS:+ # Name and variants come from the targetability read below, not from the search+ # hit, so only the id is collected here.+ if (experiment_id := int(result_id)) not in experiment_ids:+ experiment_ids.append(experiment_id)except Exception:# Losing the entity matches costs the precise filters, not the draft.logger.warning("replay_vision.scanner_draft.goal_entities_failed", team_id=team.id, exc_info=True)return _GoalEntityMatches(- surveys=list(surveys.values()), actions=list(actions.values()), cohorts=list(cohorts.values())+ surveys=list(surveys.values()),+ actions=list(actions.values()),+ cohorts=list(cohorts.values()),+ experiments=_targetable_matches(team, experiment_ids),)+def _targetable_matches(team: Team, experiment_ids: Sequence[int]) -> list[_MatchedExperiment]:+ """The matched experiments whose participants a scan can actually watch.++ An experiment the exposure filter would refuse — never launched, group-aggregated, no variants —+ must not reach the briefing: the draft would carry targeting that fails when the scan resolves+ it, and the wizard's own count would fail with it. So this fails CLOSED, unlike the action+ volume read: an unmeasured experiment is offered as no experiment.+ """+ if not experiment_ids:+ return []+ try:+ targetable = targetable_experiments(team, experiment_ids=experiment_ids)+ except Exception:+ logger.warning("replay_vision.scanner_draft.experiment_targetability_failed", team_id=team.id, exc_info=True)+ return []+ return [+ _MatchedExperiment(name=e.name, experiment_id=e.id, variants=e.variants) for e in targetable if e.name.strip()+ ]++def _live_actions(team: Team, actions: list[_MatchedAction]) -> list[_MatchedAction]:"""The matched actions that still fire, each carrying its recent session count.@@ -1284,6 +1381,7 @@ def _solve_budget(monthly_credit_budget: int,credits_per_observation: int,model_mode: str,+ experiment_targeting: dict[str, Any] | None = None,) -> _BudgetSolution:"""Set the two dials from the stated credit budget.@@ -1300,7 +1398,13 @@ def _solve_budget(Raises on estimate failure; the caller degrades to an uncosted draft."""monthly_scan_budget = monthly_credit_budget // max(1, credits_per_observation)- recordings_query = RecordingsQuery.model_validate(query or {"kind": "RecordingsQuery"})+ # Targeting is merged in here, never into the draft's own `query`: the estimate has to count the+ # experiment's participants rather than every session the pages match, or the budget is solved+ # against a population many times larger than the scan's, while the query the wizard saves stays+ # the exposure-free blob the API accepts.+ recordings_query = apply_experiment_targeting(+ RecordingsQuery.model_validate(query or {"kind": "RecordingsQuery"}), experiment_targeting+ )comprehensive = estimate_scanner_session_volume(team=team,query=recordings_query,@@ -1360,6 +1464,26 @@ def _grounded_event_properties(return out+def _grounded_targeting(+ experiment_name: str, variant: str, *, allowed: Sequence[_MatchedExperiment]+) -> dict[str, Any] | None:+ """The `experiment_targeting` blob for the drafted experiment filter, or None for no targeting.++ Grounded by construction: a name maps back to a matched experiment's own id, so an invented one+ has no id to resolve to and drops out. An invented variant falls back to every variant, because+ the exposure filter refuses a variant the experiment doesn't define — that would take the whole+ scan down, where all variants still answers a wider version of the goal.+ """+ matched = {e.name: e for e in allowed}.get(experiment_name.strip())+ if matched is None:+ return None+ variant_key = variant.strip()+ return {+ "experiment_id": matched.experiment_id,+ "variant": variant_key if variant_key in matched.variants else None,+ }++def _finalize_v2(parsed: _LlmDraftV2,*,@@ -1369,6 +1493,7 @@ def _finalize_v2(allowed_surveys: Sequence[_MatchedSurvey] = (),allowed_actions: Sequence[_MatchedAction] = (),allowed_cohorts: Sequence[_MatchedCohort] = (),+ allowed_experiments: Sequence[_MatchedExperiment] = (),) -> ScannerDraft:"""Normalize the v2 model output; costing is applied by the caller."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]@@ -1406,6 +1531,9 @@ def _finalize_v2(for name in dict.fromkeys(n.strip() for n in parsed.filter_cohorts)if name in cohorts_by_name][:_MAX_FILTER_COHORTS]+ targeting = _grounded_targeting(+ parsed.filter_experiment, parsed.filter_experiment_variant, allowed=allowed_experiments+ )narrowing = _v2_query(pages, events, event_properties, kept_actions, kept_cohorts)query: dict[str, Any] = narrowing if narrowing is not None else {"kind": "RecordingsQuery"}query["filter_test_accounts"] = True@@ -1415,10 +1543,13 @@ def _finalize_v2(# A page can ground yet drop to None in `_page_filter_value` (a too-short prefix) with nothing# formally dropped, so the query still widens to everything. Fire the warning whenever the model# wanted a filter but none survived, not only when a value was dropped.- widened_unexpectedly = narrowing is None and bool(- proposed_pages or parsed.filter_events or parsed.filter_actions or parsed.filter_cohorts+ dropped_experiment = bool(parsed.filter_experiment.strip()) and targeting is None+ widened_unexpectedly = (+ narrowing is None+ and targeting is None+ and bool(proposed_pages or parsed.filter_events or parsed.filter_actions or parsed.filter_cohorts))- if dropped_pages or dropped_events or widened_unexpectedly:+ if dropped_pages or dropped_events or dropped_experiment or widened_unexpectedly:# Every dropped value silently broadens the scan (worst case to every non-internal session,# the most expensive outcome) while the rationale may still describe a narrow one.logger.warning(@@ -1429,9 +1560,11 @@ def _finalize_v2(dropped_events=len(dropped_events),kept_screens=len(pages),kept_events=len(events),+ dropped_experiment=dropped_experiment,# `narrowing is None`, not `not pages`: a page can ground yet drop to None in- # `_page_filter_value` (a too-short prefix), leaving the query unnarrowed.- scans_every_session=narrowing is None,+ # `_page_filter_value` (a too-short prefix), leaving the query unnarrowed. Targeting+ # narrows on its own, outside the query, so it counts here too.+ scans_every_session=narrowing is None and targeting is None,)return ScannerDraft(@@ -1443,6 +1576,7 @@ def _finalize_v2(query=query,sampling_mode=parsed.sampling_mode,model=parsed.model,+ experiment_targeting=targeting,)@@ -1491,6 +1625,7 @@ def draft_scanner_from_goal_v2(surveys=matches.surveys,actions=matches.actions,cohorts=matches.cohorts,+ experiments=matches.experiments,business_context=_business_context(team, user) if include_business_context else "",company=company,)@@ -1510,6 +1645,7 @@ def draft_scanner_from_goal_v2(allowed_surveys=matches.surveys,allowed_actions=matches.actions,allowed_cohorts=matches.cohorts,+ allowed_experiments=matches.experiments,)# The cap is the stated budget, so a mis-estimate stops the scanner at the credits the user# agreed to rather than overspending. Kept even when costing fails, so the guardrail survives.@@ -1520,6 +1656,7 @@ def draft_scanner_from_goal_v2(team=team,user=user,query=draft.query,+ experiment_targeting=draft.experiment_targeting,monthly_credit_budget=monthly_credit_budget,credits_per_observation=observation_credits_for_model(draft.model or ScannerModel.GEMINI_3_FLASH_PREVIEW),model_mode=draft.sampling_mode or SamplingMode.COMPREHENSIVE,@@ -1596,6 +1733,10 @@ def _fall_back_to_pages(team=team,user=user,query=fallback,+ # Targeting survives the fallback: the goal named the experiment, so a population that+ # ignores it answers a different question, and unlike an event filter it cannot be the+ # dead part — the exposure read is resolved from the experiment itself.+ experiment_targeting=draft.experiment_targeting,monthly_credit_budget=monthly_credit_budget,credits_per_observation=observation_credits_for_model(draft.model or ScannerModel.GEMINI_3_FLASH_PREVIEW),model_mode=draft.sampling_mode or SamplingMode.COMPREHENSIVE,diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex f1d97cd26bf5..3f64b722edf9 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -14,6 +14,8 @@ from posthog.rate_limit import AIBurstRateThrottlefrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.posthog_ai.backend.models.assistant import CoreMemoryfrom products.replay_vision.backend.models.replay_scanner import ScannerTypefrom products.replay_vision.backend.queries.scanner_candidate_query import MIN_SAMPLING_RATE@@ -39,6 +41,7 @@ from products.replay_vision.backend.scanner_draft import (_LlmEventPropertyFilter,_MatchedAction,_MatchedCohort,+ _MatchedExperiment,_MatchedSurvey,_solve_budget,_v2_query,@@ -485,6 +488,7 @@ class TestDraftScannerEndpoint(_VisionAPITestCase):"sampling_rate": None,"model": None,"credit_limit": None,+ "experiment_targeting": None,"estimated_monthly_observations": None,}@@ -677,10 +681,59 @@ class TestEventsForGoal(_VisionAPITestCase):assert events == ["checkout_started"]+def _launched_experiment(team, user, name: str, *, launched: bool = True):+ flag = FeatureFlag.objects.create(+ team=team,+ key=name.lower().replace(" ", "-"),+ name=name,+ created_by=user,+ filters={+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ }+ },+ )+ return Experiment.objects.create(+ team=team,+ name=name,+ feature_flag=flag,+ created_by=user,+ start_date=timezone.now() if launched else None,+ exposure_criteria={},+ )++class TestGoalEntityMatches(_VisionAPITestCase):def _survey(self, name: str):return Survey.objects.create(team=self.team, name=name, created_by=self.user)+ def test_an_experiment_named_in_the_goal_comes_back_with_its_variants(self):+ # Who a change was shown to is not in the taxonomy: no page or event filter separates the+ # participants who got the new experience from everyone else who reached the same screen.+ experiment = _launched_experiment(self.team, self.user, "Onboarding checklist")++ matches = _goal_entity_matches(+ self.team, "summarize sessions in the onboarding checklist experiment", _access_control(allow=True)+ )++ assert [(e.name, e.experiment_id, e.variants) for e in matches.experiments] == [+ ("Onboarding checklist", experiment.id, ("control", "test"))+ ]++ def test_an_experiment_the_exposure_filter_would_refuse_never_reaches_the_briefing(self):+ # An experiment that never launched has no exposed sessions, and targeting it fails when the+ # scan resolves the filter — so it must not be offered as a target at all.+ _launched_experiment(self.team, self.user, "Onboarding checklist", launched=False)++ matches = _goal_entity_matches(+ self.team, "summarize sessions in the onboarding checklist experiment", _access_control(allow=True)+ )++ assert matches.experiments == []+def test_a_survey_named_in_the_goal_comes_back_with_its_id(self):# The filter needs the id: every survey fires the same "survey sent" event, so a name alone# cannot target one.@@ -1004,6 +1057,45 @@ class TestFinalizeV2Actions:assert "actions" not in draft.query+class TestFinalizeV2Experiments:+ _EXPERIMENT = _MatchedExperiment(name="AI creation flow", experiment_id=11, variants=("control", "test"))++ def _finalize(self, **overrides):+ return _finalize_v2(+ _draft_v2(**overrides),+ allowed_pages=[],+ allowed_events=[],+ team_id=1,+ allowed_experiments=[self._EXPERIMENT],+ )++ def test_a_grounded_experiment_becomes_targeting_on_the_named_variant(self):+ # A page filter would scan everyone who reached the same screen, control group included, so+ # the variant the goal is about has to come through as targeting.+ draft = self._finalize(filter_experiment="AI creation flow", filter_experiment_variant="test")++ assert draft.experiment_targeting == {"experiment_id": 11, "variant": "test"}+ # Exposure never rides in the query blob; the API refuses it there.+ assert draft.query is not None and "experiment_exposure" not in draft.query++ def test_no_named_variant_watches_every_variant(self):+ draft = self._finalize(filter_experiment="AI creation flow")++ assert draft.experiment_targeting == {"experiment_id": 11, "variant": None}++ def test_an_invented_experiment_name_is_dropped(self):+ draft = self._finalize(filter_experiment="Some other test", filter_experiment_variant="test")++ assert draft.experiment_targeting is None++ def test_an_invented_variant_falls_back_to_every_variant(self):+ # The exposure filter refuses a variant the experiment does not define, which would take the+ # whole scan down; every variant still answers a wider version of the goal.+ draft = self._finalize(filter_experiment="AI creation flow", filter_experiment_variant="treatment")++ assert draft.experiment_targeting == {"experiment_id": 11, "variant": None}++class TestFinalizeV2:def test_hallucinated_pages_are_dropped(self):draft = _finalize_v2(@@ -1277,6 +1369,32 @@ class TestDraftV2(_VisionAPITestCase):assert [e["id"] for e in draft.query["events"]] == ["billing_limit_set"]assert draft.estimated_monthly_observations == 0+ def test_the_experiment_the_goal_named_is_carried_as_targeting_and_counted(self):+ # The whole point of the targeting: the projection has to count that experiment's+ # participants, not every session the pages match, while the query the wizard saves stays+ # the exposure-free blob the API accepts.+ experiment = _launched_experiment(self.team, self.user, "Billing upgrade prompt")+ counted: list[RecordingsQuery] = []++ def estimate(*, team, query, user, sampling_mode, budget):+ counted.append(query)+ return ScannerVolumeEstimate(matched_sessions=300, effective_window_days=30)++ draft = self._drafted_with(+ _draft_v2(+ filter_pages=["/billing"],+ filter_experiment="Billing upgrade prompt",+ filter_experiment_variant="test",+ ),+ estimate,+ )++ assert draft.experiment_targeting == {"experiment_id": experiment.id, "variant": "test"}+ assert draft.query is not None and "experiment_exposure" not in draft.query+ assert counted[0].experiment_exposure is not None+ assert counted[0].experiment_exposure.experiment_id == experiment.id+ assert counted[0].experiment_exposure.variant == "test"+def test_solved_dials_reach_the_draft(self):draft = self._run(pages=("/billing",), generate=_draft_v2(filter_pages=["/billing"]))diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex d53c582bf5b4..97249a96196c 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2059,6 +2059,8 @@ export interface DraftScannerResponseApi {* @nullable*/credit_limit: number | null+ /** Goal-based flow only: the experiment whose participants the draft watches, when the goal named one of the project's launched experiments. Null when it named none. Carried separately from `query`, which never holds an exposure filter. */+ experiment_targeting: ScannerExperimentTargetingApi | null/*** Goal-based flow only: recordings a month the drafted scanner is projected to watch under the solved dials. Its credit cost lands at or under `monthly_credit_budget`, except when the budget is below what the minimum sampling rate can reach, where this is the floor and exceeds the budget. Null whenever `sampling_mode` is.* @nullablediff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex ef808b6813bc..8e9b792c4163 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -857,6 +857,7 @@ const goalDraft: DraftScannerResponseApi = {sampling_rate: 0.25,model: 'gemini-3-flash-preview',credit_limit: 5000,+ experiment_targeting: null,estimated_monthly_observations: 1000,}@@ -888,6 +889,90 @@ export const ScannerEditorGoalOverview: StoryObj = {],}+// The same landing step for a goal that named an experiment: the eligible-recordings section+// leads with the experiment and variant the scan watches, which no page filter can express.+export const ScannerEditorGoalOverviewExperiment: StoryObj = {+ parameters: {+ pageUrl: urls.replayVisionScannerOverview('new'),+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_BASED_CREATION_FLOW]: 'test' },+ },+ decorators: [+ mswDecorator({+ get: {+ // The targeting card and the snack read the experiment's name from this fetch.+ '/api/projects/:team_id/experiments/:id/': {+ id: 11,+ name: 'AI-based scanner creation',+ description: 'Does the goal flow beat the template gallery?',+ feature_flag_key: 'vision-goal-based-creation-flow',+ feature_flag: {+ id: 11,+ key: 'vision-goal-based-creation-flow',+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'test', rollout_percentage: 50 },+ ],+ },+ },+ },+ start_date: '2026-09-01T00:00:00Z',+ end_date: null,+ exposure_criteria: {},+ },+ },+ }),+ (StoryFn) => {+ const logic = replayScannerLogic({ id: 'new' })+ logic.mount()+ const draft: DraftScannerResponseApi = {+ ...goalDraft,+ name: 'New creation flow friction',+ description: 'Flags sessions where a participant struggles in the new AI creation flow.',+ scanner_config: {+ prompt: 'Did the participant hesitate, backtrack, or give up while describing their goal in the scanner creation flow? Answer yes or no with a one-sentence reason.',+ allow_inconclusive: true,+ },+ rationale:+ 'Your goal is about the new AI creation flow, so this watches only the sessions of people the experiment put in its test variant, on the pages where that flow lives. Struggling looks unremarkable, so it watches all matching replays rather than only the eventful ones.',+ query: {+ kind: 'RecordingsQuery',+ properties: [+ {+ type: 'recording',+ key: 'visited_page',+ value: ['/replay-vision/scanners/new'],+ operator: 'icontains',+ },+ ],+ events: [+ {+ id: 'replay_vision_scanner_creation_started',+ name: 'replay_vision_scanner_creation_started',+ type: 'events',+ order: 0,+ },+ ],+ } as RecordingsQuery,+ experiment_targeting: { experiment_id: 11, variant: 'test' },+ }+ logic.actions.draftScannerFromGoalSuccess(draft)+ logic.actions.setScannerValues({+ name: draft.name,+ description: draft.description,+ scanner_type: draft.scanner_type as ScannerType,+ scanner_config: draft.scanner_config as ScannerConfig,+ query: draft.query as RecordingsQuery,+ sampling_mode: draft.sampling_mode as SamplingMode,+ sampling_rate: draft.sampling_rate ?? 1,+ experiment_targeting: draft.experiment_targeting,+ })+ return <StoryFn />+ },+ ],+}+// The overview while the draft is still generating: the loading bar and skeleton the user sees// right after submitting the two questions.export const ScannerEditorGoalOverviewLoading: StoryObj = {diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.tsnew file mode 100644index 000000000000..29e39e7ca187--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.test.ts@@ -0,0 +1,78 @@+import { NodeKind } from '~/queries/schema/schema-general'+import { PropertyFilterType, PropertyOperator } from '~/types'++import type { ReplayScanner } from '../types'+import { eligibleFilterGroups } from './ScannerGoalOverview'++const scanner = (overrides: Partial<ReplayScanner> = {}): ReplayScanner =>+ ({+ id: 'new',+ name: 'Scanner',+ scanner_type: 'monitor',+ scanner_config: { prompt: 'Did the user struggle?' },+ sampling_rate: 1,+ sampling_mode: 'comprehensive',+ model: 'gemini-3-flash-preview',+ experiment_targeting: null,+ query: null,+ ...overrides,+ }) as ReplayScanner++describe('eligibleFilterGroups', () => {+ it('labels each kind of filter the draft can produce', () => {+ // The values alone don't say what narrows the scan, and an action or a cohort reads as a+ // bare name or an id, so the label is what tells the reader which kind each one is.+ const groups = eligibleFilterGroups(+ scanner({+ experiment_targeting: { experiment_id: 11, variant: 'test' },+ query: {+ kind: NodeKind.RecordingsQuery,+ properties: [+ {+ type: PropertyFilterType.Recording,+ key: 'visited_page',+ value: ['/billing', '/checkout'],+ operator: PropertyOperator.Regex,+ },+ { type: PropertyFilterType.Cohort, key: 'id', value: 7, operator: PropertyOperator.In },+ ],+ events: [{ id: 'billing_limit_set', name: 'billing_limit_set', type: 'events', order: 0 }],+ actions: [{ id: 42, name: 'Completed checkout', type: 'actions', order: 0 }],+ },+ }),+ { experimentName: 'Checkout CTA copy', cohortNames: { 7: 'Power users' } }+ )++ expect(groups).toEqual([+ { label: 'Experiment', values: ['Checkout CTA copy (test variant)'] },+ { label: 'Pages', values: ['/billing', '/checkout'] },+ { label: 'Event', values: ['billing_limit_set'] },+ { label: 'Action', values: ['Completed checkout'] },+ { label: 'Cohort', values: ['Power users'] },+ ])+ })++ it('names an experiment and a cohort it cannot resolve yet', () => {+ // Both load separately from the form, so the row has to stand on its own until they arrive.+ const groups = eligibleFilterGroups(+ scanner({+ experiment_targeting: { experiment_id: 11, variant: null },+ query: {+ kind: NodeKind.RecordingsQuery,+ properties: [+ { type: PropertyFilterType.Cohort, key: 'id', value: 7, operator: PropertyOperator.In },+ ],+ },+ })+ )++ expect(groups).toEqual([+ { label: 'Experiment', values: ['Experiment 11 (all variants)'] },+ { label: 'Cohort', values: ['Cohort 7'] },+ ])+ })++ it('has no groups when the draft watches every recording', () => {+ expect(eligibleFilterGroups(scanner({ query: { kind: NodeKind.RecordingsQuery } }))).toEqual([])+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsxindex 2396063600f0..80713a985fd5 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx@@ -11,11 +11,20 @@ import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'+import { cohortsModel } from '~/models/cohortsModel'+import { PropertyFilterType } from '~/types'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'import { creditsToUsd, formatCreditCount } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'import { ScannerEditorStep, scannerStepUrlWithParams } from '../scannerEditorSceneLogic'-import { OBSERVATION_CREDITS_BY_MODEL, SCANNER_TYPE_TAG_TYPE, modelName, scannerTypeLabel } from '../types'+import {+ OBSERVATION_CREDITS_BY_MODEL,+ SCANNER_TYPE_TAG_TYPE,+ modelName,+ type ReplayScanner,+ scannerTypeLabel,+} from '../types'/** Why the draft chose this model, doubling as the guidance on when each tier fits. Keyed by the* concrete model id so a retired model just falls through to the generic line. */@@ -44,7 +53,7 @@ function activityFilterLabel(mode: string): string {return 'All recordings'}-/** One label:value row in the sampling and budget block. */+/** One label:value row in the eligible-recordings and sampling blocks. */function StatRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {return (<>@@ -100,6 +109,77 @@ function OverviewSection({)}+/** One kind of filter on the drafted scanner, with the values it holds. */+export interface EligibleFilterGroup {+ label: string+ values: string[]+}++/** The targeted experiment and variant, named so the row stands alone before the experiment loads. */+function experimentValues(scanner: ReplayScanner, experimentName?: string): string[] {+ const targeting = scanner.experiment_targeting+ if (!targeting?.experiment_id) {+ return []+ }+ const variant = targeting.variant ? `${targeting.variant} variant` : 'all variants'+ return [`${experimentName ?? `Experiment ${targeting.experiment_id}`} (${variant})`]+}++/** The pages a session must have visited.+ *+ * Read by key, not by position: the properties list can hold a cohort alongside the pages, and+ * taking whichever came first would render a cohort id as a page.+ */+function pageValues(scanner: ReplayScanner): string[] {+ const property = scanner.query?.properties?.find(+ (candidate) => 'key' in candidate && candidate.key === 'visited_page'+ )+ if (!property || !('value' in property) || !Array.isArray(property.value)) {+ return []+ }+ return property.value.map(String)+}++/** The names of the query's events or actions, whichever list is asked for. */+function namedQueryEntities(scanner: ReplayScanner, key: 'events' | 'actions'): string[] {+ const query = scanner.query+ const entities = (query && key in query ? query[key] : null) ?? []+ return entities.map((entity) => String(entity.name ?? entity.id)).filter(Boolean)+}++/** The cohorts the scan is limited to. The query carries only ids, so the name is looked up. */+function cohortValues(scanner: ReplayScanner, cohortNames?: Record<string, string>): string[] {+ return (scanner.query?.properties ?? [])+ .filter((property) => property.type === PropertyFilterType.Cohort)+ .map((property) => String(cohortNames?.[String(property.value)] ?? `Cohort ${property.value}`))+}++/** What the drafted scanner watches, grouped by the kind of filter each value came from.+ *+ * Each kind narrows differently. An experiment picks the people, a page picks where they went, an+ * event or an action picks what they did, and a cohort picks who they are. They also combine, so a+ * flat row of values leaves the reader to guess which value is which kind. The label is also the+ * only thing that makes an action or a cohort readable: neither value says what it is.+ */+export function eligibleFilterGroups(+ scanner: ReplayScanner,+ { experimentName, cohortNames }: { experimentName?: string; cohortNames?: Record<string, string> } = {}+): EligibleFilterGroup[] {+ const kinds: [singular: string, plural: string, values: string[]][] = [+ ['Experiment', 'Experiments', experimentValues(scanner, experimentName)],+ ['Page', 'Pages', pageValues(scanner)],+ ['Event', 'Events', namedQueryEntities(scanner, 'events')],+ ['Action', 'Actions', namedQueryEntities(scanner, 'actions')],+ ['Cohort', 'Cohorts', cohortValues(scanner, cohortNames)],+ ]+ return kinds+ .filter(([, , values]) => values.length > 0)+ .map(([singular, plural, values]) => ({+ label: pluralize(values.length, singular, plural, false),+ values,+ }))+}+/** The landing step after a goal-based draft: the whole drafted config, ordered by comprehension,* with each section deep-linking into the wizard step that edits it. */export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.Element {@@ -112,7 +192,10 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.EscannerEstimate,scannerEstimateLoading,isScannerSubmitting,+ experimentContext,} = useValues(logic)+ // Names the drafted cohort, which the query carries only by id.+ const { cohortsById } = useValues(cohortsModel)const { submitScanner, loadScannerEstimate } = useActions(logic)useEffect(() => {@@ -124,19 +207,12 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E// eslint-disable-next-line react-hooks/exhaustive-deps}, [])- const firstProperty = scanner.query?.properties?.[0]- const pageValues =- firstProperty &&- 'value' in firstProperty &&- Array.isArray(firstProperty.value) &&- firstProperty.value.length > 0- ? firstProperty.value- : null-- const eventValues =- scanner.query && 'events' in scanner.query && Array.isArray(scanner.query.events)- ? scanner.query.events.map((e) => String(e.name ?? e.id)).filter(Boolean)- : []+ const filterGroups = eligibleFilterGroups(scanner, {+ experimentName: experimentContext?.experiment.name,+ cohortNames: Object.fromEntries(+ Object.entries(cohortsById).map(([id, cohort]) => [id, cohort?.name ?? `Cohort ${id}`])+ ),+ })// The draft is still generating: show the page's shape so the wait reads as progress.if (goalDraftLoading) {@@ -196,13 +272,16 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E</OverviewSection><OverviewSection label="Eligible recordings" editStep="triggers" scannerId={scannerId}>- {pageValues || eventValues.length > 0 ? (- <div className="flex flex-wrap gap-1">- {(pageValues ?? []).map((page) => (- <LemonSnack key={`page-${String(page)}`}>{String(page)}</LemonSnack>- ))}- {eventValues.map((event) => (- <LemonSnack key={`event-${event}`}>{event}</LemonSnack>+ {filterGroups.length > 0 ? (+ <div className="grid grid-cols-[auto_1fr] items-start gap-x-3 gap-y-1 text-sm">+ {filterGroups.map((group) => (+ <StatRow key={group.label} label={group.label}>+ <span className="flex flex-wrap gap-1">+ {group.values.map((value) => (+ <LemonSnack key={value}>{value}</LemonSnack>+ ))}+ </span>+ </StatRow>))}</div>) : (diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 8e3f1b365f2f..8c3a0cfce745 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -170,6 +170,30 @@ describe('replayScannerLogic', () => {expect(logic.values.scanner?.query).toEqual({ kind: 'RecordingsQuery' })})+ it('carries the drafted experiment targeting onto the form', async () => {+ // Targeting is not part of the query, so the form is its only carrier: dropped here, the+ // saved scanner watches every visitor of the drafted pages instead of the participants.+ draftSpy.mockReturnValue([+ 200,+ {+ name: 'New entrypoint friction',+ description: 'Classifies friction in the new entrypoint.',+ scanner_type: 'classifier',+ scanner_config: { prompt: 'Classify the friction.', tags: ['smooth'], multi_label: false },+ rationale: '',+ query: null,+ experiment_targeting: { experiment_id: 11, variant: 'test' },+ },+ ])+ router.actions.push(urls.replayVisionScannerTemplate('new'))++ await expectLogic(logic, () =>+ logic.actions.draftScannerFromGoal('friction in the new AI entrypoint')+ ).toFinishAllListeners()++ expect(logic.values.scanner?.experiment_targeting).toEqual({ experiment_id: 11, variant: 'test' })+ })+it('drops a stale draft when the user has left the template step mid-request', async () => {draftSpy.mockReturnValue([200,diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex a04688149c18..8b740ad98df2 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -1713,7 +1713,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// still edits normally.rebuildExperimentContext: async () => {const targeting = values.scanner?.experiment_targeting- if (!targeting?.experiment_id || values.experimentContext) {+ if (!targeting?.experiment_id) {+ // A card left over from earlier targeting would keep offering variants of an+ // experiment this scanner no longer watches, and the picker would re-persist it.+ if (values.experimentContext) {+ actions.setExperimentContext(null)+ }+ return+ }+ if (values.experimentContext?.experiment.id === targeting.experiment_id) {return}try {@@ -1723,7 +1731,10 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// response restores a card for targeting the scanner no longer carries, which a later// variant change would then re-persist.const current = values.scanner?.experiment_targeting- if (current?.experiment_id !== targeting.experiment_id || values.experimentContext) {+ if (+ current?.experiment_id !== targeting.experiment_id ||+ values.experimentContext?.experiment.id === targeting.experiment_id+ ) {return}actions.setExperimentContext({ experiment, variantKey: current.variant ?? null })@@ -1823,7 +1834,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([...(goalDraft.credit_limit != null? { credit_limit: goalDraft.credit_limit, credit_limit_enabled: true }: {}),+ // The experiment the goal named, if any. It watches that experiment's+ // participants, which the query itself can't express — the backend derives the+ // exposure filter from this field at scan time.+ experiment_targeting: goalDraft.experiment_targeting ?? null,})+ // Loads the targeted experiment so the Triggers step shows its card and variant+ // picker, the same way it does for a scanner started from the experiment itself.+ actions.rebuildExperimentContext()// Solved dials mark a goal-flow draft, which reviews on the overview; legacy drafts// open the details step. The goal flow is already on the overview (pushed on request),// so this only navigates the legacy path.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex eda320b9e5f1..ab1b5c18f7f7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29947,6 +29947,25 @@ export namespace Schemas {Gemini38Flash: 'gemini-3.8-flash',} as const;+ /**+ * The experiment a scanner watches. Scans derive their person-scoped exposure filter from+ * this blob at query time, so it is the only place an experiment can enter a scanner's+ * targeting — which is what lets the write-side access check and read-side redaction cover it.+ */+ export interface ScannerExperimentTargeting {+ /**+ * The experiment the scanner watches.+ * @minimum 1+ */+ experiment_id: number;+ /**+ * Narrow to sessions of people exposed to this variant. Null means every variant.+ * @maxLength 400+ * @nullable+ */+ variant?: string | null;+ }+/*** An AI-drafted scanner configuration, ready to seed the creation wizard. Nothing is persisted.*/@@ -29990,6 +30009,8 @@ export namespace Schemas {* @nullable*/credit_limit: number | null;+ /** Goal-based flow only: the experiment whose participants the draft watches, when the goal named one of the project's launched experiments. Null when it named none. Carried separately from `query`, which never holds an exposure filter. */+ experiment_targeting: ScannerExperimentTargeting | null;/*** Goal-based flow only: recordings a month the drafted scanner is projected to watch under the solved dials. Its credit cost lands at or under `monthly_credit_budget`, except when the budget is below what the minimum sampling rate can reach, where this is the floor and exceeds the budget. Null whenever `sampling_mode` is.* @nullable@@ -33303,25 +33324,6 @@ export namespace Schemas {content_hash: string;}- /**- * The experiment a scanner watches. Scans derive their person-scoped exposure filter from- * this blob at query time, so it is the only place an experiment can enter a scanner's- * targeting — which is what lets the write-side access check and read-side redaction cover it.- */- export interface ScannerExperimentTargeting {- /**- * The experiment the scanner watches.- * @minimum 1- */- experiment_id: number;- /**- * Narrow to sessions of people exposed to this variant. Null means every variant.- * @maxLength 400- * @nullable- */- variant?: string | null;- }-/*** Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/