:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): attribute an experiment scan's variant before the model call (#108862)
Kim Svatos Dugan46f3aa9a812b
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex 525c70c28a01..af9255e92bbd 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -63,6 +63,16 @@ class ExperimentPromptContext:primary_metric_names: tuple[str, ...]+@frozen+class SessionAttribution:+ """One person's attribution in an experiment's exposed population, as the analysis buckets it."""++ variant: str+ # The person's earliest exposure in the experiment window. A session that ended before this+ # predates the exposure, so surfaces comparing variants must not count it.+ first_exposure_time: datetime | None++@frozenclass ExperimentStatus:"""The lifecycle facts a replay surface reads to decide whether an experiment is still worth watching."""diff --git a/products/experiments/backend/facade/replay.py b/products/experiments/backend/facade/replay.pyindex 4c7a60671909..7ae27d58298c 100644--- a/products/experiments/backend/facade/replay.py+++ b/products/experiments/backend/facade/replay.py@@ -4,11 +4,14 @@ from products.experiments.backend.replay_context import (accessible_experiment_ids,experiment_prompt_context,experiment_status,+ session_attribution,session_variant,variant_rollout_shares,)from products.experiments.backend.replay_linkage import (ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES,+ COHORT_NOT_CALCULATED_MESSAGE,+ EXPOSURES_STILL_COMPUTING_MESSAGE,IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES,ExperimentExposureLinkage,InSessionExposureSemantics,@@ -22,6 +25,8 @@ from products.experiments.backend.replay_linkage import (__all__ = ["ACTIVATION_LIVE_SCAN_MAX_MEMORY_BYTES",+ "COHORT_NOT_CALCULATED_MESSAGE",+ "EXPOSURES_STILL_COMPUTING_MESSAGE","IN_SESSION_EVIDENCE_SCAN_MAX_MEMORY_BYTES","ExperimentExposureLinkage","InSessionExposureSemantics",@@ -32,6 +37,7 @@ __all__ = ["exposed_session_ids_select","resolve_exposure_linkage","resolve_in_session_exposure_semantics",+ "session_attribution","session_variant","targetable_experiments","validate_experiment_exposure_access",diff --git a/products/experiments/backend/replay_context.py b/products/experiments/backend/replay_context.pyindex 65e8ac944b6c..0a4b8ef36572 100644--- a/products/experiments/backend/replay_context.py+++ b/products/experiments/backend/replay_context.py@@ -24,6 +24,7 @@ from products.experiments.backend.facade.contracts import (ExperimentPromptContext,ExperimentStatus,ExperimentVariantPromptContext,+ SessionAttribution,)from products.experiments.backend.metric_utils import get_default_metric_titlefrom products.experiments.backend.models.experiment import Experiment@@ -59,13 +60,15 @@ def _live_experiment(team: Team, experiment_id: int) -> Experiment | None:return Experiment.objects.filter(id=experiment_id, team=team, deleted=False).select_related("feature_flag").first()-def session_variant(linkage: ExperimentExposureLinkage, distinct_id: str) -> str | None:- """The variant the experiment's analysis attributes to this distinct id's person, or None.+def session_attribution(linkage: ExperimentExposureLinkage, distinct_id: str) -> SessionAttribution | None:+ """The attribution the experiment's analysis gives this distinct id's person, or None.None means the person is not cleanly exposed within the linkage's requested variants:never exposed, exposed only to a variant outside the requested set, or set aside asmultiple-variant under "exclude" handling. The attribution follows the experiment's``multiple_variant_handling``, because it reads the same population the analysis buckets.+ ``first_exposure_time`` rides along so callers can refuse sessions that predate the exposure,+ the same bound the recordings list enforces.Runs a ClickHouse query, so call it from a run path, never while building an AST."""@@ -87,7 +90,15 @@ def session_variant(linkage: ExperimentExposureLinkage, distinct_id: str) -> strreturn Nonecolumns = response.columns or []variant = rows[0][columns.index("variant")]- return str(variant) if variant is not None else None+ if variant is None:+ return None+ return SessionAttribution(variant=str(variant), first_exposure_time=rows[0][columns.index("first_exposure_time")])+++def session_variant(linkage: ExperimentExposureLinkage, distinct_id: str) -> str | None:+ """The variant half of :func:`session_attribution`, for callers that need no exposure time."""+ attribution = session_attribution(linkage, distinct_id)+ return attribution.variant if attribution is not None else Nonedef variant_rollout_shares(team: Team, *, experiment_id: int) -> dict[str, float]:diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.pyindex 3399ce3ad492..17e85823665e 100644--- a/products/replay_vision/backend/api/backfills.py+++ b/products/replay_vision/backend/api/backfills.py@@ -25,7 +25,7 @@ from posthog.rate_limit import PersonalApiKeyOrUserRateThrottlefrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_observation import IN_FLIGHT_STATUSES, ObservationStatus-from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner+from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner, ScannerTypefrom products.replay_vision.backend.models.replay_scanner_backfill import (ACTIVE_BACKFILL_STATUSES,BackfillStatus,@@ -37,6 +37,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (WindowedCandidateQuery,)from products.replay_vision.backend.quota import quota_state+from products.replay_vision.backend.scanner_access import can_read_targeted_experimentfrom products.replay_vision.backend.scout_writes import refuse_scout_scanner_scanfrom products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot@@ -50,6 +51,26 @@ ENUMERATION_MAX_EXECUTION_SECONDS = 30MAX_BACKFILL_WINDOW_DAYS = 365+def _experiment_end_date(scanner: ReplayScanner) -> datetime | None:+ """When an experiment scanner's experiment ended, or None while it runs or for other types.++ Ending an experiment leaves its flag on, so exposed users keep producing sessions that would+ still match. A backfill covers the experiment's own run, and stopping at the end is what keeps+ it from paying for that afterlife.+ """+ if scanner.scanner_type != ScannerType.EXPERIMENT:+ return None+ experiment_id = (scanner.experiment_scope() or {}).get("experiment_id")+ if experiment_id is None:+ return None+ # Deferred: the experiments replay facade pulls in the recordings query modules, which circle+ # back into this package's importers.+ from products.experiments.backend.facade.replay import experiment_status # noqa: PLC0415++ status = experiment_status(scanner.team, experiment_id=experiment_id)+ return status.end_date if status is not None else None++class BackfillEnumerationThrottle(PersonalApiKeyOrUserRateThrottle):"""Covers session-authenticated callers, which the global burst/sustained throttles skip.@@ -63,7 +84,12 @@ class BackfillEnumerationThrottle(PersonalApiKeyOrUserRateThrottle):class BackfillWindowSerializer(serializers.Serializer):window_start = serializers.DateTimeField(help_text="Inclusive lower bound of the historical window to scan.")- window_end = serializers.DateTimeField(help_text="Exclusive upper bound of the window; clamped server-side to now.")+ window_end = serializers.DateTimeField(+ help_text=(+ "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to "+ "the experiment's end date."+ ),+ )def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:if attrs["window_start"] >= attrs["window_end"]:@@ -99,7 +125,11 @@ class BackfillEstimateResponseSerializer(serializers.Serializer):allow_null=True, help_text="Credits left in the org's monthly quota; null when the org is uncapped.")window_start = serializers.DateTimeField(help_text="The window lower bound the estimate covered.")- window_end = serializers.DateTimeField(help_text="The window upper bound after clamping to now.")+ window_end = serializers.DateTimeField(+ help_text=(+ "The window upper bound after clamping to now and, for an experiment scanner, to the experiment's end date."+ ),+ )class ReplayScannerBackfillSerializer(serializers.ModelSerializer):@@ -189,6 +219,11 @@ class ReplayScannerBackfillViewSet(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("Replay Vision backfills require session_recording read access.")+ # Before any window handling: the window clamp reads the experiment's end date, so a denied+ # caller who reached it could binary-search that date from which error comes back.+ # Not-found, not 403, matching the observations endpoint.+ if not can_read_targeted_experiment(self.user_access_control, self.team_id, scanner):+ raise NotFound()self._scanner_for_url_cache = scannerreturn scanner@@ -206,7 +241,8 @@ class ReplayScannerBackfillViewSet()def _clamped_window(self, data: dict[str, Any]) -> tuple[datetime, datetime]:- """The requested window, bounded above by the settle horizon the live sweep also waits for.+ """The requested window, bounded above by the settle horizon the live sweep also waits for,+ and for an experiment scanner by the experiment's end (see `_experiment_end_date`).Not `now`: a session inside the settle window is still recording or still merging, so scanning ityields a truncated observation, and the unique (scanner, session) constraint makes that the only@@ -221,8 +257,15 @@ class ReplayScannerBackfillViewSet(find, which `_enumerate` answers directly."""window_end = min(data["window_end"], timezone.now() - SETTLE_INTERVAL)+ experiment_end = _experiment_end_date(self._scanner_for_url())+ if experiment_end is not None:+ window_end = min(window_end, experiment_end)window_start = data["window_start"]if window_start >= window_end:+ if experiment_end is not None and window_start >= experiment_end:+ raise ValidationError(+ "This experiment ended before the start of the range. Pick a range from while it ran."+ )raise ValidationError("The end of the range must be in the past. Pick an earlier range.")return window_start, window_enddiff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex dcb616c26960..c99bc50d4a74 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -176,6 +176,19 @@ class ScannerResultSerializer(serializers.Serializer):allow_null=True,help_text="Extra draws taken to verify a monitor `yes` verdict. Null when the scan did not verify one.",)+ experiment_variant = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ "Experiment scanners only: the variant the exposure data attributes this session's person to. "+ "Null on the other types and on rows scanned before variant attribution shipped."+ ),+ )+ session_duration_s = serializers.FloatField(+ required=False,+ allow_null=True,+ help_text="Experiment scanners only: the scanned session's duration in seconds.",+ )class ReplayObservationLabelSerializer(serializers.Serializer):diff --git a/products/replay_vision/backend/error_kinds.py b/products/replay_vision/backend/error_kinds.pyindex d341e7501005..b3d7b7f10336 100644--- a/products/replay_vision/backend/error_kinds.py+++ b/products/replay_vision/backend/error_kinds.py@@ -18,6 +18,15 @@ class IneligibleSessionKind(StrEnum):# The recording's snapshot blocks exceed the rasterizer's size cap, so the render is refused before it starts.# This is a fixed property of the recording, so no retry can make the scan succeed.TOO_LARGE = "too_large"+ # An experiment scanner's session whose person the exposure data does not attribute to a watched+ # variant: never exposed, exposed only outside the selected variants, or set aside as+ # multiple-variant. Also a session outside the experiment's run: ended before the person's first+ # exposure, or after the experiment ended. Decided before any model call, so it costs no credits.+ NOT_EXPOSED = "not_exposed"+ # An experiment scanner whose experiment cannot answer for its exposed population right now+ # (deleted, a removed flag or variant, or no principal with access). The sweep disables the+ # scanner when the experiment is gone for good; this covers the scans already in flight.+ EXPERIMENT_UNRESOLVED = "experiment_unresolved"class FailureKind(StrEnum):diff --git a/products/replay_vision/backend/migrations/0105_alter_replayobservation_error_reason.py b/products/replay_vision/backend/migrations/0105_alter_replayobservation_error_reason.pynew file mode 100644index 000000000000..3730d7c24d1d--- /dev/null+++ b/products/replay_vision/backend/migrations/0105_alter_replayobservation_error_reason.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-30 01:33++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0104_alter_replayscanner_scanner_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="replayobservation",+ name="error_reason",+ field=models.TextField(+ blank=True,+ default="",+ help_text="Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large / not_exposed / experiment_unresolved. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex f076d8108044..c355b91537e3 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0104_alter_replayscanner_scanner_type+0105_alter_replayobservation_error_reasondiff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex ad1c5a41eefd..018d939fa86f 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -193,6 +193,8 @@ class ScannerCandidateQuery:skip_negative_blocklists: bool = False,# Tags the ClickHouse query for per-scanner read metering; sweep callers should always pass it.scanner_id: str | None = None,+ # Caps the settle horizon, so a sweep stops at a known end (an ended experiment's end date).+ until: dt.datetime | None = None,) -> None:if not isinstance(last_swept_at, dt.datetime):raise TypeError(f"last_swept_at must be a datetime, got {type(last_swept_at).__name__}")@@ -213,6 +215,8 @@ class ScannerCandidateQuery:self._scanner_id = scanner_id# Fixed at construction and exposed so callers can persist exactly the horizon the query filtered on.self.settle_cutoff = dt.datetime.now(dt.UTC) - SETTLE_INTERVAL+ if until is not None:+ self.settle_cutoff = min(self.settle_cutoff, until)# The schedule owns the time window, not the user.inner_query = query.model_copy(deep=True)diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 5f810df61067..c1325774ea92 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -44,6 +44,7 @@ from products.replay_vision.backend.temporal.activities import (record_evaluation_result_activity,refresh_prompt_suggestion_activity,refresh_scanner_estimate_activity,+ resolve_experiment_variant_activity,select_evaluation_sessions_activity,upload_video_to_gemini_activity,upsert_scanner_schedule_activity,@@ -126,6 +127,7 @@ ACTIVITIES: list[Callable[..., Any]] = [prepare_observation_media_activity,finalize_observation_thumbnail_activity,finalize_observation_media_activity,+ resolve_experiment_variant_activity,find_scanner_candidates_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex ec909859fb6a..9006cfc2474f 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -68,6 +68,9 @@ from products.replay_vision.backend.temporal.activities.refresh_prompt_suggestiofrom products.replay_vision.backend.temporal.activities.refresh_scanner_estimate import (refresh_scanner_estimate_activity,)+from products.replay_vision.backend.temporal.activities.resolve_experiment_variant import (+ resolve_experiment_variant_activity,+)from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity__all__ = [@@ -112,6 +115,7 @@ __all__ = ["reap_orphaned_observations_activity","record_evaluation_result_activity","refresh_prompt_suggestion_activity",+ "resolve_experiment_variant_activity","refresh_scanner_estimate_activity","select_evaluation_sessions_activity","upload_video_to_gemini_activity",diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex acb5636f4969..5c9990743706 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -11,6 +11,7 @@ import mathimport timeimport asyncioimport functools+import dataclassesfrom collections import Counterfrom collections.abc import Callable, Iterablefrom dataclasses import dataclass, replace@@ -88,6 +89,7 @@ from products.replay_vision.backend.temporal.scanners.base import (TextSegment,)from products.replay_vision.backend.temporal.scanners.classifier import ClassifierScanner+from products.replay_vision.backend.temporal.scanners.experiment import ExperimentScannerfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorLlmResponse, MonitorScannerfrom products.replay_vision.backend.temporal.state import load_scanner_llm_inputs, load_session_networkfrom products.replay_vision.backend.temporal.types import (@@ -197,6 +199,7 @@ async def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCa)scanner: BaseScanner = scanner_from_snapshot(snapshot)scanner = await _inject_known_freeform_tags(scanner, inputs)+ scanner = await _apply_experiment_scan_context(scanner, inputs)video_clock = await sync_to_async(_load_video_clock)(inputs.team_id, inputs.exported_asset_id, llm_inputs.metadata.duration_seconds)@@ -433,6 +436,50 @@ def _is_taglike(slug: str) -> bool:)+async def _apply_experiment_scan_context(scanner: BaseScanner, inputs: CallScannerProviderInputs) -> BaseScanner:+ """Give an experiment scanner the variant and experiment description the workflow resolved.++ Scan-time context, never persisted (see `ExperimentScanner`). A no-op for the other types.+ When the inputs carry neither field — a prompt evaluation re-scanning a rated session, or a+ history from before attribution shipped — the source observation's persisted attribution+ stands in, so an evaluation tests the prompt with its experiment block rather than without.+ Best effort there: a lookup failure must not fail the scan, and a pre-attribution row simply+ has nothing persisted to inject."""+ if not isinstance(scanner, ExperimentScanner):+ return scanner+ variant, context = inputs.experiment_variant, inputs.experiment_context+ if variant is None and context is None:+ try:+ variant, context = await sync_to_async(_load_persisted_experiment_context)(+ inputs.observation_id, inputs.team_id, scanner.experiment_id+ )+ except Exception:+ logger.warning("replay_vision.call_scanner_provider.experiment_context_fallback_failed", exc_info=True)+ return scanner+ if variant is None and context is None:+ return scanner+ return scanner.model_copy(update={"experiment_context": context, "session_variant": variant})+++def _load_persisted_experiment_context(+ observation_id: UUID, team_id: int, experiment_id: int+) -> tuple[str | None, dict[str, Any] | None]:+ # Deferred: the experiments replay facade pulls in the recordings query modules, which circle+ # back into this package's importers.+ from products.experiments.backend.facade.replay import experiment_prompt_context # noqa: PLC0415++ result = (+ ReplayObservation.objects.filter(pk=observation_id, team_id=team_id)+ .values_list("scanner_result", flat=True)+ .first()+ )+ variant = result.get("experiment_variant") if isinstance(result, dict) else None+ if not isinstance(variant, str):+ return None, None+ context = experiment_prompt_context(Team.objects.get(pk=team_id), experiment_id=experiment_id)+ return variant, dataclasses.asdict(context) if context is not None else None++def apply_known_freeform_tags(scanner: BaseScanner, tags: list[str]) -> BaseScanner:"""No-op unless `scanner` is a freeform-emitting classifier and there are tags to inject."""if not tags or not isinstance(scanner, ClassifierScanner) or not scanner.allow_freeform_tags:diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.pyindex 950dfec5d15c..026a169fe6cf 100644--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py@@ -70,6 +70,7 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:"emits_signals": snapshot.emits_signals,# Flatten scanner output so HogQL can query individual fields without a JSON extract.**inputs.model_output.to_event_properties(),+ **_experiment_properties(observation, snapshot),**_group_properties(team, observation),}distinct_id = (@@ -93,6 +94,21 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:result.raise_for_status()+def _experiment_properties(observation: ReplayObservation, snapshot: ScannerSnapshot) -> dict:+ """The watched experiment and this session's attributed variant, so HogQL readouts over+ `$recording_observed` need no exposure join. Empty for scans that watch no experiment; the+ variant is absent on rows scanned before attribution shipped."""+ scope = snapshot.experiment_scope()+ if not scope or scope.get("experiment_id") is None:+ return {}+ properties: dict = {"experiment_id": scope["experiment_id"]}+ result = observation.scanner_result if isinstance(observation.scanner_result, dict) else {}+ variant = result.get("experiment_variant")+ if variant is not None:+ properties["experiment_variant"] = variant+ return properties++def _group_properties(team: Team, observation: ReplayObservation) -> dict:"""Group attribution for the recorded session: `$group_N` for group analytics, `$groups` for readers.diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.pyindex 3f738d384a7a..7fc958e5e3e8 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -18,7 +18,12 @@ from posthog.temporal.session_replay.rasterize_recording.activities.stuck_countefrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.replay_vision.backend.models.replay_observation import ReplayObservation-from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner+from products.replay_vision.backend.models.replay_scanner import (+ SETTLE_INTERVAL,+ ReplayScanner,+ ScannerType,+ initial_watermark,+)from products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEEP_SWEEP_CANDIDATE_QUERY_TYPE,@@ -28,6 +33,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (CandidateSession,ScannerCandidateQuery,WindowedCandidateQuery,+ build_candidate_batch,)from products.replay_vision.backend.temporal.constants import (DEEP_SWEEP_INTERVAL,@@ -67,6 +73,51 @@ class _DeepProgress:seen_session_id: str = ""+@frozen+class _LifecycleBlock:+ kind: str+ # Set for an ended experiment: the sweep still covers its run up to here before it stops.+ end_date: dt.datetime | None = None+++def _experiment_lifecycle_block(scanner: ReplayScanner) -> _LifecycleBlock | None:+ """Why this scanner's experiment can't be watched now: 'deleted', 'ended', 'archived', or 'paused'.++ None when the scanner watches no experiment or the experiment is running. A pause turns the+ flag off, so an exposed user's sessions from then on show no variant, and attributing them to+ one would mislabel the readout. An archived experiment with no end date has no known end to+ sweep up to, so it stops like a pause. Only the experiment type is judged: a legacy scanner+ targeting an experiment through the column predates this gate, and changing those on deploy+ is not its call.+ """+ if scanner.scanner_type != ScannerType.EXPERIMENT:+ return None+ scope = scanner.experiment_scope()+ experiment_id = (scope or {}).get("experiment_id")+ if experiment_id is None:+ return None+ # Deferred: the experiments replay facade pulls in the recordings query modules, which circle+ # back into this package's importers.+ from products.experiments.backend.facade.replay import experiment_status # noqa: PLC0415++ status = experiment_status(scanner.team, experiment_id=experiment_id)+ if status is None:+ return _LifecycleBlock(kind="deleted")+ if status.end_date is not None:+ return _LifecycleBlock(kind="ended", end_date=status.end_date)+ if status.archived:+ return _LifecycleBlock(kind="archived")+ if status.status == "paused":+ return _LifecycleBlock(kind="paused")+ return None+++def _swept_past(scanner: ReplayScanner, end: dt.datetime) -> bool:+ """Whether both passes have covered everything up to `end`."""+ deep_done = scanner.deep_swept_through is None or scanner.deep_swept_through >= end+ return scanner.last_swept_at >= end and deep_done++def _seconds_left(started_at: float) -> float:"""What the activity has left of its own timeout, which both ClickHouse budgets are carved from."""return FIND_SCANNER_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at)@@ -90,6 +141,40 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin).check_access_level_for_resource("session_recording", required_level="viewer"):return FindScannerCandidatesOutput(candidates=[], saturated=False)+ lifecycle_block = _experiment_lifecycle_block(scanner)+ sweep_until: dt.datetime | None = None+ if lifecycle_block is not None and lifecycle_block.kind == "deleted":+ # A deleted experiment can't resolve a population again, so disable: the reconciler drops+ # the schedule and the owner sees the scanner off instead of silently idle.+ # nosemgrep: semgrep.rules.security.replay-vision-alert-state-direct-mutation — disables a ReplayScanner, not an alert; scanners have no state machine.+ scanner.enabled = False+ scanner.save(update_fields=["enabled"])+ record_sweep_outcome("experiment_deleted")+ activity.logger.info("replay_vision.sweep.disabled_experiment_scanner scanner_id=%s", inputs.scanner_id)+ return FindScannerCandidatesOutput(candidates=[], saturated=False)+ if lifecycle_block is not None:+ end = lifecycle_block.end_date+ if end is None or _swept_past(scanner, end):+ # A pause resumes, and an ended or archived experiment comes back through reset and+ # relaunch, but a disabled scanner has no schedule left to notice either. So skip the+ # tick instead, before any ClickHouse read. Both watermarks move to now, as a re-enable+ # does, so the sweep picks up from the resume or relaunch and never bills the gap.+ record_sweep_outcome("experiment_over")+ horizon = initial_watermark()+ return FindScannerCandidatesOutput(+ candidates=[], saturated=False, swept_through=horizon, deep_swept_through=horizon+ )+ # Ended, but its last sessions and the deep pass's late arrivals are not swept yet. Keep+ # sweeping with the horizon capped at the end, so the readout gets the whole run.+ sweep_until = end++ if scanner.scanner_type == ScannerType.EXPERIMENT and scanner.created_by is None:+ # The exposure filter runs as the creator and refuses a userless caller, as each scan's+ # variant lookup does. Skip before any read instead of building a query that can only be+ # refused. The watermark holds, like any other skipped tick.+ record_sweep_outcome("no_principal")+ return FindScannerCandidatesOutput(candidates=[], saturated=False)+try:query = scanner.targeted_recordings_query()except ValidationError as exc:@@ -119,9 +204,12 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin# Exclusion is applied below against the fetched batch instead.skip_negative_blocklists=True,scanner_id=str(scanner.id),+ until=sweep_until,)+ # The fast walk has reached the end; only the deep pass is still behind it.+ fast_done = sweep_until is not None and scanner.last_swept_at >= sweep_untiltry:- batch = candidate_query.run_batch(limit)+ batch = build_candidate_batch([], [], limit, limit) if fast_done else 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@@ -207,7 +295,8 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Finreturn FindScannerCandidatesOutput(candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],saturated=batch.saturated,- swept_through=candidate_query.settle_cutoff,+ # Held at the fast watermark once the walk reached the end, so the advance never moves it back.+ swept_through=scanner.last_swept_at if fast_done else candidate_query.settle_cutoff,keyset_end=batch.keyset_end,keyset_session_id=batch.keyset_session_id,deep_candidates=[diff --git a/products/replay_vision/backend/temporal/activities/resolve_experiment_variant.py b/products/replay_vision/backend/temporal/activities/resolve_experiment_variant.pynew file mode 100644index 000000000000..f82735f6e941--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/resolve_experiment_variant.py@@ -0,0 +1,162 @@+"""Resolve which variant an experiment scanner's session belongs to, before any model call.++The variant comes from the exposure data through the experiments facade, never from the model,+so the value the prompt names and the value the observation stores cannot disagree. A session+the exposure data does not attribute to a watched variant is ineligible at no credit cost.+"""++import dataclasses++import structlog+from temporalio import activity++from posthog.clickhouse.client.connection import ClickHouseUser+from posthog.models.team import Team+from posthog.models.user import User+from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.sync import database_sync_to_async++from products.access_control.backend.facade.user_access_control import UserAccessControlError+from products.replay_vision.backend.error_kinds import IneligibleSessionKind+from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.errors import FailureKind, IneligibleSessionError, ScannerFailureError+from products.replay_vision.backend.temporal.snapshots import ScannerSnapshot+from products.replay_vision.backend.temporal.types import ResolveExperimentVariantInputs, ResolveExperimentVariantOutput++logger = structlog.get_logger(__name__)++# The context is stored in the workflow history twice (this activity's result and the provider+# call's input), and an experiment description has no length bound of its own. Enough for the+# prompt to know what the experiment tests; anything longer adds history weight, not signal.+_MAX_DESCRIPTION_CHARS = 2_000+++@track_activity()+async def resolve_experiment_variant_activity(inputs: ResolveExperimentVariantInputs) -> ResolveExperimentVariantOutput:+ return await database_sync_to_async(_resolve, thread_sensitive=False)(inputs)+++def _resolve(inputs: ResolveExperimentVariantInputs) -> ResolveExperimentVariantOutput:+ # Deferred: the experiments replay facade pulls in the recordings query modules, which circle+ # back into this package's importers.+ from rest_framework.exceptions import ValidationError as DRFValidationError # noqa: PLC0415++ from products.experiments.backend.facade.replay import ( # noqa: PLC0415+ COHORT_NOT_CALCULATED_MESSAGE,+ EXPOSURES_STILL_COMPUTING_MESSAGE,+ experiment_prompt_context,+ experiment_status,+ resolve_exposure_linkage,+ session_attribution,+ validate_experiment_exposure_access,+ )++ observation = (+ ReplayObservation.objects.filter(pk=inputs.observation_id, team_id=inputs.team_id)+ .select_related("scanner__created_by", "backfill__created_by")+ .first()+ )+ if observation is None:+ raise ScannerFailureError(+ f"ReplayObservation {inputs.observation_id} not found for team {inputs.team_id}",+ kind=FailureKind.INTERNAL_ERROR,+ )+ snapshot = ScannerSnapshot.load_for(inputs.observation_id, observation.scanner_snapshot)+ scope = snapshot.experiment_scope()+ experiment_id = (scope or {}).get("experiment_id")+ if experiment_id is None:+ return ResolveExperimentVariantOutput(applicable=False)++ team = Team.objects.get(pk=inputs.team_id)+ try:+ # The same object-level check every other exposure read runs, as the principal the+ # candidate enumeration for this scan authorized as (see `_principal`).+ validate_experiment_exposure_access(team, _principal(observation), experiment_id)+ linkage = resolve_exposure_linkage(+ team,+ experiment_id=experiment_id,+ variant=scope.get("variant") if scope else None,+ variants=scope.get("variants") if scope else None,+ )+ except UserAccessControlError as exc:+ raise IneligibleSessionError(+ "The scan's principal no longer has access to this experiment",+ kind=IneligibleSessionKind.EXPERIMENT_UNRESOLVED,+ ) from exc+ except DRFValidationError as exc:+ transient = next(+ (+ message+ for message in (EXPOSURES_STILL_COMPUTING_MESSAGE, COHORT_NOT_CALCULATED_MESSAGE)+ if message in str(exc.detail)+ ),+ None,+ )+ if transient is not None:+ # Transient: the precomputation or cohort calculation finishes on its own, so the retry+ # policy owns this rather than the session being failed for good.+ raise ScannerFailureError(transient, kind=FailureKind.INFRA_TRANSIENT) from exc+ raise IneligibleSessionError(+ f"The experiment's exposed population can't be resolved: {exc.detail}",+ kind=IneligibleSessionKind.EXPERIMENT_UNRESOLVED,+ ) from exc++ metadata = SessionReplayEvents().get_metadata(+ session_id=inputs.session_id, team=team, ch_user=ClickHouseUser.REPLAY_VISION+ )+ if metadata is None:+ # The same gate `fetch_session_events` applies; whichever of the two parallel activities+ # lands first fails the scan with the same reason.+ raise IneligibleSessionError("No replay metadata found", kind=IneligibleSessionKind.NO_RECORDING)+ distinct_id = metadata.get("distinct_id")+ attribution = session_attribution(linkage, distinct_id) if distinct_id else None+ if attribution is None:+ raise IneligibleSessionError(+ "This session's user is not attributed to a watched variant of the experiment",+ kind=IneligibleSessionKind.NOT_EXPOSED,+ )+ # The bound the recordings list enforces in-query: a session that ended before the person's+ # first exposure shows behavior the experiment can't have caused. The sweep never selects one,+ # but a manual observe on an older session reaches here.+ if attribution.first_exposure_time is not None and metadata["end_time"] < attribution.first_exposure_time:+ raise IneligibleSessionError(+ "This session ended before the user's first exposure to the experiment",+ kind=IneligibleSessionKind.NOT_EXPOSED,+ )+ # The other end of the same bound. Ending an experiment leaves its flag on, so a manual observe+ # can reach a later session, and the sweep and backfills already stop at the end date.+ status = experiment_status(team, experiment_id=experiment_id)+ if status is not None and status.end_date is not None and metadata["end_time"] > status.end_date:+ raise IneligibleSessionError(+ "This session ended after the experiment ended",+ kind=IneligibleSessionKind.NOT_EXPOSED,+ )++ context = experiment_prompt_context(team, experiment_id=experiment_id)+ context_dict = dataclasses.asdict(context) if context is not None else None+ if context_dict and context_dict.get("description"):+ context_dict["description"] = context_dict["description"][:_MAX_DESCRIPTION_CHARS]+ return ResolveExperimentVariantOutput(+ applicable=True,+ experiment_variant=attribution.variant,+ session_duration_s=float(metadata["duration"]),+ experiment_context=context_dict,+ )+++def _principal(observation: ReplayObservation) -> User | None:+ """Whoever triggered the scan, else the backfill's launcher, else the scanner's creator.++ Each is the principal that scan's candidates were enumerated as, so the variant lookup never+ authorizes as someone the enumeration did not check. A backfill whose launcher is gone does not+ fall back to the scanner's creator. None means nobody can be authorized, and the check refuses.+ """+ if observation.triggered_by_user_id is not None:+ triggering_user = User.objects.filter(pk=observation.triggered_by_user_id).first()+ if triggering_user is not None:+ return triggering_user+ if observation.backfill_id is not None:+ return observation.backfill.created_by if observation.backfill is not None else None+ return observation.scanner.created_by if observation.scanner is not None else Nonediff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex f6723d081520..48a2d70d1324 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -123,7 +123,10 @@ REPLAY_VISION_SWEEP_OUTCOMES = Counter("replay_vision_sweep_outcomes_total","Sweep tick outcomes: throttled at an in-flight cap, capped by the scanner's own credit limit ""(settled spend, which skips the window for good, or in-flight reservations, which preserve the "- "watermark), no candidates, or candidates found",+ "watermark), skipped because its experiment is paused, ended, or archived (experiment_over), disabled "+ "because its experiment was deleted (experiment_deleted), skipped because an experiment scanner has "+ "no creator to authorize as (no_principal), no candidates, or "+ "candidates found",["outcome"],)diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex af812bf4aa71..571b8501bf16 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -60,6 +60,13 @@ class ScannerResult(BaseModel, frozen=True):# this shipped; `signal_problem_types` stays because those older rows carry only it.signal_summaries: list[EmittedSignal] = Field(default_factory=list)verification: VerificationRecord | None = None+ # Experiment scanners only. The variant comes from the exposure data, never from the model, so+ # readouts that group by it cannot disagree with the prompt's framing. Null on rows scanned+ # before attribution shipped, which readouts count as unattributed.+ experiment_variant: str | None = None+ # From the session metadata the scan already fetched, so the variants readout needs no+ # ClickHouse query per page load.+ session_duration_s: float | None = Noneclass ApplyScannerInputs(BaseModel, frozen=True):@@ -280,6 +287,11 @@ class CallScannerProviderInputs(BaseModel, frozen=True):mime_type: str# When set, replaces the observation row's snapshot (evaluations re-run rated sessions with the suggested prompt).snapshot_override: ScannerSnapshot | None = None+ # Experiment scanners only: scan-time context the workflow resolved before this call, injected+ # into the scanner's prompt (see `ExperimentScanner`). Both stay None for the other types and+ # for histories that predate variant attribution.+ experiment_variant: str | None = None+ experiment_context: dict[str, Any] | None = Noneclass ScannerCallOutput(BaseModel, frozen=True):@@ -333,6 +345,27 @@ class MarkObservationSucceededInputs(BaseModel, frozen=True):scanner_type: ScannerType+class ResolveExperimentVariantInputs(BaseModel, frozen=True):+ observation_id: UUID+ team_id: int+ session_id: str+++class ResolveExperimentVariantOutput(BaseModel, frozen=True):+ """What the exposure data says about this session, for an experiment scanner's scan.++ `applicable=False` means the observation's snapshot watches no experiment, so the scan runs+ like a plain summarizer. An unexposed session never reaches this output: the activity raises+ `IneligibleSessionError` instead, before any model call.+ """++ applicable: bool = False+ experiment_variant: str | None = None+ session_duration_s: float | None = None+ # `ExperimentPromptContext` as a plain dict, the shape `experiment_step.jinja` renders.+ experiment_context: dict[str, Any] | None = None++class EmitObservationEventInputs(BaseModel, frozen=True):"""Payload for the `$recording_observed` capture."""diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 6fef406e09cd..cd92f7ef52c1 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -46,6 +46,7 @@ from products.replay_vision.backend.temporal.activities import (mark_observation_ineligible_activity,mark_observation_running_activity,mark_observation_succeeded_activity,+ resolve_experiment_variant_activity,upload_video_to_gemini_activity,)from products.replay_vision.backend.temporal.constants import (@@ -91,6 +92,8 @@ from products.replay_vision.backend.temporal.types import (MarkObservationRunningInputs,MarkObservationSucceededInputs,ObservationProgress,+ ResolveExperimentVariantInputs,+ ResolveExperimentVariantOutput,ScannerCallOutput,ScannerResult,UploadedVideo,@@ -317,7 +320,9 @@ class ApplyScannerWorkflow(PostHogWorkflow):retry_policy=STATE_ACTIVITY_RETRY,)self._advance_phase("fetching")- asset_result = await self._fetch_and_ensure_asset(inputs, observation_id)+ asset_result, experiment_resolution = await self._fetch_and_ensure_asset(+ inputs, observation_id, scanner_type+ )self._advance_phase("rendering", rasterizer_workflow_id=_rasterizer_workflow_id(inputs))await self._run_rasterize_child(inputs, asset_result.asset_id)self._advance_phase("uploading")@@ -339,6 +344,12 @@ class ApplyScannerWorkflow(PostHogWorkflow):exported_asset_id=asset_result.asset_id,file_uri=uploaded.file_uri,mime_type=uploaded.mime_type,+ experiment_variant=(+ experiment_resolution.experiment_variant if experiment_resolution is not None else None+ ),+ experiment_context=(+ experiment_resolution.experiment_context if experiment_resolution is not None else None+ ),),# Multi-turn tool conversation (video + on-demand event lookups) needs more headroom than a single# call, and must cover both mission passes plus the one verify-positives draw: a pass that@@ -411,6 +422,12 @@ class ApplyScannerWorkflow(PostHogWorkflow):signal_problem_types=signal_problem_types,signal_summaries=signal_summaries,verification=call_output.verification,+ experiment_variant=(+ experiment_resolution.experiment_variant if experiment_resolution is not None else None+ ),+ session_duration_s=(+ experiment_resolution.session_duration_s if experiment_resolution is not None else None+ ),),),start_to_close_timeout=dt.timedelta(seconds=30),@@ -455,8 +472,29 @@ class ApplyScannerWorkflow(PostHogWorkflow):passasync def _fetch_and_ensure_asset(- self, inputs: ApplyScannerInputs, observation_id: UUID- ) -> EnsureSessionAssetOutput:+ self, inputs: ApplyScannerInputs, observation_id: UUID, scanner_type: ScannerType+ ) -> tuple[EnsureSessionAssetOutput, ResolveExperimentVariantOutput | None]:+ # Gating on scanner_type is deterministic: it comes from the create activity's recorded+ # output. `patched` keeps histories from before attribution shipped replaying without the+ # extra command.+ resolve_task = None+ if scanner_type == ScannerType.EXPERIMENT and wf.patched("replay-vision-experiment-variant-2026-09"):+ # Rides alongside the fetch, so attribution costs no wall-clock. An unexposed session+ # raises IneligibleSessionError here, before any model call and at no credit cost.+ resolve_task = wf.execute_activity(+ resolve_experiment_variant_activity,+ ResolveExperimentVariantInputs(+ observation_id=observation_id,+ team_id=inputs.team_id,+ session_id=inputs.session_id,+ ),+ # The linkage resolution can run a lazy exposure precomputation on its first touch+ # of a large experiment, so it gets the fetch's budget rather than a state+ # activity's 30 seconds.+ start_to_close_timeout=dt.timedelta(minutes=2),+ schedule_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=_FETCH_RETRY,+ )fetch_task = wf.execute_activity(fetch_session_events_activity,FetchSessionEventsInputs(@@ -489,10 +527,19 @@ class ApplyScannerWorkflow(PostHogWorkflow):schedule_to_close_timeout=dt.timedelta(minutes=5),retry_policy=_FETCH_RETRY,)- _, asset_result, _ = await asyncio.gather(fetch_task, asset_task, _optional(network_task))+ if resolve_task is not None:+ _, asset_result, _, experiment_resolution = await asyncio.gather(+ fetch_task, asset_task, _optional(network_task), resolve_task+ )+ else:+ _, asset_result, _ = await asyncio.gather(fetch_task, asset_task, _optional(network_task))+ experiment_resolution = None+ elif resolve_task is not None:+ _, asset_result, experiment_resolution = await asyncio.gather(fetch_task, asset_task, resolve_task)else:_, asset_result = await asyncio.gather(fetch_task, asset_task)- return asset_result+ experiment_resolution = None+ return asset_result, experiment_resolutionasync def _run_rasterize_child(self, inputs: ApplyScannerInputs, asset_id: int) -> None:try:diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.pyindex a3cd999d7fb3..5cdb15897766 100644--- a/products/replay_vision/backend/tests/test_access_control.py+++ b/products/replay_vision/backend/tests/test_access_control.py@@ -1,3 +1,5 @@+import datetime as dt+from unittest.mock import MagicMock, patchfrom django.db import connection@@ -495,6 +497,33 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):plain_resp = self.client.get(f"{self.scanners_url}{plain.id}/prompt_suggestions/current/")self.assertEqual(plain_resp.status_code, 200, plain_resp.json())+ def test_backfills_of_a_denied_experiment_scanner_read_as_not_found(self) -> None:+ # The backfill window clamp reads the experiment's end date, so a denied caller who got past the+ # scanner lookup could binary-search that date from the error a window start before or after it+ # returns. Both sides of the end must answer the same not-found.+ experiment = create_experiment(self.team, "hidden-flag", launched=True)+ ended_at = timezone.now() - dt.timedelta(days=3)+ experiment.end_date = ended_at+ experiment.save()+ 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_experiment_scoped_scanner("targeted", experiment.id, "config")+ plain = self._create_scanner(name="plain")++ self.client.force_login(self.other_user)+ targeted_url = f"{self.scanners_url}{targeted.id}/backfills/"+ self.assertEqual(self.client.get(targeted_url).status_code, 404)+ for window_start in (ended_at - dt.timedelta(days=1), ended_at + dt.timedelta(days=1)):+ body = {"window_start": window_start.isoformat(), "window_end": timezone.now().isoformat()}+ resp = self.client.post(f"{targeted_url}estimate/", body, format="json")+ self.assertEqual(resp.status_code, 404, resp.json())++ # Same access, non-targeted scanner: the experiment gate must not have widened to a blanket block.+ plain_resp = self.client.get(f"{self.scanners_url}{plain.id}/backfills/")+ self.assertEqual(plain_resp.status_code, 200, plain_resp.json())+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 mustdiff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pyindex f0e660d955fe..42061c1bd695 100644--- a/products/replay_vision/backend/tests/test_backfills.py+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -70,7 +70,7 @@ from products.replay_vision.backend.temporal.constants import (from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshotfrom products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayloadfrom products.replay_vision.backend.temporal.types import CreateObservationInputs-from products.replay_vision.backend.tests.helpers import seed_scanner_spend+from products.replay_vision.backend.tests.helpers import create_experiment, seed_scanner_spend_WINDOW_END = dt.datetime(2026, 5, 1, tzinfo=dt.UTC)_WINDOW_START = _WINDOW_END - dt.timedelta(days=30)@@ -689,6 +689,34 @@ class TestBackfillsApi(APIBaseTest):# The quote has to describe the window actually walked, or it counts sessions the walk skips.assert mock_query.call_args.kwargs["window_end"] == window_end+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")+ def test_an_ended_experiments_window_stops_at_its_end(self, mock_query: MagicMock) -> None:+ # Ending an experiment leaves its flag on, so exposed users keep producing matching sessions.+ # A backfill of the experiment's own run is fine after the end; paying for that afterlife is not.+ mock_query.return_value.count.return_value = 3+ experiment = create_experiment(self.team, "ended-flag", launched=True, variants=["control", "test"])+ ended_at = timezone.now() - dt.timedelta(days=3)+ experiment.end_date = ended_at+ experiment.save()+ self.scanner.scanner_type = ScannerType.EXPERIMENT+ self.scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}+ self.scanner.save()++ response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")++ assert response.status_code == 200, response.json()+ window_end = dt.datetime.fromisoformat(response.json()["window_end"])+ assert window_end == ended_at+ assert mock_query.call_args.kwargs["window_end"] == window_end++ after_the_end = {+ "window_start": (ended_at + dt.timedelta(days=1)).isoformat(),+ "window_end": timezone.now().isoformat(),+ }+ response = self.client.post(f"{self.base_url}/estimate/", after_the_end, format="json")+ assert response.status_code == 400+ assert "ended before the start of the range" in response.json()["detail"]+def test_window_entirely_inside_the_settle_horizon_is_rejected(self) -> None:body = {"window_start": (timezone.now() - dt.timedelta(minutes=5)).isoformat(),diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex b85a7e19d850..4c7d95e7b447 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -942,3 +942,64 @@ async def test_video_cache_creation_is_best_effort() -> None:cast(Any, _BoomClient()), "models/gemini-3-flash-preview", _VIDEO, "PRE", tools=[events_tool()])assert result is None+++async def test_apply_experiment_scan_context_injects_into_experiment_scanners_only() -> None:+ # The injected fields are exclude=True, so this per-scan context is the only way the prompt+ # ever learns the variant; a broken injection silently degrades every experiment scan.+ from uuid import uuid4++ from products.replay_vision.backend.temporal.activities.call_scanner_provider import _apply_experiment_scan_context+ from products.replay_vision.backend.temporal.scanners.experiment import ExperimentScanner+ from products.replay_vision.backend.temporal.types import CallScannerProviderInputs++ inputs = CallScannerProviderInputs(+ team_id=1,+ observation_id=uuid4(),+ exported_asset_id=1,+ file_uri="file://x",+ mime_type="video/mp4",+ experiment_variant="test",+ experiment_context={+ "id": 42,+ "name": "Checkout CTA copy",+ "description": "",+ "feature_flag_key": "checkout-cta",+ "variants": [{"key": "test", "description": "", "rollout_percentage": 50.0}],+ "primary_metric_names": [],+ },+ )++ experiment_scanner = ExperimentScanner(prompt="p", experiment_id=42)+ injected = await _apply_experiment_scan_context(experiment_scanner, inputs)+ assert isinstance(injected, ExperimentScanner)+ assert injected.session_variant == "test"+ assert injected.experiment_context is not None and injected.experiment_context["name"] == "Checkout CTA copy"+ assert "`test` variant" in injected.core_steps()[0].instruction++ monitor = MonitorScanner(prompt="p")+ assert await _apply_experiment_scan_context(monitor, inputs) is monitor+++async def test_evaluation_calls_fall_back_to_the_persisted_attribution() -> None:+ # Evaluations re-scan a rated session and dispatch no resolve activity; without the fallback+ # they would test a suggested prompt without its experiment block.+ from uuid import uuid4++ from products.replay_vision.backend.temporal.activities.call_scanner_provider import _apply_experiment_scan_context+ from products.replay_vision.backend.temporal.scanners.experiment import ExperimentScanner+ from products.replay_vision.backend.temporal.types import CallScannerProviderInputs++ inputs = CallScannerProviderInputs(+ team_id=1, observation_id=uuid4(), exported_asset_id=1, file_uri="file://x", mime_type="video/mp4"+ )+ with patch(+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._load_persisted_experiment_context",+ return_value=("control", None),+ ):+ injected = await _apply_experiment_scan_context(ExperimentScanner(prompt="p", experiment_id=42), inputs)++ assert isinstance(injected, ExperimentScanner)+ assert injected.session_variant == "control"diff --git a/products/replay_vision/backend/tests/test_resolve_experiment_variant.py b/products/replay_vision/backend/tests/test_resolve_experiment_variant.pynew file mode 100644index 000000000000..b7fcd564562b--- /dev/null+++ b/products/replay_vision/backend/tests/test_resolve_experiment_variant.py@@ -0,0 +1,248 @@+from datetime import UTC, datetime, timedelta++import pytest+import time_machine+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from parameterized import parameterized++from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from posthog.test.persons import create_person++from products.replay_vision.backend.error_kinds import IneligibleSessionKind+from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill+from products.replay_vision.backend.temporal.activities.resolve_experiment_variant import _resolve+from products.replay_vision.backend.temporal.errors import FailureKind, IneligibleSessionError, ScannerFailureError+from products.replay_vision.backend.temporal.types import ResolveExperimentVariantInputs+from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for++FROZEN_NOW = "2026-01-10T20:00:00Z"+BASE_TIME = datetime(2026, 1, 9, 10, 0, tzinfo=UTC)+++def _launched_experiment(test: BaseTest, key: str, variants: list[str]):+ # The helper launches "now"; exposures in these tests happen at BASE_TIME, so the experiment+ # must have started before them or every session reads as unexposed.+ experiment = create_experiment(test.team, key, launched=True, variants=variants)+ experiment.start_date = BASE_TIME - timedelta(days=1)+ experiment.save()+ return experiment+++@time_machine.travel(FROZEN_NOW, tick=False)+class TestResolveExperimentVariant(ClickhouseTestMixin, BaseTest):+ def _scanner(self, experiment_id: int | None, *, variants: list[str] | None = None) -> ReplayScanner:+ config: dict = {"prompt": "p"}+ if experiment_id is None:+ scanner_type = ScannerType.MONITOR+ else:+ scanner_type = ScannerType.EXPERIMENT+ config["experiment_id"] = experiment_id+ if variants is not None:+ config["variants"] = variants+ return ReplayScanner.objects.create(+ team=self.team,+ name=f"scanner-{scanner_type}-{experiment_id}-{variants}",+ scanner_type=scanner_type,+ scanner_config=config,+ model=ScannerModel.GEMINI_3_8_FLASH,+ # The access check runs as the scan's principal; a scanner without one is refused.+ created_by=self.user,+ )++ def _inputs(+ self, scanner: ReplayScanner, session_id: str, *, backfill: ReplayScannerBackfill | None = None+ ) -> ResolveExperimentVariantInputs:+ observation = ReplayObservation.objects.create(+ scanner=scanner,+ team=self.team,+ session_id=session_id,+ scanner_snapshot=snapshot_for(scanner),+ backfill=backfill,+ )+ return ResolveExperimentVariantInputs(+ observation_id=observation.id, team_id=self.team.pk, session_id=session_id+ )++ def _session(+ self,+ distinct_id: str,+ variant: str | None,+ *,+ flag_key: str = "checkout-flag",+ exposure_at: datetime = BASE_TIME,+ ) -> str:+ session_id = f"session-{distinct_id}"+ create_person(team=self.team, distinct_ids=[distinct_id])+ produce_replay_summary(+ team_id=self.team.pk,+ session_id=session_id,+ distinct_id=distinct_id,+ first_timestamp=BASE_TIME,+ last_timestamp=BASE_TIME + timedelta(minutes=5),+ )+ if variant is not None:+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp=exposure_at,+ properties={"$feature_flag": flag_key, "$feature_flag_response": variant},+ )+ return session_id++ def test_attributes_the_variant_and_returns_the_prompt_context(self) -> None:+ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ # The description rides in the workflow history twice; only its head does.+ experiment.description = "x" * 3_000+ experiment.save()+ scanner = self._scanner(experiment.pk)+ session_id = self._session("exposed-user", "test")+ flush_persons_and_events()++ output = _resolve(self._inputs(scanner, session_id))++ assert output.applicable is True+ assert output.experiment_variant == "test"+ assert output.session_duration_s == 300.0+ assert output.experiment_context is not None+ assert output.experiment_context["feature_flag_key"] == "checkout-flag"+ assert len(output.experiment_context["description"]) == 2_000++ def test_an_unattributed_session_is_ineligible_with_not_exposed(self) -> None:+ # Both flavors of unattributed: never exposed, and exposed only outside the watched variants.+ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ unexposed_session = self._session("unexposed-user", None)+ control_session = self._session("control-user", "control")+ flush_persons_and_events()++ with pytest.raises(IneligibleSessionError) as never_exposed:+ _resolve(self._inputs(self._scanner(experiment.pk), unexposed_session))+ assert never_exposed.value.kind == IneligibleSessionKind.NOT_EXPOSED++ narrowed = self._scanner(experiment.pk, variants=["test"])+ with pytest.raises(IneligibleSessionError) as outside_variants:+ _resolve(self._inputs(narrowed, control_session))+ assert outside_variants.value.kind == IneligibleSessionKind.NOT_EXPOSED++ @parameterized.expand(+ [+ # Sessions run from BASE_TIME to five minutes later.+ ("before_first_exposure", BASE_TIME + timedelta(hours=2), None),+ # Ending an experiment leaves its flag on, so a manual observe can reach a later session.+ ("after_the_experiment_ended", BASE_TIME, BASE_TIME + timedelta(minutes=2)),+ ]+ )+ def test_a_session_outside_the_experiments_run_is_not_exposed(+ self, name: str, exposure_at: datetime, end_date: datetime | None+ ) -> None:+ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ if end_date is not None:+ experiment.end_date = end_date+ experiment.save()+ scanner = self._scanner(experiment.pk)+ # Distinct per case: ClickHouse rows outlive each test's transaction.+ session_id = self._session(f"outside-run-{name}", "test", exposure_at=exposure_at)+ flush_persons_and_events()++ with pytest.raises(IneligibleSessionError) as excinfo:+ _resolve(self._inputs(scanner, session_id))+ assert excinfo.value.kind == IneligibleSessionKind.NOT_EXPOSED++ @parameterized.expand(+ [+ # (scanner has a creator, backfill launcher: None = not a backfill, False = launcher gone)+ ("scanner_creator_gone", False, None, False),+ # The backfill enumerated its candidates as its launcher, so its scans authorize the same way.+ ("backfill_launcher_authorizes", False, True, True),+ # A gone launcher must not borrow the scanner creator's access the enumeration never checked.+ ("no_fallback_from_a_gone_launcher", True, False, False),+ ]+ )+ def test_a_scan_authorizes_as_the_principal_its_candidates_were_enumerated_as(+ self, name: str, scanner_creator: bool, backfill_launcher: bool | None, resolves: bool+ ) -> None:+ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ scanner = self._scanner(experiment.pk)+ if not scanner_creator:+ scanner.created_by = None+ scanner.save()+ backfill = (+ None+ if backfill_launcher is None+ else ReplayScannerBackfill.objects.for_team(self.team.pk).create(+ scanner=scanner,+ team=self.team,+ window_start=BASE_TIME - timedelta(days=1),+ window_end=BASE_TIME + timedelta(days=1),+ scanner_snapshot=snapshot_for(scanner),+ credits_per_observation=1,+ total_count=1,+ created_by=self.user if backfill_launcher else None,+ )+ )+ # Distinct per case: ClickHouse rows outlive each test's transaction.+ session_id = self._session(f"principal-{name}", "test")+ flush_persons_and_events()++ if resolves:+ assert _resolve(self._inputs(scanner, session_id, backfill=backfill)).experiment_variant == "test"+ else:+ with pytest.raises(IneligibleSessionError) as excinfo:+ _resolve(self._inputs(scanner, session_id, backfill=backfill))+ assert excinfo.value.kind == IneligibleSessionKind.EXPERIMENT_UNRESOLVED++ @parameterized.expand(+ [+ ("exposures_still_computing", "EXPOSURES_STILL_COMPUTING_MESSAGE"),+ ("cohort_calculating", "COHORT_NOT_CALCULATED_MESSAGE"),+ ]+ )+ def test_a_transient_linkage_state_is_retryable_not_terminal(self, name: str, message_name: str) -> None:+ # Both finish on their own, and the unique (scanner, session) row means a session failed for+ # good is never picked up again.+ from rest_framework.exceptions import ValidationError as DRFValidationError++ from products.experiments.backend.facade import replay as experiments_replay++ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ scanner = self._scanner(experiment.pk)+ session_id = self._session(f"transient-{name}", "test")+ flush_persons_and_events()++ with (+ patch(+ "products.experiments.backend.facade.replay.resolve_exposure_linkage",+ side_effect=DRFValidationError(getattr(experiments_replay, message_name)),+ ),+ pytest.raises(ScannerFailureError) as excinfo,+ ):+ _resolve(self._inputs(scanner, session_id))+ assert excinfo.value.kind == FailureKind.INFRA_TRANSIENT++ def test_a_deleted_experiment_is_ineligible_with_experiment_unresolved(self) -> None:+ # Its own distinct id: ClickHouse rows outlive each test's transaction, so reusing another+ # test's id on the shared team would double-map the person.+ experiment = _launched_experiment(self, "checkout-flag", ["control", "test"])+ scanner = self._scanner(experiment.pk)+ session_id = self._session("deleted-exp-user", "test")+ flush_persons_and_events()+ experiment.deleted = True+ experiment.save()++ with pytest.raises(IneligibleSessionError) as excinfo:+ _resolve(self._inputs(scanner, session_id))+ assert excinfo.value.kind == IneligibleSessionKind.EXPERIMENT_UNRESOLVED++ def test_a_scanner_without_an_experiment_is_not_applicable(self) -> None:+ scanner = self._scanner(None)+ session_id = self._session("plain-user", None)+ flush_persons_and_events()++ output = _resolve(self._inputs(scanner, session_id))++ assert output.applicable is False+ assert output.experiment_variant is Nonediff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.pyindex df7b229c0f8c..e31f855bb7bb 100644--- a/products/replay_vision/backend/tests/test_sweep.py+++ b/products/replay_vision/backend/tests/test_sweep.py@@ -12,7 +12,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError-from posthog.models import Organization, Team+from posthog.models import Organization, Team, Userfrom posthog.redis import get_clientfrom posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import (STUCK_SESSION_THRESHOLD,@@ -26,7 +26,12 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.replay_scanner import (+ SETTLE_INTERVAL,+ ReplayScanner,+ ScannerModel,+ ScannerType,+)from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfillfrom products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import (@@ -73,7 +78,7 @@ from products.replay_vision.backend.temporal.sweep_types import (InFlightApplyCounts,SweepScannerInputs,)-from products.replay_vision.backend.tests.helpers import seed_scanner_spend, snapshot_for+from products.replay_vision.backend.tests.helpers import create_experiment, seed_scanner_spend, snapshot_for# Every scanner built below runs on this model, so its price sets what one observation draws._OBSERVATION_CREDITS = observation_credits_for_model(ScannerModel.GEMINI_3_8_FLASH)@@ -172,6 +177,107 @@ class TestFindScannerCandidatesActivity:result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=uuid.uuid4(), team_id=999))assert result == FindScannerCandidatesOutput(candidates=[], saturated=False)+ def test_an_experiment_scanner_without_a_creator_skips_before_any_read(self) -> None:+ # Every exposure read and every scan's variant lookup refuse a userless principal, so a tick+ # that queried or dispatched anyway could only produce refusals.+ scanner = _make_scanner(scanner_type=ScannerType.EXPERIMENT, created_by=None)+ experiment = create_experiment(scanner.team, "orphan-flag", launched=True, variants=["control", "test"])+ scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}+ scanner.save()++ with _patched_queries() as (fast_query, deep_query):+ result = find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ assert result.candidates == [] and result.swept_through is None+ assert not fast_query.called and not deep_query.called++ @parameterized.expand([("paused",), ("ended",), ("archived",), ("deleted",)])+ def test_an_experiment_that_is_not_running_stops_the_sweep(self, state: str) -> None:+ # Paused, ended, and archived experiments come back (resume, or reset and relaunch), and a+ # disabled scanner has no schedule to notice that, so those skip the tick and stay enabled.+ # Their watermarks move to now, or a comeback would bill the whole gap. Only a deleted+ # experiment disables.+ scanner = _make_scanner(scanner_type=ScannerType.EXPERIMENT)+ experiment = create_experiment(scanner.team, "over-flag", launched=True, variants=["control", "test"])+ scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}+ scanner.save()+ if state == "paused":+ experiment.feature_flag.active = False+ experiment.feature_flag.save()+ elif state == "ended":+ # Ended before the scanner's watermark, so the run is already swept to its end.+ experiment.end_date = timezone.now() - dt.timedelta(days=1)+ elif state == "archived":+ # No end date: no known end to sweep up to, so it stops like a pause.+ experiment.archived = True+ else:+ experiment.deleted = True+ experiment.save()++ with _patched_queries() as (fast_query, deep_query):+ result = find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ assert result.candidates == []+ assert not fast_query.called and not deep_query.called+ scanner.refresh_from_db()+ assert scanner.enabled is (state != "deleted")+ if state != "deleted":+ settled_now = timezone.now() - SETTLE_INTERVAL+ assert result.swept_through is not None and result.deep_swept_through is not None+ assert abs(result.swept_through - settled_now) < dt.timedelta(minutes=1)+ assert result.deep_swept_through == result.swept_through++ @parameterized.expand([("fast_walk_behind_the_end", False), ("only_the_deep_pass_behind", True)])+ def test_an_ended_experiment_is_swept_up_to_its_end_before_it_stops(self, _name: str, fast_at_end: bool) -> None:+ # Jumping to now on the first tick after the end would drop the run's last sessions and the+ # late arrivals the deep pass catches, which skews the per-variant readout.+ end = timezone.now() - dt.timedelta(hours=1)+ scanner = _make_scanner(+ scanner_type=ScannerType.EXPERIMENT,+ last_swept_at=end if fast_at_end else end - dt.timedelta(hours=2),+ deep_swept_through=end - dt.timedelta(hours=2),+ )+ scanner.created_by = User.objects.create_and_join(scanner.team.organization, "[email protected]", None)+ experiment = create_experiment(scanner.team, "ended-flag", launched=True, variants=["control", "test"])+ experiment.end_date = end+ experiment.save()+ scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}+ scanner.save()++ with _patched_queries() as (fast_query, _deep_query):+ fast_query.return_value.settle_cutoff = end+ result = find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ assert fast_query.call_args.kwargs["until"] == end+ assert fast_query.return_value.run_batch.called is not fast_at_end+ # Held at the end rather than moved to now, so the deep pass can still finish behind it.+ assert result.swept_through == end++ def test_a_legacy_column_targeted_scanner_is_never_disabled(self) -> None:+ # Scanners that target an experiment through the column predate the lifecycle gate;+ # flipping them off on deploy would change scanners that exist today.+ scanner = _make_scanner(experiment_targeting=None)+ experiment = create_experiment(scanner.team, "legacy-flag", launched=True, variants=["control", "test"])+ experiment.end_date = timezone.now()+ experiment.save()+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ experiment_targeting={"experiment_id": experiment.id, "variant": None, "variants": None}+ )++ with _patched_queries():+ find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ scanner.refresh_from_db()+ assert scanner.enabled is True+def test_returns_empty_when_scanner_belongs_to_other_team(self) -> None:scanner = _make_scanner()result = find_scanner_candidates_activity(diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 8ff3b475d0a4..97aca5c41e86 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -91,6 +91,9 @@ from products.replay_vision.backend.temporal.activities.observation_state importmark_observation_running_activity,mark_observation_succeeded_activity,)+from products.replay_vision.backend.temporal.activities.resolve_experiment_variant import (+ resolve_experiment_variant_activity,+)from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import (_write_and_upload,upload_video_to_gemini_activity,@@ -143,6 +146,7 @@ from products.replay_vision.backend.temporal.types import (MarkObservationIneligibleInputs,MarkObservationRunningInputs,MarkObservationSucceededInputs,+ ResolveExperimentVariantOutput,ScannerCallOutput,ScannerLlmInputs,ScannerResult,@@ -1440,6 +1444,29 @@ class TestObservationStateActivities:@pytest.mark.django_db(transaction=True)class TestEmitObservationEventActivity:+ def test_experiment_scanner_event_carries_experiment_and_variant(self) -> None:+ # HogQL readouts group `$recording_observed` by these two properties instead of joining+ # the exposure data; dropping either silently empties every per-variant chart.+ from products.replay_vision.backend.temporal.scanners.experiment import ExperimentOutput++ scanner = _make_scanner(+ scanner_type=ScannerType.EXPERIMENT, scanner_config={"prompt": "p", "experiment_id": 42}+ )+ observation = _make_observation(scanner, scanner_result={"experiment_variant": "test"})+ inputs = EmitObservationEventInputs(+ observation_id=observation.id,+ model_output=ExperimentOutput(title="t", summary="s", confidence=0.9),+ )++ with patch(+ "products.replay_vision.backend.temporal.activities.emit_observation_event.capture_internal"+ ) as capture:+ _emit_event(inputs)++ properties = capture.call_args.kwargs["properties"]+ assert properties["experiment_id"] == 42+ assert properties["experiment_variant"] == "test"+def test_event_prices_credits_from_the_frozen_snapshot(self) -> None:# The spend chart sums this property; dropping or mispricing it silently flatlines the chart.scanner = _make_scanner()@@ -2635,8 +2662,14 @@ class _WorkflowMocks:async def _run_workflow(- inputs: ApplyScannerInputs, mocks: _WorkflowMocks, workflow_id: str = "wf-test", patched: bool = True+ inputs: ApplyScannerInputs,+ mocks: _WorkflowMocks,+ workflow_id: str = "wf-test",+ patched: bool | dict[str, bool] = True,) -> None:+ """`patched` is one answer for every marker, or a per-marker map where unlisted markers are patched."""+ markers = patched if isinstance(patched, dict) else {}+ default = patched if isinstance(patched, bool) else Trueworkflow_info = MagicMock()workflow_info.workflow_id = workflow_idwith (@@ -2647,7 +2680,7 @@ async def _run_workflow(patch("temporalio.workflow.logger"),# `wf.patched` also needs that loop; True models a fresh execution, False a history that# already ran past this point before the patch existed.- patch("temporalio.workflow.patched", return_value=patched),+ patch("temporalio.workflow.patched", side_effect=lambda marker: markers.get(marker, default)),):await ApplyScannerWorkflow().run(inputs)@@ -2729,6 +2762,81 @@ async def test_apply_scanner_workflow_marks_failed_when_fetch_raises() -> None:assert "no events" in failed_input.error_reason.lower()+ "variant_patched,network_patched,exposed",+ [+ # Both parallel fetches: the four-way gather.+ (True, True, True),+ # A history from before the network fetch: the three-way gather.+ (True, False, True),+ # A history from before attribution: no lookup, so no variant anywhere.+ (False, True, True),+ # An unexposed session is refused before the model call, as ineligible.+ (True, True, False),+ ],+)+async def test_apply_scanner_workflow_attributes_an_experiment_scan_end_to_end(+ variant_patched: bool, network_patched: bool, exposed: bool+) -> None:+ # The gather unpacks results by position, so a swapped index would hand the provider and the+ # stored result the wrong value without any activity-level test noticing.+ from products.replay_vision.backend.temporal.scanners.experiment import ExperimentOutput++ context = {"name": "Checkout test", "feature_flag_key": "checkout-flag"}+ mocks = _WorkflowMocks(+ activity_results={+ create_observation_activity: CreateObservationOutput(+ observation_id=uuid.uuid4(), was_created=True, scanner_type=ScannerType.EXPERIMENT+ ),+ ensure_session_asset_activity: EnsureSessionAssetOutput(asset_id=42),+ resolve_experiment_variant_activity: ResolveExperimentVariantOutput(+ applicable=True, experiment_variant="test", session_duration_s=250.0, experiment_context=context+ ),+ upload_video_to_gemini_activity: UploadedVideo(+ file_uri="gemini://files/x", mime_type="video/mp4", gemini_file_name="files/x"+ ),+ call_scanner_provider_activity: ScannerCallOutput(+ model_output=ExperimentOutput(title="t", summary="s", confidence=0.9)+ ),+ },+ activity_errors=(+ {}+ if exposed+ else {+ resolve_experiment_variant_activity: IneligibleSessionError(+ "not exposed", kind=IneligibleSessionKind.NOT_EXPOSED+ )+ }+ ),+ )+ patched = {+ "replay-vision-experiment-variant-2026-09": variant_patched,+ "replay-vision-session-network-2026-09": network_patched,+ }++ if exposed:+ await _run_workflow(_build_inputs(session_id="sess-exp"), mocks, patched=patched)+ else:+ with pytest.raises(IneligibleSessionError):+ await _run_workflow(_build_inputs(session_id="sess-exp"), mocks, patched=patched)++ called = [fn for fn, _ in mocks.activity_calls]+ assert (resolve_experiment_variant_activity in called) is variant_patched+ assert (fetch_session_network_activity in called) is network_patched+ if not exposed:+ ineligible = next(arg for fn, arg in mocks.activity_calls if fn is mark_observation_ineligible_activity)+ assert ineligible.error_reason.startswith(f"{IneligibleSessionKind.NOT_EXPOSED}:")+ assert call_scanner_provider_activity not in called+ return+ provider = next(arg for fn, arg in mocks.activity_calls if fn is call_scanner_provider_activity)+ succeeded = next(arg for fn, arg in mocks.activity_calls if fn is mark_observation_succeeded_activity)+ assert provider.experiment_variant == ("test" if variant_patched else None)+ assert provider.experiment_context == (context if variant_patched else None)+ assert succeeded.scanner_result.experiment_variant == ("test" if variant_patched else None)+ assert succeeded.scanner_result.session_duration_s == (250.0 if variant_patched else None)++@pytest.mark.asyncio@pytest.mark.parametrize("rasterizer_type,patched,expect_ineligible,expected_kind",diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 29d87832f397..296927bd719d 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -688,6 +688,16 @@ export interface ScannerResultApi {signals_count: number/** Extra draws taken to verify a monitor `yes` verdict. Null when the scan did not verify one. */verification: VerificationRecordApi | null+ /**+ * Experiment scanners only: the variant the exposure data attributes this session's person to. Null on the other types and on rows scanned before variant attribution shipped.+ * @nullable+ */+ experiment_variant?: string | null+ /**+ * Experiment scanners only: the scanned session's duration in seconds.+ * @nullable+ */+ session_duration_s?: number | null}/**@@ -781,7 +791,7 @@ export interface ReplayObservationApi {* * `failed` - Failed* * `ineligible` - Ineligible */readonly status: ObservationStatusEnumApi- /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */+ /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large / not_exposed / experiment_unresolved. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */readonly error_reason: string/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */readonly workflow_id: string@@ -1584,7 +1594,7 @@ export interface PaginatedReplayScannerBackfillListApi {export interface BackfillCreateApi {/** Inclusive lower bound of the historical window to scan. */window_start: string- /** Exclusive upper bound of the window; clamped server-side to now. */+ /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */window_end: string/*** The most this backfill may cost, in credits (1 credit = $0.01): pass the `total_credits` from the estimate the person agreed to. The create is rejected if the window now costs more.@@ -1596,7 +1606,7 @@ export interface BackfillCreateApi {export interface BackfillWindowApi {/** Inclusive lower bound of the historical window to scan. */window_start: string- /** Exclusive upper bound of the window; clamped server-side to now. */+ /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */window_end: string}@@ -1614,7 +1624,7 @@ export interface BackfillEstimateResponseApi {credits_remaining: number | null/** The window lower bound the estimate covered. */window_start: string- /** The window upper bound after clamping to now. */+ /** The window upper bound after clamping to now and, for an experiment scanner, to the experiment's end date. */window_end: string}diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 64293b232391..df81405d90d1 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -872,7 +872,9 @@ export const VisionScannersBackfillsCreateBody = /* @__PURE__ */ zod.object({.describe('Inclusive lower bound of the historical window to scan.'),window_end: zod.iso.datetime({ offset: true })- .describe('Exclusive upper bound of the window; clamped server-side to now.'),+ .describe(+ "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date."+ ),max_total_credits: zod.number().min(visionScannersBackfillsCreateBodyMaxTotalCreditsMin)@@ -900,7 +902,9 @@ export const VisionScannersBackfillsEstimateCreateBody = /* @__PURE__ */ zod.obj.describe('Inclusive lower bound of the historical window to scan.'),window_end: zod.iso.datetime({ offset: true })- .describe('Exclusive upper bound of the window; clamped server-side to now.'),+ .describe(+ "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date."+ ),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 565a90f2a013..0ea6686078da 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14327,7 +14327,7 @@ export namespace Schemas {export interface BackfillCreate {/** Inclusive lower bound of the historical window to scan. */window_start: string;- /** Exclusive upper bound of the window; clamped server-side to now. */+ /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */window_end: string;/*** The most this backfill may cost, in credits (1 credit = $0.01): pass the `total_credits` from the estimate the person agreed to. The create is rejected if the window now costs more.@@ -14350,7 +14350,7 @@ export namespace Schemas {credits_remaining: number | null;/** The window lower bound the estimate covered. */window_start: string;- /** The window upper bound after clamping to now. */+ /** The window upper bound after clamping to now and, for an experiment scanner, to the experiment's end date. */window_end: string;}@@ -14373,7 +14373,7 @@ export namespace Schemas {export interface BackfillWindow {/** Inclusive lower bound of the historical window to scan. */window_start: string;- /** Exclusive upper bound of the window; clamped server-side to now. */+ /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */window_end: string;}@@ -64540,6 +64540,16 @@ export namespace Schemas {signals_count: number;/** Extra draws taken to verify a monitor `yes` verdict. Null when the scan did not verify one. */verification: VerificationRecord | null;+ /**+ * Experiment scanners only: the variant the exposure data attributes this session's person to. Null on the other types and on rows scanned before variant attribution shipped.+ * @nullable+ */+ experiment_variant?: string | null;+ /**+ * Experiment scanners only: the scanned session's duration in seconds.+ * @nullable+ */+ session_duration_s?: number | null;}/**@@ -64634,7 +64644,7 @@ export namespace Schemas {* * `failed` - Failed* * `ineligible` - Ineligible */readonly status: ObservationStatusEnum;- /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */+ /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large / not_exposed / experiment_unresolved. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */readonly error_reason: string;/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */readonly workflow_id: string;diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 18b0111330b4..20f23bdd8b09 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -1273,7 +1273,9 @@ export const VisionScannersBackfillsCreateBody = () => zod.object({.describe('Inclusive lower bound of the historical window to scan.'),window_end: zod.iso.datetime({ offset: true })- .describe('Exclusive upper bound of the window; clamped server-side to now.'),+ .describe(+ "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date."+ ),max_total_credits: zod.number().min(visionScannersBackfillsCreateBodyMaxTotalCreditsMin)@@ -1343,7 +1345,9 @@ export const VisionScannersBackfillsEstimateCreateBody = () => zod.object({.describe('Inclusive lower bound of the historical window to scan.'),window_end: zod.iso.datetime({ offset: true })- .describe('Exclusive upper bound of the window; clamped server-side to now.'),+ .describe(+ "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date."+ ),})/**diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-create.jsonindex cb4edc960ac3..038fc9e3f9cf 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-create.json@@ -10,7 +10,7 @@"type": "string"},"window_end": {- "description": "Exclusive upper bound of the window; clamped server-side to now.",+ "description": "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date.","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-estimate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-estimate.jsonindex faa45fc0da4e..06cd492079ef 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-estimate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-backfills-estimate.json@@ -5,7 +5,7 @@"type": "string"},"window_end": {- "description": "Exclusive upper bound of the window; clamped server-side to now.",+ "description": "Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date.","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$","type": "string"