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): verify monitor yes verdicts with extra draws (#96742)

Arno Hillenc26a5af8d3a8
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.md
index 9f421612202f..716588c9a14e 100644
--- a/products/replay_vision/README.md
+++ b/products/replay_vision/README.md
@@ -15,6 +15,7 @@ A scanner with `emits_signals` also pushes one signal per finding into the Signa
**Observation** — one application of a scanner to a session, unique per (scanner, session).
Created in `pending` when triggered (by the scanner's schedule, the `/observe/` and `/bulk_observe/` actions, or a retry of a failed observation), transitions to `running` while `ApplyScannerWorkflow` executes (rasterize the recording to video → upload to Gemini → multi-turn scan), and lands in `succeeded` (result persisted under `scanner_result.model_output`, then a `$recording_observed` event plus embeddings/tags emitted fail-soft), `failed` (with a `kind:message` `error_reason`), or `ineligible` (the session doesn't qualify — too short, too idle, no recording).
Each observation snapshots the full scanner state (`scanner_snapshot`) that produced it, so subsequent edits to the scanner don't retro-mutate history.
+The snapshot's `verify_positives` mode (default `off`) makes a monitor re-draw its core step over the cached video when the first pass says `yes`. Replay Vision optimizes for precision over recall, so a `yes` stands only when the second draw agrees; a dissent replaces it with the dissenting verdict and reasoning, and no third draw breaks the tie. `shadow` records the draws under `scanner_result.verification` but serves the first pass; `enforce` serves the settled verdict. A draw that fails, or that would run past the activity's timeout, leaves the first pass in place, so verification only ever tightens a scan.
Rows stranded in `pending`/`running` by a dead workflow are failed as `orphaned` by a reaper on the reconciler tick.
Teams rate observations thumbs up/down, and those ratings drive the scanner's quality view and its AI prompt suggestions.
A finding can also be turned into a PostHog Task once (the observation remembers the task it minted).
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 340df9f66502..7b2cf933da2e 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -122,6 +122,31 @@ class ScannerSnapshotSerializer(serializers.Serializer):
scanner_config = serializers.JSONField(
help_text="Scanner-type-specific configuration at run time (prompt, tags, scale, etc.).",
)
+ verify_positives = serializers.CharField(
+ help_text="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).",
+ )
+
+
+class VerificationRecordSerializer(serializers.Serializer):
+ """Mirrors `temporal.types.VerificationRecord` for OpenAPI generation."""
+
+ mode = serializers.CharField(
+ help_text="Verify-positives mode the scan ran with: `shadow` records the second draw only, `enforce` serves the settled verdict.",
+ )
+ draws = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Monitor verdicts in draw order: the pass that triggered verification, then the second draw when it ran.",
+ )
+ resolved_verdict = serializers.CharField(
+ help_text="The verdict verification settled on: the first pass when the second draw agrees, else the dissent.",
+ )
+ served_verdict = serializers.CharField(
+ help_text="The verdict `model_output` carries: the resolved one under `enforce`, the first draw under `shadow`.",
+ )
+ skipped_reason = serializers.CharField(
+ allow_null=True,
+ help_text="Why verification stopped early (`no_cache`, `no_budget`, `draw_failed`), leaving the first pass in place. Null when every draw ran.",
+ )
class ScannerResultSerializer(serializers.Serializer):
@@ -134,6 +159,10 @@ class ScannerResultSerializer(serializers.Serializer):
min_value=0,
help_text="Number of PostHog Signals emitted from this observation.",
)
+ verification = VerificationRecordSerializer(
+ allow_null=True,
+ help_text="Extra draws taken to verify a monitor `yes` verdict. Null when the scan did not verify one.",
+ )
class ReplayObservationLabelSerializer(serializers.Serializer):
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 21ba8ae2ad18..5ff371917b2e 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -30,6 +30,7 @@ from posthoganalytics.ai.gemini import genai
from pydantic import BaseModel, ValidationError
from temporalio import activity
+from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.temporal.common.heartbeat import Heartbeater
@@ -42,9 +43,14 @@ from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.events_tool import build_events_index, dispatch_events_tool, events_tool
from products.replay_vision.backend.temporal.gemini import classify_gemini_error, describe_gemini_error, gemini_api_key
-from products.replay_vision.backend.temporal.metrics import record_mission_pass, record_provider_call
+from products.replay_vision.backend.temporal.metrics import (
+ record_mission_pass,
+ record_provider_call,
+ record_verification_outcome,
+)
from products.replay_vision.backend.temporal.scanners import scanner_from_snapshot
from products.replay_vision.backend.temporal.scanners.base import (
+ STEP_CORE,
STEP_SIGNALS,
TIMESTAMP_CITATION_RE,
BaseScanner,
@@ -57,12 +63,14 @@ from products.replay_vision.backend.temporal.scanners.base import (
TextSegment,
)
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierScanner
+from products.replay_vision.backend.temporal.scanners.monitor import MonitorLlmResponse, MonitorScanner
from products.replay_vision.backend.temporal.state import load_scanner_llm_inputs
from products.replay_vision.backend.temporal.types import (
CallScannerProviderInputs,
ScannerCallOutput,
ScannerLlmInputs,
ScannerSnapshot,
+ VerificationRecord,
)
logger = structlog.get_logger(__name__)
@@ -71,6 +79,10 @@ _MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation er
# One clean re-ask after a validation failure. The per-step re-prompt above retries inside the same conversation,
# where the model stays anchored on the answer it just got wrong; a fresh conversation is an independent draw.
_MAX_MISSION_ATTEMPTS = 2
+# Snapshot `verify_positives` values that draw; anything else (including a typo) behaves as `off`.
+_VERIFY_MODES = ("shadow", "enforce")
+# Activity time kept free of verify draws, so assembling and returning the result never races the timeout.
+_VERIFY_BUDGET_RESERVE_SECONDS = 60.0
# Cache TTL: a scan is a handful of turns and finishes in minutes; well under this.
_VIDEO_CACHE_TTL = "900s"
@@ -85,6 +97,15 @@ class _StepResult:
provider_refused: bool = False
+@frozen
+class _MissionOutcome:
+ """What one scan produced: the finalized output, the side-mission findings, and the verify-positives audit."""
+
+ finalized: BaseScannerOutput
+ signals: list[SignalFinding]
+ verification: VerificationRecord | None = None
+
+
@activity.defn
@track_activity()
async def call_scanner_provider_activity(inputs: CallScannerProviderInputs) -> ScannerCallOutput:
@@ -175,7 +196,7 @@ async def run_scan(
)
video_part = types.Part(file_data=types.FileData(file_uri=file_uri, mime_type=mime_type))
- finalized, signals = await _run_mission(
+ outcome = await _run_mission(
scanner=scanner,
snapshot=snapshot,
video_part=video_part,
@@ -185,8 +206,8 @@ async def run_scan(
trace_id=trace_id if trace_id is not None else str(uuid4()),
)
duration_ms = int(llm_inputs.metadata.duration_seconds * 1000)
- finalized = _resolve_citations(finalized, scanner, duration_ms)
- return ScannerCallOutput(model_output=finalized, signals=signals)
+ finalized = _resolve_citations(outcome.finalized, scanner, duration_ms)
+ return ScannerCallOutput(model_output=finalized, signals=outcome.signals, verification=outcome.verification)
def _scan_trace_id(inputs: CallScannerProviderInputs) -> str:
@@ -356,7 +377,7 @@ async def _run_mission(
team_id: int,
llm_inputs: ScannerLlmInputs,
trace_id: str,
-) -> tuple[BaseScannerOutput, list[SignalFinding]]:
+) -> _MissionOutcome:
"""Cache the video, run every mission step as a tool-using turn, then assemble the output + side-mission findings.
Caching is best-effort: a video too short to cache (or any cache hiccup) falls back to sending it inline, and a
@@ -410,13 +431,112 @@ async def _run_mission(
metric_labels=metric_labels,
trace_id=trace_id,
)
+ verification: VerificationRecord | None = None
try:
step_outputs = await _run_mission_attempts(run=run, cache=cache, model=snapshot.model)
+ core = step_outputs.get(STEP_CORE)
+ if (
+ isinstance(scanner, MonitorScanner)
+ and isinstance(core, MonitorLlmResponse)
+ and snapshot.verify_positives in _VERIFY_MODES
+ and core.verdict == "yes"
+ ):
+ # Verification re-draws over the cache, so it has to finish before the `finally` below deletes it.
+ served, verification = await _verify_positive_verdict(
+ scanner=scanner,
+ mode=snapshot.verify_positives,
+ core_step=next(step for step in steps if step.name == STEP_CORE),
+ first=core,
+ run=run,
+ cache=cache,
+ model=snapshot.model,
+ )
+ step_outputs = {**step_outputs, STEP_CORE: served}
finally:
if cache is not None:
await _delete_video_cache(cache_client, cache.name)
- return scanner.assemble(step_outputs)
+ finalized, signals = scanner.assemble(step_outputs)
+ return _MissionOutcome(finalized=finalized, signals=signals, verification=verification)
+
+
+async def _verify_positive_verdict(
+ *,
+ scanner: MonitorScanner,
+ mode: str,
+ core_step: MissionStep,
+ first: MonitorLlmResponse,
+ run: Any,
+ cache: Any | None,
+ model: str,
+) -> tuple[MonitorLlmResponse, VerificationRecord]:
+ """Re-draw the core step once; a `yes` is served only when the second draw agrees.
+
+ Replay Vision optimizes for precision, not recall: a finding it presents must hold up, and a missed one costs
+ less than a wrong one. So a single dissenting draw is enough to drop the `yes`, and the dissent (its verdict and
+ its reasoning) is what gets served. No third draw breaks the tie in favour of the finding.
+
+ Every draw is a fresh conversation over the same cached video and preamble, so it never sees the first pass or
+ its reasoning. Verification only ever tightens a scan that already succeeded: without a cache, without time left
+ in the activity budget, or when the draw fails for any reason, the first verdict stands and the record says why.
+ """
+ draws = [first]
+ skipped_reason: str | None = None
+ if cache is None:
+ skipped_reason = "no_cache"
+ else:
+ # An activity timeout fires outside the `except` below and fails the whole scan, first verdict included.
+ # Capping the draw at the remaining budget turns that into a `draw_failed` the first pass survives.
+ budget = _remaining_verify_budget_seconds()
+ if budget is not None and budget <= 0:
+ skipped_reason = "no_budget"
+ else:
+ verify_step = replace(core_step, name=f"{STEP_CORE}_verify_2")
+ try:
+ outputs = await asyncio.wait_for(run(steps=[verify_step], cache_name=cache.name), timeout=budget)
+ draw = outputs[verify_step.name]
+ if not isinstance(draw, MonitorLlmResponse):
+ raise TypeError(f"verify draw returned {type(draw).__name__}")
+ draws.append(draw)
+ except Exception as exc:
+ # No traceback or message: a provider error body can quote the prompt, as at the activity boundary.
+ logger.warning(
+ "replay_vision.call_scanner_provider.verify_draw_failed",
+ model=model,
+ error_type=type(exc).__name__,
+ code=getattr(exc, "code", None),
+ status=getattr(exc, "status", None),
+ )
+ skipped_reason = "draw_failed"
+
+ # The dissent, when there is one, is the last draw; otherwise the first pass stands.
+ resolved_draw = draws[-1]
+ served = resolved_draw if mode == "enforce" else first
+ if skipped_reason:
+ outcome = skipped_reason
+ else:
+ outcome = "agreed" if resolved_draw.verdict == first.verdict else "flipped"
+ record_verification_outcome(scanner_type=scanner.scanner_type.value, mode=mode, outcome=outcome)
+ record = VerificationRecord(
+ mode=mode,
+ draws=[draw.verdict for draw in draws],
+ resolved_verdict=resolved_draw.verdict,
+ served_verdict=served.verdict,
+ skipped_reason=skipped_reason,
+ )
+ return served, record
+
+
+def _remaining_verify_budget_seconds() -> float | None:
+ """Seconds a verify draw may take before the activity's start-to-close timeout, or None when there is no timeout
+ (the eval suite calls `run_scan` outside an activity)."""
+ if not activity.in_activity():
+ return None
+ info = activity.info()
+ if info.start_to_close_timeout is None:
+ return None
+ elapsed = (timezone.now() - info.started_time).total_seconds()
+ return info.start_to_close_timeout.total_seconds() - elapsed - _VERIFY_BUDGET_RESERVE_SECONDS
def _validate_signal_timestamps(output: BaseModel, *, duration_seconds: float | None) -> str | None:
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index d07edd4f4e78..4f9d5174bae9 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -33,7 +33,8 @@ REPLAY_VISION_INELIGIBLE_KINDS = Counter(
)
# Extends past the default ceiling so multi-minute upload + provider-call activities don't all land in +Inf.
-_ACTIVITY_DURATION_BUCKETS = (0.1, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600)
+# The top bucket matches the provider-call activity's 20-minute start-to-close timeout.
+_ACTIVITY_DURATION_BUCKETS = (0.1, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600, 900, 1200)
REPLAY_VISION_ACTIVITY_DURATION = Histogram(
"replay_vision_activity_duration_seconds",
@@ -57,6 +58,12 @@ REPLAY_VISION_MISSION_PASSES = Counter(
["model", "path"],
)
+REPLAY_VISION_VERIFICATION_OUTCOMES = Counter(
+ "replay_vision_verification_outcomes_total",
+ "Verify-positives results per verified monitor `yes`: agreed, flipped, no_cache, no_budget, draw_failed",
+ ["scanner_type", "mode", "outcome"],
+)
+
REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS = Counter(
"replay_vision_quota_exhausted_skips_total",
"Observations skipped because the org's monthly credit quota was exhausted",
@@ -198,6 +205,12 @@ def record_mission_pass(model: str, path: str) -> None:
_otel.record_counter_twin(REPLAY_VISION_MISSION_PASSES, 1, labels)
+def record_verification_outcome(*, scanner_type: str, mode: str, outcome: str) -> None:
+ labels = {"scanner_type": scanner_type, "mode": mode, "outcome": outcome}
+ REPLAY_VISION_VERIFICATION_OUTCOMES.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_VERIFICATION_OUTCOMES, 1, labels)
+
+
def record_quota_exhausted_skip(scanner_type: str) -> None:
REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS.labels(scanner_type=scanner_type).inc()
_otel.record_counter_twin(REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS, 1, {"scanner_type": scanner_type})
diff --git a/products/replay_vision/backend/temporal/snapshots.py b/products/replay_vision/backend/temporal/snapshots.py
index f87d304f2ec8..8828a9a3ca7f 100644
--- a/products/replay_vision/backend/temporal/snapshots.py
+++ b/products/replay_vision/backend/temporal/snapshots.py
@@ -35,6 +35,10 @@ class ScannerSnapshot(BaseModel, frozen=True):
experiment_targeting: dict[str, Any] | None = None
sampling_rate: float | None = None
sampling_mode: str | None = None
+ # How a monitor `yes` verdict is re-checked: `off` (one pass), `shadow` (draw again, record the result, serve the
+ # first pass), or `enforce` (serve the `yes` only when the second draw agrees, else the dissent). A plain string
+ # so a retired mode never breaks old-row loads.
+ verify_positives: str = "off"
@classmethod
def from_scanner(cls, scanner: "ReplayScanner") -> "ScannerSnapshot":
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index e61c02d5eb0c..20500d118c79 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -9,7 +9,7 @@ from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH
from products.replay_vision.backend.temporal.scanners.base import SignalFinding
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
-from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput
+from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput, MonitorVerdict
from products.replay_vision.backend.temporal.scanners.scorer import ScorerOutput
from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput
from products.replay_vision.backend.temporal.snapshots import (
@@ -23,11 +23,25 @@ AnyScannerOutput = Annotated[
]
+class VerificationRecord(BaseModel, frozen=True):
+ """Audit of the extra draws taken to verify a monitor `yes` verdict. Absent when no verdict was verified."""
+
+ mode: str
+ # Verdicts in draw order; the first entry is the pass that triggered verification.
+ draws: list[MonitorVerdict]
+ # The verdict verification settled on: the first pass when the second draw agrees, else the dissent.
+ # `served_verdict` is what `model_output` carries: the same value under `enforce`, the first draw under `shadow`.
+ resolved_verdict: MonitorVerdict
+ served_verdict: MonitorVerdict
+ skipped_reason: str | None = None
+
+
class ScannerResult(BaseModel, frozen=True):
"""Result data of a completed observation, persisted into `ReplayObservation.scanner_result`."""
model_output: AnyScannerOutput
signals_count: int = Field(default=0, ge=0)
+ verification: VerificationRecord | None = None
class ApplyScannerInputs(BaseModel, frozen=True):
@@ -248,6 +262,7 @@ class ScannerCallOutput(BaseModel, frozen=True):
model_output: AnyScannerOutput
# Extracted from the LLM response before `finalize` so per-type output mapping can't drop them.
signals: list[SignalFinding] = Field(default_factory=list)
+ verification: VerificationRecord | None = None
class CleanupGeminiFileInputs(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index d4626d0b5ea4..d1ac0b54972e 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -320,8 +320,9 @@ class ApplyScannerWorkflow(PostHogWorkflow):
mime_type=uploaded.mime_type,
),
# Multi-turn tool conversation (video + on-demand event lookups) needs more headroom than a single
- # call, and must cover both mission passes: a second pass that overruns would surface as a Temporal
- # timeout labeled provider_transient when the real problem is the scanner's prompt.
+ # call, and must cover both mission passes plus the one verify-positives draw: a pass that
+ # overruns would surface as a Temporal timeout labeled provider_transient when the real problem is
+ # the scanner's prompt.
start_to_close_timeout=dt.timedelta(minutes=20),
# Bounds the whole retry chain, so slow attempts can't overrun the workflow's own timeout.
schedule_to_close_timeout=dt.timedelta(minutes=25),
@@ -357,7 +358,11 @@ class ApplyScannerWorkflow(PostHogWorkflow):
MarkObservationSucceededInputs(
observation_id=observation_id,
scanner_type=scanner_type,
- scanner_result=ScannerResult(model_output=call_output.model_output, signals_count=signals_count),
+ scanner_result=ScannerResult(
+ model_output=call_output.model_output,
+ signals_count=signals_count,
+ verification=call_output.verification,
+ ),
),
start_to_close_timeout=dt.timedelta(seconds=30),
schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.py
index 172e7328f4c4..8e09909ff622 100644
--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py
+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py
@@ -1,15 +1,25 @@
+import datetime as dt
+import dataclasses
from typing import Any, cast
import pytest
+import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
+from django.utils import timezone
+
import httpx
from google.genai.errors import APIError
from pydantic import BaseModel
+from temporalio.testing import ActivityEnvironment
+
+from posthog.dataclasses import frozen
from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.temporal.activities.call_scanner_provider import (
_maybe_create_video_cache,
+ _MissionOutcome,
+ _remaining_verify_budget_seconds,
_run_mission,
_run_mission_attempts,
_run_pass,
@@ -17,9 +27,10 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
_step_config,
)
from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
+from products.replay_vision.backend.temporal.metrics import REPLAY_VISION_VERIFICATION_OUTCOMES
from products.replay_vision.backend.temporal.scanners.base import MissionStep, SignalFinding, SignalsResponse
from products.replay_vision.backend.temporal.scanners.monitor import MonitorLlmResponse, MonitorOutput, MonitorScanner
-from products.replay_vision.backend.temporal.types import ScannerSnapshot
+from products.replay_vision.backend.temporal.types import ScannerSnapshot, VerificationRecord
_LABELS = {"provider": "gemini", "model": "gemini-3-flash-preview", "scanner_type": "monitor"}
# The driver treats the video part opaquely (just appended to the conversation), so a sentinel is fine.
@@ -88,6 +99,7 @@ async def _run(client: _FakeClient, steps: list[MissionStep], dispatch: Any = la
async def test_scanner_generations_include_team_attribution() -> None:
scanner = MagicMock()
scanner.mission_steps.return_value = []
+ scanner.assemble.return_value = (MagicMock(), [])
snapshot = MagicMock()
snapshot.scanner_type.value = "monitor"
snapshot.model = "gemini-3-flash-preview"
@@ -302,7 +314,7 @@ async def test_signal_timestamps_use_recording_duration(
patch(f"{module}.build_events_index", return_value={}),
patch(f"{module}._maybe_create_video_cache", new=AsyncMock(return_value=None)),
):
- finalized, signals = await _run_mission(
+ outcome = await _run_mission(
scanner=scanner,
snapshot=snapshot,
video_part=_VIDEO,
@@ -311,8 +323,8 @@ async def test_signal_timestamps_use_recording_duration(
llm_inputs=MagicMock(metadata=MagicMock(duration_seconds=duration_seconds)),
trace_id="trace-1",
)
- assert cast(MonitorOutput, finalized).verdict == "yes"
- assert signals == ([] if expected_end is None else [signal.model_copy(update={"end_time": expected_end})])
+ assert cast(MonitorOutput, outcome.finalized).verdict == "yes"
+ assert outcome.signals == ([] if expected_end is None else [signal.model_copy(update={"end_time": expected_end})])
assert len(client.models.calls) == 1 + len(end_times)
@@ -466,6 +478,240 @@ class TestRunPass:
assert calls == ["cache-1", None]
+_MODULE = "products.replay_vision.backend.temporal.activities.call_scanner_provider"
+
+
+def _verification_counts() -> dict[tuple[str, str], float]:
+ return {
+ (sample.labels["mode"], sample.labels["outcome"]): sample.value
+ for family in REPLAY_VISION_VERIFICATION_OUTCOMES.collect()
+ for sample in family.samples
+ if sample.name == "replay_vision_verification_outcomes_total"
+ }
+
+
+@frozen
+class _ScanRun:
+ outcome: _MissionOutcome
+ # Runner calls in order, then the cache deletion.
+ calls: list[Any]
+ # Verification counter increments during the scan, keyed by (mode, outcome).
+ counted: dict[tuple[str, str], float]
+
+
+class TestVerifyPositives:
+ class _Cache:
+ name = "caches/abc"
+
+ @staticmethod
+ def _answer(verdict: str) -> MonitorLlmResponse:
+ return MonitorLlmResponse(reasoning=f"because {verdict}", verdict=cast(Any, verdict), confidence=0.8)
+
+ async def _scan(
+ self,
+ *,
+ mode: str,
+ answers: list[str | Exception],
+ allow_inconclusive: bool = False,
+ cached: bool = True,
+ emits_signals: bool = False,
+ budget_seconds: float | None = None,
+ ) -> _ScanRun:
+ # `answers[0]` is the first pass; the rest are the verify draws in order.
+ scanner = MonitorScanner(
+ prompt="did it happen", allow_inconclusive=allow_inconclusive, emits_signals=emits_signals
+ )
+ snapshot = ScannerSnapshot(
+ name="m",
+ scanner_type=ScannerType.MONITOR,
+ scanner_version=1,
+ model="gemini-3-flash-preview",
+ provider="gemini",
+ emits_signals=emits_signals,
+ scanner_config={"prompt": "did it happen"},
+ verify_positives=mode,
+ )
+ pending = iter(answers)
+ calls: list[Any] = []
+ unchecked_steps: list[str] = []
+
+ async def fake_run_steps(*, steps: list[MissionStep], cache_name: str | None, **_: Any) -> dict[str, BaseModel]:
+ calls.append({"steps": [step.name for step in steps], "cache_name": cache_name})
+ # Collect rather than assert: the verify draw runs inside an `except Exception` that turns any
+ # error into `draw_failed`, so an assertion raised here would pass the test instead of failing it.
+ unchecked_steps.extend(
+ step.name
+ for step in steps
+ if step.name != "signals" and not (step.required and step.validate is not None)
+ )
+ answer = next(pending)
+ if isinstance(answer, Exception):
+ raise answer
+ return {step.name: self._answer(answer) for step in steps if step.name != "signals"}
+
+ async def fake_delete(*_: Any) -> None:
+ calls.append("delete_cache")
+
+ before = _verification_counts()
+ with (
+ patch(f"{_MODULE}.genai.AsyncClient"),
+ patch(f"{_MODULE}.GoogleGenAIClient"),
+ patch(f"{_MODULE}.build_events_index", return_value={}),
+ patch(
+ f"{_MODULE}._maybe_create_video_cache", new=AsyncMock(return_value=self._Cache() if cached else None)
+ ),
+ patch(f"{_MODULE}._delete_video_cache", new=fake_delete),
+ patch(f"{_MODULE}._run_steps", new=fake_run_steps),
+ patch(f"{_MODULE}._remaining_verify_budget_seconds", return_value=budget_seconds),
+ ):
+ outcome = await _run_mission(
+ scanner=scanner,
+ snapshot=snapshot,
+ video_part=_VIDEO,
+ preamble_text="PRE",
+ team_id=1,
+ llm_inputs=MagicMock(),
+ trace_id="trace-1",
+ )
+ # A verify draw must keep the core step's semantic check, or an `inconclusive` the scanner forbids
+ # would count as a vote.
+ assert unchecked_steps == []
+ counted = {
+ key: value - before.get(key, 0.0)
+ for key, value in _verification_counts().items()
+ if value != before.get(key, 0.0)
+ }
+ return _ScanRun(outcome=outcome, calls=calls, counted=counted)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "mode,answers",
+ [
+ ("off", ["yes"]),
+ ("Enforce", ["yes"]),
+ ("enforce", ["no"]),
+ ("enforce", ["inconclusive"]),
+ ],
+ )
+ async def test_only_a_positive_under_a_live_mode_is_verified(
+ self, mode: str, answers: list[str | Exception]
+ ) -> None:
+ run = await self._scan(mode=mode, answers=answers, allow_inconclusive=True)
+ assert len(run.calls) == 2 # the first pass and the cache deletion
+ assert cast(MonitorOutput, run.outcome.finalized).verdict == answers[0]
+ assert run.outcome.verification is None
+ assert run.counted == {}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "mode,draws,allow_inconclusive,resolved,served,outcome_label",
+ [
+ ("shadow", ["yes", "yes"], False, "yes", "yes", "agreed"),
+ ("enforce", ["yes", "yes"], False, "yes", "yes", "agreed"),
+ ("enforce", ["yes", "no"], False, "no", "no", "flipped"),
+ ("shadow", ["yes", "no"], False, "no", "yes", "flipped"),
+ ("enforce", ["yes", "inconclusive"], True, "inconclusive", "inconclusive", "flipped"),
+ ],
+ )
+ async def test_a_yes_stands_only_when_the_second_draw_agrees(
+ self,
+ mode: str,
+ draws: list[str],
+ allow_inconclusive: bool,
+ resolved: str,
+ served: str,
+ outcome_label: str,
+ ) -> None:
+ run = await self._scan(mode=mode, answers=list(draws), allow_inconclusive=allow_inconclusive)
+ finalized = cast(MonitorOutput, run.outcome.finalized)
+ # `enforce` serves the whole settled draw, reasoning included, not just its verdict.
+ assert (finalized.verdict, finalized.reasoning) == (served, f"because {served}")
+ assert run.outcome.verification == VerificationRecord(
+ mode=mode, draws=cast(Any, draws), resolved_verdict=cast(Any, resolved), served_verdict=cast(Any, served)
+ )
+ # One first pass, one verify draw, the cache deletion. A dissent never triggers a third draw.
+ assert len(run.calls) == 3
+ assert run.counted == {(mode, outcome_label): 1.0}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "failure",
+ [
+ ScannerFailureError("rejected", kind=FailureKind.VALIDATION_FAILED),
+ APIError(429, {"error": {"message": "quota", "status": "RESOURCE_EXHAUSTED"}}),
+ # `asyncio.wait_for` raises this when a draw runs past the activity budget.
+ TimeoutError(),
+ ],
+ )
+ async def test_a_failed_draw_keeps_the_first_verdict_and_never_raises(self, failure: Exception) -> None:
+ run = await self._scan(mode="enforce", answers=["yes", failure])
+ assert cast(MonitorOutput, run.outcome.finalized).verdict == "yes"
+ assert run.outcome.verification == VerificationRecord(
+ mode="enforce", draws=["yes"], resolved_verdict="yes", served_verdict="yes", skipped_reason="draw_failed"
+ )
+ assert len(run.calls) == 3
+ assert run.counted == {("enforce", "draw_failed"): 1.0}
+
+ @pytest.mark.asyncio
+ async def test_without_a_cache_the_first_pass_stands(self) -> None:
+ # A re-draw without the cache would re-send the whole video; that spend is not worth one extra vote.
+ run = await self._scan(mode="enforce", answers=["yes"], cached=False)
+ assert len(run.calls) == 1
+ assert run.outcome.verification == VerificationRecord(
+ mode="enforce", draws=["yes"], resolved_verdict="yes", served_verdict="yes", skipped_reason="no_cache"
+ )
+ assert run.counted == {("enforce", "no_cache"): 1.0}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("budget_seconds,draws_taken", [(0.0, 0), (-5.0, 0), (30.0, 1)])
+ async def test_a_draw_never_starts_past_the_activity_budget(self, budget_seconds: float, draws_taken: int) -> None:
+ # The activity timeout would fail the whole scan, first verdict included, so a draw with no time left is skipped.
+ run = await self._scan(mode="enforce", answers=["yes", "yes"], budget_seconds=budget_seconds)
+ assert len(run.calls) == 2 + draws_taken
+ assert cast(MonitorOutput, run.outcome.finalized).verdict == "yes"
+ if draws_taken == 0:
+ assert run.outcome.verification == VerificationRecord(
+ mode="enforce", draws=["yes"], resolved_verdict="yes", served_verdict="yes", skipped_reason="no_budget"
+ )
+ assert run.counted == {("enforce", "no_budget"): 1.0}
+ else:
+ assert run.counted == {("enforce", "agreed"): 1.0}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "start_to_close,elapsed,expected",
+ [
+ (dt.timedelta(minutes=20), dt.timedelta(minutes=5), 14 * 60.0),
+ (dt.timedelta(minutes=20), dt.timedelta(minutes=19, seconds=30), -30.0),
+ (None, dt.timedelta(minutes=5), None),
+ ],
+ )
+ async def test_remaining_budget_reads_the_activity_timeout(
+ self, start_to_close: dt.timedelta | None, elapsed: dt.timedelta, expected: float | None
+ ) -> None:
+ now = timezone.now()
+ env = ActivityEnvironment()
+ env.info = dataclasses.replace(env.info, start_to_close_timeout=start_to_close, started_time=now - elapsed)
+
+ async def read_budget() -> float | None:
+ return _remaining_verify_budget_seconds()
+
+ with time_machine.travel(now, tick=False):
+ assert await env.run(read_budget) == expected
+
+ def test_remaining_budget_is_unbounded_outside_an_activity(self) -> None:
+ assert _remaining_verify_budget_seconds() is None
+
+ @pytest.mark.asyncio
+ async def test_verify_draws_are_blind_core_only_turns_over_the_live_cache(self) -> None:
+ run = await self._scan(mode="enforce", answers=["yes", "no"], emits_signals=True)
+ assert run.calls == [
+ {"steps": ["core", "signals"], "cache_name": "caches/abc"},
+ {"steps": ["core_verify_2"], "cache_name": "caches/abc"},
+ "delete_cache",
+ ]
+
+
class TestStepConfig:
def test_inline_path_carries_tools_and_no_cache(self) -> None:
config = _step_config(MissionStep(name="core", instruction="c", response_model=_Core), cache_name=None)
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 9dd61e399653..278e07f1e8fe 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -57,6 +57,7 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
_extract_segments,
_inject_known_freeform_tags,
_load_known_freeform_tags,
+ _MissionOutcome,
_resolve_citations,
call_scanner_provider_activity,
)
@@ -167,6 +168,7 @@ def test_scanner_snapshot_loads_rows_with_retired_model_and_provider_ids() -> No
)
assert snapshot.model == "gemini-1.0-flash-retired-preview"
assert snapshot.provider == "hooli"
+ assert snapshot.verify_positives == "off"
def _make_scanner(**overrides) -> ReplayScanner:
@@ -1083,7 +1085,7 @@ class TestKnownFreeformTags:
patch(
"products.replay_vision.backend.temporal.activities.call_scanner_provider._run_mission",
new_callable=AsyncMock,
- return_value=(model_output, []),
+ return_value=_MissionOutcome(finalized=model_output, signals=[]),
) as mock_run_mission,
patch(
"products.replay_vision.backend.temporal.activities.call_scanner_provider._load_llm_inputs",
diff --git a/products/replay_vision/evals/README.md b/products/replay_vision/evals/README.md
index 6b6e8b622aec..2994ba67519d 100644
--- a/products/replay_vision/evals/README.md
+++ b/products/replay_vision/evals/README.md
@@ -40,6 +40,10 @@ hogli evals eval_scanner_quality
`BRAINTRUST_API_KEY` is required by the harness engine even though this private suite only logs locally.
Without `REPLAY_VISION_EVAL_DATASET` the suite logs a warning and runs nothing, so it never breaks a full `hogli evals` run.
Use `--trials N` for variance on Gemini nondeterminism and `--eval <case-substring>` for one case.
+Set `REPLAY_VISION_EVAL_VERIFY_POSITIVES=shadow` or `=enforce` to run monitor cases with verify-positives on.
+Only a first-pass `yes` is verified, so a case that answers `no` keeps `verification: null`, and a `yes` whose second draw cannot run (`no_cache`, `no_budget`, `draw_failed`) keeps the first verdict and records that reason.
+Both modes record the draw, but only `enforce` serves it, so `labeled_outcome` from a shadow run matches a run with the feature off.
+Compare `labeled_outcome` on the thumbs-downed `yes` cases against a run without it to see what the extra draws buy.
## Scorers
diff --git a/products/replay_vision/evals/eval_scanner_quality.py b/products/replay_vision/evals/eval_scanner_quality.py
index 5a984ba8ceb5..0462c7dd56ca 100644
--- a/products/replay_vision/evals/eval_scanner_quality.py
+++ b/products/replay_vision/evals/eval_scanner_quality.py
@@ -7,8 +7,10 @@ Edit the templates under backend/temporal/scanners/prompts/ and re-run to compar
in the local logs (this suite is private; nothing is sent to Braintrust).
Requires REPLAY_VISION_EVAL_DATASET (a directory written by collect.py) and GEMINI_API_KEY.
+Set REPLAY_VISION_EVAL_VERIFY_POSITIVES to `shadow` or `enforce` to run monitor cases with verify-positives on.
"""
+import os
import time
import asyncio
from functools import partial
@@ -30,6 +32,7 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
from products.replay_vision.backend.temporal.errors import ScannerFailureError
from products.replay_vision.backend.temporal.gemini import gemini_api_key
from products.replay_vision.backend.temporal.scanners import scanner_from_snapshot
+from products.replay_vision.backend.temporal.snapshots import ScannerSnapshot
from products.replay_vision.evals.dataset import (
DATASET_ENV_VAR,
GoldenCase,
@@ -51,6 +54,17 @@ SUITE_KIND = SuiteKind.ONE_SHOT
logger = structlog.get_logger(__name__)
_MAX_PROCESSING_WAIT_SECONDS = 300
+VERIFY_POSITIVES_ENV_VAR = "REPLAY_VISION_EVAL_VERIFY_POSITIVES"
+
+
+def _eval_snapshot(golden: GoldenCase) -> ScannerSnapshot:
+ """The recorded snapshot, with the verify-positives mode overridden when the run asks for one."""
+ mode = os.environ.get(VERIFY_POSITIVES_ENV_VAR, "").strip()
+ if not mode:
+ return golden.snapshot
+ if mode not in ("shadow", "enforce"):
+ raise ValueError(f"{VERIFY_POSITIVES_ENV_VAR} must be `shadow` or `enforce`, got {mode!r}")
+ return golden.snapshot.model_copy(update={"verify_positives": mode})
def build_case(golden: GoldenCase) -> BaseEvalCase:
@@ -148,7 +162,7 @@ async def _scan_task(
try:
try:
result = await run_scan(
- snapshot=golden.snapshot,
+ snapshot=_eval_snapshot(golden),
scanner=scanner,
llm_inputs=llm_inputs,
team_name=golden.team_name,
@@ -177,6 +191,7 @@ async def _scan_task(
"error": None,
"scanner_type": golden.scanner_type,
"signals_count": len(result.signals),
+ "verification": result.verification.model_dump(mode="json") if result.verification else None,
"primary": primary,
"last_message": primary or "",
}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index a1594b26a112..1bde3e7efe10 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -520,6 +520,27 @@ export interface ScannerSnapshotApi {
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
+}
+
+/**
+ * Mirrors `temporal.types.VerificationRecord` for OpenAPI generation.
+ */
+export interface VerificationRecordApi {
+ /** 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
}
/**
@@ -533,6 +554,8 @@ export interface ScannerResultApi {
* @minimum 0
*/
signals_count: number
+ /** Extra draws taken to verify a monitor `yes` verdict. Null when the scan did not verify one. */
+ verification: VerificationRecordApi | null
}
/**
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 68d1edb82cb9..48958c45be9a 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -203,6 +203,7 @@ const observation = (overrides: Partial<ReplayObservationApi> = {}): ReplayObser
provider: 'google',
emits_signals: false,
scanner_config: { prompt: 'Summarize this session.', length: 'medium' },
+ verify_positives: 'off',
},
scanner_result: {
model_output: {
@@ -280,6 +281,7 @@ const observationDetail = observation({
'The user spent most of the session in checkout, retrying an invalid coupon three times before abandoning the cart at the payment step.',
},
signals_count: 1,
+ verification: null,
},
})
@@ -310,6 +312,7 @@ const monitorObservationDetail = observation({
prompt: 'Did the user struggle at checkout? Count it as struggling if they retried a coupon code more than once, resubmitted the payment form after an error, or moved back and forth between the cart and the payment step without completing the order. Ignore sessions that never reached the checkout page at all.',
allow_inconclusive: true,
},
+ verify_positives: 'off',
},
scanner_result: {
model_output: {
@@ -320,6 +323,7 @@ const monitorObservationDetail = observation({
'The user entered a coupon code three times, each time getting a validation error, then switched to the payment form and submitted it twice before leaving the page. That is a retry loop at checkout rather than ordinary browsing.',
},
signals_count: 1,
+ verification: null,
},
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6cbae3cd6d06..a964e3972740 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55020,6 +55020,27 @@ export namespace Schemas {
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;
+ }
+
+ /**
+ * 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;
}
/**
@@ -55033,6 +55054,8 @@ export namespace Schemas {
* @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;
}
/**