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): compare experiment variants with a variant analysis scout (#111136)

Kim Svatos Duganc71167b7eb64
diff --git a/products/replay_vision/backend/api/scanner_scouts.py b/products/replay_vision/backend/api/scanner_scouts.py
index a7b46362f0de..19754f553f0f 100644
--- a/products/replay_vision/backend/api/scanner_scouts.py
+++ b/products/replay_vision/backend/api/scanner_scouts.py
@@ -2,15 +2,18 @@ from typing import Any, cast
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
-from rest_framework.exceptions import PermissionDenied
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
from posthog.models import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.scanner_access import scanner_for_recording_derived_read
from products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT
+from products.replay_vision.backend.variant_analysis import VARIANT_ANALYSIS_TAG, variant_analysis_config
from products.signals.backend.facade import api as signals_facade
from products.signals.backend.scout_harness.serializers import SignalScoutConfigSerializer, SignalScoutCreateSerializer
from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission, scout_config_context
@@ -24,6 +27,14 @@ class ScannerScoutCreateSerializer(SignalScoutCreateSerializer):
bars as one created through the generic endpoint.
"""
+ variant_analysis = serializers.BooleanField(
+ default=False,
+ help_text=(
+ "Make this the experiment scanner's variant analysis scout: its runs record a structured comparison "
+ "of the variants, which the scanner's variants readout shows. Experiment scanners only."
+ ),
+ )
+
def get_fields(self) -> dict[str, serializers.Field]:
fields = super().get_fields()
# Bundling files with a prompt is the generic endpoint's affordance; this one creates a scout
@@ -98,6 +109,27 @@ class ScannerScoutViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
payload = ScannerScoutCreateSerializer(data=request.data, context=serializer_context)
payload.is_valid(raise_exception=True)
validated = payload.validated_data
+ config_options = dict(validated.get("config", {}))
+ if validated["variant_analysis"]:
+ if scanner.scanner_type != ScannerType.EXPERIMENT:
+ raise ValidationError({"variant_analysis": "Variant analysis needs an experiment scanner."})
+ existing = signals_facade.scouts_for_source(
+ scanner.team_id, SCOUT_SOURCE_PRODUCT, str(scanner.id), tag=VARIANT_ANALYSIS_TAG
+ )
+ # One per scanner, paused ones included: the variants readout shows one scout's records.
+ # The same name again adopts that scout (a retried create), so it isn't a second one.
+ if any(scout.skill_name != validated.get("name") for scout in existing):
+ raise ValidationError(
+ {
+ "variant_analysis": (
+ "This scanner already has a variant analysis scout. "
+ "Turn that one back on or edit it instead."
+ )
+ }
+ )
+ # Attached here, not taken from the body, so the record the readout reads always has the
+ # shape it expects.
+ config_options = variant_analysis_config(config_options)
result = signals_facade.create_scout_for_source(
team=canonical_team,
@@ -107,13 +139,25 @@ class ScannerScoutViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
description=validated["description"],
body=validated["body"],
files=[],
- config_options=validated.get("config", {}),
+ config_options=config_options,
request=request,
serializer_context=serializer_context,
# From the URL the caller's access was checked against, never from the body.
source_product=SCOUT_SOURCE_PRODUCT,
source_id=str(scanner.id),
)
+ report_user_action(
+ cast(User, request.user),
+ "replay_vision_scanner_scout_created",
+ {
+ "scanner_id": str(scanner.id),
+ "scanner_type": scanner.scanner_type,
+ "variant_analysis": validated["variant_analysis"],
+ "created": result.created,
+ },
+ team=self.team,
+ request=request,
+ )
return Response(
ScannerScoutCreateResponseSerializer(
{"created": result.created, "config": result.config},
diff --git a/products/replay_vision/backend/api/variants.py b/products/replay_vision/backend/api/variants.py
index 61afce133ebd..2bd41011f274 100644
--- a/products/replay_vision/backend/api/variants.py
+++ b/products/replay_vision/backend/api/variants.py
@@ -12,6 +12,7 @@ from products.replay_vision.backend.api.observations import ReplayObservationSer
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
+from products.signals.backend.scout_harness.views import ScoutCanonicalTeamAccessPermission
class VariantsExperimentSerializer(serializers.Serializer):
@@ -41,6 +42,44 @@ class VariantsWindowSerializer(serializers.Serializer):
)
+class VariantAnalysisLineSerializer(serializers.Serializer):
+ theme = serializers.CharField(help_text="A short label for the theme, shared across variants.")
+ statement = serializers.CharField(help_text="How the theme shows up for this variant.")
+ count = serializers.IntegerField(
+ help_text="How many of this variant's summaries the analysis read show the theme, as the scout counted them."
+ )
+ example_observation_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ help_text="Observations of this variant the scout cited for the theme. Ids it can't back are dropped.",
+ )
+
+
+class VariantAnalysisDifferenceSerializer(serializers.Serializer):
+ theme = serializers.CharField(help_text="The theme the difference rests on.")
+ statement = serializers.CharField(help_text="What differs between the variants.")
+ counts = serializers.DictField(
+ child=serializers.IntegerField(),
+ help_text="Summaries the analysis read that show the theme, per variant key, as the scout counted them.",
+ )
+
+
+class VariantsAnalysisStateSerializer(serializers.Serializer):
+ scout_config_id = serializers.CharField(help_text="The variant analysis scout's config id.")
+ scout_enabled = serializers.BooleanField(help_text="Whether the scout runs on its schedule.")
+ recorded_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the run behind the newest analysis started; null before its first run."
+ )
+ scanner_version = serializers.IntegerField(
+ allow_null=True, help_text="The scanner version the newest analysis covered."
+ )
+ current = serializers.BooleanField(
+ help_text=(
+ "Whether the newest analysis covers the scanner's current version. When false, digests and "
+ "differences are null until the scout's next run."
+ )
+ )
+
+
class VariantReadoutSerializer(serializers.Serializer):
key = serializers.CharField(help_text="The variant key.")
observations = serializers.IntegerField(help_text="Succeeded observations attributed to this variant.")
@@ -55,6 +94,18 @@ class VariantReadoutSerializer(serializers.Serializer):
"counts against it: balanced sampling gives a small variant a higher rate."
),
)
+ analysis_observations = serializers.IntegerField(
+ allow_null=True,
+ help_text=(
+ "Summaries of this variant the analysis read: the denominator of its digest and difference counts. "
+ "Null without a current analysis."
+ ),
+ )
+ digest = VariantAnalysisLineSerializer(
+ many=True,
+ allow_null=True,
+ help_text="This variant's most notable themes from the variant analysis. Null without a current analysis.",
+ )
latest_observations = ReplayObservationSerializer(
many=True, help_text="This variant's most recent observations, newest first."
)
@@ -68,12 +119,24 @@ class ExperimentVariantsReadoutSerializer(serializers.Serializer):
variants = VariantReadoutSerializer(
many=True, help_text="One entry per watched variant, plus any variant still holding observations."
)
+ differences = VariantAnalysisDifferenceSerializer(
+ many=True,
+ allow_null=True,
+ help_text="What differs between variants, from the variant analysis. Null without a current analysis.",
+ )
unattributed_count = serializers.IntegerField(help_text="Succeeded observations with no attributed variant.")
+ analysis = VariantsAnalysisStateSerializer(
+ allow_null=True, help_text="The scanner's variant analysis scout and its newest run; null when none is set up."
+ )
class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"""What users in each variant of an experiment scanner's experiment do, side by side."""
+ # The variant analysis is read from the scout's canonical-team records, so access is checked
+ # against that team and not just the environment in the URL.
+ # Appended to the standard stack by `TeamAndOrgViewSetMixin.get_permissions`.
+ permission_classes = [ScoutCanonicalTeamAccessPermission]
scope_object = "replay_scanner"
required_scopes = ["replay_scanner:read", "session_recording:read"]
@@ -84,7 +147,8 @@ class ReplayScannerVariantsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
},
description=(
"Per-variant readout for an experiment scanner: observation counts, distinct people, median "
- "session length, sampling rate and latest observations per variant, read live."
+ "session length, sampling rate and latest observations per variant, read live, plus the digests "
+ "and differences of the scanner's variant analysis scout."
),
)
def list(self, request: Request, **kwargs: Any) -> Response:
diff --git a/products/replay_vision/backend/experiment_variants.py b/products/replay_vision/backend/experiment_variants.py
index 3665ef1e7896..d65254e9c54b 100644
--- a/products/replay_vision/backend/experiment_variants.py
+++ b/products/replay_vision/backend/experiment_variants.py
@@ -1,6 +1,7 @@
-"""The per-variant readout of an experiment scanner, counted from its observations.
+"""The per-variant readout of an experiment scanner: counts from its observations, prose from its scout.
-Counts are read from Postgres on every call, so they never lag the observations.
+Counts are read from Postgres on every call, so they never lag the observations. The digests and
+differences come from the scanner's variant analysis scout, when one is set up (see `variant_analysis`).
"""
from datetime import datetime
@@ -20,7 +21,12 @@ from products.replay_vision.backend.models.replay_observation import (
hydrate_for_serialization,
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
-from products.replay_vision.backend.scanner_access import accessible_observations
+from products.replay_vision.backend.scanner_access import accessible_observations, is_uuid
+from products.replay_vision.backend.variant_analysis import (
+ VariantAnalysisDifference,
+ VariantAnalysisLine,
+ variant_analysis_for_scanner,
+)
if TYPE_CHECKING:
from products.experiments.backend.facade.contracts import ExperimentPromptContext, ExperimentStatus
@@ -63,15 +69,29 @@ class VariantReadout:
distinct_people: int
median_session_duration_s: float | None
sampling_rate: float | None
+ # Summaries of this variant the analysis read: the denominator of its digest and difference counts.
+ analysis_observations: int | None
+ digest: tuple[VariantAnalysisLine, ...] | None
latest_observations: tuple[ReplayObservation, ...]
+@frozen
+class VariantsAnalysisState:
+ scout_config_id: str
+ scout_enabled: bool
+ recorded_at: datetime | None
+ scanner_version: int | None
+ current: bool
+
+
@frozen
class ExperimentVariantsReadout:
experiment: VariantsExperiment | None
window: VariantsWindow
variants: tuple[VariantReadout, ...]
+ differences: tuple[VariantAnalysisDifference, ...] | None
unattributed_count: int
+ analysis: VariantsAnalysisState | None
def experiment_variants_readout(
@@ -116,6 +136,13 @@ def experiment_variants_readout(
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)
+ def resolve_citations(ids: set[str]) -> dict[str, str]:
+ valid = [observation_id for observation_id in ids if is_uuid(observation_id)]
+ return {str(pk): variant for pk, variant in attributed.filter(id__in=valid).values_list("id", "variant")}
+
+ analysis = variant_analysis_for_scanner(scanner, resolve_citations=resolve_citations)
+ shown = analysis if analysis is not None and analysis.current else None
+
variants = []
for key in keys:
row = stats.get(key)
@@ -131,6 +158,8 @@ def experiment_variants_readout(
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,
+ analysis_observations=shown.observations_read.get(key, 0) if shown is not None else None,
+ digest=shown.lines.get(key, ()) if shown is not None else None,
latest_observations=latest,
)
)
@@ -143,7 +172,19 @@ def experiment_variants_readout(
last_observation_at=window["last"],
),
variants=tuple(variants),
+ differences=shown.differences if shown is not None else None,
unattributed_count=window["unattributed"],
+ analysis=(
+ VariantsAnalysisState(
+ scout_config_id=analysis.scout_config_id,
+ scout_enabled=analysis.scout_enabled,
+ recorded_at=analysis.recorded_at,
+ scanner_version=analysis.scanner_version,
+ current=analysis.current,
+ )
+ if analysis is not None
+ else None
+ ),
)
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 917d9e08b220..8c5c804ec324 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -64,6 +64,7 @@ from products.replay_vision.backend.temporal.sweep_types import (
FindScannerCandidatesInputs,
FindScannerCandidatesOutput,
)
+from products.replay_vision.backend.variant_analysis import pause_variant_analysis_scouts
@frozen
@@ -113,6 +114,21 @@ def _experiment_lifecycle_block(scanner: ReplayScanner) -> _LifecycleBlock | Non
return None
+def _stop_variant_analysis(scanner: ReplayScanner) -> bool:
+ """Pause the scanner's variant analysis scouts and return whether that worked.
+
+ A failure here leaves the scout running one more day, which must never fail the tick.
+ """
+ try:
+ pause_variant_analysis_scouts(scanner)
+ except Exception:
+ activity.logger.exception(
+ "replay_vision.sweep.variant_analysis_pause_failed", extra={"scanner_id": str(scanner.id)}
+ )
+ return False
+ return True
+
+
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
@@ -146,7 +162,12 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
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.
+ # the schedule and the owner sees the scanner off instead of silently idle. Its scout is
+ # paused first: a disabled scanner has no schedule left to retry a failed pause, so a
+ # failure keeps the scanner on and the next tick tries again.
+ if not _stop_variant_analysis(scanner):
+ record_sweep_outcome("experiment_deleted_pause_failed")
+ return FindScannerCandidatesOutput(candidates=[], saturated=False)
# 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"])
@@ -160,6 +181,11 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
# 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.
+ if lifecycle_block.kind != "paused":
+ # A pause resumes, and the scout can sit it out. An ended or archived experiment's
+ # data stops changing, so its scout would only re-read the same summaries on the
+ # customer's bill.
+ _stop_variant_analysis(scanner)
record_sweep_outcome("experiment_over")
horizon = initial_watermark()
return FindScannerCandidatesOutput(
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 14cf5135a4dd..7b91d179829b 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -118,7 +118,8 @@ REPLAY_VISION_SWEEP_OUTCOMES = Counter(
"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), 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 "
+ "because its experiment was deleted (experiment_deleted), kept on because the deleted experiment's "
+ "scout could not be paused (experiment_deleted_pause_failed), 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/tests/test_experiment_variants.py b/products/replay_vision/backend/tests/test_experiment_variants.py
index 4f693e25feb4..25b78da1eb98 100644
--- a/products/replay_vision/backend/tests/test_experiment_variants.py
+++ b/products/replay_vision/backend/tests/test_experiment_variants.py
@@ -1,6 +1,9 @@
-from datetime import timedelta
+import uuid
+from datetime import UTC, datetime, timedelta
from typing import Any
+from unittest.mock import patch
+
from django.utils import timezone
from parameterized import parameterized
@@ -14,8 +17,11 @@ from products.replay_vision.backend.models.replay_observation import (
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
+from products.signals.backend.facade.api import ScoutStructuredRecord, SourceScout
_UNSET = object()
+_SIGNALS = "products.replay_vision.backend.variant_analysis.signals_facade"
+_RECORDED_AT = datetime(2026, 9, 1, tzinfo=UTC)
class TestExperimentVariants(_VisionAPITestCase):
@@ -91,6 +97,108 @@ class TestExperimentVariants(_VisionAPITestCase):
assert body["window"]["total_observations"] == 6
assert body["experiment"]["id"] == self.experiment.id
assert body["experiment"]["current_day"] >= 1
+ assert body["analysis"] is None and body["differences"] is None
+
+ @parameterized.expand([("current_version", True), ("older_version", False)])
+ def test_readout_shows_the_variant_analysis_for_the_current_version(self, _name: str, current: bool) -> None:
+ control = self._observation("control")
+ test = self._observation("test")
+ payload = {
+ # A prompt edit bumps the version, and a record from before it compared differently focused summaries.
+ "scanner_version": self.scanner.scanner_version if current else self.scanner.scanner_version - 1,
+ "observations_read": {"control": 30, "test": 28},
+ "variants": {
+ # The scout cites ids itself, so one from another variant or one that isn't an observation of
+ # this scanner must not be shown as evidence.
+ "control": [
+ {
+ "theme": "Hesitates at checkout",
+ "statement": "Waits on the payment step.",
+ "count": 9,
+ "example_observation_ids": [str(control.id), str(test.id)],
+ }
+ ],
+ "test": [
+ {
+ "theme": "Hesitates at checkout",
+ "statement": "Rarely waits.",
+ "count": 2,
+ "example_observation_ids": [str(uuid.uuid4()), "not-an-id"],
+ }
+ ],
+ },
+ "differences": [
+ {
+ "theme": "Hesitates at checkout",
+ "statement": "Control waits more.",
+ "counts": {"control": 9, "test": 2},
+ }
+ ],
+ }
+ scout = SourceScout(config_id="config-1", skill_name="signals-scout-x", enabled=True, created_at=_RECORDED_AT)
+ record = ScoutStructuredRecord(
+ payload=payload, recorded_at=_RECORDED_AT, skill_name="signals-scout-x", run_id="r"
+ )
+
+ with (
+ patch(f"{_SIGNALS}.scouts_for_source", return_value=[scout]),
+ patch(f"{_SIGNALS}.latest_structured_output_for_source", return_value=record),
+ ):
+ body = self.client.get(self.variants_url).json()
+
+ by_key = {v["key"]: v for v in body["variants"]}
+ assert body["analysis"]["scout_config_id"] == "config-1"
+ assert body["analysis"]["current"] is current
+ if not current:
+ assert body["differences"] is None
+ assert all(v["digest"] is None and v["analysis_observations"] is None for v in body["variants"])
+ return
+ assert by_key["control"]["digest"] == [
+ {
+ "theme": "Hesitates at checkout",
+ "statement": "Waits on the payment step.",
+ "count": 9,
+ "example_observation_ids": [str(control.id)],
+ }
+ ]
+ assert by_key["test"]["digest"][0]["example_observation_ids"] == []
+ assert by_key["control"]["analysis_observations"] == 30
+ assert by_key["beta"]["digest"] == [] and by_key["beta"]["analysis_observations"] == 0
+ assert body["differences"] == payload["differences"]
+
+ def test_a_child_scoped_api_key_cannot_read_the_parent_teams_analysis(self) -> None:
+ # The variant analysis is read from the scout's records on the parent team, so a key
+ # scoped only to a child environment must not read it through the child's scanner.
+ from posthog.models.personal_api_key import PersonalAPIKey
+ from posthog.models.team import Team
+ from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ experiment = create_experiment(env, "env-flag", launched=True, variants=["control", "test"])
+ scanner = self._create_scanner(
+ name="child-experiment-scanner",
+ team=env,
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": experiment.id},
+ )
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="child-scoped",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["replay_scanner:read", "session_recording:read"],
+ scoped_teams=[env.id],
+ )
+ self.client.logout()
+
+ with patch(f"{_SIGNALS}.latest_structured_output_for_source") as read_analysis:
+ response = self.client.get(
+ f"/api/projects/{env.id}/vision/scanners/{scanner.id}/variants/",
+ HTTP_AUTHORIZATION=f"Bearer {raw}",
+ )
+
+ assert response.status_code == 403, response.content
+ assert not read_analysis.called
def test_a_non_experiment_scanner_has_no_variants(self) -> None:
monitor = self._create_scanner(name="monitor")
diff --git a/products/replay_vision/backend/tests/test_scanner_scouts_api.py b/products/replay_vision/backend/tests/test_scanner_scouts_api.py
index 5d5410e1ef5d..4459e1719527 100644
--- a/products/replay_vision/backend/tests/test_scanner_scouts_api.py
+++ b/products/replay_vision/backend/tests/test_scanner_scouts_api.py
@@ -6,10 +6,18 @@ from posthog.models.integration import Integration
from posthog.models.scoping import team_scope
from posthog.models.team import Team
+from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT
+from products.replay_vision.backend.tests.helpers import create_experiment
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
+from products.replay_vision.backend.variant_analysis import (
+ VARIANT_ANALYSIS_SCHEMA,
+ VARIANT_ANALYSIS_TAG,
+ pause_variant_analysis_scouts,
+)
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.model_selection import scout_model_pin_catalog
+from products.signals.backend.scout_harness.tools.structured_output import validate_structured_output_schema
class TestScannerScoutCreate(_VisionAPITestCase):
@@ -37,6 +45,57 @@ class TestScannerScoutCreate(_VisionAPITestCase):
assert config.source_product == SCOUT_SOURCE_PRODUCT
assert config.source_id == str(self.scanner.id)
+ def test_a_variant_analysis_scout_gets_the_record_schema_and_is_the_one_paused(self) -> None:
+ experiment = create_experiment(self.team, "checkout-flag", launched=True, variants=["control", "test"])
+ scanner = self._create_scanner(
+ name="experiment-scanner",
+ scanner_type=ScannerType.EXPERIMENT,
+ scanner_config={"prompt": "p", "experiment_id": experiment.id},
+ )
+ url = self._scouts_url(str(scanner.id))
+ analysis = self.client.post(
+ url, data=self._payload(name="signals-scout-variant-analysis", variant_analysis=True), format="json"
+ )
+ digest = self.client.post(url, data=self._payload(), format="json")
+ assert analysis.status_code == 201, analysis.json()
+ assert digest.status_code == 201, digest.json()
+
+ with team_scope(self.team.id):
+ config = SignalScoutConfig.objects.get(skill_name="signals-scout-variant-analysis")
+ # The readout reads only records of this shape, and Signals refuses a schema it can't compile
+ # when the scout first records.
+ assert config.structured_output_schema == VARIANT_ANALYSIS_SCHEMA
+ validate_structured_output_schema(config.structured_output_schema)
+ assert VARIANT_ANALYSIS_TAG in config.tag_list
+
+ # A retried create adopts the same scout, but a second one would split the readout's records.
+ retry = self.client.post(
+ url, data=self._payload(name="signals-scout-variant-analysis", variant_analysis=True), format="json"
+ )
+ assert retry.status_code == 200, retry.json()
+
+ assert pause_variant_analysis_scouts(scanner) == 1
+ with team_scope(self.team.id):
+ enabled = dict(
+ SignalScoutConfig.objects.filter(source_id=str(scanner.id)).values_list("skill_name", "enabled")
+ )
+ assert enabled == {"signals-scout-variant-analysis": False, "signals-scout-daily-digest": True}
+
+ # Paused still counts: the way back is to turn it on, not to add another.
+ second = self.client.post(
+ url, data=self._payload(name="signals-scout-variant-analysis-2", variant_analysis=True), format="json"
+ )
+ assert second.status_code == 400, second.json()
+ assert second.json()["attr"] == "variant_analysis"
+
+ def test_variant_analysis_needs_an_experiment_scanner(self) -> None:
+ response = self.client.post(
+ self._scouts_url(str(self.scanner.id)), data=self._payload(variant_analysis=True), format="json"
+ )
+ assert response.status_code == 400, response.json()
+ with team_scope(self.team.id):
+ assert not SignalScoutConfig.objects.filter(source_id=str(self.scanner.id)).exists()
+
def test_a_scout_can_be_created_with_a_slack_destination(self) -> None:
# The create modal offers a Slack channel, so the destination arrives on the create call
# rather than a follow-up PATCH. Validating it needs the project and the request in the
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 3efd8faeba99..39ab4a345d3b 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -213,13 +213,19 @@ class TestFindScannerCandidatesActivity:
experiment.deleted = True
experiment.save()
- with _patched_queries() as (fast_query, deep_query):
+ with (
+ _patched_queries() as (fast_query, deep_query),
+ patch(f"{_ACTIVITY}.pause_variant_analysis_scouts") as pause_scouts,
+ ):
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
+ # Once the data stops changing, the variant analysis scout would only re-read it on the
+ # customer's bill. A pause resumes, so its scout sits the pause out.
+ assert pause_scouts.called is (state != "paused")
scanner.refresh_from_db()
assert scanner.enabled is (state != "deleted")
if state != "deleted":
@@ -228,6 +234,35 @@ class TestFindScannerCandidatesActivity:
assert abs(result.swept_through - settled_now) < dt.timedelta(minutes=1)
assert result.deep_swept_through == result.swept_through
+ def test_a_deleted_experiment_keeps_its_scanner_on_until_the_scout_is_paused(self) -> None:
+ # A disabled scanner has no schedule left to retry the pause, and the scout would keep
+ # running on the customer's bill. So the scanner stays on until a later tick pauses it.
+ scanner = _make_scanner(scanner_type=ScannerType.EXPERIMENT)
+ experiment = create_experiment(scanner.team, "deleted-flag", launched=True, variants=["control", "test"])
+ scanner.scanner_config = {"prompt": "p", "experiment_id": experiment.id}
+ scanner.save()
+ experiment.deleted = True
+ experiment.save()
+ inputs = FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+
+ with (
+ _patched_queries() as (fast_query, deep_query),
+ patch(f"{_ACTIVITY}.pause_variant_analysis_scouts", side_effect=RuntimeError("signals down")),
+ ):
+ result = find_scanner_candidates_activity(inputs)
+
+ assert result.candidates == []
+ assert not fast_query.called and not deep_query.called
+ scanner.refresh_from_db()
+ assert scanner.enabled is True
+
+ with _patched_queries(), patch(f"{_ACTIVITY}.pause_variant_analysis_scouts") as pause_scouts:
+ find_scanner_candidates_activity(inputs)
+
+ assert pause_scouts.called
+ scanner.refresh_from_db()
+ assert scanner.enabled is False
+
@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
diff --git a/products/replay_vision/backend/variant_analysis.py b/products/replay_vision/backend/variant_analysis.py
new file mode 100644
index 000000000000..ef5ce850e6d2
--- /dev/null
+++ b/products/replay_vision/backend/variant_analysis.py
@@ -0,0 +1,255 @@
+"""The variant analysis scout: a customer-run scout that compares an experiment scanner's variants.
+
+The scout runs on the Signals scout schedule and submits one structured record per run, and the
+variants readout shows the newest one. The record's schema lives here, next to the reader, so the
+two can't drift: the scanner scout endpoint attaches it when a scout is created for this purpose.
+
+The scout writes its own counts, so they are its claims, not Replay Vision's. The readout keeps its
+live per-variant counts as the trusted numbers, shows a record only for the scanner's current
+version, and keeps only cited observations that belong to the variant they are cited for.
+"""
+
+from collections.abc import Callable
+from datetime import datetime
+from typing import Any
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+from products.replay_vision.backend.scout_source import SCOUT_SOURCE_PRODUCT
+from products.signals.backend.facade import api as signals_facade
+
+logger = structlog.get_logger(__name__)
+
+# pinned: marks the scouts the readout reads and the sweep pauses. Stored on the scout's config tags.
+VARIANT_ANALYSIS_TAG = "replay-vision-variant-analysis"
+
+MAX_VARIANTS = 8
+MAX_LINES_PER_VARIANT = 5
+MAX_DIFFERENCES = 5
+MAX_EXAMPLES_PER_LINE = 2
+_THEME_CHARS = 80
+_STATEMENT_CHARS = 240
+
+
+_COUNTS_BY_VARIANT: dict[str, Any] = {
+ "type": "object",
+ "maxProperties": MAX_VARIANTS,
+ "additionalProperties": {"type": "integer", "minimum": 0},
+}
+
+# One record per run: the whole analysis. Draft 2020-12, local refs only and no regex keywords, as the
+# Signals structured output channel requires.
+VARIANT_ANALYSIS_SCHEMA: dict[str, Any] = {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["scanner_version", "observations_read", "variants", "differences"],
+ "properties": {
+ "scanner_version": {
+ "type": "integer",
+ "minimum": 1,
+ "description": "The scanner's `scanner_version` when you read it. Read only that version's observations.",
+ },
+ "observations_read": {
+ **_COUNTS_BY_VARIANT,
+ "description": "How many summaries you read per variant key: the denominator of every count below.",
+ },
+ "variants": {
+ "type": "object",
+ "maxProperties": MAX_VARIANTS,
+ "description": "Per variant key, its most notable themes, most common first.",
+ "additionalProperties": {
+ "type": "array",
+ "maxItems": MAX_LINES_PER_VARIANT,
+ "items": {"$ref": "#/$defs/digest_line"},
+ },
+ },
+ "differences": {
+ "type": "array",
+ "maxItems": MAX_DIFFERENCES,
+ "description": "What differs between variants, most meaningful first. Empty when nothing does.",
+ "items": {"$ref": "#/$defs/difference"},
+ },
+ },
+ "$defs": {
+ "digest_line": {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["theme", "statement", "count"],
+ "properties": {
+ "theme": {"type": "string", "minLength": 1, "maxLength": _THEME_CHARS},
+ "statement": {"type": "string", "minLength": 1, "maxLength": _STATEMENT_CHARS},
+ "count": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Summaries of this variant you read that show the theme.",
+ },
+ "example_observation_ids": {
+ "type": "array",
+ "maxItems": MAX_EXAMPLES_PER_LINE,
+ "items": {"type": "string", "maxLength": 64},
+ },
+ },
+ },
+ "difference": {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["theme", "statement", "counts"],
+ "properties": {
+ "theme": {"type": "string", "minLength": 1, "maxLength": _THEME_CHARS},
+ "statement": {"type": "string", "minLength": 1, "maxLength": _STATEMENT_CHARS},
+ "counts": {**_COUNTS_BY_VARIANT, "description": "Summaries showing the theme, per variant key."},
+ },
+ },
+ },
+}
+
+
+def variant_analysis_config(config_options: dict[str, Any]) -> dict[str, Any]:
+ """The scout config options with the variant analysis schema and tag attached."""
+ tags = [*(config_options.get("tags") or []), VARIANT_ANALYSIS_TAG]
+ return {**config_options, "structured_output_schema": VARIANT_ANALYSIS_SCHEMA, "tags": sorted(set(tags))}
+
+
+@frozen
+class VariantAnalysisLine:
+ theme: str
+ statement: str
+ count: int
+ example_observation_ids: tuple[str, ...]
+
+
+@frozen
+class VariantAnalysisDifference:
+ theme: str
+ statement: str
+ counts: dict[str, int]
+
+
+@frozen
+class VariantAnalysis:
+ scout_config_id: str
+ scout_enabled: bool
+ recorded_at: datetime | None
+ scanner_version: int | None
+ # Whether the newest record covers the scanner's current version. Only a current record is shown.
+ current: bool
+ observations_read: dict[str, int]
+ lines: dict[str, tuple[VariantAnalysisLine, ...]]
+ differences: tuple[VariantAnalysisDifference, ...]
+
+
+def variant_analysis_for_scanner(
+ scanner: ReplayScanner, *, resolve_citations: Callable[[set[str]], dict[str, str]]
+) -> VariantAnalysis | None:
+ """The scanner's variant analysis, or None when no variant analysis scout exists.
+
+ `resolve_citations` takes the observation ids the record cites and returns, for each one the
+ caller may show, its variant. A cited id it leaves out (another scanner's, one the caller can't
+ read) or maps to another variant is dropped.
+ """
+ scouts = signals_facade.scouts_for_source(
+ scanner.team_id, SCOUT_SOURCE_PRODUCT, str(scanner.id), tag=VARIANT_ANALYSIS_TAG
+ )
+ if not scouts:
+ return None
+ scout = next((candidate for candidate in reversed(scouts) if candidate.enabled), scouts[-1])
+ record = signals_facade.latest_structured_output_for_source(
+ scanner.team_id, SCOUT_SOURCE_PRODUCT, str(scanner.id), tag=VARIANT_ANALYSIS_TAG
+ )
+ payload = record.payload if record is not None else {}
+ version = payload.get("scanner_version")
+ current = record is not None and version == scanner.scanner_version
+ cited_variants = resolve_citations(_cited_ids(payload.get("variants"))) if current else {}
+ return VariantAnalysis(
+ scout_config_id=scout.config_id,
+ scout_enabled=scout.enabled,
+ recorded_at=record.recorded_at if record is not None else None,
+ scanner_version=version if isinstance(version, int) else None,
+ current=current,
+ observations_read=_counts(payload.get("observations_read")) if current else {},
+ lines=_lines(payload.get("variants"), cited_variants) if current else {},
+ differences=_differences(payload.get("differences")) if current else (),
+ )
+
+
+def pause_variant_analysis_scouts(scanner: ReplayScanner) -> int:
+ """Turn off the scanner's enabled variant analysis scouts and return how many were turned off.
+
+ Called once the scanner has stopped for good, so the scout stops re-reading unchanged data on the
+ customer's bill. It is not turned back on by a relaunch: the person does that.
+ """
+ paused = 0
+ for scout in signals_facade.scouts_for_source(
+ scanner.team_id, SCOUT_SOURCE_PRODUCT, str(scanner.id), tag=VARIANT_ANALYSIS_TAG
+ ):
+ if scout.enabled and signals_facade.update_scout_for_source(
+ scanner.team_id, SCOUT_SOURCE_PRODUCT, scout.config_id, enabled=False
+ ):
+ paused += 1
+ if paused:
+ logger.info("replay_vision.variant_analysis.scouts_paused", scanner_id=str(scanner.id), paused=paused)
+ return paused
+
+
+def _cited_ids(raw: Any) -> set[str]:
+ if not isinstance(raw, dict):
+ return set()
+ return {
+ str(observation_id)
+ for items in raw.values()
+ if isinstance(items, list)
+ for item in items
+ if isinstance(item, dict) and isinstance(item.get("example_observation_ids"), list)
+ for observation_id in item["example_observation_ids"]
+ }
+
+
+def _counts(raw: Any) -> dict[str, int]:
+ if not isinstance(raw, dict):
+ return {}
+ return {str(key): value for key, value in raw.items() if isinstance(value, int) and value >= 0}
+
+
+def _lines(raw: Any, cited_variants: dict[str, str]) -> dict[str, tuple[VariantAnalysisLine, ...]]:
+ if not isinstance(raw, dict):
+ return {}
+ lines: dict[str, tuple[VariantAnalysisLine, ...]] = {}
+ for variant, items in raw.items():
+ if not isinstance(items, list):
+ continue
+ lines[str(variant)] = tuple(
+ VariantAnalysisLine(
+ theme=str(item["theme"])[:_THEME_CHARS],
+ statement=str(item["statement"])[:_STATEMENT_CHARS],
+ count=item["count"],
+ example_observation_ids=tuple(
+ str(observation_id)
+ for observation_id in (item.get("example_observation_ids") or [])[:MAX_EXAMPLES_PER_LINE]
+ if cited_variants.get(str(observation_id)) == str(variant)
+ ),
+ )
+ for item in items[:MAX_LINES_PER_VARIANT]
+ if isinstance(item, dict)
+ and isinstance(item.get("theme"), str)
+ and isinstance(item.get("statement"), str)
+ and isinstance(item.get("count"), int)
+ )
+ return lines
+
+
+def _differences(raw: Any) -> tuple[VariantAnalysisDifference, ...]:
+ if not isinstance(raw, list):
+ return ()
+ return tuple(
+ VariantAnalysisDifference(
+ theme=str(item["theme"])[:_THEME_CHARS],
+ statement=str(item["statement"])[:_STATEMENT_CHARS],
+ counts=_counts(item.get("counts")),
+ )
+ for item in raw[:MAX_DIFFERENCES]
+ if isinstance(item, dict) and isinstance(item.get("theme"), str) and isinstance(item.get("statement"), str)
+ )
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 086bf4503361..49c07f959ea5 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1963,6 +1963,8 @@ export interface ScannerScoutCreateApi {
body: string
/** Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination. */
config?: SignalScoutConfigOptionsApi
+ /** Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only. */
+ variant_analysis?: boolean
}
/**
@@ -2247,6 +2249,17 @@ export interface VariantsWindowApi {
last_observation_at: string | null
}
+export interface VariantAnalysisLineApi {
+ /** A short label for the theme, shared across variants. */
+ theme: string
+ /** How the theme shows up for this variant. */
+ statement: string
+ /** How many of this variant's summaries the analysis read show the theme, as the scout counted them. */
+ count: number
+ /** Observations of this variant the scout cited for the theme. Ids it can't back are dropped. */
+ example_observation_ids: string[]
+}
+
export interface VariantReadoutApi {
/** The variant key. */
key: string
@@ -2264,10 +2277,53 @@ export interface VariantReadoutApi {
* @nullable
*/
sampling_rate: number | null
+ /**
+ * Summaries of this variant the analysis read: the denominator of its digest and difference counts. Null without a current analysis.
+ * @nullable
+ */
+ analysis_observations: number | null
+ /**
+ * This variant's most notable themes from the variant analysis. Null without a current analysis.
+ * @nullable
+ */
+ digest: VariantAnalysisLineApi[] | null
/** This variant's most recent observations, newest first. */
latest_observations: ReplayObservationApi[]
}
+/**
+ * Summaries the analysis read that show the theme, per variant key, as the scout counted them.
+ */
+export type VariantAnalysisDifferenceApiCounts = { [key: string]: number }
+
+export interface VariantAnalysisDifferenceApi {
+ /** The theme the difference rests on. */
+ theme: string
+ /** What differs between the variants. */
+ statement: string
+ /** Summaries the analysis read that show the theme, per variant key, as the scout counted them. */
+ counts: VariantAnalysisDifferenceApiCounts
+}
+
+export interface VariantsAnalysisStateApi {
+ /** The variant analysis scout's config id. */
+ scout_config_id: string
+ /** Whether the scout runs on its schedule. */
+ scout_enabled: boolean
+ /**
+ * When the run behind the newest analysis started; null before its first run.
+ * @nullable
+ */
+ recorded_at: string | null
+ /**
+ * The scanner version the newest analysis covered.
+ * @nullable
+ */
+ scanner_version: number | null
+ /** Whether the newest analysis covers the scanner's current version. When false, digests and differences are null until the scout's next run. */
+ current: boolean
+}
+
export interface ExperimentVariantsReadoutApi {
/** The watched experiment; null if it was deleted. */
experiment: VariantsExperimentApi | null
@@ -2275,8 +2331,15 @@ export interface ExperimentVariantsReadoutApi {
window: VariantsWindowApi
/** One entry per watched variant, plus any variant still holding observations. */
variants: VariantReadoutApi[]
+ /**
+ * What differs between variants, from the variant analysis. Null without a current analysis.
+ * @nullable
+ */
+ differences: VariantAnalysisDifferenceApi[] | null
/** Succeeded observations with no attributed variant. */
unattributed_count: number
+ /** The scanner's variant analysis scout and its newest run; null when none is set up. */
+ analysis: VariantsAnalysisStateApi | null
}
/**
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 68a102609255..b5bf0531dcc9 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -1375,7 +1375,7 @@ export const getVisionScannersVariantsListUrl = (projectId: string, scannerId: s
}
/**
- * Per-variant readout for an experiment scanner: observation counts, distinct people, median session length, sampling rate and latest observations per variant, read live.
+ * Per-variant readout for an experiment scanner: observation counts, distinct people, median session length, sampling rate and latest observations per variant, read live, plus the digests and differences of the scanner's variant analysis scout.
*/
export const visionScannersVariantsList = async (
projectId: string,
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index f2376e9b99e5..2506c26dcea2 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -962,6 +962,8 @@ export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOn
export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = true
export const visionScannersScoutsCreateBodyConfigOneRunCronScheduleMax = 100
+export const visionScannersScoutsCreateBodyVariantAnalysisDefault = false
+
export const VisionScannersScoutsCreateBody = /* @__PURE__ */ zod
.object({
display_name: zod
@@ -1144,6 +1146,12 @@ export const VisionScannersScoutsCreateBody = /* @__PURE__ */ zod
.describe(
'Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination.'
),
+ variant_analysis: zod
+ .boolean()
+ .default(visionScannersScoutsCreateBodyVariantAnalysisDefault)
+ .describe(
+ "Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only."
+ ),
})
.describe(
"A scout to stand up for this scanner. The scanner comes from the URL, never the body: it is\nwhat the caller's access is checked against, and what the scout is recorded as belonging to.\n\nInherits the Signals scout definition so a scout created here clears the same name and prompt-size\nbars as one created through the generic endpoint."
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx
index 57f1d4111632..b87078675c13 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutsTab.tsx
@@ -1,7 +1,16 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { IconCalendar, IconNotebook, IconPencil, IconPlus, IconSearch, IconTrends, IconWarning } from '@posthog/icons'
+import {
+ IconCalendar,
+ IconFlask,
+ IconNotebook,
+ IconPencil,
+ IconPlus,
+ IconSearch,
+ IconTrends,
+ IconWarning,
+} from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'
import { ProjectTimezoneHint } from 'lib/components/ScheduledRunStatus'
@@ -9,7 +18,12 @@ import { cn } from 'lib/utils/css-classes'
import { getScoutCreateDisabledReason } from '../../utils/accessControl'
import { replayScannerLogic } from '../replayScannerLogic'
-import { scannerScoutTemplates, type ScannerScoutTemplate, type ScannerScoutTemplateKey } from '../scannerScout'
+import {
+ scannerScoutTemplates,
+ variantAnalysisScout,
+ type ScannerScoutTemplate,
+ type ScannerScoutTemplateKey,
+} from '../scannerScout'
import { scannerScoutLogic } from '../scannerScoutLogic'
import { parseScoutCadence, SCOUT_FREQUENCY_OPTIONS } from '../scoutCadence'
import { ScannerScoutFormModal } from './ScannerScoutFormModal'
@@ -17,6 +31,7 @@ import { ScannerScoutReportModal } from './ScannerScoutReportModal'
import { ScannerScoutRow } from './ScannerScoutRow'
const TEMPLATE_ICONS: Record<ScannerScoutTemplateKey, JSX.Element> = {
+ 'variant-analysis': <IconFlask />,
'daily-digest': <IconCalendar />,
'root-cause': <IconSearch />,
'weekly-themes': <IconNotebook />,
@@ -35,10 +50,13 @@ function templateScheduleLabel(template: ScannerScoutTemplate): string {
function ScoutTemplateCard({
template,
disabledReason,
+ alreadySetUp,
onUse,
}: {
template: ScannerScoutTemplate
disabledReason?: string
+ /** The scanner already has the one scout this template allows, so the card opens it instead. */
+ alreadySetUp?: boolean
onUse: () => void
}): JSX.Element {
return (
@@ -62,20 +80,26 @@ function ScoutTemplateCard({
className={template.key === 'scratch' ? 'invisible' : undefined}
aria-hidden={template.key === 'scratch'}
>
- {templateScheduleLabel(template)} <ProjectTimezoneHint />
+ {alreadySetUp ? (
+ 'Already set up'
+ ) : (
+ <>
+ {templateScheduleLabel(template)} <ProjectTimezoneHint />
+ </>
+ )}
</LemonTag>
<LemonButton
- type="primary"
+ type={alreadySetUp ? 'secondary' : 'primary'}
size="xsmall"
- icon={<IconPlus />}
+ icon={alreadySetUp ? undefined : <IconPlus />}
onClick={onUse}
- disabledReason={disabledReason}
+ disabledReason={alreadySetUp ? undefined : disabledReason}
className="self-end"
data-attr={`vision-scout-template-${template.key}`}
>
{/* The scratch card seeds a skeleton rather than a ready-made scout, so
"use template" would overpromise what the button hands you. */}
- {template.key === 'scratch' ? 'Create' : 'Use template'}
+ {alreadySetUp ? 'Open scout' : template.key === 'scratch' ? 'Create' : 'Use template'}
</LemonButton>
</div>
</LemonCard>
@@ -97,7 +121,7 @@ export function ScannerScoutsTab({ scannerId }: { scannerId: string }): JSX.Elem
enrolled,
scoutConfigsFailed,
} = useValues(logic)
- const { openCreateModal, loadScoutConfigs } = useActions(logic)
+ const { openCreateModal, openScoutSettings, loadScoutConfigs } = useActions(logic)
const templates = useMemo(
() => scannerScoutTemplates(scannerId, scanner?.scanner_type, scannerName),
[scannerId, scanner?.scanner_type, scannerName]
@@ -120,6 +144,7 @@ export function ScannerScoutsTab({ scannerId }: { scannerId: string }): JSX.Elem
}
const createDisabledReason = getScoutCreateDisabledReason(scanner?.user_access_level) ?? undefined
+ const existingVariantAnalysis = variantAnalysisScout(scoutConfigsForScanner)
return (
<div className="flex flex-col gap-6">
@@ -147,14 +172,22 @@ export function ScannerScoutsTab({ scannerId }: { scannerId: string }): JSX.Elem
templates.length > 4 ? '@2xl:grid-cols-5' : '@2xl:grid-cols-4'
)}
>
- {templates.map((template) => (
- <ScoutTemplateCard
- key={template.key}
- template={template}
- disabledReason={createDisabledReason}
- onUse={() => openCreateModal(template.key)}
- />
- ))}
+ {templates.map((template) => {
+ const existing = template.key === 'variant-analysis' ? existingVariantAnalysis : undefined
+ return (
+ <ScoutTemplateCard
+ key={template.key}
+ template={template}
+ disabledReason={createDisabledReason}
+ alreadySetUp={!!existing}
+ onUse={() =>
+ existing
+ ? openScoutSettings(existing.skill_name)
+ : openCreateModal(template.key)
+ }
+ />
+ )
+ })}
</div>
</div>
</section>
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts
index 0e525b4a9940..39587ba78121 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.test.ts
@@ -125,7 +125,10 @@ describe('scannerScout', () => {
{ scannerType: 'monitor', keys: ['daily-digest', 'root-cause', 'trend-watch', 'new-issues', 'scratch'] },
// A summarizer has no outcome to explain and no metric to trend.
{ scannerType: 'summarizer', keys: ['daily-digest', 'weekly-themes', 'new-issues', 'scratch'] },
- { scannerType: 'experiment', keys: ['daily-digest', 'trend-watch', 'new-issues', 'scratch'] },
+ {
+ scannerType: 'experiment',
+ keys: ['variant-analysis', 'daily-digest', 'trend-watch', 'new-issues', 'scratch'],
+ },
// A scanner whose type hasn't loaded still gets a usable set rather than nothing.
{ scannerType: undefined, keys: ['daily-digest', 'root-cause', 'trend-watch', 'new-issues', 'scratch'] },
] as const)('offers a $scannerType scanner only the templates that fit it', ({ scannerType, keys }) => {
@@ -148,6 +151,20 @@ describe('scannerScout', () => {
expect(rootCause.body.indexOf('scanner_output_reasoning')).toBeLessThan(rootCause.body.indexOf('`events`'))
})
+ it('has variant analysis record its comparison and ask the server for the record schema', () => {
+ const experimentTemplates = scannerScoutTemplates(scannerId, 'experiment', 'Checkout test')
+ expect(experimentTemplates[0].body).toContain('scout-record-output')
+ expect(scoutBodyPlaceholders(experimentTemplates[0].body)).toEqual([])
+
+ const payload = scannerScoutCreatePayload('Checkout test', {
+ name: 'signals-scout-checkout-test-variant-analysis',
+ body: experimentTemplates[0].body,
+ cron: experimentTemplates[0].cron,
+ templateKey: 'variant-analysis',
+ })
+ expect(payload.variant_analysis).toBe(true)
+ })
+
it('writes the trend template for the one output the scanner actually emits', () => {
const trendFor = (type: 'monitor' | 'scorer' | 'classifier' | 'experiment'): ScannerScoutTemplate =>
scannerScoutTemplates(scannerId, type, 'Rage clicks').find((template) => template.key === 'trend-watch')!
@@ -199,6 +216,8 @@ describe('scannerScout', () => {
// Slack rides on the platform's own delivery, which posts the one report each run files.
expect(payload.config?.output_destinations).toEqual({})
expect(payload.config?.run_cron_schedule).toBe('30 7 * * *')
+ // Only the variant analysis template asks the server for the record schema the variants view reads.
+ expect(payload).not.toHaveProperty('variant_analysis')
expect(payload.config?.enabled).toBe(true)
expect(payload.config?.emit).toBe(true)
})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScout.ts b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
index 3fc1838e03f8..c69a14fa19e3 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScout.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScout.ts
@@ -13,6 +13,15 @@ import { SIGNALS_SCOUT_SKILL_PREFIX } from 'products/signals/frontend/inbox/util
// agree or a scanner stops finding its own scouts.
const SCOUT_SOURCE_PRODUCT = 'replay_vision'
+// pinned: the tag the backend's `VARIANT_ANALYSIS_TAG` puts on a variant analysis scout's config. The
+// two must agree, or the template card offers a second scout the API then refuses.
+const VARIANT_ANALYSIS_TAG = 'replay-vision-variant-analysis'
+
+/** The scanner's variant analysis scout, if it has one. The API allows one per scanner. */
+export function variantAnalysisScout(configs: SignalScoutConfigApi[]): SignalScoutConfigApi | undefined {
+ return configs.find((config) => config.tags?.includes(VARIANT_ANALYSIS_TAG))
+}
+
/** Whether this scout was stood up for this scanner. The pair is recorded on the config when the
* scout is created and is not user-editable, so it cannot be lost the way a label could. */
export function isScannerScoutConfig(config: SignalScoutConfigApi, scannerId: string): boolean {
@@ -80,6 +89,7 @@ export function scoutSkillName(
}
export type ScannerScoutTemplateKey =
+ | 'variant-analysis'
| 'daily-digest'
| 'root-cause'
| 'weekly-themes'
@@ -115,6 +125,8 @@ interface ScoutFocus {
/** Replaces the default window, which is everything since the previous run. An analysis that
* needs more volume than one run collects reads a fixed trailing window instead. */
window?: string
+ /** What the run's structured record holds, for a scout whose config attaches a record schema. */
+ record?: string
}
const DEFAULT_QUIET_VERDICT =
@@ -202,7 +214,7 @@ ${focus.shape ?? DEFAULT_REPORT_SHAPE}
${focus.quietVerdict ?? DEFAULT_QUIET_VERDICT} ${focus.priority}
These are watcher findings: \`repository=NO_REPO\`. Set \`actionability\` by what the report asks of its reader. \`requires_human_input\` only when someone has to decide or act on what you found: it lands in the inbox awaiting input, and a report on a quiet window does not belong in that queue. Otherwise \`immediately_actionable\`, which surfaces the report without asking anything of anyone. Never \`not_actionable\`: it suppresses the report, which empties the scanner's report card and stops delivery, so a quiet window reads as a run that never happened.
-## Memory
+${focus.record ? `## Record the comparison\n\n${focus.record}\n\n` : ''}## Memory
Write scratchpad entries as you go (\`pattern:\` baselines, \`noise:\` known-quiet shapes, \`dedupe:\`/\`report:\` pointers). Start every key with \`${scannerId}\`, then the kind and a slugified tag name, never raw summary text — the first move searches on that id.
@@ -389,6 +401,42 @@ function weeklyThemesTemplate(scannerId: string, scannerName: string): ScannerSc
}
}
+/** Offered to experiment scanners only: its runs record a comparison of the variants, which the
+ * scanner's variants view shows. The record's schema is attached server-side, not sent from here. */
+function variantAnalysisTemplate(scannerId: string, scannerName: string): ScannerScoutTemplate {
+ return {
+ key: 'variant-analysis',
+ title: 'Variant analysis',
+ description:
+ 'Compares what users in each experiment variant do, and shows the differences on the variants view.',
+ defaultName: scoutDefaultName(scannerName, 'variant analysis'),
+ cron: SCANNER_SCOUT_CRON,
+ body: buildScoutBody(scannerId, {
+ heading: 'Replay Vision variant analysis',
+ role: 'You compare the variants of the experiment one Replay Vision experiment scanner watches. Read its session summaries variant by variant, name the behaviors they share, and report what users in each variant do differently.',
+ reads: `- \`vision-scanners-get\` with id \`${scannerId}\` gives \`scanner_version\`. Read only observations of that version: a prompt edit changes what a summary looks at, so mixing versions compares two different questions.
+- \`vision-scanners-variants-list\` (scanner_id \`${scannerId}\`) gives the variant keys, each variant's observation and people counts, and its sampling rate. Those live counts are the trusted numbers: never restate them from your own reading.
+- \`vision-scanners-observations-list\` (scanner_id \`${scannerId}\`) with \`variant\` set to each key, \`status=succeeded\` and \`order_by=-completed_at\`: up to the 40 most recent summaries per variant. Read the same number from each variant where you can, so their shares compare. \`vision-observations-get\` reads one in full when its summary line is not enough.`,
+ notable: `Name the themes first, across all variants at once, so a theme means the same thing in every variant: one observable behavior each ("Reopens the pricing page before checking out"). Then count, per variant, how many of the summaries you read show each theme.
+
+A difference is a theme whose share differs between variants by enough to matter on the summaries you read. With 40 summaries a variant, a gap of a few sessions is noise.`,
+ quiet: 'Variants that behave the same is a real result. Say so in the report, and record no differences.',
+ skip: `- Restating the variants counts as findings: the variants view already shows them.
+- A difference resting on fewer than 5 sessions in either variant.
+- Claims about which variant wins. The experiment's metrics decide that; you describe what users do.`,
+ priority: 'Priority P3 by default.',
+ record: `Every run also records exactly one structured record with \`scout-record-output\`: the whole comparison, matching the schema in your instructions. It fills in the experiment's variants view in Replay Vision, so record it even when nothing differs.
+
+- \`scanner_version\`: the version you read from \`vision-scanners-get\`. A record for an older version is not shown.
+- \`observations_read\`: per variant key, how many summaries you read. Every count below is out of this number.
+- \`variants\`: per variant key, up to 5 themes, most common first. \`count\` is how many of that variant's summaries you read show the theme. Cite up to 2 observation ids of that variant that show it in \`example_observation_ids\`.
+- \`differences\`: up to 5, most meaningful first, each resting on one theme, with \`counts\` per variant key. Empty when the variants behave the same.
+- Use the same \`theme\` label in every variant and in \`differences\`, so the view can line them up.
+- Submit once per run. The newest record replaces the previous one in the view.`,
+ }),
+ }
+}
+
/** Which templates each scanner type offers, in card order. Root cause needs outcomes to explain,
* so summarizers get weekly themes instead, and trend watch has no metric to track on a summarizer. */
const TEMPLATE_KEYS_BY_TYPE: Record<ScannerTypeEnumApi, ScannerScoutTemplateKey[]> = {
@@ -396,7 +444,8 @@ const TEMPLATE_KEYS_BY_TYPE: Record<ScannerTypeEnumApi, ScannerScoutTemplateKey[
classifier: ['daily-digest', 'root-cause', 'trend-watch', 'new-issues', 'scratch'],
scorer: ['daily-digest', 'root-cause', 'trend-watch', 'new-issues', 'scratch'],
summarizer: ['daily-digest', 'weekly-themes', 'new-issues', 'scratch'],
- experiment: ['daily-digest', 'trend-watch', 'new-issues', 'scratch'],
+ // Variant analysis leads: it is the template that compares the experiment's variants.
+ experiment: ['variant-analysis', 'daily-digest', 'trend-watch', 'new-issues', 'scratch'],
}
export function scannerScoutTemplates(
@@ -515,6 +564,7 @@ Be specific about the bar, so a quiet window stays quiet: how many distinct sess
}),
'root-cause': () => rootCauseTemplate(scannerId, scannerName, ROOT_CAUSE_LENSES[type]!),
'weekly-themes': () => weeklyThemesTemplate(scannerId, scannerName),
+ 'variant-analysis': () => variantAnalysisTemplate(scannerId, scannerName),
}
return TEMPLATE_KEYS_BY_TYPE[type].map((key) => builders[key]())
}
@@ -557,9 +607,17 @@ export function scannerScoutTemplate(
* form, seeded by the chosen template. */
export function scannerScoutCreatePayload(
scannerName: string,
- overrides: { name: string; body: string; cron: string; outputDestinations?: SignalScoutOutputDestinationsApi }
+ overrides: {
+ name: string
+ body: string
+ cron: string
+ outputDestinations?: SignalScoutOutputDestinationsApi
+ templateKey?: ScannerScoutTemplateKey
+ }
): ScannerScoutCreateApi {
return {
+ // Asks the server to attach the record schema the variants view reads.
+ ...(overrides.templateKey === 'variant-analysis' ? { variant_analysis: true } : {}),
name: overrides.name,
description:
`Replay Vision scout for the scanner "${scannerName}". Reads the scanner's new observations on a schedule and files an inbox report when something is worth reporting.`.slice(
diff --git a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
index f9319571c84a..112a277ac397 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerScoutLogic.ts
@@ -853,6 +853,7 @@ export const scannerScoutLogic = kea<scannerScoutLogicType>([
body: form.body,
cron: form.cron,
outputDestinations: form.outputDestinations,
+ templateKey,
})
)
return result.config
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index af7a2fcfe7e9..b67483019474 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -1096,7 +1096,26 @@ tools:
requires_ai_consent: true
vision-scanners-variants-list:
operation: vision_scanners_variants_list
- enabled: false
+ enabled: true
+ scopes:
+ - replay_scanner:read
+ - session_recording:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Compare an experiment scanner's variants
+ description: >
+ Read an experiment scanner's results side by side per variant: how many observations each variant has, how
+ many distinct people they cover, the median session length, the rate each variant was sampled at, and its
+ latest observations. When the scanner has a variant analysis scout, it also returns that scout's per-variant
+ digests and the differences between variants. Experiment scanners only.
+ agent_note: >
+ The observation, people and session counts are counted live and are the numbers to trust. Digest and
+ difference counts come from the variant analysis scout, so read them as shares of each variant's
+ `analysis_observations`, not of `observations`. Balanced sampling gives small variants a higher
+ `sampling_rate`, so even observation counts do not mean even traffic. To read one variant's summaries, call
+ `vision-scanners-observations-list` with `variant` set to its key.
vision-scanners-watch-feed:
operation: vision_scanners_watch_feed_retrieve
enabled: true
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 8a00456a804e..cc1abfb8b348 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -1,3 +1,4 @@
+import json
import uuid
import dataclasses
from collections.abc import Callable, Iterator, Sequence
@@ -13,6 +14,10 @@ import temporalio
import posthoganalytics
from temporalio.common import WorkflowIDReusePolicy
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
@@ -1315,6 +1320,124 @@ def delete_scout_for_source(*, team: "Team", source_product: str, config_id: str
return True
+@frozen
+class SourceScout:
+ """A scout another product created for one of its objects."""
+
+ config_id: str
+ skill_name: str
+ enabled: bool
+ created_at: datetime
+
+
+@frozen
+class ScoutStructuredRecord:
+ """One record a scout submitted through its structured output channel."""
+
+ payload: dict[str, Any]
+ # The run's start, which is the event's timestamp: Signals stamps every record of a run with it.
+ recorded_at: datetime
+ skill_name: str
+ run_id: str
+
+
+# The structured output channel writes this event (see `scout_harness/tools/structured_output.py`).
+_STRUCTURED_OUTPUT_EVENT = "$scout_structured_output"
+# How many of the scouts' latest runs to look through, so a run that recorded nothing falls back
+# to an earlier one.
+_STRUCTURED_OUTPUT_RUN_LOOKBACK = 50
+_STRUCTURED_OUTPUT_READ_LIMIT = 500
+# Covers the precision the timestamp loses on its way through the events table.
+_RUN_START_TOLERANCE = timedelta(seconds=1)
+
+
+def scouts_for_source(
+ team_id: int, source_product: str, source_id: str, *, tag: str | None = None
+) -> list[SourceScout]:
+ """The scouts recorded as belonging to one source object, oldest first, optionally narrowed to a tag."""
+ configs = SignalScoutConfig.objects.for_team(team_id).filter(source_product=source_product, source_id=source_id)
+ if tag is not None:
+ configs = configs.filter(tags__contains=[tag])
+ return [
+ SourceScout(config_id=str(config_id), skill_name=skill_name, enabled=enabled, created_at=created_at)
+ for config_id, skill_name, enabled, created_at in configs.order_by("created_at").values_list(
+ "id", "skill_name", "enabled", "created_at"
+ )
+ ]
+
+
+def latest_structured_output_for_source(
+ team_id: int, source_product: str, source_id: str, *, tag: str
+) -> ScoutStructuredRecord | None:
+ """The newest structured record any of a source object's scouts with `tag` submitted, or None.
+
+ Records exist only as events, and anyone with the project's capture token can send an event
+ with any name and properties. So a record counts only when its `run_id` is a run of one of
+ those scouts and its timestamp is that run's start, which is how the structured output channel
+ stamps every record. Run ids come from Postgres and are not public.
+ """
+ config_ids = list(
+ SignalScoutConfig.objects.for_team(team_id)
+ .filter(source_product=source_product, source_id=source_id, tags__contains=[tag])
+ .values_list("id", flat=True)
+ )
+ if not config_ids:
+ return None
+ runs = {
+ str(run_id): (run_team_id, skill_name, created_at)
+ for run_id, run_team_id, skill_name, created_at in SignalScoutRun.objects.for_team(team_id)
+ .filter(scout_config_id__in=config_ids)
+ .order_by("-created_at")
+ .values_list("id", "team_id", "skill_name", "created_at")[:_STRUCTURED_OUTPUT_RUN_LOOKBACK]
+ }
+ if not runs:
+ return None
+ # Scout configs and their runs live on the canonical team, so the events do too.
+ team = Team.objects.get(pk=next(iter(runs.values()))[0])
+ starts = [created_at for _, _, created_at in runs.values()]
+
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ result = execute_hogql_query(
+ query_type="SignalsLatestStructuredOutputForSource",
+ query="""
+ SELECT properties.output, timestamp, properties.run_id
+ FROM events
+ WHERE event = {event}
+ AND properties.run_id IN {run_ids}
+ AND timestamp >= {since}
+ AND timestamp <= {until}
+ ORDER BY timestamp DESC
+ LIMIT {limit}
+ """,
+ team=team,
+ placeholders={
+ "event": ast.Constant(value=_STRUCTURED_OUTPUT_EVENT),
+ "run_ids": ast.Tuple(exprs=[ast.Constant(value=run_id) for run_id in runs]),
+ "since": ast.Constant(value=min(starts) - _RUN_START_TOLERANCE),
+ "until": ast.Constant(value=max(starts) + _RUN_START_TOLERANCE),
+ "limit": ast.Constant(value=_STRUCTURED_OUTPUT_READ_LIMIT),
+ },
+ )
+ for output, timestamp, run_id in result.results:
+ _, skill_name, run_start = runs[str(run_id)]
+ if not isinstance(timestamp, datetime) or abs(_as_utc(timestamp) - _as_utc(run_start)) > _RUN_START_TOLERANCE:
+ # A real run id with a timestamp the channel never writes was sent by something else.
+ continue
+ try:
+ payload = json.loads(output) if isinstance(output, str) else output
+ except json.JSONDecodeError:
+ continue
+ if isinstance(payload, dict):
+ return ScoutStructuredRecord(
+ payload=payload, recorded_at=run_start, skill_name=skill_name, run_id=str(run_id)
+ )
+ return None
+
+
+def _as_utc(value: datetime) -> datetime:
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+
+
def repair_report_actionability_cache(
*, team_id: int | None, batch_size: int, after: str | None = None
) -> Iterator[RepairedBatch]:
diff --git a/products/signals/backend/test/test_source_structured_output.py b/products/signals/backend/test/test_source_structured_output.py
new file mode 100644
index 000000000000..383b82c609e9
--- /dev/null
+++ b/products/signals/backend/test/test_source_structured_output.py
@@ -0,0 +1,74 @@
+import uuid
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from django.apps import apps
+
+from products.signals.backend.facade.api import latest_structured_output_for_source
+from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
+
+_SOURCE_PRODUCT = "replay_vision"
+_TAG = "variant-analysis"
+
+
+class TestLatestStructuredOutputForSource(ClickhouseTestMixin, APIBaseTest):
+ def _scout(self, skill_name: str, *, source_id: str, tags: list[str]) -> SignalScoutConfig:
+ return SignalScoutConfig.objects.for_team(self.team.id).create(
+ team=self.team, skill_name=skill_name, source_product=_SOURCE_PRODUCT, source_id=source_id, tags=tags
+ )
+
+ def _run(self, config: SignalScoutConfig) -> SignalScoutRun:
+ task = apps.get_model("tasks", "Task").objects.create(team=self.team, title="scout", description="d")
+ task_run = apps.get_model("tasks", "TaskRun").objects.create(team=self.team, task=task)
+ return SignalScoutRun.objects.for_team(self.team.id).create(
+ team=self.team, task_run=task_run, scout_config=config, skill_name=config.skill_name, skill_version=1
+ )
+
+ def _record(self, skill_name: str, run_id: str, payload: dict | str, *, at) -> None:
+ _create_event(
+ team=self.team,
+ event="$scout_structured_output",
+ distinct_id=f"signals_scout:{skill_name}",
+ timestamp=at,
+ properties={"skill_name": skill_name, "run_id": run_id, "output": payload},
+ )
+
+ def test_returns_the_newest_record_of_a_real_run_of_the_sources_tagged_scouts(self) -> None:
+ analysis = self._scout("signals-scout-analysis", source_id="scanner-a", tags=[_TAG])
+ digest = self._scout("signals-scout-digest", source_id="scanner-a", tags=[])
+ elsewhere = self._scout("signals-scout-other-analysis", source_id="scanner-b", tags=[_TAG])
+ first, second = self._run(analysis), self._run(analysis)
+ self._record(analysis.skill_name, str(first.id), {"scanner_version": 1}, at=first.created_at)
+ self._record(analysis.skill_name, str(second.id), {"scanner_version": 2}, at=second.created_at)
+ # Real runs, but of an untagged scout on the same source and a tagged scout on another source.
+ for config in (digest, elsewhere):
+ run = self._run(config)
+ self._record(config.skill_name, str(run.id), {"scanner_version": 9}, at=run.created_at)
+ # Sent with the public capture token: a run id no scout ran, and a real run id with a later
+ # timestamp than the run's start, which would otherwise sort first.
+ self._record(analysis.skill_name, str(uuid.uuid4()), {"scanner_version": 9}, at=second.created_at)
+ self._record(
+ analysis.skill_name, str(second.id), {"scanner_version": 9}, at=second.created_at + timedelta(hours=12)
+ )
+ flush_persons_and_events()
+
+ record = latest_structured_output_for_source(self.team.id, _SOURCE_PRODUCT, "scanner-a", tag=_TAG)
+
+ assert record is not None
+ assert record.payload == {"scanner_version": 2}
+ assert (record.run_id, record.skill_name) == (str(second.id), analysis.skill_name)
+ assert latest_structured_output_for_source(self.team.id, _SOURCE_PRODUCT, "scanner-c", tag=_TAG) is None
+
+ def test_skips_a_malformed_record_and_returns_an_older_valid_one(self) -> None:
+ analysis = self._scout("signals-scout-analysis", source_id="scanner-a", tags=[_TAG])
+ first, second = self._run(analysis), self._run(analysis)
+ self._record(analysis.skill_name, str(first.id), {"scanner_version": 1}, at=first.created_at)
+ self._record(analysis.skill_name, str(second.id), "{not json", at=second.created_at)
+ flush_persons_and_events()
+
+ record = latest_structured_output_for_source(self.team.id, _SOURCE_PRODUCT, "scanner-a", tag=_TAG)
+
+ assert record is not None
+ assert record.payload == {"scanner_version": 1}
+ assert record.run_id == str(first.id)
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0358eb0d2981..7f713ab525fb 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -13871,6 +13871,20 @@
},
"requires_ai_consent": true
},
+ "vision-scanners-variants-list": {
+ "description": "Read an experiment scanner's results side by side per variant: how many observations each variant has, how many distinct people they cover, the median session length, the rate each variant was sampled at, and its latest observations. When the scanner has a variant analysis scout, it also returns that scout's per-variant digests and the differences between variants. Experiment scanners only.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Compare an experiment scanner's variants",
+ "title": "Compare an experiment scanner's variants",
+ "required_scopes": ["replay_scanner:read", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"vision-scanners-watch-feed": {
"description": "Rank succeeded replay vision observations in a window by how worth watching their recordings are, across every scanner you can read. Each item pairs the `observation` (with its `session_id`) and the `reason` it made the feed. `date_from` defaults to `-7d` (ISO 8601 or relative); the window spans at most 90 days. Narrow with `scanner_ids`, `scanner_type`, scanner `tags`, or a `search` over the scan's own words. `limit` is at most 50. Use it to answer \"which recordings should I watch this week?\".",
"category": "Replay vision",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 805bf02072de..fa7657a3505a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -14549,6 +14549,20 @@
},
"requires_ai_consent": true
},
+ "vision-scanners-variants-list": {
+ "description": "Read an experiment scanner's results side by side per variant: how many observations each variant has, how many distinct people they cover, the median session length, the rate each variant was sampled at, and its latest observations. When the scanner has a variant analysis scout, it also returns that scout's per-variant digests and the differences between variants. Experiment scanners only.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Compare an experiment scanner's variants",
+ "title": "Compare an experiment scanner's variants",
+ "required_scopes": ["replay_scanner:read", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"vision-scanners-watch-feed": {
"description": "Rank succeeded replay vision observations in a window by how worth watching their recordings are, across every scanner you can read. Each item pairs the `observation` (with its `session_id`) and the `reason` it made the feed. `date_from` defaults to `-7d` (ISO 8601 or relative); the window spans at most 90 days. Narrow with `scanner_ids`, `scanner_type`, scanner `tags`, or a `search` over the scan's own words. `limit` is at most 50. Use it to answer \"which recordings should I watch this week?\".",
"category": "Replay vision",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0e4dcf453d33..53a1e53594c6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44251,6 +44251,17 @@ export namespace Schemas {
last_observation_at: string | null;
}
+ export interface VariantAnalysisLine {
+ /** A short label for the theme, shared across variants. */
+ theme: string;
+ /** How the theme shows up for this variant. */
+ statement: string;
+ /** How many of this variant's summaries the analysis read show the theme, as the scout counted them. */
+ count: number;
+ /** Observations of this variant the scout cited for the theme. Ids it can't back are dropped. */
+ example_observation_ids: string[];
+ }
+
/**
* * `configured` - Configured
* * `inline` - Inline
@@ -44512,10 +44523,53 @@ export namespace Schemas {
* @nullable
*/
sampling_rate: number | null;
+ /**
+ * Summaries of this variant the analysis read: the denominator of its digest and difference counts. Null without a current analysis.
+ * @nullable
+ */
+ analysis_observations: number | null;
+ /**
+ * This variant's most notable themes from the variant analysis. Null without a current analysis.
+ * @nullable
+ */
+ digest: VariantAnalysisLine[] | null;
/** This variant's most recent observations, newest first. */
latest_observations: ReplayObservation[];
}
+ /**
+ * Summaries the analysis read that show the theme, per variant key, as the scout counted them.
+ */
+ export type VariantAnalysisDifferenceCounts = {[key: string]: number};
+
+ export interface VariantAnalysisDifference {
+ /** The theme the difference rests on. */
+ theme: string;
+ /** What differs between the variants. */
+ statement: string;
+ /** Summaries the analysis read that show the theme, per variant key, as the scout counted them. */
+ counts: VariantAnalysisDifferenceCounts;
+ }
+
+ export interface VariantsAnalysisState {
+ /** The variant analysis scout's config id. */
+ scout_config_id: string;
+ /** Whether the scout runs on its schedule. */
+ scout_enabled: boolean;
+ /**
+ * When the run behind the newest analysis started; null before its first run.
+ * @nullable
+ */
+ recorded_at: string | null;
+ /**
+ * The scanner version the newest analysis covered.
+ * @nullable
+ */
+ scanner_version: number | null;
+ /** Whether the newest analysis covers the scanner's current version. When false, digests and differences are null until the scout's next run. */
+ current: boolean;
+ }
+
export interface ExperimentVariantsReadout {
/** The watched experiment; null if it was deleted. */
experiment: VariantsExperiment | null;
@@ -44523,8 +44577,15 @@ export namespace Schemas {
window: VariantsWindow;
/** One entry per watched variant, plus any variant still holding observations. */
variants: VariantReadout[];
+ /**
+ * What differs between variants, from the variant analysis. Null without a current analysis.
+ * @nullable
+ */
+ differences: VariantAnalysisDifference[] | null;
/** Succeeded observations with no attributed variant. */
unattributed_count: number;
+ /** The scanner's variant analysis scout and its newest run; null when none is set up. */
+ analysis: VariantsAnalysisState | null;
}
/**
@@ -92450,6 +92511,8 @@ export namespace Schemas {
body: string;
/** Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination. */
config?: SignalScoutConfigOptions;
+ /** Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only. */
+ variant_analysis?: boolean;
}
/**
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 2607b5016281..67f037be5400 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 48 enabled ops
+ * PostHog API - MCP 49 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1678,6 +1678,8 @@ export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOn
export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = true
export const visionScannersScoutsCreateBodyConfigOneRunCronScheduleMax = 100
+export const visionScannersScoutsCreateBodyVariantAnalysisDefault = false
+
export const VisionScannersScoutsCreateBody = () => zod
.object({
display_name: zod
@@ -1860,11 +1862,29 @@ export const VisionScannersScoutsCreateBody = () => zod
.describe(
'Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination.'
),
+ variant_analysis: zod
+ .boolean()
+ .default(visionScannersScoutsCreateBodyVariantAnalysisDefault)
+ .describe(
+ "Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only."
+ ),
})
.describe(
"A scout to stand up for this scanner. The scanner comes from the URL, never the body: it is\nwhat the caller's access is checked against, and what the scout is recorded as belonging to.\n\nInherits the Signals scout definition so a scout created here clears the same name and prompt-size\nbars as one created through the generic endpoint."
)
+/**
+ * Per-variant readout for an experiment scanner: observation counts, distinct people, median session length, sampling rate and latest observations per variant, read live, plus the digests and differences of the scanner's variant analysis scout.
+ */
+export const VisionScannersVariantsListParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+ scanner_id: zod.string(),
+})
+
/**
* Draft a full scanner configuration from a natural-language goal, for the goal-based creation flow.
*/
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 903b5ea54087..779e0b7453af 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -1595,6 +1595,9 @@ const visionScannersScoutsCreate = (): ToolBase<
if (params.config !== undefined) {
body['config'] = params.config
}
+ if (params.variant_analysis !== undefined) {
+ body['variant_analysis'] = params.variant_analysis
+ }
const result = await context.api.request<Schemas.ScannerScoutCreateResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/scouts/`,
@@ -1732,6 +1735,30 @@ const visionScannersUpdate = (): ToolBase<ReturnType<typeof VisionScannersUpdate
},
})
+const VisionScannersVariantsListSchema = () => {
+ const VisionScannersVariantsListParams = orvalSchemas.VisionScannersVariantsListParams()
+ return VisionScannersVariantsListParams.omit({ project_id: true })
+}
+
+const visionScannersVariantsList = (): ToolBase<
+ ReturnType<typeof VisionScannersVariantsListSchema>,
+ WithAgentNote<Schemas.ExperimentVariantsReadout[]>
+> => ({
+ name: 'vision-scanners-variants-list',
+ schema: VisionScannersVariantsListSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof VisionScannersVariantsListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ExperimentVariantsReadout[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/variants/`,
+ })
+ return withAgentNote(
+ result,
+ "The observation, people and session counts are counted live and are the numbers to trust. Digest and difference counts come from the variant analysis scout, so read them as shares of each variant's `analysis_observations`, not of `observations`. Balanced sampling gives small variants a higher `sampling_rate`, so even observation counts do not mean even traffic. To read one variant's summaries, call `vision-scanners-observations-list` with `variant` set to its key.\n"
+ )
+ },
+})
+
const VisionScannersWatchFeedSchema = () => {
const VisionScannersWatchFeedRetrieveQueryParams = orvalSchemas.VisionScannersWatchFeedRetrieveQueryParams()
return VisionScannersWatchFeedRetrieveQueryParams
@@ -1826,5 +1853,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'vision-scanners-self-driving-stats': visionScannersSelfDrivingStats,
'vision-scanners-suggest-tags': visionScannersSuggestTags,
'vision-scanners-update': visionScannersUpdate,
+ 'vision-scanners-variants-list': visionScannersVariantsList,
'vision-scanners-watch-feed': visionScannersWatchFeed,
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
index 49b7c632e03d..52bae99b0866 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-scouts-create.json
@@ -201,6 +201,11 @@
},
"scanner_id": {
"type": "string"
+ },
+ "variant_analysis": {
+ "default": false,
+ "description": "Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only.",
+ "type": "boolean"
}
},
"required": ["scanner_id", "description", "body"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-variants-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-variants-list.json
new file mode 100644
index 000000000000..3f2c29eb4657
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-variants-list.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "scanner_id": {
+ "type": "string"
+ }
+ },
+ "required": ["scanner_id"],
+ "type": "object"
+}