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(replay-vision): target experiment scanners by person-scoped exposure (#83362)

Kim Svatos Duganc908ced79e9a
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index c57c72f6fb51..bd78b55baab1 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -184,7 +184,6 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
sessionBucketLoading,
sessionBucketError,
sessionBucketRequest,
- usingExposureFallback,
} = useValues(logic)
const {
setSelectedVariantKey,
@@ -242,8 +241,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
urls.replayVisionScannerTemplate('new'),
experimentScannerParams({
experimentId: experiment.id as number,
- variantKeys: effectiveVariantKey ? [effectiveVariantKey] : [],
- useExposureFallback: usingExposureFallback,
+ variantKey: effectiveVariantKey,
})
).url
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index cb0cf82f0ccf..86b9d2b51f2a 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -28,11 +28,6 @@ import {
eventUsageLogic,
} from 'lib/utils/eventUsageLogic'
import { addProductIntentForCrossSell } from 'lib/utils/product-intents'
-import {
- applySessionLinkability,
- getExposureFallbackFilter,
- getViewRecordingFiltersForVariant,
-} from 'scenes/experiments/utils'
import { playerSidebarLogic } from 'scenes/session-recordings/player/sidebar/playerSidebarLogic'
import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -191,7 +186,6 @@ export interface experimentReplayTabLogicValues {
sessionEventDeltas: ExperimentSessionEventDeltaResponseApi | null
sessionEventDeltasError: string | null
sessionEventDeltasLoading: boolean
- usingExposureFallback: boolean
variantKeys: string[]
}
@@ -360,7 +354,6 @@ export interface experimentReplayTabLogicMeta {
variantKeys: (arg: any) => string[]
behaviorComparisonAvailable: (featureFlags: FeatureFlagsSet) => boolean
effectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null
- usingExposureFallback: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean
metricOptions: (
linkabilityLoaded: boolean,
unlinkableEventNames: Set<string>,
@@ -655,21 +648,6 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([
// filter could only match zero sessions. Those stay listed with their reason rather than
// vanishing, which reads as the metric having been forgotten. Fails open while the check
// loads.
- // The recordings tab itself is now person-scoped, but a scanner filters recordings by a
- // persisted RecordingsQuery, which can't express person-scoped exposure (the experiment_exposure
- // filter refuses userless callers). So the cross-sell scanner link still needs the old
- // event/property exposure filter, and this tells it whether to use the server-side-exposure
- // fallback shape. Fails open (false) while the linkability check loads.
- usingExposureFallback: [
- (s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],
- (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, experiment: Experiment): boolean =>
- linkabilityLoaded &&
- applySessionLinkability(
- getViewRecordingFiltersForVariant(experiment),
- unlinkableEventNames,
- getExposureFallbackFilter(experiment)
- ).usedExposureFallback,
- ],
metricOptions: [
(s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],
(
diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.py
index 2f06bff2241d..bfb6c9719d63 100644
--- a/products/replay_vision/backend/api/backfills.py
+++ b/products/replay_vision/backend/api/backfills.py
@@ -221,7 +221,10 @@ class ReplayScannerBackfillViewSet(
snapshot = BackfillScannerSnapshot.from_scanner(scanner)
return WindowedCandidateQuery(
team=self.team,
- query=scanner.recordings_query(),
+ query=scanner.targeted_recordings_query(),
+ # The exposure filter runs as the requesting user, so previewing or launching a
+ # backfill of an experiment scanner requires the same experiment access as viewing it.
+ user=cast(Any, self.request.user),
window_start=window_start,
window_end=window_end,
query_type=BACKFILL_CANDIDATE_QUERY_TYPE,
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index a48eb46ffcb7..496b41419704 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -54,8 +54,10 @@ from products.replay_vision.backend.models.replay_observation import (
from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.scanner_access import (
+ accessible_observations,
+ can_read_targeted_experiment,
+ readable_observation_scanner_ids,
scanner_for_reading_observations,
- scanners_for_reading_observations,
)
from products.replay_vision.backend.scanning import RetryOutcome, retry_observation
from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
@@ -770,13 +772,23 @@ class ReplayObservationViewSet(
self.check_object_permissions(self.request, scanner)
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading replay observations requires session_recording read access.")
+ # An experiment scanner's observations are that experiment's exposed sessions, so reading them
+ # needs experiment access too. Not-found, not 403: a denied experiment scanner reads as if it
+ # doesn't exist, matching the serializer's targeting redaction.
+ if not can_read_targeted_experiment(self.user_access_control, self.team_id, scanner):
+ raise NotFound()
self._scanner_for_url_cache = scanner
return scanner
def safely_get_queryset(self, queryset: QuerySet[ReplayObservation]) -> QuerySet[ReplayObservation]:
scanner = self._scanner_for_url()
+ # `_scanner_for_url` gated the scanner's *current* experiment; this gates each row against the
+ # experiment recorded in its own snapshot, so retargeting can't surface historical rows the
+ # caller can't access.
return (
- queryset.filter(team_id=self.team_id, scanner_id=scanner.id)
+ accessible_observations(
+ self.user_access_control, self.team_id, queryset.filter(team_id=self.team_id, scanner_id=scanner.id)
+ )
.select_related("triggered_by_user", "label")
.order_by("-created_at", "id")
)
@@ -809,9 +821,12 @@ class ReplayObservationViewSet(
def _observation_neighbors(self, observation: ReplayObservation) -> dict[str, uuid.UUID | None]:
# Neighbors honor the same filters and ordering as the scanner's list endpoint, so prev/next
- # navigation started from a filtered table stays within the filtered set.
- siblings = ReplayObservation.objects.filter(
- team_id=observation.team_id, scanner_id=observation.scanner_id
+ # navigation started from a filtered table stays within the filtered set. Same snapshot gate
+ # as the list, so prev/next can't step onto a historical row the caller can't access.
+ siblings = accessible_observations(
+ self.user_access_control,
+ observation.team_id,
+ ReplayObservation.objects.filter(team_id=observation.team_id, scanner_id=observation.scanner_id),
).order_by("-created_at", "id")
# Empty values (`?status=`) are no-ops in the filterset, so they must not opt out of the fast path.
if not any(self.request.query_params.get(key) for key in ReplayObservationFilter.base_filters):
@@ -1075,14 +1090,16 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading replay observations requires session_recording read access.")
# Observations inherit their scanner's RBAC. The generic access filter keys on the ReplayObservation
- # row rather than its scanner, so scope explicitly to the scanners this caller can read.
- readable_scanner_ids = list(
- self.user_access_control.filter_queryset_by_access_level(
- scanners_for_reading_observations(self.team_id)
- ).values_list("id", flat=True)
- )
+ # row rather than its scanner, so scope explicitly to the scanners this caller can read (current
+ # targeting included), then gate each row against the experiment in its own snapshot so a
+ # retargeted scanner can't surface historical rows the caller can't access.
+ readable_scanner_ids = readable_observation_scanner_ids(self.user_access_control, self.team_id)
queryset = (
- queryset.filter(team_id=self.team_id, scanner_id__in=readable_scanner_ids)
+ accessible_observations(
+ self.user_access_control,
+ self.team_id,
+ queryset.filter(team_id=self.team_id, scanner_id__in=readable_scanner_ids),
+ )
.select_related("triggered_by_user", "label")
.order_by("-created_at", "id")
)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index f0eb792458b6..5256f5e7cacd 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -44,7 +44,6 @@ from posthog.rate_limit import (
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
-from products.experiments.backend.models.experiment import Experiment
from products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer
from products.replay_vision.backend.api.filters import (
MultiChoiceFilter,
@@ -79,6 +78,7 @@ from products.replay_vision.backend.models.replay_scanner import (
ScannerModel,
ScannerProvider,
ScannerType,
+ apply_experiment_targeting,
)
from products.replay_vision.backend.queries import (
ESTIMATE_STALE_AFTER,
@@ -97,6 +97,7 @@ from products.replay_vision.backend.quota import (
current_period_bounds,
spend_projection,
)
+from products.replay_vision.backend.scanner_access import is_experiment_accessible
from products.replay_vision.backend.scanner_config import (
MAX_PROMPT_LENGTH,
MAX_TAG_LENGTH,
@@ -114,6 +115,17 @@ from products.signals.backend.facade.api import get_outcomes_for_signal_source_s
# Date is set by the schedule at trigger time, not by the user — strip on save.
_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
+
+def _reject_direct_experiment_exposure(query: dict[str, Any]) -> None:
+ # Exposure is derived from experiment_targeting at scan time, never persisted in the query blob:
+ # writable exposure there would bypass experiment_targeting's access check and let an editor run
+ # the exposure filter under the creator's access.
+ if query.get("experiment_exposure") is not None:
+ raise serializers.ValidationError(
+ "Recording filter can't set experiment exposure directly. Set experiment_targeting instead."
+ )
+
+
# Size caps enforced at the write boundary; scanner_config and query are copied into every observation's snapshot.
_MAX_DESCRIPTION_LENGTH = 1_000
_MAX_QUERY_BYTES = 50_000
@@ -199,23 +211,21 @@ class FeedbackThemesSerializer(serializers.Serializer):
class ScannerExperimentTargetingSerializer(serializers.Serializer):
- """The experiment a scanner's targeting watches. Metadata only; scanning never reads it."""
+ """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."""
experiment_id = serializers.IntegerField(
min_value=1,
help_text="The experiment the scanner watches.",
)
- variant_keys = serializers.ListField(
- child=serializers.CharField(max_length=400, allow_blank=False),
- allow_empty=True,
- max_length=50,
- help_text="Targeted experiment variants. Empty means every variant.",
- )
- use_exposure_fallback = serializers.BooleanField(
- help_text=(
- "True when the exposure event is captured server-side and the query filters on the "
- "`$feature/<flag_key>` property instead."
- ),
+ variant = serializers.CharField(
+ max_length=400,
+ allow_blank=False,
+ allow_null=True,
+ required=False,
+ default=None,
+ help_text="Narrow to sessions of people exposed to this variant. Null means every variant.",
)
@@ -527,22 +537,32 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
self._reject_scanner_type_change(attrs)
self._validate_scanner_config(attrs)
self._validate_and_strip_query(attrs)
+ self._drop_redacted_targeting_clear(attrs)
return attrs
+ def _drop_redacted_targeting_clear(self, attrs: dict[str, Any]) -> None:
+ # to_representation redacts experiment_targeting to null for callers denied the experiment,
+ # and the editor form writes the whole object back on save. Without this, any save by such
+ # a caller would carry experiment_targeting=None and silently clear targeting they can't
+ # see. Dropping the key treats it as untouched; a caller who can view the experiment can
+ # still clear it explicitly.
+ if (
+ "experiment_targeting" in attrs
+ and attrs["experiment_targeting"] is None
+ and self.instance is not None
+ and self.instance.experiment_targeting
+ and not self._can_view_targeted_experiment(self.instance.experiment_targeting)
+ ):
+ attrs.pop("experiment_targeting")
+
def validate_experiment_targeting(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
# The field already validated the blob's shape; this adds the access check, which needs the
# request context the field lacks. Filtered by the caller's experiment access (not just the
# team) so a scanner-editor can't confirm an experiment they can't view exists — a denied or
- # cross-team id reads as not-found. Falls back to team scoping when there's no request context.
+ # cross-team id reads as not-found.
if value is None:
return None
- team_experiments = Experiment.objects.filter(team=self.context["get_team"]())
- accessible = (
- self.user_access_control.filter_queryset_by_access_level(team_experiments)
- if self.user_access_control
- else team_experiments
- )
- if not accessible.filter(id=value["experiment_id"]).exists():
+ if not self._can_view_targeted_experiment(value):
raise serializers.ValidationError("Experiment not found in this project.")
return value
@@ -588,6 +608,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
RecordingsQuery.model_validate(attrs["query"])
except PydanticValidationError:
raise serializers.ValidationError({"query": "Recording filter is invalid."})
+ _reject_direct_experiment_exposure(attrs["query"])
# Persist exactly what the user sent (validated), minus the date keys the schedule controls.
attrs["query"] = {k: v for k, v in attrs["query"].items() if k not in _QUERY_FIELDS_TO_STRIP}
if len(json.dumps(attrs["query"], separators=(",", ":")).encode()) > _MAX_QUERY_BYTES:
@@ -618,13 +639,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial
get_team = self.context.get("get_team")
if get_team is None: # no request context (e.g. internal serialization); don't over-redact
return True
- team_experiments = Experiment.objects.filter(team=get_team())
- accessible = (
- self.user_access_control.filter_queryset_by_access_level(team_experiments)
- if self.user_access_control
- else team_experiments
- )
- return accessible.filter(id=experiment_id).exists()
+ return is_experiment_accessible(self.user_access_control, get_team().id, experiment_id)
def create(self, validated_data: dict[str, Any]) -> ReplayScanner:
team = self.context["get_team"]()
@@ -847,22 +862,12 @@ class ReplayScannerFilter(django_filters.FilterSet):
# _can_view_targeted_experiment: without it, a scanner-viewer could pass ?experiment_id= to
# confirm (by match count and returned scanner names) that a scanner targets an experiment
# they can't otherwise see. An inaccessible or nonexistent id reads as no matches.
- if not self._caller_accessible_experiments().filter(id=experiment_id).exists():
- return queryset.none()
- return queryset.filter(experiment_targeting__experiment_id=experiment_id)
-
- def _caller_accessible_experiments(self) -> QuerySet[Experiment]:
# Reuse the viewset's resolved team and access control rather than reparsing the URL:
- # view.team_id handles @current and token-derived teams, and user_access_control is already
- # built. The scanner queryset is already scoped to this same team.
+ # view.team_id handles @current and token-derived teams, and user_access_control is already built.
view = self.request.parser_context.get("view") if self.request else None
- if view is None:
- return Experiment.objects.none()
- team_experiments = Experiment.objects.filter(team_id=view.team_id)
- access = view.user_access_control
- if access is None:
- return team_experiments
- return access.filter_queryset_by_access_level(team_experiments)
+ if view is None or not is_experiment_accessible(view.user_access_control, view.team_id, experiment_id):
+ return queryset.none()
+ return queryset.filter(experiment_targeting__experiment_id=experiment_id)
@staticmethod
def _filter_search(queryset: QuerySet[ReplayScanner], _name: str, value: str) -> QuerySet[ReplayScanner]:
@@ -1084,11 +1089,22 @@ class EstimateRequestSerializer(serializers.Serializer):
help_text="Proposed model; determines `credits_per_observation` in the response.",
)
+ experiment_targeting = ScannerExperimentTargetingField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text=(
+ "Proposed experiment targeting, merged into the query as its exposure filter the same "
+ "way a saved scanner derives it. The estimate then runs as the requesting user."
+ ),
+ )
+
def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
try:
RecordingsQuery.model_validate(value)
except PydanticValidationError:
raise serializers.ValidationError("Recording filter is invalid.")
+ _reject_direct_experiment_exposure(value)
return {k: v for k, v in value.items() if k not in _QUERY_FIELDS_TO_STRIP}
@@ -1891,14 +1907,26 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "viewer"):
raise serializers.ValidationError({"scanner_id": "No scanner with this id exists in this project."})
+ # A denied experiment must read the same as a nonexistent one, mirroring
+ # validate_experiment_targeting: the query runner's own access check answers with a 403,
+ # which would confirm to a scanner-editor that a hidden experiment id exists.
+ targeting = body.validated_data.get("experiment_targeting")
+ if targeting is not None and not is_experiment_accessible(
+ self.user_access_control, self.team_id, targeting["experiment_id"]
+ ):
+ raise serializers.ValidationError({"experiment_targeting": "Experiment not found in this project."})
+
# validate_query already validated this; the empty-dict default needs `kind` to parse.
query_dict: dict[str, Any] = dict(body.validated_data.get("query") or {})
query_dict.setdefault("kind", "RecordingsQuery")
- recordings_query = RecordingsQuery.model_validate(query_dict)
+ recordings_query = apply_experiment_targeting(RecordingsQuery.model_validate(query_dict), targeting)
estimate = estimate_scanner_session_volume(
team=self.team,
query=recordings_query,
+ # The exposure filter's access check runs as the requesting user, so a preview can't
+ # count exposed sessions of an experiment the caller is denied.
+ user=cast(User, request.user),
sampling_mode=body.validated_data["sampling_mode"],
budget=PREVIEW_ESTIMATE_BUDGET,
)
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.py
index 25f4c81d2443..3c1527baeaa1 100644
--- a/products/replay_vision/backend/facade/api.py
+++ b/products/replay_vision/backend/facade/api.py
@@ -7,7 +7,7 @@ from posthog.rbac.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.observation_formatting import format_line, read_output
-from products.replay_vision.backend.scanner_access import scanners_for_reading_observations
+from products.replay_vision.backend.scanner_access import accessible_observations, readable_observation_scanner_ids
from ee.hogai.utils.untrusted import as_untrusted_data
@@ -31,9 +31,11 @@ def fetch_page_session_observations(
Returns an `<observations>` block wrapped by the shared indirect-prompt-injection fence, or `None` when
the user can read no scanners, or none of the sessions were observed. `None` (not an empty string) is the "no Vision enrichment" signal the caller degrades on.
- Access: an observation inherits its scanner's RBAC, so the scanner set is filtered by the user's access
- level — never `team_id` alone — otherwise output from scanners the user can't read would leak. This
- mirrors `SearchReplayVisionObservationsTool`; the session-existence tradeoff it documents applies here too.
+ Access: an observation inherits its scanner's RBAC and, for an experiment scanner, the access to its
+ targeted experiment — so the scanner set is filtered by the user's access level (never `team_id` alone)
+ and each row is gated against the experiment in its snapshot. Otherwise output from scanners the user
+ can't read, or from experiments they can't view, would leak. This mirrors `SearchReplayVisionObservationsTool`;
+ the session-existence tradeoff it documents applies here too.
The observations summarize the *whole session* (which may span many pages), so the caller must present
this as session-level color for visitors who touched the page, not page-specific ground truth.
@@ -42,21 +44,21 @@ def fetch_page_session_observations(
"""
if not session_ids:
return None
- readable_scanner_ids = [
- str(sid)
- for sid in UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
- .filter_queryset_by_access_level(scanners_for_reading_observations(team.id))
- .values_list("id", flat=True)
- ]
+ access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
+ readable_scanner_ids = readable_observation_scanner_ids(access, team.id)
if not readable_scanner_ids:
return None
queryset = (
- ReplayObservation.objects.filter(
- team_id=team.id,
- scanner_id__in=readable_scanner_ids,
- session_id__in=session_ids,
- status=ObservationStatus.SUCCEEDED,
+ accessible_observations(
+ access,
+ team.id,
+ ReplayObservation.objects.filter(
+ team_id=team.id,
+ scanner_id__in=readable_scanner_ids,
+ session_id__in=session_ids,
+ status=ObservationStatus.SUCCEEDED,
+ ),
)
.select_related("scanner")
.only("id", "session_id", "scanner_result", "created_at", "scanner__name", "scanner__scanner_type")
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 73bc0e15ff63..f75535287b5d 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -49,9 +49,11 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import (
)
from products.replay_vision.backend.quota import compute_quota_snapshot, quota_state
from products.replay_vision.backend.scanner_access import (
+ accessible_observations,
+ can_read_targeted_experiment,
is_uuid,
+ readable_observation_scanner_ids,
scanner_for_reading_observations,
- scanners_for_reading_observations,
selection_target_ids,
)
from products.replay_vision.backend.scanner_config import scanner_config_error
@@ -245,7 +247,8 @@ class ReplayVisionGatesMixin:
return action
def _observation_for(self, observation_id: str, level: AccessControlLevel = "editor") -> "ReplayObservation | None":
- """An observation this user may act on at `level`. Observations inherit their scanner's RBAC."""
+ """An observation this user may act on at `level`. Observations inherit their scanner's RBAC,
+ and an experiment scanner's observations also need access to the experiment in their snapshot."""
if not is_uuid(observation_id):
return None
observation = (
@@ -255,6 +258,10 @@ class ReplayVisionGatesMixin:
observation.scanner, level
):
return None
+ if not accessible_observations(
+ self.user_access_control, self._team.id, ReplayObservation.objects.filter(pk=observation.pk)
+ ).exists():
+ return None
return observation
@staticmethod
@@ -334,7 +341,10 @@ class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):
return f"Scanner {scanner_id} not found.", {"error": "not_found"}
# Summaries inherit the scanner's RBAC — a team member without viewer access to this scanner
# must not read its recording-derived output. Treat as not-found so we don't leak existence.
- if not self.user_access_control.check_access_level_for_object(scanner, "viewer"):
+ # An experiment scanner also needs access to its targeted experiment.
+ if not self.user_access_control.check_access_level_for_object(
+ scanner, "viewer"
+ ) or not can_read_targeted_experiment(self.user_access_control, self._team.id, scanner):
return f"Scanner {scanner_id} not found.", {"error": "forbidden"}
if scanner.scanner_type != ScannerType.SUMMARIZER:
# Never interpolate the user-editable scanner name into tool output — it's outside the data fence.
@@ -597,11 +607,15 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
observations = {
str(obs.id): obs
- for obs in ReplayObservation.objects.filter(
- team_id=self._team.id,
- scanner_id__in=scanner_ids,
- status=ObservationStatus.SUCCEEDED,
- id__in=ordered_ids,
+ for obs in accessible_observations(
+ self.user_access_control,
+ self._team.id,
+ ReplayObservation.objects.filter(
+ team_id=self._team.id,
+ scanner_id__in=scanner_ids,
+ status=ObservationStatus.SUCCEEDED,
+ id__in=ordered_ids,
+ ),
)
.select_related("scanner")
.only("id", "session_id", "scanner_result", "created_at", "scanner__name")
@@ -636,15 +650,19 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
# A model-supplied non-UUID would raise ValidationError deeper in the ORM (alert noise); treat as not-found.
return None
scanner = scanner_for_reading_observations(self._team.id, scanner_uuid)
- # Observations inherit the scanner's RBAC — treat missing access as not-found.
- if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "viewer"):
+ # Observations inherit the scanner's RBAC, and an experiment scanner also needs access to
+ # its targeted experiment — treat either miss as not-found.
+ if (
+ scanner is None
+ or not self.user_access_control.check_access_level_for_object(scanner, "viewer")
+ or not can_read_targeted_experiment(self.user_access_control, self._team.id, scanner)
+ ):
return None
# The scanner name is user-editable and the header sits outside the data fence, so keep it out of
# tool output entirely (stored-injection guard); the searcher already knows which scanner they're on.
return [str(scanner.id)], "the selected Replay Vision scanner", False
- readable = self.user_access_control.filter_queryset_by_access_level(
- scanners_for_reading_observations(self._team.id)
- ).values_list("id", flat=True)
+ # Experiment access included, and the experiment lookup batched into one query.
+ readable = readable_observation_scanner_ids(self.user_access_control, self._team.id)
return [str(sid) for sid in readable], "your Replay Vision scanners", True
def _rank_observation_ids(
@@ -1707,7 +1725,9 @@ class EstimateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):
try:
estimate = estimate_scanner_session_volume(
team=self._team,
- query=scanner.recordings_query(),
+ query=scanner.targeted_recordings_query(),
+ # The exposure filter's access check runs as whoever is asking Max.
+ user=self._user,
sampling_mode=scanner.sampling_mode,
ch_user=ClickHouseUser.REPLAY_VISION,
budget=PREVIEW_ESTIMATE_BUDGET,
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index ab123402261d..88c7d482f9f7 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -22,6 +22,28 @@ if TYPE_CHECKING:
SETTLE_INTERVAL = dt.timedelta(minutes=35)
+def apply_experiment_targeting(query: "RecordingsQuery", targeting: dict | None) -> "RecordingsQuery":
+ """Set a recordings query's exposure filter from an `experiment_targeting` blob.
+
+ Shared by the scanner (live query) and the backfill snapshot (frozen copy of the blob), so the
+ two derive the exposure filter identically. No targeting *clears* the filter rather than leaving
+ it in place: a `query` blob saved before the write-guard (or with targeting later removed) can
+ still carry an `experiment_exposure` that nothing access-checks, and the sweep now runs the query
+ as the creator — so an untouched blob would run an exposure filter no one authorized.
+ """
+ from posthog.schema import RecordingsQueryExperimentExposureFilter # noqa: PLC0415
+
+ exposure = None
+ if targeting and targeting.get("experiment_id") is not None:
+ exposure = RecordingsQueryExperimentExposureFilter(
+ experiment_id=targeting["experiment_id"],
+ variant=targeting.get("variant") or None,
+ )
+ # Shallow copy replacing only the one field: the caller's query is left untouched, and the
+ # unrelated nested filters are shared by reference rather than deep-copied since nothing mutates them.
+ return query.model_copy(update={"experiment_exposure": exposure})
+
+
class ScannerType(models.TextChoices):
MONITOR = "monitor", "Monitor"
CLASSIFIER = "classifier", "Classifier"
@@ -298,6 +320,7 @@ class ReplayScanner(UUIDModel):
"scanner_type",
"scanner_config",
"query",
+ "experiment_targeting",
"sampling_rate",
"sampling_mode",
"provider",
@@ -305,7 +328,7 @@ class ReplayScanner(UUIDModel):
"emits_signals",
)
# Fields the persisted volume estimate is computed from; changing them marks the estimate stale.
- _ESTIMATE_FIELDS = frozenset({"query", "sampling_rate", "sampling_mode"})
+ _ESTIMATE_FIELDS = frozenset({"query", "experiment_targeting", "sampling_rate", "sampling_mode"})
# Written by sweeps and the read meter through queryset updates; a stale full save must not clobber them.
_MACHINE_OWNED_FIELDS = (
@@ -375,5 +398,15 @@ class ReplayScanner(UUIDModel):
return RecordingsQuery.model_validate(self.query or {"kind": "RecordingsQuery"})
+ def targeted_recordings_query(self) -> "RecordingsQuery":
+ """The query every scan and estimate must run: the persisted filter plus the exposure
+ filter derived from `experiment_targeting`.
+
+ Derived here rather than persisted into `query` so the experiment can only ever enter
+ through `experiment_targeting`, the field the API access-checks on write and redacts on
+ read. The serializer rejects `experiment_exposure` inside `query` for the same reason.
+ """
+ return apply_experiment_targeting(self.recordings_query(), self.experiment_targeting)
+
def __str__(self) -> str:
return f"{self.name} ({self.scanner_type})"
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 472f8a237e98..c176df6294e3 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -17,7 +17,7 @@ from posthog.hogql.visitor import TraversingVisitor
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.session_recordings.queries.session_recording_list_from_query import (
UNSCORED_SURFACING_SCORE,
SessionRecordingListFromQuery,
@@ -180,6 +180,10 @@ class ScannerCandidateQuery:
query: RecordingsQuery,
last_swept_at: dt.datetime,
sampling_rate: float,
+ # The principal the recordings query runs as, for the experiment_exposure filter's access
+ # check. The sweep passes the scanner's creator; a None principal makes that check refuse a
+ # query carrying an exposure filter. A query without one is unaffected either way.
+ user: User | None = None,
# Per-scanner sampling salt (pass the scanner id); must stay stable across sweeps of the same scanner.
sampling_salt: str,
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
@@ -238,6 +242,7 @@ class ScannerCandidateQuery:
self._inner = SessionRecordingListFromQuery(
team=team,
query=inner_query,
+ user=user,
extra_having_predicates=extra_having,
events_timestamp_floor=events_timestamp_floor,
skip_negative_blocklists=skip_negative_blocklists,
@@ -541,6 +546,10 @@ class WindowedCandidateQuery:
# Tags this caller's reads in `system.query_log`; required so a new caller names itself.
query_type: str,
sampling_rate: float,
+ # The principal the recordings query runs as, for the experiment_exposure filter's access
+ # check. The backfill passes whoever launched it; a None principal makes that check refuse a
+ # query carrying an exposure filter. A query without one is unaffected either way.
+ user: User | None = None,
sampling_salt: str,
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
cursor_end_time: dt.datetime | None = None,
@@ -601,6 +610,7 @@ class WindowedCandidateQuery:
self._inner = SessionRecordingListFromQuery(
team=team,
query=inner_query,
+ user=user,
extra_having_predicates=extra_having,
session_ids_to_exclude=exclude_session_ids,
skip_negative_blocklists=skip_negative_blocklists,
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index b815b3fae327..153030a62d16 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -16,7 +16,7 @@ from posthog.exceptions import (
ClickHouseQueryMemoryLimitExceeded,
ClickHouseQueryTimeOut,
)
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingMode
@@ -91,6 +91,7 @@ def estimate_scanner_session_volume(
*,
team: Team,
query: RecordingsQuery,
+ user: User | None = None,
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
ch_user: ClickHouseUser = ClickHouseUser.APP,
budget: EstimateBudget = BATCH_ESTIMATE_BUDGET,
@@ -101,6 +102,11 @@ def estimate_scanner_session_volume(
recordings list agree on what "matches". The exact count runs first; when it times out, is
rejected as too slow, or hits a memory limit, it retries with sampled events subqueries and
corrects the count back up (`sampled=True` on the result).
+
+ `user` is the principal the experiment_exposure filter's access check runs as. With no
+ principal (a genuinely userless caller, or a scanner whose creator was deleted) the exposure
+ filter is dropped and the broader eligible set counted — an over-count is the safe direction
+ for a budget forecast.
"""
# Sampling is only sound when every match must pass the sampled events leg; under OR, sessions
# matched via unsampled branches (persons, cohorts, console logs) would be multiplied by the
@@ -119,6 +125,7 @@ def estimate_scanner_session_volume(
sampled_plan = _plan_estimate_query(
team=team,
query=windowed,
+ user=user,
sampling_mode=sampling_mode,
sample_factor=sample_factor,
scan_window_days=scan_window_days,
@@ -140,6 +147,7 @@ def estimate_scanner_session_volume(
exact_plan = _plan_estimate_query(
team=team,
query=windowed,
+ user=user,
sampling_mode=sampling_mode,
sample_factor=None,
scan_window_days=scan_window_days,
@@ -175,6 +183,7 @@ def _plan_estimate_query(
*,
team: Team,
query: RecordingsQuery,
+ user: User | None,
sampling_mode: SamplingMode | str,
sample_factor: float | None,
scan_window_days: int,
@@ -184,9 +193,17 @@ def _plan_estimate_query(
extra_having = eligibility_predicates()
if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:
extra_having.append(surfacing)
+ # Without a principal the experiment_exposure access check would raise, so drop the filter and
+ # count the broader eligible set: an over-count is the safe direction for a budget forecast.
+ # Callers that have a principal keep the filter and get the real, narrowed count.
+ estimate_query = query
+ if query.experiment_exposure is not None and user is None:
+ estimate_query = query.model_copy(deep=True)
+ estimate_query.experiment_exposure = None
list_query = SessionRecordingListFromQuery(
team=team,
- query=query,
+ query=estimate_query,
+ user=user,
extra_having_predicates=extra_having,
events_sample_factor=sample_factor,
)
@@ -278,7 +295,9 @@ def refresh_scanner_estimate(
with tags_context(scanner_id=str(scanner.pk)):
estimate = estimate_scanner_session_volume(
team=scanner.team,
- query=scanner.recordings_query(),
+ query=scanner.targeted_recordings_query(),
+ # The refresher has no request; the creator is the same principal the sweep scans as.
+ user=scanner.created_by,
sampling_mode=scanner.sampling_mode,
budget=budget,
ch_user=ch_user,
@@ -286,8 +305,17 @@ def refresh_scanner_estimate(
projection = project_monthly_observations(estimate, scanner.sampling_rate)
estimated_at = timezone.now()
# Filtered write so a config edit racing the (slow) estimate query can't get stamped fresh with stale numbers.
+ # JSONField quirk: `field=None` filters for JSON null, not SQL NULL, so the no-targeting case needs isnull.
updated = ReplayScanner.objects.filter(
- pk=scanner.pk, query=scanner.query, sampling_rate=scanner.sampling_rate, sampling_mode=scanner.sampling_mode
+ pk=scanner.pk,
+ query=scanner.query,
+ sampling_rate=scanner.sampling_rate,
+ sampling_mode=scanner.sampling_mode,
+ **(
+ {"experiment_targeting__isnull": True}
+ if scanner.experiment_targeting is None
+ else {"experiment_targeting": scanner.experiment_targeting}
+ ),
).update(estimated_monthly_observations=projection, estimated_at=estimated_at)
if updated:
scanner.estimated_monthly_observations = projection
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index 2d9d21248c46..dbfa808242d6 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -8,11 +8,14 @@ appears once instead of at every reading call site."""
import uuid
from typing import TYPE_CHECKING, Any
+from django.db.models import Q
+
from rest_framework.exceptions import NotFound, PermissionDenied
from posthog.models.team import Team
from posthog.rbac.user_access_control import UserAccessControl
+from products.experiments.backend.models.experiment import Experiment
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
if TYPE_CHECKING:
@@ -20,6 +23,8 @@ if TYPE_CHECKING:
from posthog.models.user import User
+ from products.replay_vision.backend.models.replay_observation import ReplayObservation
+
def is_uuid(value: str) -> bool:
try:
@@ -41,6 +46,99 @@ def scanners_for_reading_observations(team_id: int) -> "QuerySet[ReplayScanner]"
return ReplayScanner.all_origins.filter(team_id=team_id)
+def is_experiment_accessible(access: UserAccessControl | None, team_id: int, experiment_id: int) -> bool:
+ """Whether the caller may view this experiment, filtered by object-level access (not just team).
+
+ The single source of truth for "is a scanner-viewer allowed to know this experiment exists".
+ A denied or cross-team id reads as inaccessible, so callers can treat it as not-found rather
+ than disclosing the experiment through a scanner surface. `access` is None only outside request
+ context (internal serialization), where there is no viewer to gate on, so it passes.
+ """
+ team_experiments = Experiment.objects.filter(team_id=team_id)
+ accessible = access.filter_queryset_by_access_level(team_experiments) if access is not None else team_experiments
+ return accessible.filter(id=experiment_id).exists()
+
+
+def _accessible_experiment_ids(access: UserAccessControl, team_id: int, experiment_ids: set[int]) -> set[int]:
+ """The subset of `experiment_ids` the caller may view, in one query. Empty input, empty result."""
+ if not experiment_ids:
+ return set()
+ accessible = access.filter_queryset_by_access_level(
+ Experiment.objects.filter(team_id=team_id, id__in=experiment_ids)
+ )
+ return set(accessible.values_list("id", flat=True))
+
+
+def accessible_observations(
+ access: UserAccessControl, team_id: int, observations: "QuerySet[ReplayObservation]"
+) -> "QuerySet[ReplayObservation]":
+ """Drop observations whose recorded experiment the caller can't view.
+
+ An observation's population is fixed at creation, so it authorizes against the experiment in its
+ own `scanner_snapshot`, not the scanner's *current* targeting — retargeting or clearing a scanner
+ must not expose the historical rows it produced under a restricted experiment. A snapshot with no
+ experiment targeting (every observation predating this feature) is unrestricted here and stays
+ subject to the scanner and session-recording gates the caller already passed.
+
+ One experiment query for the whole page, not one per row.
+ """
+ snapshot_experiment_ids = {
+ eid
+ for eid in observations.values_list(
+ "scanner_snapshot__experiment_targeting__experiment_id", flat=True
+ ).distinct()
+ if eid is not None
+ }
+ accessible = _accessible_experiment_ids(access, team_id, snapshot_experiment_ids)
+ if accessible == snapshot_experiment_ids:
+ return observations
+ # Keep rows whose snapshot names no experiment (untargeted, unrestricted) OR an accessible one.
+ # Phrased positively rather than `.exclude(path__in=inaccessible)`: on a nullable JSON path, exclude
+ # negates to `NOT (path IN (...))`, which is NULL — and therefore false — for untargeted rows, so it
+ # would wrongly drop them. `isnull` OR membership is null-safe. The lookup keys are written as
+ # literals (not composed from a variable) so the ORM-field-injection lint sees they're not caller input.
+ return observations.filter(
+ Q(scanner_snapshot__experiment_targeting__experiment_id__isnull=True)
+ | Q(scanner_snapshot__experiment_targeting__experiment_id__in=accessible)
+ )
+
+
+def readable_observation_scanner_ids(access: UserAccessControl, team_id: int) -> list[uuid.UUID]:
+ """Scanner ids whose observations the caller may read across scanners, experiment access included.
+
+ For the surfaces that scope by scanner (the session dock, Max search) rather than filter rows. A
+ scanner is included when the caller can read the scanner (recording RBAC) and can view its current
+ targeted experiment, if any. Batches the experiment lookup into one query instead of one per
+ scanner. Row-level history is still gated by `accessible_observations` on the rows themselves; this
+ only narrows which scanners are in scope.
+ """
+ scanners = list(
+ access.filter_queryset_by_access_level(scanners_for_reading_observations(team_id)).only(
+ "id", "experiment_targeting"
+ )
+ )
+ targeted = {eid for s in scanners if (eid := (s.experiment_targeting or {}).get("experiment_id")) is not None}
+ accessible = _accessible_experiment_ids(access, team_id, targeted)
+ return [
+ s.id
+ for s in scanners
+ if (eid := (s.experiment_targeting or {}).get("experiment_id")) is None or eid in accessible
+ ]
+
+
+def can_read_targeted_experiment(access: UserAccessControl, team_id: int, scanner: ReplayScanner) -> bool:
+ """Whether the caller may read a scanner given its *current* targeted experiment.
+
+ Gates the per-scanner observation endpoint at the scanner level, so a denied experiment scanner
+ reads as not-found. Row-level history within an accessible scanner is gated separately by
+ `accessible_observations`, which follows each row's snapshot. A scanner with no targeting passes.
+ """
+ targeting = scanner.experiment_targeting
+ if not targeting or targeting.get("experiment_id") is None:
+ return True
+ return is_experiment_accessible(access, team_id, targeting["experiment_id"])
+
+
def scanner_for_reading_observations(team_id: int, scanner_id: "str | uuid.UUID") -> ReplayScanner | None:
"""Resolve one scanner by id for reading its observations. See `scanners_for_reading_observations`."""
if not is_uuid(str(scanner_id)):
@@ -100,4 +198,9 @@ def scanner_for_recording_derived_read(
viewset.check_object_permissions(viewset.request, scanner)
if not viewset.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
raise PermissionDenied("Reading replay observations requires session_recording read access.")
+ # An experiment scanner's output is that experiment's exposed sessions, so reading it needs
+ # experiment access too. Not-found, not 403: a denied experiment scanner reads as if it doesn't
+ # exist, matching the serializer's targeting redaction.
+ if not can_read_targeted_experiment(viewset.user_access_control, viewset.team_id, scanner):
+ raise NotFound()
return scanner
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index a5e1bef9868a..c6f8f4e343ea 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -9,6 +9,10 @@ from django.utils import timezone
import structlog
from pydantic import ValidationError
+from rest_framework.exceptions import (
+ PermissionDenied,
+ ValidationError as DRFValidationError,
+)
from temporalio import activity
from temporalio.client import Client
from temporalio.exceptions import ApplicationError
@@ -21,6 +25,7 @@ from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counte
from products.replay_vision.backend.enqueue_claims import claim_enqueue_slot_prefix
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import apply_experiment_targeting
from products.replay_vision.backend.models.replay_scanner_backfill import (
ACTIVE_BACKFILL_STATUSES,
BackfillStatus,
@@ -138,7 +143,7 @@ def prepare_backfill_tick_activity(inputs: BackfillTickInputs) -> PrepareBackfil
def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> FindBackfillCandidatesOutput:
backfill = (
ReplayScannerBackfill.objects.for_team(inputs.team_id)
- .select_related("team")
+ .select_related("team", "created_by")
.filter(pk=inputs.backfill_id)
.first()
)
@@ -161,10 +166,13 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
raise ApplicationError(
f"ReplayScannerBackfill {inputs.backfill_id} has malformed frozen query: {exc}", non_retryable=True
) from exc
+ query = apply_experiment_targeting(query, snapshot.experiment_targeting)
candidate_query = WindowedCandidateQuery(
team=backfill.team,
query=query,
+ # The exposure filter's access check runs as whoever launched the backfill.
+ user=backfill.created_by,
window_start=backfill.window_start,
window_end=backfill.window_end,
query_type=BACKFILL_CANDIDATE_QUERY_TYPE,
@@ -179,7 +187,21 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
skip_negative_blocklists=True,
)
started_at = time.monotonic()
- candidates = candidate_query.run()
+ try:
+ candidates = candidate_query.run()
+ except (PermissionDenied, DRFValidationError) as exc:
+ # The exposure filter can't run anymore: the launcher was deleted or lost experiment
+ # access, or the experiment can't answer for its exposed population (deleted, back to
+ # draft, renamed variant). Cancelling on a condition that might heal is deliberate: a
+ # stuck backfill silently counts its unspent credits into the spend projection, while a
+ # cancelled one is visible and can be relaunched.
+ ReplayScannerBackfill.objects.for_team(inputs.team_id).filter(
+ pk=backfill.pk, status__in=ACTIVE_BACKFILL_STATUSES
+ ).update(status=BackfillStatus.CANCELLED, finished_at=timezone.now())
+ raise ApplicationError(
+ f"ReplayScannerBackfill {inputs.backfill_id} cancelled: its exposure filter can't run: {exc}",
+ non_retryable=True,
+ ) from exc
# Succeeded only, matching the `$recording_observed` event the creation-time count excludes on.
# Postgres rather than that count's fail-soft ClickHouse read, whose hiccup would report every session
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 112626785a8d..d4e4efb835fc 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -4,6 +4,10 @@ import datetime as dt
from django.utils import timezone
from pydantic import ValidationError
+from rest_framework.exceptions import (
+ PermissionDenied,
+ ValidationError as DRFValidationError,
+)
from temporalio import activity
from temporalio.exceptions import ApplicationError
@@ -87,7 +91,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
return FindScannerCandidatesOutput(candidates=[], saturated=False)
try:
- query = scanner.recordings_query()
+ query = scanner.targeted_recordings_query()
except ValidationError as exc:
raise ApplicationError(
f"ReplayScanner {inputs.scanner_id} has malformed query: {exc}", non_retryable=True
@@ -103,6 +107,8 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
candidate_query = ScannerCandidateQuery(
team=scanner.team,
query=query,
+ # The exposure filter's access check runs as the creator, matching the defence-in-depth check above.
+ user=scanner.created_by,
last_swept_at=scanner.last_swept_at,
sampling_rate=scanner.sampling_rate,
sampling_salt=str(scanner.id),
@@ -114,7 +120,16 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
skip_negative_blocklists=True,
scanner_id=str(scanner.id),
)
- batch = candidate_query.run_batch(limit)
+ try:
+ batch = candidate_query.run_batch(limit)
+ except (DRFValidationError, PermissionDenied):
+ # The exposure filter (run as the creator) can't resolve the targeted experiment: the creator
+ # lost experiment access, or the experiment can't answer for its exposed population — most
+ # often a draft that hasn't launched, but also deleted, group-aggregated, or renamed-variant.
+ # A draft heals itself at launch and none of the rest are the sweep's to repair, so skip the
+ # tick (no watermark advance) instead of failing it on every fire.
+ record_sweep_outcome("experiment_linkage_unresolved")
+ return FindScannerCandidatesOutput(candidates=[], saturated=False)
fetched = batch.matched
if batch.saturated:
record_candidate_page_full()
@@ -346,6 +361,7 @@ def _deep_sweep(
deep_query = WindowedCandidateQuery(
team=scanner.team,
query=query,
+ user=scanner.created_by,
window_start=swept_through,
window_end=window_end,
ascending=True,
diff --git a/products/replay_vision/backend/temporal/snapshots.py b/products/replay_vision/backend/temporal/snapshots.py
index a0d30a17ff61..f87d304f2ec8 100644
--- a/products/replay_vision/backend/temporal/snapshots.py
+++ b/products/replay_vision/backend/temporal/snapshots.py
@@ -32,6 +32,7 @@ class ScannerSnapshot(BaseModel, frozen=True):
# rebuilt from these snapshots, so without them a version bumped by a sampling or filter change reads
# as "nothing changed". Optional so older rows decode as not recorded rather than as unchanged.
query: dict[str, Any] | None = None
+ experiment_targeting: dict[str, Any] | None = None
sampling_rate: float | None = None
sampling_mode: str | None = None
@@ -47,6 +48,7 @@ class ScannerSnapshot(BaseModel, frozen=True):
emits_signals=scanner.emits_signals,
scanner_config=scanner.scanner_config,
query=scanner.query,
+ experiment_targeting=scanner.experiment_targeting,
sampling_rate=scanner.sampling_rate,
sampling_mode=scanner.sampling_mode,
)
diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.py
index 29ae64004eac..7c893f766177 100644
--- a/products/replay_vision/backend/tests/test_access_control.py
+++ b/products/replay_vision/backend/tests/test_access_control.py
@@ -1,12 +1,15 @@
from unittest.mock import MagicMock, patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, PersonalAPIKey, User
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatus
-from products.replay_vision.backend.tests.helpers import create_experiment
+from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
from products.replay_vision.backend.tests.test_vision_actions_api import _VisionActionAPITestCase
@@ -215,8 +218,6 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
"model": "gemini-3.7-flash",
"experiment_targeting": {
"experiment_id": experiment.id,
- "variant_keys": [],
- "use_exposure_fallback": False,
},
},
format="json",
@@ -228,7 +229,7 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
# A scanner is viewable at a coarser grain than its targeted experiment; a viewer who can't
# access the experiment must not learn its id or variants from the scanner payload.
experiment = create_experiment(self.team, "hidden-flag")
- targeting = {"experiment_id": experiment.id, "variant_keys": ["test"], "use_exposure_fallback": False}
+ targeting = {"experiment_id": experiment.id, "variant": "test"}
scanner = self._create_scanner(name="targeted", experiment_targeting=targeting)
self._set_resource_default("replay_scanner", "viewer")
self._set_resource_default("experiment", "none")
@@ -244,12 +245,59 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
resp = self.client.get(f"{self.scanners_url}{scanner.id}/")
self.assertEqual(resp.json()["experiment_targeting"], targeting)
+ def test_save_by_a_viewer_denied_the_experiment_keeps_the_targeting(self) -> None:
+ # The API redacts experiment_targeting to null for such an editor, and the editor form
+ # writes the whole object back on save. Without the write-side guard, renaming the scanner
+ # would silently clear targeting the caller can't even see.
+ experiment = create_experiment(self.team, "hidden-flag")
+ targeting = {"experiment_id": experiment.id, "variant": "test"}
+ scanner = self._create_scanner(name="targeted", experiment_targeting=targeting)
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/",
+ data={"name": "renamed", "experiment_targeting": None},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 200, resp.json())
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.experiment_targeting, targeting)
+
+ # The creator, who can view the experiment, can still clear it explicitly.
+ self.client.force_login(self.user)
+ resp = self.client.patch(
+ f"{self.scanners_url}{scanner.id}/", data={"experiment_targeting": None}, format="json"
+ )
+ self.assertEqual(resp.status_code, 200, resp.json())
+ scanner.refresh_from_db()
+ self.assertIsNone(scanner.experiment_targeting)
+
+ def test_estimate_treats_a_denied_experiment_targeting_as_not_found(self) -> None:
+ # The query runner's own access check answers a denied experiment with a 403, which would
+ # confirm the hidden id exists; the endpoint must answer 400 not-found, like the scanner
+ # write path does.
+ experiment = create_experiment(self.team, "hidden-flag")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.post(
+ f"{self.scanners_url}estimate/",
+ data={"experiment_targeting": {"experiment_id": experiment.id}},
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertEqual(resp.json()["attr"], "experiment_targeting")
+
def test_experiment_id_filter_returns_no_matches_for_an_inaccessible_experiment(self) -> None:
# Guards the ?experiment_id= disclosure: a scanner-viewer who can't access the experiment must
# not confirm a scanner targets it via the filter's match count. Distinct code path from the
# serializer redaction above — the scanner is hidden from the list entirely, not just nulled.
experiment = create_experiment(self.team, "hidden-flag")
- targeting = {"experiment_id": experiment.id, "variant_keys": ["test"], "use_exposure_fallback": False}
+ targeting = {"experiment_id": experiment.id, "variant": "test"}
self._create_scanner(name="targeted", experiment_targeting=targeting)
self._set_resource_default("replay_scanner", "viewer")
self._set_resource_default("experiment", "none")
@@ -269,13 +317,101 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
# The filter must resolve @current the way the viewset does, not pass the literal string to
# the DB lookup (which 500s). The user's current team is set by the test harness.
experiment = create_experiment(self.team, "aliased-flag")
- targeting = {"experiment_id": experiment.id, "variant_keys": [], "use_exposure_fallback": False}
+ targeting = {"experiment_id": experiment.id}
self._create_scanner(name="targeted", experiment_targeting=targeting)
resp = self.client.get(f"/api/environments/@current/vision/scanners/?experiment_id={experiment.id}")
self.assertEqual(resp.status_code, 200, resp.json())
self.assertEqual([s["name"] for s in resp.json()["results"]], ["targeted"])
+ def test_observations_of_a_denied_experiment_scanner_read_as_not_found(self) -> None:
+ # An experiment scanner's observations are the experiment's exposed sessions, so scanner +
+ # session_recording access is not enough to read them: a caller denied the experiment must
+ # not learn which sessions and people were exposed. Reads as not-found, not 403, matching
+ # the targeting redaction. A non-targeted scanner the same caller can read is the control.
+ experiment = create_experiment(self.team, "hidden-flag")
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("session_recording", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+ targeted = self._create_scanner(name="targeted", experiment_targeting={"experiment_id": experiment.id})
+ plain = self._create_scanner(name="plain")
+ # Observations carry the scanner's snapshot, so their experiment targeting is recorded on the row.
+ ReplayObservation.objects.create(
+ scanner=targeted, session_id="exposed-sess", scanner_snapshot=snapshot_for(targeted)
+ )
+ ReplayObservation.objects.create(scanner=plain, session_id="plain-sess", scanner_snapshot=snapshot_for(plain))
+
+ self.client.force_login(self.other_user)
+ targeted_url = self.observations_url(str(targeted.id))
+ self.assertEqual(self.client.get(targeted_url).status_code, 404)
+ self.assertEqual(self.client.get(f"{targeted_url}stats/").status_code, 404)
+
+ # Same access, non-targeted scanner: the experiment gate must not have widened to a blanket block.
+ plain_resp = self.client.get(self.observations_url(str(plain.id)))
+ self.assertEqual(plain_resp.status_code, 200, plain_resp.json())
+ self.assertEqual([o["session_id"] for o in plain_resp.json()["results"]], ["plain-sess"])
+
+ # The session-wide dock endpoint drops the exposed session but keeps the readable one.
+ dock_url = f"/api/environments/{self.team.id}/vision/observations/"
+ dock_resp = self.client.get(f"{dock_url}?session_id=exposed-sess")
+ self.assertEqual(dock_resp.status_code, 200, dock_resp.json())
+ self.assertEqual(dock_resp.json()["results"], [])
+
+ def test_retargeting_a_scanner_does_not_expose_historical_observations(self) -> None:
+ # An observation's population is fixed at creation, so the read gate follows the experiment in
+ # each row's snapshot, not the scanner's current targeting. Removing or changing targeting must
+ # not turn historical rows from a restricted experiment readable.
+ restricted = create_experiment(self.team, "restricted-flag")
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("session_recording", "editor")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(restricted.id), "none")
+
+ scanner = self._create_scanner(name="retargeted", experiment_targeting={"experiment_id": restricted.id})
+ # A row produced while the scanner targeted the restricted experiment.
+ ReplayObservation.objects.create(
+ scanner=scanner, session_id="restricted-sess", scanner_snapshot=snapshot_for(scanner)
+ )
+ # The editor clears targeting; the scanner's current targeting is now null.
+ scanner.experiment_targeting = None
+ scanner.save()
+ ReplayObservation.objects.create(
+ scanner=scanner, session_id="untargeted-sess", scanner_snapshot=snapshot_for(scanner)
+ )
+
+ self.client.force_login(self.other_user)
+ # The scanner itself now reads (no current targeting), but the historical restricted row is withheld.
+ resp = self.client.get(self.observations_url(str(scanner.id)))
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual([o["session_id"] for o in resp.json()["results"]], ["untargeted-sess"])
+
+ # Same through the session-wide dock: the restricted session stays hidden.
+ dock_url = f"/api/environments/{self.team.id}/vision/observations/"
+ dock_resp = self.client.get(f"{dock_url}?session_id=restricted-sess")
+ self.assertEqual(dock_resp.status_code, 200, dock_resp.json())
+ self.assertEqual(dock_resp.json()["results"], [])
+
+ def test_dock_experiment_access_check_does_not_scale_per_scanner(self) -> None:
+ # The dock's readable-scanner filter must batch the experiment-access lookup, not run one
+ # query per targeted scanner — otherwise a team member can amplify one request into a query
+ # per scanner. The query count stays flat as targeted scanners grow.
+ experiment = create_experiment(self.team, "shared-flag")
+ self._set_resource_default("replay_scanner", "editor")
+ self._set_resource_default("session_recording", "editor")
+ dock_url = f"/api/environments/{self.team.id}/vision/observations/?session_id=s1"
+ self.client.force_login(self.other_user)
+
+ self._create_scanner(name="t0", experiment_targeting={"experiment_id": experiment.id})
+ self.client.get(dock_url) # warm request-scoped caches so the two captures compare cleanly.
+ with CaptureQueriesContext(connection) as one:
+ self.assertEqual(self.client.get(dock_url).status_code, 200)
+ for i in range(1, 6):
+ self._create_scanner(name=f"t{i}", experiment_targeting={"experiment_id": experiment.id})
+ with CaptureQueriesContext(connection) as six:
+ self.assertEqual(self.client.get(dock_url).status_code, 200)
+ self.assertEqual(len(one.captured_queries), len(six.captured_queries))
+
class TestVisionActionAccessControlInheritance(_VisionActionAPITestCase):
def setUp(self) -> None:
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 9e82afe0c57d..5977b21bf02b 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -869,8 +869,7 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):
self.experiment = create_experiment(self.team, "checkout-redesign")
self.targeting = {
"experiment_id": self.experiment.id,
- "variant_keys": ["test"],
- "use_exposure_fallback": False,
+ "variant": "test",
}
def _create_payload(self, name: str, **extra: Any) -> dict[str, Any]:
@@ -898,17 +897,9 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):
@parameterized.expand(
[
- ("missing_experiment", {"variant_keys": [], "use_exposure_fallback": False}),
- ("bad_experiment_id", {"experiment_id": 0, "variant_keys": [], "use_exposure_fallback": False}),
- (
- "variant_keys_not_a_list",
- {"experiment_id": 9, "variant_keys": "not-a-list", "use_exposure_fallback": False},
- ),
- ("blank_variant_key", {"experiment_id": 9, "variant_keys": [""], "use_exposure_fallback": False}),
- (
- "too_many_variant_keys",
- {"experiment_id": 9, "variant_keys": [f"v{i}" for i in range(51)], "use_exposure_fallback": False},
- ),
+ ("missing_experiment", {"variant": "test"}),
+ ("bad_experiment_id", {"experiment_id": 0, "variant": "test"}),
+ ("blank_variant", {"experiment_id": 9, "variant": ""}),
]
)
def test_experiment_targeting_rejects_malformed(self, _name: str, targeting: dict[str, Any]) -> None:
@@ -917,7 +908,7 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):
)
self.assertEqual(resp.status_code, 400, resp.json())
# The field's nested validation reports the exact offending key (e.g.
- # experiment_targeting__variant_keys__0), so match on the prefix rather than the exact attr.
+ # experiment_targeting__variant), so match on the prefix rather than the exact attr.
self.assertTrue(resp.json()["attr"].startswith("experiment_targeting"), resp.json())
def test_partial_update_cannot_save_a_half_filled_targeting(self) -> None:
@@ -926,7 +917,7 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):
scanner = self._create_scanner(name="patch-me", experiment_targeting=self.targeting)
resp = self.client.patch(
f"{self.scanners_url}{scanner.id}/",
- data={"experiment_targeting": {"variant_keys": ["control"]}},
+ data={"experiment_targeting": {"variant": "control"}},
format="json",
)
self.assertEqual(resp.status_code, 400)
diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.py
index c423fd97f88d..a7c2450e64e7 100644
--- a/products/replay_vision/backend/tests/test_backfills.py
+++ b/products/replay_vision/backend/tests/test_backfills.py
@@ -7,8 +7,9 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.utils import timezone
+from rest_framework.exceptions import PermissionDenied
from rest_framework.status import HTTP_429_TOO_MANY_REQUESTS
-from temporalio.exceptions import WorkflowAlreadyStartedError
+from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
from posthog.models import Organization, Team
from posthog.redis import get_client
@@ -504,6 +505,25 @@ class TestBackfillTickActivities:
assert result.next_cursor_end_time is None
assert result.skipped_delta == 0
+ def test_unrunnable_exposure_filter_cancels_the_backfill(self) -> None:
+ # The candidate query raises PermissionDenied when the launcher was deleted or lost
+ # experiment access. Left RUNNING, the backfill would fail every minute forever while its
+ # unspent credits kept inflating the spend projection — the tick must cancel it terminally.
+ # Also pins the fail-closed manager path: the cancel runs outside request context, where a
+ # bare `objects` access raises TeamScopeError instead of cancelling.
+ scanner = _make_scanner()
+ backfill = _make_backfill(scanner)
+ with patch("products.replay_vision.backend.temporal.activities.backfill.WindowedCandidateQuery") as query_cls:
+ query_cls.return_value.run.side_effect = PermissionDenied("experiment access lost")
+ with pytest.raises(ApplicationError) as raised:
+ find_backfill_candidates_activity(
+ FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)
+ )
+ assert raised.value.non_retryable
+ backfill.refresh_from_db()
+ assert backfill.status == BackfillStatus.CANCELLED
+ assert backfill.finished_at is not None
+
def test_excluded_sessions_are_walked_over_not_dispatched(self) -> None:
# The cursor must pass an excluded session exactly as it passes an already-succeeded one.
# Filtering before the walk would leave the cursor short and refetch the same rows forever.
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 2fd08384609f..d8637688f1c2 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -384,3 +384,25 @@ class TestScannerCreditLimit(APIBaseTest):
assert scanner.scanner_version == version_before
assert scanner.estimated_at == estimated_at_before
+
+
+class TestTargetedRecordingsQuery(BaseTest):
+ def test_no_targeting_clears_a_stale_exposure_filter_in_the_query(self) -> None:
+ # A query saved before the write-guard (or after targeting was removed) can still carry an
+ # experiment_exposure that nothing access-checks. Since the sweep runs the derived query as the
+ # creator, an untouched blob would run an unauthorized exposure filter — so it must be cleared.
+ scanner = _make_scanner(
+ self.team,
+ query={"kind": "RecordingsQuery", "experiment_exposure": {"experiment_id": 999}},
+ experiment_targeting=None,
+ )
+ assert scanner.targeted_recordings_query().experiment_exposure is None
+
+ def test_targeting_sets_the_exposure_filter(self) -> None:
+ scanner = _make_scanner(
+ self.team, query={"kind": "RecordingsQuery"}, experiment_targeting={"experiment_id": 42, "variant": "test"}
+ )
+ exposure = scanner.targeted_recordings_query().experiment_exposure
+ assert exposure is not None
+ assert exposure.experiment_id == 42
+ assert exposure.variant == "test"
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index ea449397a3db..de7f088f4fcf 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -203,6 +203,16 @@ class TestFindScannerCandidatesActivity:
)
assert result == FindScannerCandidatesOutput(candidates=[], saturated=False)
+ def test_targeted_scanner_with_no_creator_skips_instead_of_failing(self) -> None:
+ # The exposure filter refuses userless principals, so a deleted creator would otherwise
+ # raise out of the activity and fail every scheduled tick forever. The skip also keeps the
+ # watermark still, so access restored later resumes from where scanning stopped.
+ scanner = _make_scanner(created_by=None, experiment_targeting={"experiment_id": 12345})
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+ assert result == FindScannerCandidatesOutput(candidates=[], saturated=False)
+
def test_proceeds_when_created_by_is_null(self) -> None:
scanner = _make_scanner(created_by=None)
with patch(
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 23c0b3c65be0..e01d3dbd1244 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -762,7 +762,9 @@ export const ScannerModelEnumApi = {
} as const
/**
- * The experiment a scanner's targeting watches. Metadata only; scanning never reads it.
+ * 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 ScannerExperimentTargetingApi {
/**
@@ -771,13 +773,11 @@ export interface ScannerExperimentTargetingApi {
*/
experiment_id: number
/**
- * Targeted experiment variants. Empty means every variant.
- * @maxItems 50
- * @items.maxLength 400
+ * Narrow to sessions of people exposed to this variant. Null means every variant.
+ * @maxLength 400
+ * @nullable
*/
- variant_keys: string[]
- /** True when the exposure event is captured server-side and the query filters on the `$feature/<flag_key>` property instead. */
- use_exposure_fallback: boolean
+ variant?: string | null
}
export interface FeedbackThemeSessionApi {
@@ -2005,6 +2005,8 @@ export interface EstimateRequestApi {
* * `gemini-3-flash-preview` - Gemini 3 Flash
* * `gemini-3.7-flash` - Gemini 3.7 Flash */
model?: ScannerModelEnumApi
+ /** Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user. */
+ experiment_targeting?: ScannerExperimentTargetingApi | null
}
/**
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 58155dd34cf4..6aa6b54e7ff3 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -418,9 +418,7 @@ export const visionScannersCreateBodySamplingRateMax = 1
export const visionScannersCreateBodyCreditLimitMax = 2147483647
-export const visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax = 400
-
-export const visionScannersCreateBodyExperimentTargetingOneVariantKeysMax = 50
+export const visionScannersCreateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersCreateBody = /* @__PURE__ */ zod
.object({
@@ -512,17 +510,17 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod
zod
.object({
experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
- variant_keys: zod
- .array(zod.string().max(visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax))
- .max(visionScannersCreateBodyExperimentTargetingOneVariantKeysMax)
- .describe('Targeted experiment variants. Empty means every variant.'),
- use_exposure_fallback: zod
- .boolean()
+ variant: zod
+ .string()
+ .max(visionScannersCreateBodyExperimentTargetingOneVariantMax)
+ .nullish()
.describe(
- 'True when the exposure event is captured server-side and the query filters on the `$feature\/<flag_key>` property instead.'
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
),
})
- .describe("The experiment a scanner's targeting watches. Metadata only; scanning never reads it."),
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
zod.null(),
zod.null(),
])
@@ -549,9 +547,7 @@ export const visionScannersPartialUpdateBodySamplingRateMax = 1
export const visionScannersPartialUpdateBodyCreditLimitMax = 2147483647
-export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax = 400
-
-export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax = 50
+export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
.object({
@@ -647,21 +643,17 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
zod
.object({
experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
- variant_keys: zod
- .array(
- zod
- .string()
- .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax)
- )
- .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax)
- .describe('Targeted experiment variants. Empty means every variant.'),
- use_exposure_fallback: zod
- .boolean()
+ variant: zod
+ .string()
+ .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantMax)
+ .nullish()
.describe(
- 'True when the exposure event is captured server-side and the query filters on the `$feature\/<flag_key>` property instead.'
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
),
})
- .describe("The experiment a scanner's targeting watches. Metadata only; scanning never reads it."),
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
zod.null(),
zod.null(),
])
@@ -1023,6 +1015,7 @@ export const visionScannersEstimateCreateBodySamplingRateMax = 1
export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensive`
export const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`
+export const visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.object({
@@ -1060,6 +1053,29 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.describe(
'Proposed model; determines `credits_per_observation` in the response.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.7-flash` - Gemini 3.7 Flash'
),
+ experiment_targeting: zod
+ .union([
+ zod
+ .object({
+ experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
+ variant: zod
+ .string()
+ .max(visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax)
+ .nullish()
+ .describe(
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
+ ),
+ })
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
+ zod.null(),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user.'
+ ),
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
index 3ba7fbd9aa54..9bdfe74e512e 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { LemonBanner, LemonCard, LemonInputSelect, LemonTag } from '@posthog/lemon-ui'
+import { LemonBanner, LemonCard, LemonSelect, LemonTag } from '@posthog/lemon-ui'
import { resolveCategoryDropdownVariant, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
@@ -93,20 +93,25 @@ function ScannerFilterGroup(): JSX.Element {
)
}
-// Variant selection for a scanner created from an experiment. Compiles the choice into the
-// exposure filter in the card below, so users never have to build that filter by hand.
+// Variant selection for a scanner targeting an experiment. The choice is stored as the scanner's
+// experiment targeting; the backend derives the person-scoped exposure filter from it at scan
+// time, so there is no filter in the card below to hand-edit.
function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element | null {
const { experimentContext } = useValues(replayScannerLogic({ id: scannerId }))
- const { setExperimentVariantKeys, detachExperimentContext } = useActions(replayScannerLogic({ id: scannerId }))
+ const { setExperimentVariant, detachExperimentContext } = useActions(replayScannerLogic({ id: scannerId }))
if (!experimentContext) {
return null
}
- const { experiment, variantKeys } = experimentContext
- const variantOptions = getExperimentVariants(experiment).map((variant) => ({
- key: variant.key,
- label: variant.key,
- }))
+ const { experiment, variantKey } = experimentContext
+ // A null value targets every variant; each experiment variant is a single-select option.
+ const variantOptions: { value: string | null; label: string }[] = [
+ { value: null, label: 'All variants' },
+ ...getExperimentVariants(experiment).map((variant) => ({
+ value: variant.key,
+ label: variant.key,
+ })),
+ ]
return (
<LemonCard hoverEffect={false} className="p-3 space-y-3" data-attr="vision-experiment-targeting">
@@ -114,31 +119,28 @@ function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element
<div className="space-y-1">
<LemonLabel>Experiment targeting</LemonLabel>
<div className="text-xs text-muted">
- This scanner watches sessions exposed to{' '}
- <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>. Changing variants updates
- the exposure filter below. Filters you add yourself are kept.
+ This scanner watches sessions of people exposed to{' '}
+ <Link to={urls.experiment(experiment.id)}>{experiment.name}</Link>. Pick a variant to narrow it,
+ or watch every variant. Filters you add yourself are kept.
</div>
</div>
<LemonButton
size="xsmall"
type="secondary"
onClick={() => detachExperimentContext()}
- tooltip="Remove the experiment link and edit the recording filters directly."
+ tooltip="Stop limiting this scanner to people exposed to this experiment. Filters you added yourself are kept."
data-attr="vision-experiment-targeting-detach"
>
- Edit as filters
+ Remove targeting
</LemonButton>
</div>
<div className="max-w-160">
- <LemonInputSelect
- mode="multiple"
- value={variantKeys}
- onChange={(keys) => setExperimentVariantKeys(keys)}
+ <LemonSelect
+ value={variantKey}
+ onChange={(key) => setExperimentVariant(key)}
options={variantOptions}
- placeholder="All variants"
data-attr="vision-experiment-targeting-variants"
/>
- <div className="text-xs text-muted mt-1">Leave empty to watch every variant.</div>
</div>
</LemonCard>
)
diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts
index f83b02fd848c..cd01718bc4b6 100644
--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts
@@ -1,14 +1,14 @@
-import { RecordingsQuery } from '~/queries/schema/schema-general'
-import { Experiment, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
+import { Experiment } from '~/types'
import {
- buildExperimentScannerQuery,
+ buildExperimentTargeting,
experimentScannerName,
experimentScannerParams,
parseExperimentScannerParams,
- reconcileVariantKeys,
- replaceExperimentExposureFilter,
+ prefillScannerForExperiment,
+ reconcileVariantKey,
} from './experimentTargeting'
+import type { ReplayScanner } from './types'
const experiment = {
id: 7,
@@ -28,19 +28,18 @@ const experiment = {
} as unknown as Experiment
describe('experimentTargeting', () => {
- it.each([
- [{ experimentId: 7, variantKeys: [], useExposureFallback: false }],
- [{ experimentId: 7, variantKeys: ['test'], useExposureFallback: false }],
- [{ experimentId: 7, variantKeys: ['control', 'test'], useExposureFallback: true }],
- ])('deep-link params round-trip through the parser: %j', (params) => {
- expect(parseExperimentScannerParams(experimentScannerParams(params))).toEqual(params)
- })
+ it.each([[{ experimentId: 7, variantKey: null }], [{ experimentId: 7, variantKey: 'test' }]])(
+ 'deep-link params round-trip through the parser: %j',
+ (params) => {
+ expect(parseExperimentScannerParams(experimentScannerParams(params))).toEqual(params)
+ }
+ )
it.each([
[{}],
[{ experiment: 'not-a-number' }],
[{ experiment: '-3' }],
- [{ variants: 'test' }],
+ [{ variant: 'test' }],
// kea-router coerces `?experiment=true` to boolean true, and Number(true) is 1; without a
// type guard that would prefill experiment 1 rather than parse as null.
[{ experiment: true }],
@@ -52,143 +51,43 @@ describe('experimentTargeting', () => {
it.each([
// kea-router hands single numeric query values back as numbers, not strings. The router
// values, not the stringified ones experimentScannerParams emits, are what the parser sees.
- [{ experiment: 7 }, { experimentId: 7, variantKeys: [], useExposureFallback: false }],
+ [{ experiment: 7 }, { experimentId: 7, variantKey: null }],
[
- { experiment: 7, variants: 1 },
- { experimentId: 7, variantKeys: ['1'], useExposureFallback: false },
- ],
- [
- { experiment: '7', variants: '1,2' },
- { experimentId: 7, variantKeys: ['1', '2'], useExposureFallback: false },
+ { experiment: 7, variant: 1 },
+ { experimentId: 7, variantKey: '1' },
],
])('parses raw router values (numbers, not strings): %j', (searchParams, expected) => {
expect(parseExperimentScannerParams(searchParams)).toEqual(expected)
})
it.each([
- // No selection means every variant, so an empty request stays empty.
- [[], []],
- // A stale key that the experiment no longer has is dropped rather than persisted.
- [['test', 'old-variant'], ['test']],
- // When every requested key is unknown, fall back to the full variant set rather than the
- // empty list that would broaden to an IsSet filter matching every enrolled session.
- [['old-variant'], ['control', 'test']],
- ])('reconciles requested variant keys against the experiment: %j', (requested, expected) => {
- expect(reconcileVariantKeys(experiment, requested)).toEqual(expected)
- })
-
- it('compiles the default exposure event filter with the selected variants', () => {
- const query = buildExperimentScannerQuery(experiment, ['test'], false)
- expect(query.events).toEqual([
- expect.objectContaining({
- id: '$feature_flag_called',
- properties: [
- {
- key: '$feature_flag_response',
- type: PropertyFilterType.Event,
- value: ['test'],
- operator: PropertyOperator.Exact,
- },
- {
- key: '$feature_flag',
- type: PropertyFilterType.Event,
- value: ['checkout-redesign'],
- operator: PropertyOperator.Exact,
- },
- ],
- }),
- ])
- expect(query.filter_test_accounts).toBe(true)
- })
-
- it('targets every variant when no subset is selected', () => {
- const query = buildExperimentScannerQuery(experiment, [], false)
- expect(query.events?.[0]?.properties?.[0]).toMatchObject({
- key: '$feature_flag_response',
- value: ['control', 'test'],
- })
+ // No selection means all variants, so null stays null.
+ [null, null],
+ // A valid variant survives.
+ ['test', 'test'],
+ // A stale key the experiment no longer has drops to all variants rather than an impossible target.
+ ['old-variant', null],
+ ])('reconciles the requested variant key against the experiment: %j', (requested, expected) => {
+ expect(reconcileVariantKey(experiment, requested)).toEqual(expected)
})
- it('compiles the flag-value property filter in fallback mode', () => {
- const query = buildExperimentScannerQuery(experiment, ['test'], true)
- expect(query.events).toEqual([])
- expect(query.properties).toEqual([
- {
- key: '$feature/checkout-redesign',
- type: PropertyFilterType.Event,
- value: ['test'],
- operator: PropertyOperator.Exact,
- },
- ])
- })
-
- it('never persists playlist-only query fields', () => {
- const query = buildExperimentScannerQuery(experiment, [], false)
- expect(Object.keys(query)).toEqual(
- expect.not.arrayContaining(['date_from', 'date_to', 'order', 'session_ids', 'limit'])
- )
- })
-
- it('variant changes swap the exposure filter and keep user-added filters', () => {
- const initial = buildExperimentScannerQuery(experiment, ['test'], false)
- const userFilter = {
- key: '$browser',
- type: PropertyFilterType.Event,
- value: ['Chrome'],
- operator: PropertyOperator.Exact,
- }
- const edited = { ...initial, properties: [userFilter] } as RecordingsQuery
-
- const updated = replaceExperimentExposureFilter(edited, {
- experiment,
- variantKeys: ['control'],
- useExposureFallback: false,
- })
-
- expect(updated.events?.[0]?.properties?.[0]).toMatchObject({
- key: '$feature_flag_response',
- value: ['control'],
- })
- expect(updated.properties).toEqual([userFilter])
+ it.each([
+ ['test', { experiment_id: 7, variant: 'test' }],
+ [null, { experiment_id: 7, variant: null }],
+ ])('builds the persisted targeting for variant %j', (variantKey, expected) => {
+ expect(buildExperimentTargeting({ experiment, variantKey })).toEqual(expected)
})
- it('fallback-mode variant changes keep user event filters and swap only the flag property', () => {
- const initial = buildExperimentScannerQuery(experiment, ['test'], true)
- const userEvent = { id: '$pageview', name: '$pageview', type: 'events' }
- const edited = { ...initial, events: [userEvent] } as RecordingsQuery
-
- const updated = replaceExperimentExposureFilter(edited, {
- experiment,
- variantKeys: ['control'],
- useExposureFallback: true,
- })
+ it('prefills targeting and test-account filtering without touching exposure in the query', () => {
+ const scanner = { name: 'Frustration score', query: { kind: 'RecordingsQuery' } } as unknown as ReplayScanner
- expect(updated.events).toEqual([expect.objectContaining({ id: '$pageview' })])
- expect(updated.properties).toEqual([
- expect.objectContaining({ key: '$feature/checkout-redesign', value: ['control'] }),
- ])
- })
-
- it('forces AND when swapping the exposure filter into an OR query', () => {
- const orQuery = {
- ...buildExperimentScannerQuery(experiment, ['test'], false),
- operand: FilterLogicalOperator.Or,
- } as RecordingsQuery
- const updated = replaceExperimentExposureFilter(orQuery, {
- experiment,
- variantKeys: ['test'],
- useExposureFallback: false,
- })
- expect(updated.operand).toEqual(FilterLogicalOperator.And)
- })
+ const prefilled = prefillScannerForExperiment(scanner, { experiment, variantKey: 'test' })
- it('inserts the exposure filter when the user removed it', () => {
- const emptied = replaceExperimentExposureFilter(
- { ...buildExperimentScannerQuery(experiment, [], false), events: [] },
- { experiment, variantKeys: ['test'], useExposureFallback: false }
- )
- expect(emptied.events).toHaveLength(1)
- expect(emptied.events?.[0]?.properties?.[0]).toMatchObject({ value: ['test'] })
+ expect(prefilled.experiment_targeting).toEqual({ experiment_id: 7, variant: 'test' })
+ expect(prefilled.query?.filter_test_accounts).toBe(true)
+ // Exposure must never enter the query blob: the API rejects it there, and access control
+ // for the experiment hangs off experiment_targeting alone.
+ expect(prefilled.query).not.toHaveProperty('experiment_exposure')
})
it.each([
diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
index 36539c98a8a8..a2adefde1acd 100644
--- a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
@@ -1,58 +1,32 @@
-import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
-import {
- getExperimentVariants,
- getExposureFallbackFilter,
- getViewRecordingFiltersForVariant,
-} from 'scenes/experiments/utils'
-import {
- convertUniversalFiltersToRecordingsQuery,
- recordingsQueryToUniversalFilters,
-} from 'scenes/session-recordings/filters/recordingsQueryConversions'
-import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
+import { getExperimentVariants } from 'scenes/experiments/utils'
-import { RecordingsQuery } from '~/queries/schema/schema-general'
-import {
- Experiment,
- FilterLogicalOperator,
- RecordingUniversalFilters,
- UniversalFiltersGroup,
- UniversalFiltersGroupValue,
-} from '~/types'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { Experiment } from '~/types'
+
+import type { ScannerExperimentTargetingApi } from 'products/replay_vision/frontend/generated/api.schemas'
import type { ReplayScanner } from './types'
/**
- * Experiment context a scanner is being created against. Held by replayScannerLogic for the
- * lifetime of the wizard so the Triggers step can offer variant targeting instead of raw filters.
- * An empty `variantKeys` means every variant of the experiment.
+ * Experiment context a scanner is being created or edited against. Held by replayScannerLogic so
+ * the Triggers step can offer variant targeting instead of raw filters. A null `variantKey` means
+ * every variant of the experiment.
*/
export interface ExperimentScannerContext {
experiment: Experiment
- variantKeys: string[]
- /**
- * When the experiment's default exposure event is captured server-side (no `$session_id`),
- * the entry point passes this so the scanner filters on `$feature/<flag_key>` instead of an
- * exposure event that can never match a recording. Mirrors the experiment Recordings tab's
- * fallback behavior; the linkability check already ran there, so the deep link carries the
- * answer rather than re-running it here.
- */
- useExposureFallback: boolean
+ variantKey: string | null
}
export interface ExperimentScannerParams {
experimentId: number
- variantKeys: string[]
- useExposureFallback: boolean
+ variantKey: string | null
}
/** Builds the search params an entry point appends to a new-scanner wizard URL. */
export function experimentScannerParams(params: ExperimentScannerParams): Record<string, string> {
const result: Record<string, string> = { experiment: String(params.experimentId) }
- if (params.variantKeys.length > 0) {
- result.variants = params.variantKeys.join(',')
- }
- if (params.useExposureFallback) {
- result.exposure = 'fallback'
+ if (params.variantKey) {
+ result.variant = params.variantKey
}
return result
}
@@ -69,173 +43,38 @@ export function parseExperimentScannerParams(searchParams: Record<string, any>):
if (!Number.isInteger(experimentId) || experimentId <= 0) {
return null
}
- // kea-router coerces `?variants=1` to the number 1, so stringify before splitting.
- const variantsRaw = searchParams.variants
- const variantKeys =
- typeof variantsRaw === 'string' || typeof variantsRaw === 'number'
- ? String(variantsRaw)
- .split(',')
- .map((key) => key.trim())
- .filter(Boolean)
- : []
- return { experimentId, variantKeys, useExposureFallback: searchParams.exposure === 'fallback' }
-}
-
-/**
- * The exposure filter for the selected variants, in the same shape the experiment Recordings tab
- * uses, so a scanner watches exactly the sessions that tab lists.
- */
-export function buildExperimentExposureFilter(
- experiment: Experiment,
- variantKeys: string[],
- useExposureFallback: boolean
-): UniversalFiltersGroupValue | null {
- const variantArg = variantKeys.length > 0 ? variantKeys : undefined
- if (useExposureFallback) {
- // Null only for custom exposure configs, which carry semantics a flag-value filter can't
- // stand in for; those keep the real exposure filter below.
- const fallback = getExposureFallbackFilter(experiment, variantArg)
- if (fallback) {
- return fallback
- }
- }
- return getViewRecordingFiltersForVariant(experiment, variantArg)[0] ?? null
-}
-
-/**
- * A scanner `query` targeting the experiment's selected variants. The exposure filter is the
- * first (and only) leaf so the Triggers step can later swap it when the variant selection
- * changes without touching filters the user added by hand.
- */
-export function buildExperimentScannerQuery(
- experiment: Experiment,
- variantKeys: string[],
- useExposureFallback: boolean
-): RecordingsQuery {
- const exposureFilter = buildExperimentExposureFilter(experiment, variantKeys, useExposureFallback)
- return toScannerQuery({
- ...DEFAULT_RECORDING_FILTERS,
- filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,
- filter_group: {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.And,
- values: exposureFilter ? [exposureFilter] : [],
- },
- ],
- },
- })
-}
-
-/**
- * True for a filter the experiment targeting compiled: it references the experiment's flag key,
- * either as the `$feature/<flag_key>` variant property (fallback filter, or a property on a
- * custom exposure event) or as a `$feature_flag` property on the default exposure event. User
- * filters on the same flag are indistinguishable by design; the variant selector owns flag
- * targeting while the experiment link is attached.
- */
-function isManagedExposureFilter(value: UniversalFiltersGroupValue, experiment: Experiment): boolean {
- if (isUniversalGroupFilterLike(value)) {
- return false
- }
- const variantProperty = `$feature/${experiment.feature_flag_key}`
- if ('key' in value && value.key === variantProperty) {
- return true
- }
- if ('type' in value && (value.type === 'events' || value.type === 'actions')) {
- const properties = ('properties' in value ? value.properties : undefined) ?? []
- return properties.some((property) => {
- if (!property || typeof property !== 'object' || !('key' in property)) {
- return false
- }
- if (property.key === variantProperty) {
- return true
- }
- if (property.key !== '$feature_flag' || !('value' in property)) {
- return false
- }
- return Array.isArray(property.value)
- ? property.value.includes(experiment.feature_flag_key)
- : property.value === experiment.feature_flag_key
- })
- }
- return false
+ // kea-router coerces `?variant=1` to the number 1, so stringify.
+ const variantRaw = searchParams.variant
+ const variantKey =
+ typeof variantRaw === 'string' || typeof variantRaw === 'number' ? String(variantRaw).trim() || null : null
+ return { experimentId, variantKey }
}
/**
- * Swaps the managed exposure filter in an existing scanner query for one targeting `variantKeys`,
- * keeping every other filter the user added. The managed filter is recognized by the experiment's
- * flag key (see `isManagedExposureFilter`); if the user removed it, the new one is inserted at
- * the front.
+ * The scanner's persisted experiment targeting. The backend derives the person-scoped exposure
+ * filter from this field at scan time — the same resolution the experiment Recordings tab uses —
+ * so the scanner watches exactly the sessions that tab lists, including when the exposure event
+ * fires server-side or in an earlier session. The exposure filter never enters `query` directly;
+ * the API rejects it there so targeting stays behind this field's experiment access check.
*/
-export function replaceExperimentExposureFilter(
- query: RecordingsQuery | null,
- context: ExperimentScannerContext
-): RecordingsQuery {
- const exposureFilter = buildExperimentExposureFilter(
- context.experiment,
- context.variantKeys,
- context.useExposureFallback
- )
- const universal = recordingsQueryToUniversalFilters(query)
- // Forced to AND: a recordings query has a single operand across its whole flattened filter
- // tree, so an OR group would make the exposure filter optional and match unexposed sessions.
- const swapIn = (group: UniversalFiltersGroup): UniversalFiltersGroup => ({
- ...group,
- type: FilterLogicalOperator.And,
- values: [
- ...(exposureFilter ? [exposureFilter] : []),
- ...group.values.filter((value) => !isManagedExposureFilter(value, context.experiment)),
- ],
- })
- const [first, ...rest] = universal.filter_group.values
- const filterGroup: UniversalFiltersGroup =
- first !== undefined && isUniversalGroupFilterLike(first)
- ? { ...universal.filter_group, type: FilterLogicalOperator.And, values: [swapIn(first), ...rest] }
- : swapIn(universal.filter_group)
- return toScannerQuery({ ...universal, filter_group: filterGroup })
-}
-
-/**
- * Converts editor-shaped universal filters to the scanner's persisted query, keeping only the
- * dimensions the Triggers editor writes; the rest (dates, order, session ids) are playlist
- * concerns the scanner model strips or never stores.
- */
-function toScannerQuery(universal: RecordingUniversalFilters): RecordingsQuery {
- const converted = convertUniversalFiltersToRecordingsQuery(universal)
+export function buildExperimentTargeting(context: ExperimentScannerContext): ScannerExperimentTargetingApi {
return {
- kind: converted.kind,
- events: converted.events,
- actions: converted.actions,
- properties: converted.properties,
- console_log_filters: converted.console_log_filters,
- having_predicates: converted.having_predicates,
- comment_text: converted.comment_text,
- filter_test_accounts: converted.filter_test_accounts,
- operand: converted.operand,
+ experiment_id: context.experiment.id as number,
+ variant: context.variantKey,
}
}
/**
- * Keeps only the requested variant keys that the loaded experiment actually has. A URL can carry a
- * stale `?variants=old-key`, which would build an exposure filter that never matches yet still
- * persist on save; dropping the unknown keys prevents that. When some keys are valid and some are
- * not, only the valid ones survive. When every requested key is unknown but the experiment does
- * have variants, this returns the full variant set rather than the empty list that would broaden to
- * an `IsSet` filter matching every session that evaluated the flag. An experiment with no variants
- * loaded still yields an empty list, which is the only enrollment marker available there.
+ * Keeps the requested variant key only if the loaded experiment actually has it. A URL can carry a
+ * stale `?variant=old-key`, which would target a variant that no longer exists; dropping it falls
+ * back to all variants (null) rather than persisting an impossible target.
*/
-export function reconcileVariantKeys(experiment: Experiment, requestedKeys: string[]): string[] {
- if (requestedKeys.length === 0) {
- return []
+export function reconcileVariantKey(experiment: Experiment, requestedKey: string | null): string | null {
+ if (requestedKey === null) {
+ return null
}
const known = new Set(getExperimentVariants(experiment).map((variant) => variant.key))
- const valid = requestedKeys.filter((key) => known.has(key))
- if (valid.length > 0) {
- return valid
- }
- return [...known]
+ return known.has(requestedKey) ? requestedKey : null
}
/** Scanner name for an experiment-scoped scanner, within the model's 255-char limit. */
@@ -244,11 +83,15 @@ export function experimentScannerName(baseName: string, experimentName: string):
return name.slice(0, 255)
}
-/** Applies the experiment context to a fresh (or freshly templated) scanner: targeted query, scoped name. */
+/** Applies the experiment context to a fresh (or freshly templated) scanner: targeting, scoped name. */
export function prefillScannerForExperiment(scanner: ReplayScanner, context: ExperimentScannerContext): ReplayScanner {
return {
...scanner,
name: experimentScannerName(scanner.name, context.experiment.name),
- query: buildExperimentScannerQuery(context.experiment, context.variantKeys, context.useExposureFallback),
+ experiment_targeting: buildExperimentTargeting(context),
+ query: {
+ ...(scanner.query ?? { kind: NodeKind.RecordingsQuery }),
+ filter_test_accounts: context.experiment.exposure_criteria?.filterTestAccounts ?? false,
+ },
}
}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 6e480c7fac2a..e8d66f93a651 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -1419,4 +1419,40 @@ describe('replayScannerLogic', () => {
})
})
})
+
+ describe('rebuildExperimentContext', () => {
+ it('installs the targeting card from the form targeting', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }],
+ },
+ })
+ logic.actions.setScannerValues({ experiment_targeting: { experiment_id: 7, variant: 'control' } })
+
+ await expectLogic(logic, () => logic.actions.rebuildExperimentContext()).toFinishAllListeners()
+
+ expect(logic.values.experimentContext).toEqual({
+ experiment: { id: 7, name: 'Checkout redesign' },
+ variantKey: 'control',
+ })
+ })
+
+ it('does not restore targeting a template pick discarded while the request was in flight', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }],
+ },
+ })
+ logic.actions.setScannerValues({ experiment_targeting: { experiment_id: 7, variant: 'control' } })
+
+ await expectLogic(logic, () => {
+ logic.actions.rebuildExperimentContext()
+ // Fires during the in-flight experiment request; resetScanner drops the form targeting.
+ logic.actions.startFromTemplate(null)
+ }).toFinishAllListeners()
+
+ expect(logic.values.scanner?.experiment_targeting).toBeFalsy()
+ expect(logic.values.experimentContext).toBeNull()
+ })
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index fc06ced4d8ee..6b949aad40c7 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -67,10 +67,10 @@ import {
import { clampDurationFilter, durationFilterError } from './durationBounds'
import {
ExperimentScannerContext,
+ buildExperimentTargeting,
parseExperimentScannerParams,
prefillScannerForExperiment,
- reconcileVariantKeys,
- replaceExperimentExposureFilter,
+ reconcileVariantKey,
} from './experimentTargeting'
import { consumeGoalDraftIntent } from './goalDraftIntent'
import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'
@@ -457,6 +457,9 @@ export interface replayScannerLogicActions {
tagSuggestions: TagSuggestionApi[]
payload?: any
}
+ rebuildExperimentContext: () => {
+ value: true
+ }
refreshObservations: () => {
value: true
}
@@ -543,8 +546,8 @@ export interface replayScannerLogicActions {
setExperimentContext: (context: ExperimentScannerContext | null) => {
context: ExperimentScannerContext | null
}
- setExperimentVariantKeys: (variantKeys: string[]) => {
- variantKeys: string[]
+ setExperimentVariant: (variantKey: string | null) => {
+ variantKey: string | null
}
setGoalDraftInput: (goal: string) => {
goal: string
@@ -713,8 +716,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// originalScanner, and submitIntent, and can refire the observation loads.
scannerWatermarkRefreshed: (scanner: ReplayScanner) => ({ scanner }),
setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),
- setExperimentVariantKeys: (variantKeys: string[]) => ({ variantKeys }),
+ setExperimentVariant: (variantKey: string | null) => ({ variantKey }),
detachExperimentContext: true,
+ rebuildExperimentContext: true,
saveAffectedCohort: (tag?: string) => ({ tag }),
setScannerType: (scannerType: ScannerType) => ({ scannerType }),
startFromTemplate: (templateKey: string | null) => ({ templateKey }),
@@ -1007,7 +1011,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
null as ExperimentScannerContext | null,
{
setExperimentContext: (_, { context }) => context,
- setExperimentVariantKeys: (state, { variantKeys }) => (state ? { ...state, variantKeys } : state),
+ setExperimentVariant: (state, { variantKey }) => (state ? { ...state, variantKey } : state),
detachExperimentContext: () => null,
},
],
@@ -1521,8 +1525,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
if (experimentParams) {
delete nextParams.experiment
- delete nextParams.variants
- delete nextParams.exposure
+ delete nextParams.variant
}
if (nextParams.goal !== undefined) {
delete nextParams.goal
@@ -1539,8 +1542,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
const experiment = await api.experiments.get(experimentParams.experimentId)
const context: ExperimentScannerContext = {
experiment,
- variantKeys: reconcileVariantKeys(experiment, experimentParams.variantKeys),
- useExposureFallback: experimentParams.useExposureFallback,
+ variantKey: reconcileVariantKey(experiment, experimentParams.variantKey),
}
const prefilled = prefillScannerForExperiment(newScanner(templateKey, teamName), context)
// Set the context only after the prefill is built, so a throw inside it
@@ -1563,6 +1565,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
if (draft) {
actions.setScannerValues(draft.scanner)
actions.setScannerDraftSavedAt(draft.savedAt)
+ // A draft made from an experiment prefill carries targeting the
+ // loadScannerSuccess above (a bare newScanner) didn't see.
+ actions.rebuildExperimentContext()
}
} finally {
cache.restoringDraft = false
@@ -1606,19 +1611,51 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.loadObservations()
actions.loadObservationStats()
}
+ actions.rebuildExperimentContext()
},
- // The reducer has already stored the new keys; recompile only the managed exposure
- // filter so filters the user added by hand survive a variant change.
- setExperimentVariantKeys: () => {
+ // Rebuilds the targeting card from the form's current targeting — a loaded scanner or a
+ // restored draft — so the variant picker and detach stay usable wherever it came from.
+ // The API nulls experiment_targeting for viewers denied the experiment, so this never
+ // fetches an experiment the viewer can't see. Fails soft: without the card the scanner
+ // still edits normally.
+ rebuildExperimentContext: async () => {
+ const targeting = values.scanner?.experiment_targeting
+ if (!targeting?.experiment_id || values.experimentContext) {
+ return
+ }
+ try {
+ const experiment = await api.experiments.get(targeting.experiment_id)
+ // The form's targeting can change while this request is in flight (a template pick or
+ // draft discard resets it), so re-check before installing the card. Otherwise a late
+ // 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) {
+ return
+ }
+ actions.setExperimentContext({ experiment, variantKey: current.variant ?? null })
+ } catch {
+ // The card simply doesn't render; targeting stays intact on the scanner.
+ }
+ },
+
+ // The reducer has already stored the new key; targeting lives in its own field, so a
+ // variant change never touches `query` and filters the user added by hand survive.
+ setExperimentVariant: () => {
const context = values.experimentContext
if (!context) {
return
}
- actions.setScannerValue(
- 'query',
- replaceExperimentExposureFilter(values.scanner?.query ?? null, context)
- )
+ actions.setScannerValue('experiment_targeting', buildExperimentTargeting(context))
+ },
+
+ // Clearing the context alone would leave the persisted targeting silently filtering to
+ // exposed persons with nothing in the Triggers UI able to show or remove it.
+ detachExperimentContext: () => {
+ if (values.scanner?.experiment_targeting) {
+ actions.setScannerValue('experiment_targeting', null)
+ }
},
// Changing type keeps the rest of the form: it spreads `current`, so an experiment
@@ -1778,6 +1815,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
try {
const response = await visionScannersEstimateCreate(String(teamId), {
query: scanner.query ?? undefined,
+ // Sent alongside the query so the preview counts the same exposed-person
+ // population the scan will, instead of every eligible session.
+ experiment_targeting: scanner.experiment_targeting ?? null,
sampling_rate: scanner.sampling_rate,
// The proposed model prices the credit estimate.
model: scanner.model,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3691bf5efd3b..a7d8d69538f5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31189,6 +31189,25 @@ export namespace Schemas {
Gemini37Flash: 'gemini-3.7-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;
+ }
+
/**
* Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.
*/
@@ -31218,6 +31237,8 @@ export namespace Schemas {
* * `gemini-3-flash-preview` - Gemini 3 Flash
* * `gemini-3.7-flash` - Gemini 3.7 Flash */
model?: ScannerModelEnum;
+ /** Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user. */
+ experiment_targeting?: ScannerExperimentTargeting | null;
}
/**
@@ -52844,25 +52865,6 @@ export namespace Schemas {
Google: 'google',
} as const;
- /**
- * The experiment a scanner's targeting watches. Metadata only; scanning never reads it.
- */
- export interface ScannerExperimentTargeting {
- /**
- * The experiment the scanner watches.
- * @minimum 1
- */
- experiment_id: number;
- /**
- * Targeted experiment variants. Empty means every variant.
- * @maxItems 50
- * @items.maxLength 400
- */
- variant_keys: string[];
- /** True when the exposure event is captured server-side and the query filters on the `$feature/<flag_key>` property instead. */
- use_exposure_fallback: boolean;
- }
-
/**
* A Replay Vision scanner: its type, targeting query, and AI configuration.
*/
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 68b6864e7535..93d434685fe6 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -683,9 +683,7 @@ export const visionScannersCreateBodySamplingRateMax = 1
export const visionScannersCreateBodyCreditLimitMax = 2147483647
-export const visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax = 400
-
-export const visionScannersCreateBodyExperimentTargetingOneVariantKeysMax = 50
+export const visionScannersCreateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersCreateBody = /* @__PURE__ */ zod
.object({
@@ -777,17 +775,17 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod
zod
.object({
experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
- variant_keys: zod
- .array(zod.string().max(visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax))
- .max(visionScannersCreateBodyExperimentTargetingOneVariantKeysMax)
- .describe('Targeted experiment variants. Empty means every variant.'),
- use_exposure_fallback: zod
- .boolean()
+ variant: zod
+ .string()
+ .max(visionScannersCreateBodyExperimentTargetingOneVariantMax)
+ .nullish()
.describe(
- 'True when the exposure event is captured server-side and the query filters on the `$feature\/<flag_key>` property instead.'
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
),
})
- .describe("The experiment a scanner's targeting watches. Metadata only; scanning never reads it."),
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
zod.null(),
zod.null(),
])
@@ -835,9 +833,7 @@ export const visionScannersPartialUpdateBodySamplingRateMax = 1
export const visionScannersPartialUpdateBodyCreditLimitMax = 2147483647
-export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax = 400
-
-export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax = 50
+export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
.object({
@@ -933,21 +929,17 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod
zod
.object({
experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
- variant_keys: zod
- .array(
- zod
- .string()
- .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax)
- )
- .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax)
- .describe('Targeted experiment variants. Empty means every variant.'),
- use_exposure_fallback: zod
- .boolean()
+ variant: zod
+ .string()
+ .max(visionScannersPartialUpdateBodyExperimentTargetingOneVariantMax)
+ .nullish()
.describe(
- 'True when the exposure event is captured server-side and the query filters on the `$feature\/<flag_key>` property instead.'
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
),
})
- .describe("The experiment a scanner's targeting watches. Metadata only; scanning never reads it."),
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
zod.null(),
zod.null(),
])
@@ -1388,6 +1380,7 @@ export const visionScannersEstimateCreateBodySamplingRateMax = 1
export const visionScannersEstimateCreateBodySamplingModeDefault = `comprehensive`
export const visionScannersEstimateCreateBodyModelDefault = `gemini-3-flash-preview`
+export const visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax = 400
export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.object({
@@ -1425,6 +1418,29 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
.describe(
'Proposed model; determines `credits_per_observation` in the response.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.7-flash` - Gemini 3.7 Flash'
),
+ experiment_targeting: zod
+ .union([
+ zod
+ .object({
+ experiment_id: zod.number().min(1).describe('The experiment the scanner watches.'),
+ variant: zod
+ .string()
+ .max(visionScannersEstimateCreateBodyExperimentTargetingOneVariantMax)
+ .nullish()
+ .describe(
+ 'Narrow to sessions of people exposed to this variant. Null means every variant.'
+ ),
+ })
+ .describe(
+ "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it."
+ ),
+ zod.null(),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ 'Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user.'
+ ),
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 030b0d6798a4..335e8479abae 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -512,6 +512,9 @@ const visionScannersEstimateCreate = (): ToolBase<
if (params.model !== undefined) {
body['model'] = params.model
}
+ if (params.experiment_targeting !== undefined) {
+ body['experiment_targeting'] = params.experiment_targeting
+ }
const result = await context.api.request<Schemas.EstimateResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/estimate/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
index 7e264ddce3d1..e90b938159bf 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json
@@ -31,28 +31,27 @@
"experiment_targeting": {
"anyOf": [
{
- "description": "The experiment a scanner's targeting watches. Metadata only; scanning never reads it.",
+ "description": "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it.",
"properties": {
"experiment_id": {
"description": "The experiment the scanner watches.",
"minimum": 1,
"type": "number"
},
- "use_exposure_fallback": {
- "description": "True when the exposure event is captured server-side and the query filters on the `$feature/<flag_key>` property instead.",
- "type": "boolean"
- },
- "variant_keys": {
- "description": "Targeted experiment variants. Empty means every variant.",
- "items": {
- "maxLength": 400,
- "type": "string"
- },
- "maxItems": 50,
- "type": "array"
+ "variant": {
+ "anyOf": [
+ {
+ "maxLength": 400,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Narrow to sessions of people exposed to this variant. Null means every variant."
}
},
- "required": ["experiment_id", "variant_keys", "use_exposure_fallback"],
+ "required": ["experiment_id"],
"type": "object"
},
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json
index c6cb25bdb587..5f5a6f4436b2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json
@@ -2,6 +2,41 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.",
"properties": {
+ "experiment_targeting": {
+ "anyOf": [
+ {
+ "description": "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it.",
+ "properties": {
+ "experiment_id": {
+ "description": "The experiment the scanner watches.",
+ "minimum": 1,
+ "type": "number"
+ },
+ "variant": {
+ "anyOf": [
+ {
+ "maxLength": 400,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Narrow to sessions of people exposed to this variant. Null means every variant."
+ }
+ },
+ "required": ["experiment_id"],
+ "type": "object"
+ },
+ {
+ "type": "null"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user."
+ },
"model": {
"default": "gemini-3-flash-preview",
"description": "Proposed model; determines `credits_per_observation` in the response.\n\n* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n* `gemini-3-flash-preview` - Gemini 3 Flash\n* `gemini-3.7-flash` - Gemini 3.7 Flash",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
index 1e2dc9d4e560..c37cda9239e6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json
@@ -30,28 +30,27 @@
"experiment_targeting": {
"anyOf": [
{
- "description": "The experiment a scanner's targeting watches. Metadata only; scanning never reads it.",
+ "description": "The experiment a scanner watches. Scans derive their person-scoped exposure filter from\nthis blob at query time, so it is the only place an experiment can enter a scanner's\ntargeting — which is what lets the write-side access check and read-side redaction cover it.",
"properties": {
"experiment_id": {
"description": "The experiment the scanner watches.",
"minimum": 1,
"type": "number"
},
- "use_exposure_fallback": {
- "description": "True when the exposure event is captured server-side and the query filters on the `$feature/<flag_key>` property instead.",
- "type": "boolean"
- },
- "variant_keys": {
- "description": "Targeted experiment variants. Empty means every variant.",
- "items": {
- "maxLength": 400,
- "type": "string"
- },
- "maxItems": 50,
- "type": "array"
+ "variant": {
+ "anyOf": [
+ {
+ "maxLength": 400,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Narrow to sessions of people exposed to this variant. Null means every variant."
}
},
- "required": ["experiment_id", "variant_keys", "use_exposure_fallback"],
+ "required": ["experiment_id"],
"type": "object"
},
{