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): add the experiment scanner variants readout (#110443)

Kim Svatos Dugan9b4525bf4d43
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index a522eaf8de41..933b57639551 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -203,6 +203,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.replay_vision.backend.api.quota.VisionQuotaViewSet",
"products.replay_vision.backend.api.scanners.ReplayScannerViewSet",
"products.replay_vision.backend.api.scout_reports.ScannerScoutReportViewSet",
+ "products.replay_vision.backend.api.variants.ReplayScannerVariantsViewSet",
"products.replay_vision.backend.api.vision_alerts.VisionAlertViewSet",
"products.review_hog.backend.api.blind_spots.ReviewBlindSpotsConfigViewSet",
"products.review_hog.backend.api.perspectives.ReviewPerspectiveConfigViewSet",
diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.py
index 55222588737b..accee8dc6c10 100644
--- a/products/replay_vision/backend/api/__init__.py
+++ b/products/replay_vision/backend/api/__init__.py
@@ -5,6 +5,7 @@ from products.replay_vision.backend.api.quota import VisionQuotaViewSet
from products.replay_vision.backend.api.scanner_scouts import ScannerScoutViewSet
from products.replay_vision.backend.api.scanners import ReplayScannerViewSet
from products.replay_vision.backend.api.scout_reports import ScannerScoutReportViewSet
+from products.replay_vision.backend.api.variants import ReplayScannerVariantsViewSet
from products.replay_vision.backend.api.vision_alerts import VisionAlertViewSet
__all__ = [
@@ -14,6 +15,7 @@ __all__ = [
"ReplayScannerViewSet",
"ScannerScoutReportViewSet",
"ScannerScoutViewSet",
+ "ReplayScannerVariantsViewSet",
"SessionReplayObservationViewSet",
"VisionAlertViewSet",
"VisionQuotaViewSet",
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 11b6e454cb8c..27ce6e003722 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -50,6 +50,7 @@ from products.replay_vision.backend.api.observation_progress import stream_obser
from products.replay_vision.backend.api.observation_stats import compute_observation_stats
from products.replay_vision.backend.consent import AI_CONSENT_REQUIRED_CODE, is_ai_data_processing_approved
from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
+from products.replay_vision.backend.experiment_variants import UNATTRIBUTED_VARIANT
from products.replay_vision.backend.models.replay_observation import (
IN_FLIGHT_STATUSES,
ObservationStatus,
@@ -738,6 +739,13 @@ class ReplayObservationFilter(django_filters.FilterSet):
"(comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`."
),
)
+ variant = django_filters.CharFilter(
+ method="_filter_variant",
+ help_text=(
+ "Experiment scanners only: filter to observations attributed to any of the given variant keys "
+ f"(comma-separated). `{UNATTRIBUTED_VARIANT}` matches observations with no attributed variant."
+ ),
+ )
session_id = MultiChoiceFilter(
field_name="session_id",
help_text="Filter to observations of one or more session recordings. Accepts a comma-separated list.",
@@ -862,6 +870,19 @@ class ReplayObservationFilter(django_filters.FilterSet):
q |= Q(scanner_result__model_output__tags_freeform__contains=[tag])
return queryset.filter(q)
+ def _filter_variant(
+ self, queryset: QuerySet[ReplayObservation], _name: str, value: str
+ ) -> QuerySet[ReplayObservation]:
+ keys = set(split_csv(value))
+ if not keys:
+ return queryset
+ named = keys - {UNATTRIBUTED_VARIANT}
+ q = Q(_variant__in=named) if named else Q(pk__in=[])
+ if UNATTRIBUTED_VARIANT in keys:
+ q |= Q(_variant__isnull=True)
+ # `->>` reads a missing key and a JSON null alike as SQL NULL, so both count as unattributed.
+ return queryset.alias(_variant=KeyTextTransform("experiment_variant", "scanner_result")).filter(q)
+
# OrderingFilter renders as an array by default, which the MCP client serializes as a JSON-bracketed
# string the filter rejects. Declare it as a single-value string enum so it serializes as ?order_by=field.
diff --git a/products/replay_vision/backend/api/variants.py b/products/replay_vision/backend/api/variants.py
new file mode 100644
index 000000000000..61afce133ebd
--- /dev/null
+++ b/products/replay_vision/backend/api/variants.py
@@ -0,0 +1,95 @@
+from typing import Any
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.replay_vision.backend.api.observations import ReplayObservationSerializer
+from products.replay_vision.backend.experiment_variants import experiment_variants_readout
+from products.replay_vision.backend.models.replay_scanner import ScannerType
+from products.replay_vision.backend.scanner_access import scanner_for_recording_derived_read
+
+
+class VariantsExperimentSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="The experiment's id.")
+ name = serializers.CharField(help_text="The experiment's name.")
+ status = serializers.CharField(help_text="draft, running, paused, exposure_frozen, or stopped.")
+ start_date = serializers.DateTimeField(allow_null=True, help_text="When the experiment launched.")
+ end_date = serializers.DateTimeField(allow_null=True, help_text="When the experiment ended; null while it runs.")
+ planned_duration_days = serializers.FloatField(
+ allow_null=True, help_text="The experiment's recommended running time in days, when one was set."
+ )
+ current_day = serializers.IntegerField(
+ allow_null=True,
+ help_text="The experiment's day number: 1 on its launch day, frozen once it ends. Null before launch.",
+ )
+
+
+class VariantsWindowSerializer(serializers.Serializer):
+ total_observations = serializers.IntegerField(
+ help_text="Succeeded observations of this scanner, attributed to a variant or not."
+ )
+ first_observation_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the earliest of those observations completed."
+ )
+ last_observation_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the latest of those observations completed."
+ )
+
+
+class VariantReadoutSerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="The variant key.")
+ observations = serializers.IntegerField(help_text="Succeeded observations attributed to this variant.")
+ distinct_people = serializers.IntegerField(help_text="Distinct people (by distinct id) behind those observations.")
+ median_session_duration_s = serializers.FloatField(
+ allow_null=True, help_text="Median scanned session length in seconds; null with no observations."
+ )
+ sampling_rate = serializers.FloatField(
+ allow_null=True,
+ help_text=(
+ "The 0..1 rate this variant was sampled at when its latest observation was dispatched. Read even "
+ "counts against it: balanced sampling gives a small variant a higher rate."
+ ),
+ )
+ latest_observations = ReplayObservationSerializer(
+ many=True, help_text="This variant's most recent observations, newest first."
+ )
+
+
+class ExperimentVariantsReadoutSerializer(serializers.Serializer):
+ experiment = VariantsExperimentSerializer(
+ allow_null=True, help_text="The watched experiment; null if it was deleted."
+ )
+ window = VariantsWindowSerializer(help_text="The span of observations the counts cover.")
+ variants = VariantReadoutSerializer(
+ many=True, help_text="One entry per watched variant, plus any variant still holding observations."
+ )
+ unattributed_count = serializers.IntegerField(help_text="Succeeded observations with no attributed variant.")
+
+
+class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ """What users in each variant of an experiment scanner's experiment do, side by side."""
+
+ scope_object = "replay_scanner"
+ required_scopes = ["replay_scanner:read", "session_recording:read"]
+
+ @extend_schema(
+ responses={
+ 200: ExperimentVariantsReadoutSerializer,
+ 400: OpenApiResponse(description="The scanner is not an experiment scanner."),
+ },
+ description=(
+ "Per-variant readout for an experiment scanner: observation counts, distinct people, median "
+ "session length, sampling rate and latest observations per variant, read live."
+ ),
+ )
+ def list(self, request: Request, **kwargs: Any) -> Response:
+ scanner = scanner_for_recording_derived_read(self)
+ if scanner.scanner_type != ScannerType.EXPERIMENT:
+ raise ValidationError("Only experiment scanners have variants.")
+ readout = experiment_variants_readout(scanner, access=self.user_access_control, viewer_id=request.user.id)
+ return Response(ExperimentVariantsReadoutSerializer(readout).data)
diff --git a/products/replay_vision/backend/experiment_variants.py b/products/replay_vision/backend/experiment_variants.py
new file mode 100644
index 000000000000..3665ef1e7896
--- /dev/null
+++ b/products/replay_vision/backend/experiment_variants.py
@@ -0,0 +1,180 @@
+"""The per-variant readout of an experiment scanner, counted from its observations.
+
+Counts are read from Postgres on every call, so they never lag the observations.
+"""
+
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from django.db.models import Aggregate, Count, FloatField, Max, Min, Q
+from django.db.models.fields.json import KT
+from django.db.models.functions import Cast
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ReplayObservation,
+ hydrate_for_serialization,
+)
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.scanner_access import accessible_observations
+
+if TYPE_CHECKING:
+ from products.experiments.backend.facade.contracts import ExperimentPromptContext, ExperimentStatus
+
+# The `variant` filter value for observations with no attributed variant. Variant keys are flag variant
+# keys, so a name with this shape can't collide with a real one in practice.
+UNATTRIBUTED_VARIANT = "__unattributed__"
+LATEST_OBSERVATIONS_PER_VARIANT = 2
+
+
+class _Median(Aggregate):
+ function = "percentile_cont"
+ template = "%(function)s(0.5) WITHIN GROUP (ORDER BY %(expressions)s)"
+ output_field = FloatField()
+
+
+@frozen
+class VariantsExperiment:
+ id: int
+ name: str
+ status: str
+ start_date: datetime | None
+ end_date: datetime | None
+ planned_duration_days: float | None
+ # The experiment's day number: 1 on its launch day, frozen once it ends.
+ current_day: int | None
+
+
+@frozen
+class VariantsWindow:
+ total_observations: int
+ first_observation_at: datetime | None
+ last_observation_at: datetime | None
+
+
+@frozen
+class VariantReadout:
+ key: str
+ observations: int
+ distinct_people: int
+ median_session_duration_s: float | None
+ sampling_rate: float | None
+ latest_observations: tuple[ReplayObservation, ...]
+
+
+@frozen
+class ExperimentVariantsReadout:
+ experiment: VariantsExperiment | None
+ window: VariantsWindow
+ variants: tuple[VariantReadout, ...]
+ unattributed_count: int
+
+
+def experiment_variants_readout(
+ scanner: ReplayScanner, *, access: UserAccessControl, viewer_id: int | None
+) -> ExperimentVariantsReadout:
+ """The readout for an experiment scanner the caller may already read (see `scanner_for_recording_derived_read`)."""
+ # 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, experiment_status # noqa: PLC0415
+
+ scope = scanner.experiment_scope() or {}
+ experiment_id = scope.get("experiment_id")
+ context = experiment_prompt_context(scanner.team, experiment_id=experiment_id) if experiment_id else None
+ status = experiment_status(scanner.team, experiment_id=experiment_id) if experiment_id else None
+
+ # `->>` reads both a missing key and a JSON null as SQL NULL, so rows scanned before attribution
+ # shipped and rows written with an explicit null both land in `variant__isnull=True`.
+ observations = accessible_observations(
+ access,
+ scanner.team_id,
+ ReplayObservation.objects.filter(team_id=scanner.team_id, scanner=scanner, status=ObservationStatus.SUCCEEDED),
+ ).annotate(variant=KT("scanner_result__experiment_variant"))
+ window = observations.aggregate(
+ total=Count("id"),
+ unattributed=Count("id", filter=Q(variant__isnull=True)),
+ first=Min("completed_at"),
+ last=Max("completed_at"),
+ )
+ attributed = observations.filter(variant__isnull=False)
+ stats = {
+ row["variant"]: row
+ for row in attributed.values("variant").annotate(
+ observations=Count("id"),
+ distinct_people=Count("distinct_id", distinct=True),
+ median_duration=_Median(Cast(KT("scanner_result__session_duration_s"), FloatField())),
+ )
+ }
+
+ # Watched variants first, in the scanner's order, so a variant with no observations yet still shows.
+ # A key seen in observations but no longer watched (the selection changed) follows them.
+ configured = scope.get("variants")
+ watched = list(configured) if configured else [variant.key for variant in context.variants] if context else []
+ keys = watched + sorted(key for key in stats if key not in watched)
+
+ variants = []
+ for key in keys:
+ row = stats.get(key)
+ latest = tuple(
+ hydrate_for_serialization(attributed.filter(variant=key), viewer_id=viewer_id).order_by("-completed_at")[
+ :LATEST_OBSERVATIONS_PER_VARIANT
+ ]
+ )
+ variants.append(
+ VariantReadout(
+ key=key,
+ observations=row["observations"] if row else 0,
+ distinct_people=row["distinct_people"] if row else 0,
+ median_session_duration_s=row["median_duration"] if row else None,
+ sampling_rate=_sampling_rate(latest[0], key) if latest else None,
+ latest_observations=latest,
+ )
+ )
+
+ return ExperimentVariantsReadout(
+ experiment=_experiment(context, status),
+ window=VariantsWindow(
+ total_observations=window["total"],
+ first_observation_at=window["first"],
+ last_observation_at=window["last"],
+ ),
+ variants=tuple(variants),
+ unattributed_count=window["unattributed"],
+ )
+
+
+def _sampling_rate(observation: ReplayObservation, key: str) -> float | None:
+ """The rate the variant was sampled at by the tick that scanned its latest observation.
+
+ Balanced sampling records a rate per variant; without it every variant shared the scanner's rate.
+ """
+ snapshot = observation.scanner_snapshot if isinstance(observation.scanner_snapshot, dict) else {}
+ rates = snapshot.get("variant_sampling_rates")
+ if isinstance(rates, dict) and isinstance(rates.get(key), int | float):
+ return float(rates[key])
+ rate = snapshot.get("sampling_rate")
+ return float(rate) if isinstance(rate, int | float) else None
+
+
+def _experiment(
+ context: "ExperimentPromptContext | None", status: "ExperimentStatus | None"
+) -> VariantsExperiment | None:
+ if context is None or status is None:
+ return None
+ current_day = None
+ if status.start_date is not None:
+ until = min(timezone.now(), status.end_date) if status.end_date is not None else timezone.now()
+ current_day = max((until - status.start_date).days + 1, 1)
+ return VariantsExperiment(
+ id=context.id,
+ name=context.name,
+ status=status.status,
+ start_date=status.start_date,
+ end_date=status.end_date,
+ planned_duration_days=status.planned_duration_days,
+ current_day=current_day,
+ )
diff --git a/products/replay_vision/backend/routes.py b/products/replay_vision/backend/routes.py
index 6fbeb0157431..ce88a25728cc 100644
--- a/products/replay_vision/backend/routes.py
+++ b/products/replay_vision/backend/routes.py
@@ -4,6 +4,7 @@ from products.replay_vision.backend.api import (
ReplayObservationViewSet,
ReplayScannerBackfillViewSet,
ReplayScannerPromptSuggestionViewSet,
+ ReplayScannerVariantsViewSet,
ReplayScannerViewSet,
ScannerScoutReportViewSet,
ScannerScoutViewSet,
@@ -35,6 +36,9 @@ def register_routes(routers: RouterRegistry) -> None:
project_vision_scanners_router.register(
r"backfills", ReplayScannerBackfillViewSet, "project_vision_scanner_backfills", ["team_id", "scanner_id"]
)
+ project_vision_scanners_router.register(
+ r"variants", ReplayScannerVariantsViewSet, "project_vision_scanner_variants", ["team_id", "scanner_id"]
+ )
project_vision_scanners_router.register(
r"prompt_suggestions",
ReplayScannerPromptSuggestionViewSet,
diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.py
index 5cdb15897766..b4b11618dd71 100644
--- a/products/replay_vision/backend/tests/test_access_control.py
+++ b/products/replay_vision/backend/tests/test_access_control.py
@@ -524,6 +524,26 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
plain_resp = self.client.get(f"{self.scanners_url}{plain.id}/backfills/")
self.assertEqual(plain_resp.status_code, 200, plain_resp.json())
+ def test_variants_of_a_denied_experiment_scanner_read_as_not_found(self) -> None:
+ # The variants readout counts the experiment's exposed people per variant and quotes their
+ # summaries, so a caller denied the experiment must not reach it through the scanner alone.
+ experiment = create_experiment(
+ self.team, "hidden-flag", created_by=self.user, launched=True, variants=["control", "test"]
+ )
+ 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")
+
+ self.client.force_login(self.other_user)
+ self.assertEqual(self.client.get(f"{self.scanners_url}{targeted.id}/variants/").status_code, 404)
+
+ # The experiment's creator reads it.
+ self.client.force_login(self.user)
+ resp = self.client.get(f"{self.scanners_url}{targeted.id}/variants/")
+ self.assertEqual(resp.status_code, 200, 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 must
diff --git a/products/replay_vision/backend/tests/test_experiment_variants.py b/products/replay_vision/backend/tests/test_experiment_variants.py
new file mode 100644
index 000000000000..4f693e25feb4
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_experiment_variants.py
@@ -0,0 +1,119 @@
+from datetime import timedelta
+from typing import Any
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.replay_vision.backend.experiment_variants import UNATTRIBUTED_VARIANT
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
+from products.replay_vision.backend.models.replay_scanner import ScannerType
+from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for
+from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
+
+_UNSET = object()
+
+
+class TestExperimentVariants(_VisionAPITestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.experiment = create_experiment(
+ self.team, "checkout-flag", launched=True, variants=["control", "test", "beta"]
+ )
+ self.scanner = self._create_scanner(
+ name="experiment-scanner",
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": self.experiment.id},
+ )
+ self.variants_url = f"{self.scanners_url}{self.scanner.id}/variants/"
+ self._minutes_ago = 100
+
+ def _observation(
+ self,
+ variant: Any = _UNSET,
+ *,
+ distinct_id: str = "person-a",
+ duration_s: float = 60,
+ status: str = ObservationStatus.SUCCEEDED,
+ rates: dict[str, float] | None = None,
+ ) -> ReplayObservation:
+ result: dict[str, Any] = {"model_output": {"title": "t", "summary": "s"}, "session_duration_s": duration_s}
+ if variant is not _UNSET:
+ result["experiment_variant"] = variant
+ snapshot = {**snapshot_for(self.scanner), "variant_sampling_rates": rates}
+ # Each call lands later than the last, so "newest first" has a defined order.
+ self._minutes_ago -= 1
+ return ReplayObservation.objects.create(
+ scanner=self.scanner,
+ team=self.team,
+ session_id=f"sess-{self._minutes_ago}",
+ distinct_id=distinct_id,
+ status=status,
+ completed_at=timezone.now() - timedelta(minutes=self._minutes_ago),
+ scanner_snapshot=snapshot,
+ scanner_result=result if status == ObservationStatus.SUCCEEDED else {},
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+
+ def test_readout_counts_each_variant_from_its_observations(self) -> None:
+ rates = {"control": 0.1, "test": 0.9, "beta": 0.5}
+ self._observation("control", distinct_id="a", duration_s=100, rates=rates)
+ second = self._observation("control", distinct_id="a", duration_s=200, rates=rates)
+ newest = self._observation("control", distinct_id="c", duration_s=600, rates=rates)
+ # Without balancing the variant shared the scanner-wide rate the snapshot recorded.
+ self._observation("test", distinct_id="b", duration_s=50, rates=None)
+ self._observation(_UNSET)
+ self._observation(None)
+ # Only succeeded scans count.
+ self._observation("control", distinct_id="z", status=ObservationStatus.FAILED)
+
+ resp = self.client.get(self.variants_url)
+
+ assert resp.status_code == 200, resp.json()
+ body = resp.json()
+ by_key = {v["key"]: v for v in body["variants"]}
+ # Watched variants in the experiment's order, a variant with no scans included.
+ assert [v["key"] for v in body["variants"]] == ["control", "test", "beta"]
+ assert by_key["control"]["observations"] == 3
+ assert by_key["control"]["distinct_people"] == 2
+ assert by_key["control"]["median_session_duration_s"] == 200
+ assert by_key["control"]["sampling_rate"] == 0.1
+ assert [o["id"] for o in by_key["control"]["latest_observations"]] == [str(newest.id), str(second.id)]
+ assert by_key["test"]["observations"] == 1
+ assert by_key["test"]["sampling_rate"] == self.scanner.sampling_rate
+ assert by_key["beta"] == {**by_key["beta"], "observations": 0, "sampling_rate": None, "latest_observations": []}
+ # A missing key and a JSON null both mean unattributed.
+ assert body["unattributed_count"] == 2
+ assert body["window"]["total_observations"] == 6
+ assert body["experiment"]["id"] == self.experiment.id
+ assert body["experiment"]["current_day"] >= 1
+
+ def test_a_non_experiment_scanner_has_no_variants(self) -> None:
+ monitor = self._create_scanner(name="monitor")
+ resp = self.client.get(f"{self.scanners_url}{monitor.id}/variants/")
+ assert resp.status_code == 400
+
+ @parameterized.expand(
+ [
+ ("named", "test", {"test"}),
+ ("unattributed", UNATTRIBUTED_VARIANT, {"missing", "null"}),
+ ("both", f"control,{UNATTRIBUTED_VARIANT}", {"control", "missing", "null"}),
+ ]
+ )
+ def test_observations_filter_by_variant(self, _name: str, value: str, expected: set[str]) -> None:
+ observations = {
+ "control": self._observation("control"),
+ "test": self._observation("test"),
+ "missing": self._observation(_UNSET),
+ "null": self._observation(None),
+ }
+
+ resp = self.client.get(f"{self.observations_url(str(self.scanner.id))}?variant={value}")
+
+ assert resp.status_code == 200, resp.json()
+ returned = {o["id"] for o in resp.json()["results"]}
+ assert returned == {str(observations[name].id) for name in expected}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 1640ee4a2937..5d7ffc9e35a2 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -2409,6 +2409,82 @@ export interface ScannerScoutCreateResponseApi {
config: SignalScoutConfigApi
}
+export interface VariantsExperimentApi {
+ /** The experiment's id. */
+ id: number
+ /** The experiment's name. */
+ name: string
+ /** draft, running, paused, exposure_frozen, or stopped. */
+ status: string
+ /**
+ * When the experiment launched.
+ * @nullable
+ */
+ start_date: string | null
+ /**
+ * When the experiment ended; null while it runs.
+ * @nullable
+ */
+ end_date: string | null
+ /**
+ * The experiment's recommended running time in days, when one was set.
+ * @nullable
+ */
+ planned_duration_days: number | null
+ /**
+ * The experiment's day number: 1 on its launch day, frozen once it ends. Null before launch.
+ * @nullable
+ */
+ current_day: number | null
+}
+
+export interface VariantsWindowApi {
+ /** Succeeded observations of this scanner, attributed to a variant or not. */
+ total_observations: number
+ /**
+ * When the earliest of those observations completed.
+ * @nullable
+ */
+ first_observation_at: string | null
+ /**
+ * When the latest of those observations completed.
+ * @nullable
+ */
+ last_observation_at: string | null
+}
+
+export interface VariantReadoutApi {
+ /** The variant key. */
+ key: string
+ /** Succeeded observations attributed to this variant. */
+ observations: number
+ /** Distinct people (by distinct id) behind those observations. */
+ distinct_people: number
+ /**
+ * Median scanned session length in seconds; null with no observations.
+ * @nullable
+ */
+ median_session_duration_s: number | null
+ /**
+ * The 0..1 rate this variant was sampled at when its latest observation was dispatched. Read even counts against it: balanced sampling gives a small variant a higher rate.
+ * @nullable
+ */
+ sampling_rate: number | null
+ /** This variant's most recent observations, newest first. */
+ latest_observations: ReplayObservationApi[]
+}
+
+export interface ExperimentVariantsReadoutApi {
+ /** The watched experiment; null if it was deleted. */
+ experiment: VariantsExperimentApi | null
+ /** The span of observations the counts cover. */
+ window: VariantsWindowApi
+ /** One entry per watched variant, plus any variant still holding observations. */
+ variants: VariantReadoutApi[]
+ /** Succeeded observations with no attributed variant. */
+ unattributed_count: number
+}
+
/**
* Distinct creators across all scanners on the team — feeds the `Created by` filter dropdown.
*/
@@ -2927,6 +3003,10 @@ export type VisionObservationsRetrieveParams = {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -3150,6 +3230,10 @@ export type VisionScannersObservationsListParams = {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -3205,6 +3289,10 @@ export type VisionScannersObservationsRetrieveParams = {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -3260,6 +3348,10 @@ export type VisionScannersObservationsSignalReportsListParams = {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -3323,6 +3415,10 @@ export type VisionScannersObservationsStatsRetrieveParams = {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index f707f5aa3ad2..c37665fedcb9 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -24,6 +24,7 @@ import type {
EstimateRequestApi,
EstimateResponseApi,
EvaluatePromptSuggestionRequestApi,
+ ExperimentVariantsReadoutApi,
InlineScanRequestApi,
InlineScanResponseApi,
ObservationSearchResponseApi,
@@ -1535,6 +1536,24 @@ export const visionScannersScoutsCreate = async (
})
}
+export const getVisionScannersVariantsListUrl = (projectId: string, scannerId: string) => {
+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/variants/`
+}
+
+/**
+ * Per-variant readout for an experiment scanner: observation counts, distinct people, median session length, sampling rate and latest observations per variant, read live.
+ */
+export const visionScannersVariantsList = async (
+ projectId: string,
+ scannerId: string,
+ options?: RequestInit
+): Promise<ExperimentVariantsReadoutApi[]> => {
+ return apiMutator<ExperimentVariantsReadoutApi[]>(getVisionScannersVariantsListUrl(projectId, scannerId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getVisionScannersCreatorsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/vision/scanners/creators/`
}
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index f895d5519084..fd7f7109495f 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -1169,6 +1169,9 @@ tools:
- created_by
- updated_at
requires_ai_consent: true
+ vision-scanners-variants-list:
+ operation: vision_scanners_variants_list
+ enabled: false
vision-scanners-watch-feed:
operation: vision_scanners_watch_feed_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8dacd3ac7ed6..54c89488d39c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44377,6 +44377,349 @@ export namespace Schemas {
prompt_version?: string | null;
}
+ export interface VariantsExperiment {
+ /** The experiment's id. */
+ id: number;
+ /** The experiment's name. */
+ name: string;
+ /** draft, running, paused, exposure_frozen, or stopped. */
+ status: string;
+ /**
+ * When the experiment launched.
+ * @nullable
+ */
+ start_date: string | null;
+ /**
+ * When the experiment ended; null while it runs.
+ * @nullable
+ */
+ end_date: string | null;
+ /**
+ * The experiment's recommended running time in days, when one was set.
+ * @nullable
+ */
+ planned_duration_days: number | null;
+ /**
+ * The experiment's day number: 1 on its launch day, frozen once it ends. Null before launch.
+ * @nullable
+ */
+ current_day: number | null;
+ }
+
+ export interface VariantsWindow {
+ /** Succeeded observations of this scanner, attributed to a variant or not. */
+ total_observations: number;
+ /**
+ * When the earliest of those observations completed.
+ * @nullable
+ */
+ first_observation_at: string | null;
+ /**
+ * When the latest of those observations completed.
+ * @nullable
+ */
+ last_observation_at: string | null;
+ }
+
+ /**
+ * * `configured` - Configured
+ * * `inline` - Inline
+ */
+ export type ScannerOriginEnum = typeof ScannerOriginEnum[keyof typeof ScannerOriginEnum];
+
+
+ export const ScannerOriginEnum = {
+ Configured: 'configured',
+ Inline: 'inline',
+ } as const;
+
+ /**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `succeeded` - Succeeded
+ * * `failed` - Failed
+ * * `ineligible` - Ineligible
+ */
+ export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
+
+
+ export const ObservationStatusEnum = {
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+ Failed: 'failed',
+ Ineligible: 'ineligible',
+ } as const;
+
+ /**
+ * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
+ * @nullable
+ */
+ export type ScannerSnapshotVariantSamplingRates = {[key: string]: number} | null;
+
+ /**
+ * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
+ */
+ export interface ScannerSnapshot {
+ /** Scanner name at run time. */
+ name: string;
+ /** Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.
+ *
+ * * `monitor` - Monitor
+ * * `classifier` - Classifier
+ * * `scorer` - Scorer
+ * * `summarizer` - Summarizer
+ * * `experiment` - Experiment */
+ scanner_type: ScannerTypeEnum;
+ /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
+ scanner_version: number;
+ /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
+ model: string;
+ /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
+ provider: string;
+ /** Whether the observation was run with Signal emission enabled. */
+ emits_signals: boolean;
+ /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
+ scanner_config: unknown;
+ /** How a monitor `yes` was re-checked at run time: `off` (one pass, the default), `shadow` (second draw recorded only), or `enforce` (the `yes` stands only when the second draw agrees). */
+ verify_positives: string;
+ /**
+ * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
+ * @nullable
+ */
+ variant_sampling_rates?: ScannerSnapshotVariantSamplingRates;
+ }
+
+ /**
+ * Mirrors `temporal.types.VerificationRecord` for OpenAPI generation.
+ */
+ export interface VerificationRecord {
+ /** Verify-positives mode the scan ran with: `shadow` records the second draw only, `enforce` serves the settled verdict. */
+ mode: string;
+ /** Monitor verdicts in draw order: the pass that triggered verification, then the second draw when it ran. */
+ draws: string[];
+ /** The verdict verification settled on: the first pass when the second draw agrees, else the dissent. */
+ resolved_verdict: string;
+ /** The verdict `model_output` carries: the resolved one under `enforce`, the first draw under `shadow`. */
+ served_verdict: string;
+ /**
+ * Why verification stopped early (`no_cache`, `no_budget`, `draw_failed`), leaving the first pass in place. Null when every draw ran.
+ * @nullable
+ */
+ skipped_reason: string | null;
+ }
+
+ /**
+ * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.
+ */
+ export interface ScannerResult {
+ /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */
+ model_output: unknown;
+ /**
+ * Number of PostHog Signals emitted from this observation.
+ * @minimum 0
+ */
+ 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;
+ }
+
+ /**
+ * * `schedule` - Schedule
+ * * `on_demand` - On demand
+ * * `retry` - Retry
+ * * `backfill` - Backfill
+ */
+ export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];
+
+
+ export const ObservationTriggerEnum = {
+ Schedule: 'schedule',
+ OnDemand: 'on_demand',
+ Retry: 'retry',
+ Backfill: 'backfill',
+ } as const;
+
+ /**
+ * The team's shared judgement on whether the scanner scored this session correctly.
+ */
+ export interface ReplayObservationLabel {
+ /** True if the scanner scored this session correctly, false if not. */
+ is_correct: boolean;
+ /**
+ * Optional written context on the rating, for thumbs-up and thumbs-down alike: what the scanner got right or wrong, or what it should have concluded.
+ * @maxLength 5000
+ */
+ feedback?: string;
+ }
+
+ /**
+ * * `thumbnail` - Thumbnail
+ * * `clip` - Clip
+ * * `chapter` - Chapter
+ */
+ export type ReplayObservationMediaKindEnum = typeof ReplayObservationMediaKindEnum[keyof typeof ReplayObservationMediaKindEnum];
+
+
+ export const ReplayObservationMediaKindEnum = {
+ Thumbnail: 'thumbnail',
+ Clip: 'clip',
+ Chapter: 'chapter',
+ } as const;
+
+ /**
+ * One thumbnail or clip illustrating an observation.
+ */
+ export interface ReplayObservationMedia {
+ /** Id of this media entry. */
+ readonly id: string;
+ /** `thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one summary chapter, `clip` for a short video.
+ *
+ * * `thumbnail` - Thumbnail
+ * * `clip` - Clip
+ * * `chapter` - Chapter */
+ readonly kind: ReplayObservationMediaKindEnum;
+ /** Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`. */
+ readonly position: number;
+ /** Export asset holding the bytes; fetch it from the export content endpoint. */
+ readonly asset_id: number;
+ /**
+ * One sentence saying what the clip shows. Null for thumbnails.
+ * @nullable
+ */
+ readonly description: string | null;
+ /** Where this media starts in the analysis video, in milliseconds. */
+ readonly video_start_ms: number;
+ /**
+ * Where a clip ends in the analysis video, in milliseconds. Null for thumbnails.
+ * @nullable
+ */
+ readonly video_end_ms: number | null;
+ }
+
+ export interface ReplayObservation {
+ readonly id: string;
+ /** The scanner that produced this observation. */
+ readonly scanner_id: string;
+ /** Where the producing scanner came from. `configured` scanners are saved, named, and have a detail page; `inline` ones are throwaways minted for a one-off scan and are not addressable, so callers must not link to them.
+ *
+ * * `configured` - Configured
+ * * `inline` - Inline */
+ readonly scanner_origin: ScannerOriginEnum;
+ /** Session recording id this scanner was applied to. */
+ readonly session_id: string;
+ /** Observation status (pending, running, succeeded, failed, ineligible).
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `succeeded` - Succeeded
+ * * `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 / 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;
+ /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */
+ readonly scanner_snapshot: ScannerSnapshot | null;
+ /** Result data persisted on success; null until the observation succeeds. */
+ readonly scanner_result: ScannerResult | null;
+ /**
+ * The scanner's prompt condensed into the one question it answers about a session. Null when the prompt has changed since this observation was scanned, since the question then describes a different prompt; read `scanner_snapshot.scanner_config.prompt` instead.
+ * @nullable
+ */
+ readonly prompt_question: string | null;
+ /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
+ *
+ * * `schedule` - Schedule
+ * * `on_demand` - On demand
+ * * `retry` - Retry
+ * * `backfill` - Backfill */
+ readonly triggered_by: ObservationTriggerEnum;
+ /** User who triggered an on-demand observation; null for scheduled observations. */
+ readonly triggered_by_user: UserBasic | null;
+ /**
+ * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.
+ * @nullable
+ */
+ readonly backfill_id: string | null;
+ /**
+ * Distinct id of the person in the recorded session (the subject being watched); null if unknown.
+ * @nullable
+ */
+ readonly distinct_id: string | null;
+ /**
+ * Email of the person in the recorded session (the subject being watched, not the user who triggered the observation), captured at scan time. Null when the session had no identified person.
+ * @nullable
+ */
+ readonly recording_subject_email: string | null;
+ /**
+ * Id of the preceding sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the start of the set.
+ * @nullable
+ */
+ readonly previous_observation_id: string | null;
+ /**
+ * Id of the following sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the end of the set.
+ * @nullable
+ */
+ readonly next_observation_id: string | null;
+ /** The team's shared label on this observation (correct/incorrect + feedback), or null if unlabeled. */
+ readonly label: ReplayObservationLabel | null;
+ /** Whether the calling user has opened this observation. */
+ readonly viewed: boolean;
+ /** Thumbnails and clips illustrating this observation, in order. Empty until the media render finishes. */
+ readonly media: readonly ReplayObservationMedia[];
+ /** One line of plain text saying what the scanner found: its verdict, score, tags or title, then its own words, with markdown flattened and the text truncated. An observation that produced no result carries the reason instead, and one still in flight carries an empty string. Read this in place of `scanner_result` when you scan a list of observations. */
+ readonly summary_line: string;
+ /** @nullable */
+ started_at?: string | null;
+ /** @nullable */
+ completed_at?: string | null;
+ readonly created_at: string;
+ }
+
+ export interface VariantReadout {
+ /** The variant key. */
+ key: string;
+ /** Succeeded observations attributed to this variant. */
+ observations: number;
+ /** Distinct people (by distinct id) behind those observations. */
+ distinct_people: number;
+ /**
+ * Median scanned session length in seconds; null with no observations.
+ * @nullable
+ */
+ median_session_duration_s: number | null;
+ /**
+ * The 0..1 rate this variant was sampled at when its latest observation was dispatched. Read even counts against it: balanced sampling gives a small variant a higher rate.
+ * @nullable
+ */
+ sampling_rate: number | null;
+ /** This variant's most recent observations, newest first. */
+ latest_observations: ReplayObservation[];
+ }
+
+ export interface ExperimentVariantsReadout {
+ /** The watched experiment; null if it was deleted. */
+ experiment: VariantsExperiment | null;
+ /** The span of observations the counts cover. */
+ window: VariantsWindow;
+ /** One entry per watched variant, plus any variant still holding observations. */
+ variants: VariantReadout[];
+ /** Succeeded observations with no attributed variant. */
+ unattributed_count: number;
+ }
+
/**
* The experiment state as the client last read it, used together with `version` to resolve concurrent edits: metric collections merge per metric uuid, and any other field the update carries merges per field against its base value here (only a same-field double edit fails). Relevant keys are metrics, metrics_secondary, saved_metrics_ids, plus the last-read values of whichever scalar fields the update writes; unknown keys are ignored. Changed fields without a base value — and, without this object, any version mismatch — fail with HTTP 409.
* @nullable
@@ -64460,273 +64803,6 @@ export namespace Schemas {
version_markers: ObservationVersionMarker[];
}
- /**
- * * `configured` - Configured
- * * `inline` - Inline
- */
- export type ScannerOriginEnum = typeof ScannerOriginEnum[keyof typeof ScannerOriginEnum];
-
-
- export const ScannerOriginEnum = {
- Configured: 'configured',
- Inline: 'inline',
- } as const;
-
- /**
- * * `pending` - Pending
- * * `running` - Running
- * * `succeeded` - Succeeded
- * * `failed` - Failed
- * * `ineligible` - Ineligible
- */
- export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
-
-
- export const ObservationStatusEnum = {
- Pending: 'pending',
- Running: 'running',
- Succeeded: 'succeeded',
- Failed: 'failed',
- Ineligible: 'ineligible',
- } as const;
-
- /**
- * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
- * @nullable
- */
- export type ScannerSnapshotVariantSamplingRates = {[key: string]: number} | null;
-
- /**
- * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
- */
- export interface ScannerSnapshot {
- /** Scanner name at run time. */
- name: string;
- /** Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.
- *
- * * `monitor` - Monitor
- * * `classifier` - Classifier
- * * `scorer` - Scorer
- * * `summarizer` - Summarizer
- * * `experiment` - Experiment */
- scanner_type: ScannerTypeEnum;
- /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
- scanner_version: number;
- /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
- model: string;
- /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
- provider: string;
- /** Whether the observation was run with Signal emission enabled. */
- emits_signals: boolean;
- /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
- scanner_config: unknown;
- /** How a monitor `yes` was re-checked at run time: `off` (one pass, the default), `shadow` (second draw recorded only), or `enforce` (the `yes` stands only when the second draw agrees). */
- verify_positives: string;
- /**
- * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
- * @nullable
- */
- variant_sampling_rates?: ScannerSnapshotVariantSamplingRates;
- }
-
- /**
- * Mirrors `temporal.types.VerificationRecord` for OpenAPI generation.
- */
- export interface VerificationRecord {
- /** Verify-positives mode the scan ran with: `shadow` records the second draw only, `enforce` serves the settled verdict. */
- mode: string;
- /** Monitor verdicts in draw order: the pass that triggered verification, then the second draw when it ran. */
- draws: string[];
- /** The verdict verification settled on: the first pass when the second draw agrees, else the dissent. */
- resolved_verdict: string;
- /** The verdict `model_output` carries: the resolved one under `enforce`, the first draw under `shadow`. */
- served_verdict: string;
- /**
- * Why verification stopped early (`no_cache`, `no_budget`, `draw_failed`), leaving the first pass in place. Null when every draw ran.
- * @nullable
- */
- skipped_reason: string | null;
- }
-
- /**
- * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.
- */
- export interface ScannerResult {
- /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */
- model_output: unknown;
- /**
- * Number of PostHog Signals emitted from this observation.
- * @minimum 0
- */
- 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;
- }
-
- /**
- * * `schedule` - Schedule
- * * `on_demand` - On demand
- * * `retry` - Retry
- * * `backfill` - Backfill
- */
- export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];
-
-
- export const ObservationTriggerEnum = {
- Schedule: 'schedule',
- OnDemand: 'on_demand',
- Retry: 'retry',
- Backfill: 'backfill',
- } as const;
-
- /**
- * The team's shared judgement on whether the scanner scored this session correctly.
- */
- export interface ReplayObservationLabel {
- /** True if the scanner scored this session correctly, false if not. */
- is_correct: boolean;
- /**
- * Optional written context on the rating, for thumbs-up and thumbs-down alike: what the scanner got right or wrong, or what it should have concluded.
- * @maxLength 5000
- */
- feedback?: string;
- }
-
- /**
- * * `thumbnail` - Thumbnail
- * * `clip` - Clip
- * * `chapter` - Chapter
- */
- export type ReplayObservationMediaKindEnum = typeof ReplayObservationMediaKindEnum[keyof typeof ReplayObservationMediaKindEnum];
-
-
- export const ReplayObservationMediaKindEnum = {
- Thumbnail: 'thumbnail',
- Clip: 'clip',
- Chapter: 'chapter',
- } as const;
-
- /**
- * One thumbnail or clip illustrating an observation.
- */
- export interface ReplayObservationMedia {
- /** Id of this media entry. */
- readonly id: string;
- /** `thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one summary chapter, `clip` for a short video.
- *
- * * `thumbnail` - Thumbnail
- * * `clip` - Clip
- * * `chapter` - Chapter */
- readonly kind: ReplayObservationMediaKindEnum;
- /** Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`. */
- readonly position: number;
- /** Export asset holding the bytes; fetch it from the export content endpoint. */
- readonly asset_id: number;
- /**
- * One sentence saying what the clip shows. Null for thumbnails.
- * @nullable
- */
- readonly description: string | null;
- /** Where this media starts in the analysis video, in milliseconds. */
- readonly video_start_ms: number;
- /**
- * Where a clip ends in the analysis video, in milliseconds. Null for thumbnails.
- * @nullable
- */
- readonly video_end_ms: number | null;
- }
-
- export interface ReplayObservation {
- readonly id: string;
- /** The scanner that produced this observation. */
- readonly scanner_id: string;
- /** Where the producing scanner came from. `configured` scanners are saved, named, and have a detail page; `inline` ones are throwaways minted for a one-off scan and are not addressable, so callers must not link to them.
- *
- * * `configured` - Configured
- * * `inline` - Inline */
- readonly scanner_origin: ScannerOriginEnum;
- /** Session recording id this scanner was applied to. */
- readonly session_id: string;
- /** Observation status (pending, running, succeeded, failed, ineligible).
- *
- * * `pending` - Pending
- * * `running` - Running
- * * `succeeded` - Succeeded
- * * `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 / 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;
- /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */
- readonly scanner_snapshot: ScannerSnapshot | null;
- /** Result data persisted on success; null until the observation succeeds. */
- readonly scanner_result: ScannerResult | null;
- /**
- * The scanner's prompt condensed into the one question it answers about a session. Null when the prompt has changed since this observation was scanned, since the question then describes a different prompt; read `scanner_snapshot.scanner_config.prompt` instead.
- * @nullable
- */
- readonly prompt_question: string | null;
- /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
- *
- * * `schedule` - Schedule
- * * `on_demand` - On demand
- * * `retry` - Retry
- * * `backfill` - Backfill */
- readonly triggered_by: ObservationTriggerEnum;
- /** User who triggered an on-demand observation; null for scheduled observations. */
- readonly triggered_by_user: UserBasic | null;
- /**
- * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.
- * @nullable
- */
- readonly backfill_id: string | null;
- /**
- * Distinct id of the person in the recorded session (the subject being watched); null if unknown.
- * @nullable
- */
- readonly distinct_id: string | null;
- /**
- * Email of the person in the recorded session (the subject being watched, not the user who triggered the observation), captured at scan time. Null when the session had no identified person.
- * @nullable
- */
- readonly recording_subject_email: string | null;
- /**
- * Id of the preceding sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the start of the set.
- * @nullable
- */
- readonly previous_observation_id: string | null;
- /**
- * Id of the following sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the end of the set.
- * @nullable
- */
- readonly next_observation_id: string | null;
- /** The team's shared label on this observation (correct/incorrect + feedback), or null if unlabeled. */
- readonly label: ReplayObservationLabel | null;
- /** Whether the calling user has opened this observation. */
- readonly viewed: boolean;
- /** Thumbnails and clips illustrating this observation, in order. Empty until the media render finishes. */
- readonly media: readonly ReplayObservationMedia[];
- /** One line of plain text saying what the scanner found: its verdict, score, tags or title, then its own words, with markdown flattened and the text truncated. An observation that produced no result carries the reason instead, and one still in flight carries an empty string. Read this in place of `scanner_result` when you scan a list of observations. */
- readonly summary_line: string;
- /** @nullable */
- started_at?: string | null;
- /** @nullable */
- completed_at?: string | null;
- readonly created_at: string;
- }
-
export interface ObservationSearchResult {
/** The matching observation. */
observation: ReplayObservation;
@@ -123382,6 +123458,10 @@ export namespace Schemas {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string;
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string;
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -123604,6 +123684,10 @@ export namespace Schemas {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string;
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string;
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -123659,6 +123743,10 @@ export namespace Schemas {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string;
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string;
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -123714,6 +123802,10 @@ export namespace Schemas {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string;
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string;
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
@@ -123777,6 +123869,10 @@ export namespace Schemas {
* Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
*/
triggered_by?: string;
+ /**
+ * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
+ */
+ variant?: string;
/**
* Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
*/
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 20f23bdd8b09..7f441dec99a7 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -503,6 +503,12 @@ export const VisionObservationsRetrieveQueryParams = () => zod.object({
.describe(
'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'
),
+ variant: zod
+ .string()
+ .optional()
+ .describe(
+ 'Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.'
+ ),
verdict: zod
.string()
.optional()
@@ -1423,6 +1429,12 @@ export const VisionScannersObservationsListQueryParams = () => zod.object({
.describe(
'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'
),
+ variant: zod
+ .string()
+ .optional()
+ .describe(
+ 'Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.'
+ ),
verdict: zod
.string()
.optional()
@@ -1501,6 +1513,12 @@ export const VisionScannersObservationsRetrieveQueryParams = () => zod.object({
.describe(
'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'
),
+ variant: zod
+ .string()
+ .optional()
+ .describe(
+ 'Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.'
+ ),
verdict: zod
.string()
.optional()
@@ -1578,6 +1596,12 @@ export const VisionScannersObservationsStatsRetrieveQueryParams = () => zod.obje
.describe(
'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'
),
+ variant: zod
+ .string()
+ .optional()
+ .describe(
+ 'Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.'
+ ),
verdict: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 29a74cc81048..e003c66de216 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -389,6 +389,7 @@ const visionObservationsGet = (): ToolBase<
status: params.status,
tags: params.tags,
triggered_by: params.triggered_by,
+ variant: params.variant,
verdict: params.verdict,
},
})
@@ -550,6 +551,7 @@ const visionObservationsRetrieve = (): ToolBase<
status: params.status,
tags: params.tags,
triggered_by: params.triggered_by,
+ variant: params.variant,
verdict: params.verdict,
},
})
@@ -1352,6 +1354,7 @@ const visionScannersObservationsGet = (): ToolBase<
status: params.status,
tags: params.tags,
triggered_by: params.triggered_by,
+ variant: params.variant,
verdict: params.verdict,
},
})
@@ -1397,6 +1400,7 @@ const visionScannersObservationsList = (): ToolBase<
status: params.status,
tags: params.tags,
triggered_by: params.triggered_by,
+ variant: params.variant,
verdict: params.verdict,
},
})
@@ -1454,6 +1458,7 @@ const visionScannersObservationsStats = (): ToolBase<
status: params.status,
tags: params.tags,
triggered_by: params.triggered_by,
+ variant: params.variant,
verdict: params.verdict,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-get.json
index 80590cdef76a..00154a9ce77d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-get.json
@@ -53,6 +53,10 @@
"description": "Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",
"type": "string"
},
+ "variant": {
+ "description": "Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.",
+ "type": "string"
+ },
"verdict": {
"description": "Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-retrieve.json
index 80590cdef76a..00154a9ce77d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-retrieve.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-retrieve.json
@@ -53,6 +53,10 @@
"description": "Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",
"type": "string"
},
+ "variant": {
+ "description": "Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.",
+ "type": "string"
+ },
"verdict": {
"description": "Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-get.json
index 03d70e6af99d..024d0b256fad 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-get.json
@@ -56,6 +56,10 @@
"description": "Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",
"type": "string"
},
+ "variant": {
+ "description": "Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.",
+ "type": "string"
+ },
"verdict": {
"description": "Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-list.json
index 6c50db9f30fe..000516af4168 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-list.json
@@ -60,6 +60,10 @@
"description": "Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",
"type": "string"
},
+ "variant": {
+ "description": "Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.",
+ "type": "string"
+ },
"verdict": {
"description": "Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-stats.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-stats.json
index e781b125ad6a..a792ea14d3ab 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-stats.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-observations-stats.json
@@ -52,6 +52,10 @@
"description": "Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",
"type": "string"
},
+ "variant": {
+ "description": "Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.",
+ "type": "string"
+ },
"verdict": {
"description": "Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).",
"type": "string"