Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): add golden-dataset eval loop for scanner prompts (#75128)

Arno Hillenda49fa971ea8
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 42341ffd030f..81b957fbefe5 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -11,6 +11,7 @@ import time
import asyncio
import functools
from collections import Counter
+from collections.abc import Iterable
from dataclasses import dataclass
from datetime import timedelta
from typing import Any, TypeVar
@@ -127,7 +128,38 @@ async def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCa
)
scanner: BaseScanner = scanner_from_snapshot(snapshot)
scanner = await _inject_known_freeform_tags(scanner, inputs)
+ return await run_scan(
+ snapshot=snapshot,
+ scanner=scanner,
+ llm_inputs=llm_inputs,
+ team_name=team_name,
+ file_uri=inputs.file_uri,
+ mime_type=inputs.mime_type,
+ team_id=inputs.team_id,
+ trace_id=_scan_trace_id(inputs),
+ )
+
+async def run_scan(
+ *,
+ snapshot: ScannerSnapshot,
+ scanner: BaseScanner,
+ llm_inputs: ScannerLlmInputs,
+ team_name: str,
+ file_uri: str,
+ mime_type: str,
+ team_id: int,
+ trace_id: str | None = None,
+) -> ScannerCallOutput:
+ """Run the scanner conversation over an already-uploaded video, independent of where the inputs came from.
+
+ The activity path above loads the snapshot and inputs from the observation row and Redis; the golden-dataset
+ eval suite (products/replay_vision/evals) feeds this same function from files on disk so prompt changes are
+ tested against the exact production pipeline. `scanner` is required (no snapshot fallback) so no caller can
+ silently skip the known-freeform-tags injection. The production activity checks AI data-processing consent
+ before calling this; any other caller must do the same before recording data reaches the provider (the eval
+ suite is covered because dataset collection is consent-gated and time-boxed).
+ """
preamble_text = scanner.preamble(
team_name=team_name,
session_metadata=llm_inputs.metadata.as_prompt_dict(),
@@ -137,16 +169,16 @@ async def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCa
product_context=llm_inputs.product_context,
event_descriptions=llm_inputs.event_descriptions,
)
- video_part = types.Part(file_data=types.FileData(file_uri=inputs.file_uri, mime_type=inputs.mime_type))
+ video_part = types.Part(file_data=types.FileData(file_uri=file_uri, mime_type=mime_type))
finalized, signals = await _run_mission(
scanner=scanner,
snapshot=snapshot,
video_part=video_part,
preamble_text=preamble_text,
- team_id=inputs.team_id,
+ team_id=team_id,
llm_inputs=llm_inputs,
- trace_id=_scan_trace_id(inputs),
+ 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)
@@ -227,6 +259,13 @@ def _is_taglike(slug: str) -> bool:
)
+def apply_known_freeform_tags(scanner: BaseScanner, tags: list[str]) -> BaseScanner:
+ """No-op unless `scanner` is a freeform-emitting classifier and there are tags to inject."""
+ if not tags or not isinstance(scanner, ClassifierScanner) or not scanner.allow_freeform_tags:
+ return scanner
+ return scanner.model_copy(update={"known_freeform_tags": tags})
+
+
async def _inject_known_freeform_tags(scanner: BaseScanner, inputs: CallScannerProviderInputs) -> BaseScanner:
"""Give a freeform-emitting classifier the freeform tags it recently coined, so it reuses established
names instead of inventing synonyms per scan. Best effort: a lookup failure must not fail the scan."""
@@ -237,9 +276,20 @@ async def _inject_known_freeform_tags(scanner: BaseScanner, inputs: CallScannerP
except Exception:
logger.warning("replay_vision.call_scanner_provider.known_freeform_tags_failed", exc_info=True)
return scanner
- if not known:
- return scanner
- return scanner.model_copy(update={"known_freeform_tags": known})
+ return apply_known_freeform_tags(scanner, known)
+
+
+def rank_freeform_tags(tag_lists: Iterable[Any]) -> list[str]:
+ """Slug-normalized freeform tags ranked most frequent first, capped to bound prompt size."""
+ counts: Counter[str] = Counter()
+ for tags in tag_lists:
+ if not isinstance(tags, list):
+ continue
+ # Stored values are already slugified at emission; re-slugify so nothing unnormalized reaches the prompt.
+ counts.update(slug for tag in tags if isinstance(tag, str) and _is_taglike(slug := slugify_tag(tag)))
+ # Alphabetical tie-break so equal-count tags keep a stable order across scans.
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
+ return [tag for tag, _ in ranked[:_KNOWN_FREEFORM_TAGS_MAX]]
def _load_known_freeform_tags(observation_id: UUID, team_id: int) -> list[str]:
@@ -261,15 +311,7 @@ def _load_known_freeform_tags(observation_id: UUID, team_id: int) -> list[str]:
.order_by("-created_at")
.values_list("scanner_result__model_output__tags_freeform", flat=True)[:_KNOWN_FREEFORM_TAGS_MAX_ROWS]
)
- counts: Counter[str] = Counter()
- for tags in recent:
- if not isinstance(tags, list):
- continue
- # Stored values are already slugified at emission; re-slugify so nothing unnormalized reaches the prompt.
- counts.update(slug for tag in tags if isinstance(tag, str) and _is_taglike(slug := slugify_tag(tag)))
- # Alphabetical tie-break so equal-count tags keep a stable order across scans.
- ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
- return [tag for tag, _ in ranked[:_KNOWN_FREEFORM_TAGS_MAX]]
+ return rank_freeform_tags(recent)
def _load_snapshot(observation_id: UUID, team_id: int) -> ScannerSnapshot:
@@ -679,4 +721,4 @@ async def _delete_video_cache(cache_client: GoogleGenAIClient, name: str) -> Non
logger.info("replay_vision.video_cache.delete_failed", error=str(e))
-__all__ = ["call_scanner_provider_activity"]
+__all__ = ["apply_known_freeform_tags", "call_scanner_provider_activity", "rank_freeform_tags", "run_scan"]
diff --git a/products/replay_vision/backend/temporal/team_context.py b/products/replay_vision/backend/temporal/team_context.py
index 33bd45f3c34b..ec0ddc1d3f96 100644
--- a/products/replay_vision/backend/temporal/team_context.py
+++ b/products/replay_vision/backend/temporal/team_context.py
@@ -7,6 +7,7 @@ before it is stored.
import re
from collections import Counter
+from collections.abc import Mapping
from functools import cache
from typing import Any
@@ -49,13 +50,17 @@ def _sanitize(text: str, max_len: int, *, keep_newlines: bool = False) -> str:
return cleaned
+def sanitize_product_context(text: str) -> str:
+ # Core memory is one fact per line; keep the newlines so the model sees a list, not a wall of text.
+ return _sanitize(text, _MAX_PRODUCT_CONTEXT_LEN, keep_newlines=True)
+
+
def fetch_product_context(team: Team) -> str:
"""The team's Max core memory, falling back to the project's (deprecated) product description; "" when neither exists."""
text = get_team_business_context(team)
if not text:
text = (team.project.product_description or "").strip()
- # Core memory is one fact per line; keep the newlines so the model sees a list, not a wall of text.
- return _sanitize(text, _MAX_PRODUCT_CONTEXT_LEN, keep_newlines=True)
+ return sanitize_product_context(text)
def _event_names_by_frequency(columns: list[str], rows: list[list[Any]]) -> list[str]:
@@ -67,6 +72,25 @@ def _event_names_by_frequency(columns: list[str], rows: list[list[Any]]) -> list
return [name for name, _ in sorted(counts.items(), key=lambda item: (-item[1], item[0]))]
+def session_custom_event_names(columns: list[str], rows: list[list[Any]]) -> list[str]:
+ """This session's custom event names, most frequent first, capped for the description lookup."""
+ # A backtick in a name would escape the prompt's inline-code fencing; drop such names rather than rewrite an identifier.
+ return [
+ name for name in _event_names_by_frequency(columns, rows) if name not in _core_event_names() and "`" not in name
+ ][:_MAX_LOOKUP_NAMES]
+
+
+def select_event_descriptions(custom_names: list[str], found: Mapping[str, str | None]) -> dict[str, str]:
+ """Sanitize and cap the looked-up descriptions, preserving the frequency order of `custom_names`."""
+ described: dict[str, str] = {}
+ for name in custom_names:
+ if sanitized := _sanitize(found.get(name) or "", _MAX_EVENT_DESCRIPTION_LEN):
+ described[name] = sanitized
+ if len(described) >= _MAX_EVENT_DESCRIPTIONS:
+ break
+ return described
+
+
def fetch_event_descriptions(team: Team, columns: list[str], rows: list[list[Any]]) -> dict[str, str]:
"""Customer-written descriptions for this session's custom events, keyed by name, most frequent first.
@@ -76,11 +100,7 @@ def fetch_event_descriptions(team: Team, columns: list[str], rows: list[list[Any
return {}
from ee.models.event_definition import EnterpriseEventDefinition # noqa: PLC0415 — absent from OSS builds
- # A backtick in a name would escape the prompt's inline-code fencing; drop such names rather than rewrite an identifier.
- custom_names = [
- name for name in _event_names_by_frequency(columns, rows) if name not in _core_event_names() and "`" not in name
- ][:_MAX_LOOKUP_NAMES]
-
+ custom_names = session_custom_event_names(columns, rows)
found = dict(
EnterpriseEventDefinition.objects.filter(
# Definitions are project-scoped with a team-scoped legacy fallback; mirrors posthog/api/event_definition.py.
@@ -91,10 +111,4 @@ def fetch_event_descriptions(team: Team, columns: list[str], rows: list[list[Any
.exclude(description="")
.values_list("name", "description")
)
- described: dict[str, str] = {}
- for name in custom_names:
- if sanitized := _sanitize(found.get(name) or "", _MAX_EVENT_DESCRIPTION_LEN):
- described[name] = sanitized
- if len(described) >= _MAX_EVENT_DESCRIPTIONS:
- break
- return described
+ return select_event_descriptions(custom_names, found)
diff --git a/products/replay_vision/evals/README.md b/products/replay_vision/evals/README.md
new file mode 100644
index 000000000000..98358de7baec
--- /dev/null
+++ b/products/replay_vision/evals/README.md
@@ -0,0 +1,64 @@
+# Replay Vision golden-dataset evals
+
+Test scanner prompt changes against a fixed set of real, already-observed sessions instead of shipping and watching production.
+The suite re-runs the exact production scan pipeline (`run_scan`: same Jinja templates, response schemas, events tool) over collected videos, then scores the fresh output against the recorded output and its human thumbs label.
+
+## The loop
+
+1. Collect a dataset once (and re-collect occasionally as labels accumulate).
+2. Run the suite to get a baseline.
+3. Edit prompt templates under `../backend/temporal/scanners/prompts/`.
+4. Re-run the suite and compare scores across runs (same experiment name accumulates history).
+
+## Collecting a dataset
+
+Uses only the public API plus the dogfood warehouse, with a personal API key that can read the source project (scanner read + session recording read + query scopes):
+
+```bash
+POSTHOG_API_KEY=... python -m products.replay_vision.evals.collect \
+ --project-id 2 --per-type 25 --output ~/.posthog/replay-vision-golden-dataset
+```
+
+Selection is per scanner type: human-labeled observations first (thumbs up/down carry ground truth), then a seeded uniform sample of unlabeled ones.
+Only observations whose original rasterized MP4 still exists are collectable: the system assets expire after 90 days, a session re-rasterized after that is a different video than the one behind the recorded output (so those are skipped too), and the warehouse copy of the exports table lags up to a day, so very fresh observations are skipped.
+Each case also captures the prompt context the production scan carried: the project's product context (Max core memory needs a full-access personal key; otherwise the project description is used), the session's custom-event descriptions, and, for freeform classifiers, the known-tag vocabulary.
+Re-running the collector is idempotent per case: completed cases are reused as-is, half-written ones are re-collected, and the manifest is merged with previously collected cases that are still valid on disk.
+After a collector change that alters what a case captures, collect into a fresh directory so reused cases don't keep the old shape.
+
+## Running the suite
+
+```bash
+REPLAY_VISION_EVAL_DATASET=~/.posthog/replay-vision-golden-dataset \
+GEMINI_API_KEY=... \
+LLM_GATEWAY_ANTHROPIC_API_KEY=... \
+BRAINTRUST_API_KEY=... \
+hogli evals eval_scanner_quality
+```
+
+`GEMINI_API_KEY` runs the scans themselves.
+`LLM_GATEWAY_ANTHROPIC_API_KEY` satisfies the suite env preflight (judge models are routed through the internal LLM gateway).
+`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.
+
+## Scorers
+
+| Scorer | Applies to | Meaning |
+| ------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
+| `scan_completed` | all cases | The scan produced schema-valid, semantically-valid output. |
+| `labeled_outcome` | labeled monitor/classifier | kept/fixed = 1, regressed/still_wrong = 0 (same semantics as the in-product prompt-suggestion evaluation). |
+| `output_stability` | unlabeled monitor/classifier | Fresh outcome matches the recorded baseline; measures churn, not correctness. |
+| `score_alignment` | scorer (reference not thumbs-downed) | 1 minus the scale-normalized distance from the recorded score. |
+| `summary_alignment` | summarizer (reference not thumbs-downed) | LLM judge: does the fresh summary tell the same story as the recorded one? |
+
+`output_stability` and `labeled_outcome` deliberately pull in opposite directions, so read them as a pair: a prompt change that only adds churn shows up as `labeled_outcome` flat or up while `output_stability` drops.
+
+## Data handling
+
+The dataset contains real session recordings and event data.
+
+- Keep it in a local or internal location only; never commit it, upload it, or reference its contents in PRs.
+- A dataset expires 30 days after its last collection: the suite refuses to run it, because the consent verification (and the recordings themselves) can lapse after collection. Re-running collect.py re-verifies consent and refreshes the manifest.
+- The suite is `OneShotPrivateEval`: results stay in the local `eval_harness/logs/` directory and are not sent to Braintrust.
+- `summary_alignment` sends the recorded and fresh session summaries to the LLM judge (`gpt-5.4` via the internal LLM gateway); besides the Gemini scans themselves, this is the only path where dataset-derived content leaves the machine.
+- Collecting from projects other than PostHog's own requires a data-governance decision first; see the product's consent gating (`backend/consent.py`) and note that customer-facing copy does not cover internal reuse today.
diff --git a/products/replay_vision/evals/__init__.py b/products/replay_vision/evals/__init__.py
new file mode 100644
index 000000000000..37fea886e23c
--- /dev/null
+++ b/products/replay_vision/evals/__init__.py
@@ -0,0 +1 @@
+"""Replay Vision golden-dataset eval suites (see README.md in this directory)."""
diff --git a/products/replay_vision/evals/collect.py b/products/replay_vision/evals/collect.py
new file mode 100644
index 000000000000..e2fcaf308af2
--- /dev/null
+++ b/products/replay_vision/evals/collect.py
@@ -0,0 +1,63 @@
+"""Collect a Replay Vision golden dataset from an existing project's observations.
+
+Usage, from the repo root, with a personal API key that can read the source project:
+
+ POSTHOG_API_KEY=... python -m products.replay_vision.evals.collect \\
+ --project-id 2 --per-type 25 --output ~/.posthog/replay-vision-golden-dataset
+
+Then point REPLAY_VISION_EVAL_DATASET at the output directory to run the eval suite.
+The dataset contains real session data: keep it out of the repo and off any public surface.
+"""
+
+import os
+import argparse
+from pathlib import Path
+
+import django
+
+_DEFAULT_OUTPUT = "~/.posthog/replay-vision-golden-dataset"
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--host", default="https://us.posthog.com", help="PostHog instance to collect from.")
+ parser.add_argument("--project-id", type=int, default=2, help="Source project (default: PostHog dogfood).")
+ parser.add_argument("--output", default=_DEFAULT_OUTPUT, help="Dataset directory to write.")
+ parser.add_argument("--per-type", type=int, default=25, help="Cases to collect per scanner type.")
+ parser.add_argument(
+ "--scanner-id", action="append", dest="scanner_ids", help="Restrict to specific scanner ids (repeatable)."
+ )
+ parser.add_argument("--seed", type=int, default=42, help="Seed for the uniform sample, for reproducibility.")
+ args = parser.parse_args()
+
+ # Env var only, deliberately: a key passed as a CLI flag leaks into shell history and ps output.
+ api_key = os.environ.get("POSTHOG_API_KEY", "")
+ if not api_key:
+ parser.error("set POSTHOG_API_KEY")
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+ django.setup()
+ from products.replay_vision.evals.collector import collect # noqa: PLC0415 - needs Django configured first
+
+ dataset = collect(
+ host=args.host,
+ project_id=args.project_id,
+ api_key=api_key,
+ output=Path(args.output).expanduser(),
+ per_type=args.per_type,
+ scanner_ids=args.scanner_ids,
+ seed=args.seed,
+ )
+ by_type: dict[str, int] = {}
+ for case in dataset.cases:
+ by_type[case.scanner_type] = by_type.get(case.scanner_type, 0) + 1
+ labeled = sum(1 for case in dataset.cases if case.label_is_correct is not None)
+ print(f"Collected {len(dataset.cases)} cases ({labeled} labeled): {by_type}") # noqa: T201
+ print( # noqa: T201
+ f"Run the suite with: REPLAY_VISION_EVAL_DATASET={args.output} GEMINI_API_KEY=... "
+ "LLM_GATEWAY_ANTHROPIC_API_KEY=... BRAINTRUST_API_KEY=... hogli evals eval_scanner_quality"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/products/replay_vision/evals/collector.py b/products/replay_vision/evals/collector.py
new file mode 100644
index 000000000000..e6659303b9dd
--- /dev/null
+++ b/products/replay_vision/evals/collector.py
@@ -0,0 +1,536 @@
+"""Implementation of the golden-dataset collector; run it via collect.py (needs Django configured).
+
+Everything goes through a PostHog instance's public API with a personal API key, so it works
+against any project the key can read: the replay-vision scanner/observation endpoints drive the
+selection, the synced ``postgres.posthog_exportedasset`` warehouse table locates each session's
+rasterized MP4 (system assets are invisible to the exports list endpoint), the exports content
+endpoint downloads the bytes, and HogQL queries mirroring ``fetch_session_events`` rebuild each
+session's ``ScannerLlmInputs``. The core-memory, project, and event-definition endpoints rebuild
+the prompt context (``product_context``, ``event_descriptions``) the production preamble carries.
+"""
+
+import os
+import random
+import datetime as dt
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import requests
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.session_recordings.queries.session_replay_events import DEFAULT_EVENT_FIELDS
+
+from products.replay_vision.backend.temporal.activities.call_scanner_provider import (
+ _KNOWN_FREEFORM_TAGS_DAYS,
+ _KNOWN_FREEFORM_TAGS_MAX_ROWS,
+ rank_freeform_tags,
+)
+from products.replay_vision.backend.temporal.activities.ensure_session_asset import (
+ _EXPORT_FORMAT,
+ _MOUSE_TAIL,
+ _PLAYBACK_SPEED,
+ _RECORDING_FPS,
+ _SHOW_METADATA_FOOTER,
+)
+from products.replay_vision.backend.temporal.activities.fetch_session_events import (
+ _EVENTS_PER_PAGE,
+ _EVENTS_TO_IGNORE,
+ _EXTRA_FIELDS,
+ _MAX_TOTAL_EVENT_ROWS,
+ _process_events,
+)
+from products.replay_vision.backend.temporal.team_context import (
+ sanitize_product_context,
+ select_event_descriptions,
+ session_custom_event_names,
+)
+from products.replay_vision.backend.temporal.types import EventTable, ScannerLlmInputs, ScannerSnapshot, SessionMetadata
+from products.replay_vision.evals.dataset import (
+ MANIFEST_NAME,
+ GoldenCase,
+ GoldenDataset,
+ load_dataset,
+ parse_utc,
+ save_dataset,
+)
+
+logger = structlog.get_logger(__name__)
+
+# The exports table syncs into the warehouse with up to ~a day of lag, so freshly-created
+# observations often have no findable asset yet; we over-fetch candidates and skip those.
+_ASSET_LOOKUP_CHUNK = 100
+_OBSERVATION_PAGE = 100
+_EVENT_DEFINITION_NAMES_CHUNK = 100
+
+
+class PostHogApi:
+ """Minimal authenticated client for the endpoints the collector needs."""
+
+ def __init__(self, host: str, project_id: int, api_key: str) -> None:
+ self.host = host.rstrip("/")
+ self.project_id = project_id
+ self._session = requests.Session()
+ self._session.headers["Authorization"] = f"Bearer {api_key}"
+
+ def get_json(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
+ response = self._session.get(f"{self.host}{path}", params=params, timeout=60)
+ response.raise_for_status()
+ return response.json()
+
+ def paginate(
+ self, path: str, params: dict[str, Any] | None = None, max_items: int | None = None
+ ) -> Iterator[dict[str, Any]]:
+ url: str | None = f"{self.host}{path}"
+ yielded = 0
+ while url:
+ response = self._session.get(url, params=params, timeout=60)
+ response.raise_for_status()
+ data = response.json()
+ for item in data.get("results", []):
+ yield item
+ yielded += 1
+ if max_items is not None and yielded >= max_items:
+ return
+ url = data.get("next")
+ params = None
+
+ def hogql(self, query: str, values: dict[str, Any] | None = None) -> list[list[Any]]:
+ payload = {"query": {"kind": "HogQLQuery", "query": query, "values": values or {}}}
+ response = self._session.post(
+ f"{self.host}/api/environments/{self.project_id}/query/", json=payload, timeout=120
+ )
+ response.raise_for_status()
+ return response.json().get("results") or []
+
+ def download(self, path: str, target: Path) -> None:
+ # The content endpoint 302s to a presigned S3 URL; requests drops the auth header on the
+ # cross-host redirect, which is exactly right for a presigned link.
+ partial = target.with_name(target.name + ".partial")
+ with self._session.get(f"{self.host}{path}", timeout=300, stream=True) as response:
+ response.raise_for_status()
+ with partial.open("wb") as handle:
+ # iter_content applies the transport decoding (gzip/deflate) that response.raw skips.
+ for chunk in response.iter_content(chunk_size=1 << 20):
+ handle.write(chunk)
+ # Publish atomically so an interrupted download can never be mistaken for a complete file.
+ os.replace(partial, target)
+
+
+def order_candidates(candidates: list[dict[str, Any]], rng: random.Random) -> dict[str, list[dict[str, Any]]]:
+ """Per scanner type: labeled observations first (they carry ground truth), then the rest uniformly shuffled."""
+ by_type: dict[str, list[dict[str, Any]]] = {}
+ for candidate in candidates:
+ by_type.setdefault(candidate["scanner_type"], []).append(candidate)
+ ordered: dict[str, list[dict[str, Any]]] = {}
+ for scanner_type, group in by_type.items():
+ labeled = [c for c in group if c["observation"].get("label")]
+ unlabeled = [c for c in group if not c["observation"].get("label")]
+ rng.shuffle(unlabeled)
+ ordered[scanner_type] = labeled + unlabeled
+ return ordered
+
+
+@frozen
+class _VideoAsset:
+ asset_id: int
+ created_at: dt.datetime
+
+
+def lookup_video_assets(api: PostHogApi, team_id: int, session_ids: list[str]) -> dict[str, _VideoAsset]:
+ """Map session id to its system rasterized-MP4 asset, for sessions that still have one.
+
+ min(id) mirrors ensure_session_asset's oldest-first get-or-create, so this is the asset the
+ production scans actually watched, for as long as it lives.
+ """
+ found: dict[str, _VideoAsset] = {}
+ for start in range(0, len(session_ids), _ASSET_LOOKUP_CHUNK):
+ chunk = session_ids[start : start + _ASSET_LOOKUP_CHUNK]
+ rows = api.hogql(
+ """
+ SELECT JSONExtractString(toString(export_context), 'session_recording_id') AS sid,
+ min(id) AS asset_id,
+ argMin(toTimeZone(created_at, 'UTC'), id) AS asset_created_at
+ FROM postgres.posthog_exportedasset
+ WHERE team_id = {team_id}
+ AND export_format = {export_format}
+ AND is_system
+ AND expires_after > now()
+ AND JSONExtractFloat(toString(export_context), 'playback_speed') = {playback_speed}
+ AND JSONExtractInt(toString(export_context), 'recording_fps') = {recording_fps}
+ AND JSONExtractBool(toString(export_context), 'show_metadata_footer') = {show_metadata_footer}
+ AND JSONExtractBool(toString(export_context), 'mouse_tail') = {mouse_tail}
+ AND JSONExtractString(toString(export_context), 'session_recording_id') IN {session_ids}
+ GROUP BY sid
+ """,
+ {
+ "team_id": team_id,
+ "export_format": _EXPORT_FORMAT,
+ "playback_speed": _PLAYBACK_SPEED,
+ "recording_fps": _RECORDING_FPS,
+ "show_metadata_footer": _SHOW_METADATA_FOOTER,
+ "mouse_tail": _MOUSE_TAIL,
+ "session_ids": chunk,
+ },
+ )
+ for sid, asset_id, created_raw in rows:
+ found[str(sid)] = _VideoAsset(asset_id=int(asset_id), created_at=parse_utc(created_raw))
+ return found
+
+
+def asset_is_recorded_video(asset: _VideoAsset, observation: dict[str, Any]) -> bool:
+ """An asset created after the observation completed is a re-rasterization from after the original
+ expired: not the video behind recorded_output, so the case would score the wrong footage."""
+ completed_raw = observation.get("completed_at")
+ return bool(completed_raw) and asset.created_at <= parse_utc(completed_raw)
+
+
+# toTimeZone pins the timestamps to UTC regardless of the project timezone, so parse_utc never
+# sees a value it would have to guess a timezone for.
+_METADATA_QUERY = """
+SELECT distinct_id, toTimeZone(start_time, 'UTC') AS start_time, toTimeZone(end_time, 'UTC') AS end_time,
+ click_count, keypress_count, mouse_activity_count,
+ active_milliseconds, console_error_count, first_url
+FROM session_replay_events
+WHERE session_id = {session_id}
+"""
+
+
+@frozen
+class _SessionEvents:
+ columns: list[str]
+ rows: list[list[Any]]
+ truncated: bool
+
+
+def _fetch_events(api: PostHogApi, session_id: str, start: dt.datetime, end: dt.datetime) -> _SessionEvents:
+ fields = [*DEFAULT_EVENT_FIELDS, *_EXTRA_FIELDS]
+ select_exprs = [f"toTimeZone({field}, 'UTC') AS timestamp" if field == "timestamp" else field for field in fields]
+ # The uuid tie-break makes OFFSET paging deterministic when many events share a timestamp.
+ query = (
+ f"SELECT {', '.join(select_exprs)} FROM events"
+ " WHERE timestamp >= {start_time} AND timestamp <= {end_time} AND $session_id = {session_id}"
+ " AND event NOT IN {events_to_ignore}"
+ " ORDER BY timestamp ASC, uuid ASC LIMIT {limit} OFFSET {offset}"
+ )
+ rows: list[list[Any]] = []
+ truncated = False
+ offset = 0
+ while True:
+ page = api.hogql(
+ query,
+ {
+ # Same 100s wiggle as production get_events_query: the range only bounds the scan.
+ "start_time": (start - dt.timedelta(seconds=100)).isoformat(),
+ "end_time": (end + dt.timedelta(seconds=100)).isoformat(),
+ "session_id": session_id,
+ "events_to_ignore": _EVENTS_TO_IGNORE,
+ "limit": _EVENTS_PER_PAGE,
+ "offset": offset,
+ },
+ )
+ rows.extend(list(row) for row in page)
+ if len(rows) >= _MAX_TOTAL_EVENT_ROWS:
+ # Same cap as the production fetch: eligibility bounds active seconds, not event count,
+ # so an instrumentation loop can still emit millions of rows.
+ truncated = len(rows) > _MAX_TOTAL_EVENT_ROWS or len(page) == _EVENTS_PER_PAGE
+ del rows[_MAX_TOTAL_EVENT_ROWS:]
+ break
+ if len(page) < _EVENTS_PER_PAGE:
+ break
+ offset += _EVENTS_PER_PAGE
+ return _SessionEvents(columns=list(fields), rows=rows, truncated=truncated)
+
+
+class EventDescriptionLookup:
+ """API-backed twin of team_context.fetch_event_descriptions, cached across sessions in one run."""
+
+ def __init__(self, api: PostHogApi) -> None:
+ self._api = api
+ self._cache: dict[str, str] = {}
+
+ def for_session(self, columns: list[str], rows: list[list[Any]]) -> dict[str, str]:
+ names = session_custom_event_names(columns, rows)
+ missing = [name for name in names if name not in self._cache]
+ for start in range(0, len(missing), _EVENT_DEFINITION_NAMES_CHUNK):
+ chunk = missing[start : start + _EVENT_DEFINITION_NAMES_CHUNK]
+ # Pre-cache the whole chunk as undescribed so names the API doesn't return are not refetched.
+ self._cache.update(dict.fromkeys(chunk, ""))
+ for definition in self._api.paginate(
+ f"/api/projects/{self._api.project_id}/event_definitions/",
+ {"names": ",".join(chunk), "limit": _EVENT_DEFINITION_NAMES_CHUNK},
+ ):
+ self._cache[str(definition.get("name") or "")] = str(definition.get("description") or "")
+ return select_event_descriptions(names, self._cache)
+
+
+def fetch_product_context_via_api(api: PostHogApi) -> str:
+ """Product context the way production builds it: Max core memory, then the project's product description."""
+ text = ""
+ try:
+ results = api.get_json(f"/api/projects/{api.project_id}/core_memory/").get("results") or []
+ text = str(results[0].get("text") or "").strip() if results else ""
+ except requests.HTTPError as exc:
+ # Core memory is an INTERNAL-scope endpoint, unreadable with a scoped personal key; degrade to the fallback.
+ logger.warning("collector.core_memory_unreadable", error=str(exc))
+ if not text:
+ text = str(api.get_json(f"/api/projects/{api.project_id}/").get("product_description") or "").strip()
+ return sanitize_product_context(text)
+
+
+def build_llm_inputs(
+ api: PostHogApi,
+ team_id: int,
+ session_id: str,
+ *,
+ product_context: str = "",
+ event_descriptions: EventDescriptionLookup | None = None,
+) -> ScannerLlmInputs | None:
+ """Rebuild the ScannerLlmInputs production stashed in Redis, from the query API instead of ClickHouse."""
+ metadata_rows = api.hogql(_METADATA_QUERY, {"session_id": session_id})
+ if not metadata_rows:
+ return None
+ (distinct_id, start_raw, end_raw, clicks, keypresses, mouse, active_ms, console_errors, first_url) = metadata_rows[
+ 0
+ ]
+ start, end = parse_utc(start_raw), parse_utc(end_raw)
+ duration_seconds = (end - start).total_seconds()
+
+ fetched = _fetch_events(api, session_id, start, end)
+ if not fetched.rows:
+ return None
+ # _process_events needs real datetimes to compute per-event offsets from session start.
+ timestamp_index = fetched.columns.index("timestamp")
+ for row in fetched.rows:
+ row[timestamp_index] = parse_utc(row[timestamp_index])
+ # HogQL surfaces `properties.$window_id` as a bare `$window_id` column, matching production's runner output.
+ columns = [column.removeprefix("properties.") for column in fetched.columns]
+ processed = _process_events(columns, fetched.rows, session_start=start)
+
+ active_seconds = float(active_ms or 0) / 1000
+ return ScannerLlmInputs(
+ session_id=session_id,
+ team_id=team_id,
+ events_truncated=fetched.truncated,
+ events=EventTable(columns=processed.columns, rows=processed.rows),
+ url_mapping=processed.url_mapping,
+ window_mapping=processed.window_mapping,
+ event_timestamps=processed.event_timestamps,
+ navigation=processed.navigation,
+ navigation_dropped=processed.navigation_dropped,
+ product_context=product_context,
+ event_descriptions=event_descriptions.for_session(processed.columns, processed.rows)
+ if event_descriptions
+ else {},
+ distinct_id=str(distinct_id) if distinct_id else None,
+ metadata=SessionMetadata(
+ start_time=start,
+ end_time=end,
+ duration_seconds=duration_seconds,
+ active_seconds=active_seconds,
+ inactive_seconds=max(0.0, duration_seconds - active_seconds),
+ click_count=clicks,
+ keypress_count=keypresses,
+ mouse_activity_count=mouse,
+ start_url=first_url or None,
+ console_error_count=console_errors,
+ ),
+ )
+
+
+def _known_freeform_tags(observations: list[dict[str, Any]]) -> list[str]:
+ """Approximate the tag vocabulary production injects at scan time (recent window, ranked by frequency);
+ the vocabulary each recorded scan actually saw is not reconstructable after the fact."""
+ cutoff = dt.datetime.now(dt.UTC) - dt.timedelta(days=_KNOWN_FREEFORM_TAGS_DAYS)
+ recent = [
+ ((observation.get("scanner_result") or {}).get("model_output") or {}).get("tags_freeform")
+ for observation in observations
+ if observation.get("created_at") and parse_utc(observation["created_at"]) >= cutoff
+ ]
+ return rank_freeform_tags(recent[:_KNOWN_FREEFORM_TAGS_MAX_ROWS])
+
+
+def _fetch_candidates(
+ api: PostHogApi, scanner_ids: list[str] | None, max_observations_per_scanner: int
+) -> list[dict[str, Any]]:
+ candidates: list[dict[str, Any]] = []
+ for scanner in api.paginate(f"/api/projects/{api.project_id}/vision/scanners/", {"limit": 100}):
+ if scanner_ids and scanner["id"] not in scanner_ids:
+ continue
+ observations = list(
+ api.paginate(
+ f"/api/projects/{api.project_id}/vision/scanners/{scanner['id']}/observations/",
+ {"status": "succeeded", "limit": _OBSERVATION_PAGE},
+ max_items=max_observations_per_scanner,
+ )
+ )
+ known_tags = _known_freeform_tags(observations) if scanner["scanner_type"] == "classifier" else []
+ for observation in observations:
+ if not (observation.get("scanner_result") or {}).get("model_output"):
+ continue
+ candidates.append(
+ {
+ "observation": observation,
+ "scanner": scanner,
+ "scanner_type": scanner["scanner_type"],
+ "known_freeform_tags": known_tags,
+ }
+ )
+ return candidates
+
+
+@frozen
+class _SourceProject:
+ """Per-run context of the project being collected from, shared by every case."""
+
+ team_id: int
+ team_name: str
+ product_context: str
+ event_descriptions: EventDescriptionLookup
+
+
+def _write_case(
+ api: PostHogApi, root: Path, candidate: dict[str, Any], asset_id: int, source: _SourceProject
+) -> GoldenCase | None:
+ observation = candidate["observation"]
+ scanner = candidate["scanner"]
+ label = observation.get("label") or {}
+ case = GoldenCase(
+ case_id=observation["id"],
+ scanner_id=scanner["id"],
+ scanner_name=scanner["name"],
+ scanner_type=scanner["scanner_type"],
+ session_id=observation["session_id"],
+ team_id=source.team_id,
+ team_name=source.team_name,
+ snapshot=ScannerSnapshot.model_validate(observation["scanner_snapshot"]),
+ recorded_output=observation["scanner_result"]["model_output"],
+ known_freeform_tags=candidate.get("known_freeform_tags") or [],
+ label_is_correct=label.get("is_correct"),
+ label_feedback=label.get("feedback") or "",
+ collected_at=dt.datetime.now(dt.UTC).isoformat(),
+ )
+ case_dir = case.case_dir(root)
+ if case.video_path(root).exists() and case.inputs_path(root).exists():
+ try:
+ case.load_inputs(root)
+ return case
+ except Exception:
+ logger.warning("collector.reused_case_invalid", case_id=case.case_id)
+
+ inputs = build_llm_inputs(
+ api,
+ source.team_id,
+ case.session_id,
+ product_context=source.product_context,
+ event_descriptions=source.event_descriptions,
+ )
+ if inputs is None:
+ logger.warning("collector.no_events_for_session", session_id=case.session_id)
+ return None
+ case_dir.mkdir(parents=True, exist_ok=True)
+ api.download(f"/api/environments/{api.project_id}/exports/{asset_id}/content/?download=true", case.video_path(root))
+ # inputs.json lands last, so the reuse shortcut above only ever sees fully written cases.
+ case.inputs_path(root).write_text(inputs.model_dump_json())
+ return case
+
+
+def _reusable_existing_cases(root: Path) -> dict[str, GoldenCase]:
+ """Previously collected cases whose files are still present and parseable, keyed by case id."""
+ if not (root / MANIFEST_NAME).exists():
+ return {}
+ try:
+ existing = load_dataset(root)
+ except Exception:
+ logger.warning("collector.existing_manifest_unreadable", root=str(root))
+ return {}
+ reusable: dict[str, GoldenCase] = {}
+ for case in existing.cases:
+ try:
+ case.load_inputs(root)
+ except Exception:
+ continue
+ if case.video_path(root).exists():
+ reusable[case.case_id] = case
+ return reusable
+
+
+def _check_ai_consent(api: PostHogApi, environment: dict[str, Any]) -> None:
+ """The scan pipeline only runs over consented orgs; collecting recordings for evals holds the same bar."""
+ organization = api.get_json(f"/api/organizations/{environment['organization']}/")
+ if not organization.get("is_ai_data_processing_approved"):
+ raise RuntimeError(
+ "The source project's organization has not approved AI data processing; "
+ "collecting recordings for LLM evals requires that consent"
+ )
+
+
+def collect(
+ *,
+ host: str,
+ project_id: int,
+ api_key: str,
+ output: Path,
+ per_type: int,
+ scanner_ids: list[str] | None = None,
+ seed: int = 42,
+ max_observations_per_scanner: int = 200,
+) -> GoldenDataset:
+ api = PostHogApi(host, project_id, api_key)
+ # The environments API is keyed by team id; resolve the real team id once instead of assuming
+ # it equals the project id, and fail loudly when the two point at different projects.
+ environment = api.get_json(f"/api/environments/{project_id}/")
+ team_id = int(environment["id"])
+ if int(environment["project_id"]) != project_id:
+ raise RuntimeError(f"Environment {team_id} belongs to project {environment['project_id']}, not {project_id}")
+ _check_ai_consent(api, environment)
+ source = _SourceProject(
+ team_id=team_id,
+ team_name=str(environment.get("name", "")),
+ product_context=fetch_product_context_via_api(api),
+ event_descriptions=EventDescriptionLookup(api),
+ )
+ rng = random.Random(seed)
+
+ candidates = _fetch_candidates(api, scanner_ids, max_observations_per_scanner)
+ ordered = order_candidates(candidates, rng)
+ all_session_ids = sorted({c["observation"]["session_id"] for c in candidates})
+ assets = lookup_video_assets(api, team_id, all_session_ids)
+ logger.info(
+ "collector.candidates",
+ candidates=len(candidates),
+ with_video_asset=sum(1 for c in candidates if c["observation"]["session_id"] in assets),
+ types={t: len(group) for t, group in ordered.items()},
+ )
+
+ cases: list[GoldenCase] = []
+ for scanner_type, group in sorted(ordered.items()):
+ collected = 0
+ for candidate in group:
+ if collected >= per_type:
+ break
+ session_id = candidate["observation"]["session_id"]
+ asset = assets.get(session_id)
+ if asset is None or not asset_is_recorded_video(asset, candidate["observation"]):
+ continue
+ try:
+ case = _write_case(api, output, candidate, asset.asset_id, source)
+ except requests.HTTPError as exc:
+ logger.warning("collector.case_failed", observation_id=candidate["observation"]["id"], error=str(exc))
+ continue
+ if case is None:
+ continue
+ cases.append(case)
+ collected += 1
+ logger.info("collector.type_done", scanner_type=scanner_type, collected=collected, target=per_type)
+
+ # Merge with previously collected cases so re-runs extend the dataset instead of orphaning the
+ # case folders of earlier runs; this run's freshly collected version wins on overlap.
+ merged = _reusable_existing_cases(output)
+ merged.update({case.case_id: case for case in cases})
+ dataset = GoldenDataset(
+ created_at=dt.datetime.now(dt.UTC).isoformat(), host=host, project_id=project_id, cases=list(merged.values())
+ )
+ save_dataset(output, dataset)
+ return dataset
diff --git a/products/replay_vision/evals/dataset.py b/products/replay_vision/evals/dataset.py
new file mode 100644
index 000000000000..328ad5d7e782
--- /dev/null
+++ b/products/replay_vision/evals/dataset.py
@@ -0,0 +1,98 @@
+"""Golden-dataset layout shared by the collector (collect.py) and the eval suite.
+
+A dataset is a plain directory, never committed to the repo (it contains real session data):
+
+ manifest.json # GoldenDataset
+ cases/<case_id>/video.mp4 # rasterized recording, byte-identical to what production sent to Gemini
+ cases/<case_id>/inputs.json # ScannerLlmInputs snapshot (events table, session metadata, navigation)
+"""
+
+import os
+import datetime as dt
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from products.replay_vision.backend.temporal.types import ScannerLlmInputs, ScannerSnapshot
+
+DATASET_ENV_VAR = "REPLAY_VISION_EVAL_DATASET"
+MANIFEST_NAME = "manifest.json"
+VIDEO_NAME = "video.mp4"
+INPUTS_NAME = "inputs.json"
+# Production re-checks AI data-processing consent right before every generation; for the eval the only
+# check happens when collect.py runs, so bound how long that verification (and the collected recordings
+# themselves) may be trusted.
+DATASET_MAX_AGE_DAYS = 30
+
+
+def parse_utc(raw: Any) -> dt.datetime:
+ """Parse an ISO timestamp into UTC; a naive string would silently shift by this machine's timezone, so reject it."""
+ parsed = dt.datetime.fromisoformat(str(raw))
+ if parsed.tzinfo is None:
+ raise ValueError(f"timestamp {raw!r} has no timezone; expected an offset-aware ISO string")
+ return parsed.astimezone(dt.UTC)
+
+
+class GoldenCase(BaseModel, frozen=True):
+ """One collected observation: the frozen scanner config, its recorded output, and the human label if any."""
+
+ case_id: str = Field(description="Source ReplayObservation id; doubles as the case directory name.")
+ scanner_id: str
+ scanner_name: str
+ scanner_type: str
+ session_id: str
+ team_id: int
+ team_name: str
+ snapshot: ScannerSnapshot
+ recorded_output: dict[str, Any] = Field(description="scanner_result.model_output at collection time.")
+ known_freeform_tags: list[str] = Field(
+ default_factory=list,
+ description="Tag vocabulary a freeform classifier scans with, captured at collection time.",
+ )
+ label_is_correct: bool | None = None
+ label_feedback: str = ""
+ collected_at: str
+
+ def case_dir(self, root: Path) -> Path:
+ return root / "cases" / self.case_id
+
+ def video_path(self, root: Path) -> Path:
+ return self.case_dir(root) / VIDEO_NAME
+
+ def inputs_path(self, root: Path) -> Path:
+ return self.case_dir(root) / INPUTS_NAME
+
+ def load_inputs(self, root: Path) -> ScannerLlmInputs:
+ return ScannerLlmInputs.model_validate_json(self.inputs_path(root).read_text())
+
+
+class GoldenDataset(BaseModel, frozen=True):
+ created_at: str
+ host: str
+ project_id: int
+ cases: list[GoldenCase] = Field(default_factory=list)
+
+
+def dataset_root() -> Path | None:
+ raw = os.environ.get(DATASET_ENV_VAR, "").strip()
+ return Path(raw).expanduser() if raw else None
+
+
+def load_dataset(root: Path) -> GoldenDataset:
+ return GoldenDataset.model_validate_json((root / MANIFEST_NAME).read_text())
+
+
+def ensure_dataset_fresh(dataset: GoldenDataset, root: Path) -> None:
+ """Refuse to scan a dataset whose consent verification has lapsed (see DATASET_MAX_AGE_DAYS)."""
+ age = dt.datetime.now(dt.UTC) - parse_utc(dataset.created_at)
+ if age > dt.timedelta(days=DATASET_MAX_AGE_DAYS):
+ raise RuntimeError(
+ f"Dataset at {root} was collected {age.days} days ago (limit {DATASET_MAX_AGE_DAYS}); "
+ "re-run collect.py, which re-verifies AI data-processing consent"
+ )
+
+
+def save_dataset(root: Path, dataset: GoldenDataset) -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ (root / MANIFEST_NAME).write_text(dataset.model_dump_json(indent=2))
diff --git a/products/replay_vision/evals/eval_scanner_quality.py b/products/replay_vision/evals/eval_scanner_quality.py
new file mode 100644
index 000000000000..5a984ba8ceb5
--- /dev/null
+++ b/products/replay_vision/evals/eval_scanner_quality.py
@@ -0,0 +1,212 @@
+"""Golden-dataset quality suite for Replay Vision scanner prompts.
+
+Each case re-runs the production scan pipeline (same Jinja templates, response schemas, events
+tool, and citation handling, via run_scan) against a collected session video plus its event
+snapshot, then scores the fresh output against the recorded output and its human thumbs label.
+Edit the templates under backend/temporal/scanners/prompts/ and re-run to compare experiments
+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.
+"""
+
+import time
+import asyncio
+from functools import partial
+from pathlib import Path
+from typing import Any
+
+import structlog
+from google.genai import (
+ Client as RawGenAIClient,
+ types as genai_types,
+)
+
+from products.posthog_ai.eval_harness.config import BaseEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind
+from products.posthog_ai.eval_harness.one_shot import OneShotPrivateEval
+from products.replay_vision.backend.prompt_evaluation import primary_outcome
+from products.replay_vision.backend.temporal.activities.call_scanner_provider import apply_known_freeform_tags, run_scan
+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.evals.dataset import (
+ DATASET_ENV_VAR,
+ GoldenCase,
+ dataset_root,
+ ensure_dataset_fresh,
+ load_dataset,
+)
+from products.replay_vision.evals.scorers import (
+ SUMMARY_FIELDS,
+ LabeledOutcome,
+ OutputStability,
+ ScanCompleted,
+ ScoreAlignment,
+ SummaryAlignment,
+)
+
+SUITE_KIND = SuiteKind.ONE_SHOT
+
+logger = structlog.get_logger(__name__)
+
+_MAX_PROCESSING_WAIT_SECONDS = 300
+
+
+def build_case(golden: GoldenCase) -> BaseEvalCase:
+ """Map a golden case onto the scorer contract: which scorer applies, and what its reference is."""
+ expected: dict[str, Any] = {}
+ recorded_primary = primary_outcome(golden.recorded_output)
+ if golden.scanner_type in ("monitor", "classifier"):
+ if golden.label_is_correct is not None:
+ expected["labeled_outcome"] = {
+ "is_correct": golden.label_is_correct,
+ "recorded_primary": recorded_primary,
+ }
+ else:
+ expected["output_stability"] = {"recorded_primary": recorded_primary}
+ elif golden.scanner_type == "scorer":
+ recorded_score = golden.recorded_output.get("score")
+ scale = golden.snapshot.scanner_config.get("scale") or {}
+ scale_min, scale_max = scale.get("min"), scale.get("max")
+ # Default the bounds as a pair: defaulting them independently can fabricate a zero-width
+ # scale (e.g. min set to 1.0 with max defaulting to 1.0) that no scanner actually has.
+ if scale_min is None and scale_max is None:
+ scale_min, scale_max = 0.0, 1.0
+ # A thumbs-downed recorded score is a known-bad reference, so those cases only get scan_completed.
+ if (
+ golden.label_is_correct is not False
+ and isinstance(recorded_score, int | float)
+ and scale_min is not None
+ and scale_max is not None
+ ):
+ expected["score_alignment"] = {
+ "recorded_score": recorded_score,
+ "scale_min": scale_min,
+ "scale_max": scale_max,
+ }
+ elif golden.scanner_type == "summarizer":
+ if golden.label_is_correct is not False:
+ expected["summary_alignment"] = {
+ "reference": {field: golden.recorded_output.get(field) for field in SUMMARY_FIELDS}
+ }
+ return BaseEvalCase(
+ # The full case id: UUIDv7 ids collected in the same minute share their first characters,
+ # so any truncation makes same-type cases collide.
+ name=f"{golden.scanner_type}-{golden.case_id}",
+ prompt=str(golden.snapshot.scanner_config.get("prompt", "")),
+ expected=expected,
+ metadata={
+ "case_id": golden.case_id,
+ "scanner_name": golden.scanner_name,
+ "scanner_type": golden.scanner_type,
+ "session_id": golden.session_id,
+ "label_is_correct": golden.label_is_correct,
+ },
+ )
+
+
+def _upload_video(client: RawGenAIClient, path: Path) -> genai_types.File:
+ uploaded = client.files.upload(
+ file=str(path),
+ config=genai_types.UploadFileConfig(
+ mime_type="video/mp4", display_name=f"replay-vision-eval-{path.parent.name}"
+ ),
+ )
+ waited = 0.0
+ while uploaded.state and uploaded.state.name == "PROCESSING":
+ if waited >= _MAX_PROCESSING_WAIT_SECONDS:
+ raise RuntimeError(f"Gemini file for {path} stuck in PROCESSING after {waited:.0f}s")
+ time.sleep(0.5)
+ waited += 0.5
+ uploaded = client.files.get(name=uploaded.name or "")
+ state = uploaded.state.name if uploaded.state else None
+ if state != "ACTIVE" or not uploaded.uri:
+ raise RuntimeError(f"Gemini upload for {path} ended in state {state!r}")
+ return uploaded
+
+
+def _delete_file_quiet(client: RawGenAIClient, name: str | None) -> None:
+ if not name:
+ return
+ try:
+ client.files.delete(name=name)
+ except Exception:
+ logger.warning("replay_vision.eval.gemini_delete_failed", file=name)
+
+
+async def _scan_task(
+ root: Path, golden_by_case_id: dict[str, GoldenCase], case: BaseEvalCase, ctx: EvalContext
+) -> dict[str, Any]:
+ golden = golden_by_case_id[case.metadata["case_id"]]
+ llm_inputs = await asyncio.to_thread(golden.load_inputs, root)
+ # Rebuild the scanner the way production does, tag vocabulary included, so a freeform classifier
+ # is scored on its prompt rather than on missing context.
+ scanner = apply_known_freeform_tags(scanner_from_snapshot(golden.snapshot), golden.known_freeform_tags)
+ client = RawGenAIClient(api_key=gemini_api_key())
+ uploaded = await asyncio.to_thread(_upload_video, client, golden.video_path(root))
+ try:
+ try:
+ result = await run_scan(
+ snapshot=golden.snapshot,
+ scanner=scanner,
+ llm_inputs=llm_inputs,
+ team_name=golden.team_name,
+ file_uri=uploaded.uri or "",
+ mime_type=uploaded.mime_type or "video/mp4",
+ team_id=golden.team_id,
+ )
+ except ScannerFailureError as exc:
+ # A scan the model cannot complete is a prompt-quality signal (broken schema compliance),
+ # not an infra error, so it must score 0 rather than be excluded from the aggregate.
+ return {
+ "exit_code": 1,
+ "model_output": None,
+ "error": str(exc),
+ "scanner_type": golden.scanner_type,
+ "last_message": f"scan failed: {exc}",
+ }
+ finally:
+ await asyncio.to_thread(_delete_file_quiet, client, uploaded.name)
+
+ model_output = result.model_output.model_dump(mode="json")
+ primary = primary_outcome(model_output)
+ return {
+ "exit_code": 0,
+ "model_output": model_output,
+ "error": None,
+ "scanner_type": golden.scanner_type,
+ "signals_count": len(result.signals),
+ "primary": primary,
+ "last_message": primary or "",
+ }
+
+
+async def eval_scanner_quality(ctx: EvalContext) -> None:
+ root = dataset_root()
+ if root is None:
+ # Skip rather than fail: the dataset is local-only and most environments (CI included) won't have one.
+ logger.warning("replay_vision.eval.skipped_no_dataset", env_var=DATASET_ENV_VAR)
+ return
+ if not gemini_api_key():
+ raise RuntimeError("Set GEMINI_API_KEY (or REPLAY_VISION_GEMINI_API_KEY) to run replay-vision scans")
+
+ dataset = load_dataset(root)
+ ensure_dataset_fresh(dataset, root)
+ golden_cases = dataset.cases
+ missing = [g.case_id for g in golden_cases if not (g.video_path(root).exists() and g.inputs_path(root).exists())]
+ if missing:
+ raise RuntimeError(f"Dataset at {root} is missing files for cases {missing[:5]}; re-run collect.py")
+
+ cases = [build_case(golden) for golden in golden_cases]
+ golden_by_case_id = {case.metadata["case_id"]: golden for case, golden in zip(cases, golden_cases)}
+ # A collision here would silently score one observation against another session's video.
+ if len(golden_by_case_id) != len(golden_cases):
+ raise RuntimeError(f"Dataset at {root} contains duplicate case ids; re-collect into a clean directory")
+ await OneShotPrivateEval(
+ experiment_name="replay-vision-scanner-quality",
+ cases=cases,
+ scorers=[ScanCompleted(), LabeledOutcome(), OutputStability(), ScoreAlignment(), SummaryAlignment()],
+ task=partial(_scan_task, root, golden_by_case_id),
+ ctx=ctx,
+ )
diff --git a/products/replay_vision/evals/scorers.py b/products/replay_vision/evals/scorers.py
new file mode 100644
index 000000000000..f6b9be50fe8b
--- /dev/null
+++ b/products/replay_vision/evals/scorers.py
@@ -0,0 +1,167 @@
+"""Scorers for the replay-vision golden-dataset suite.
+
+Every scorer reads the task output dict built in eval_scanner_quality._scan_task plus its own
+sub-dict of ``case.expected``, and self-skips (score=None) when its key is absent, so one scorer
+list spans all four scanner types. Correctness scoring reuses the same primary-outcome and
+kept/regressed/fixed/still_wrong semantics as the in-product prompt-suggestion evaluation.
+"""
+
+import json
+from typing import Any
+
+from products.posthog_ai.eval_harness.scorers import GRADED_ALIGNMENT_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer
+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
+from products.replay_vision.backend.prompt_evaluation import classify_outcome, primary_outcome
+
+_OUTCOME_SCORES = {"kept": 1.0, "fixed": 1.0, "regressed": 0.0, "still_wrong": 0.0}
+
+# The summarizer output fields the judge compares; build_case snapshots the same fields as the reference.
+SUMMARY_FIELDS = ("title", "summary", "intent", "outcome", "friction_points", "keywords")
+
+
+def _spec(expected: dict[str, Any] | None, name: str) -> dict[str, Any] | None:
+ value = (expected or {}).get(name)
+ return value if isinstance(value, dict) else None
+
+
+class ScanCompleted(Scorer):
+ """Did the scan produce a validated output at all? A prompt change that breaks the response
+ schema or the semantic validators fails here before any quality scorer gets a say."""
+
+ def _name(self) -> str:
+ return "scan_completed"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ if not output:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "no output"})
+ if output.get("model_output"):
+ return Score(name=self._name(), score=1.0)
+ return Score(name=self._name(), score=0.0, metadata={"reason": output.get("error") or "no model_output"})
+
+
+class LabeledOutcome(Scorer):
+ """For human-labeled monitor/classifier cases: kept and fixed score 1, regressed and
+ still_wrong score 0, mirroring the in-product prompt-suggestion evaluation."""
+
+ def _name(self) -> str:
+ return "labeled_outcome"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ spec = _spec(expected, self._name())
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not a labeled discrete case"})
+ if not output or not output.get("model_output"):
+ return Score(name=self._name(), score=0.0, metadata={"reason": "scan produced no output"})
+ after = primary_outcome(output["model_output"])
+ outcome = classify_outcome(bool(spec["is_correct"]), spec.get("recorded_primary"), after)
+ return Score(
+ name=self._name(),
+ score=_OUTCOME_SCORES[outcome],
+ metadata={"outcome": outcome, "before": spec.get("recorded_primary"), "after": after},
+ )
+
+
+class OutputStability(Scorer):
+ """For unlabeled monitor/classifier cases there is no ground truth; score whether the fresh
+ outcome matches the recorded baseline. This measures churn introduced by a prompt change,
+ not correctness, so it is reported separately from labeled_outcome."""
+
+ def _name(self) -> str:
+ return "output_stability"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ spec = _spec(expected, self._name())
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not an unlabeled discrete case"})
+ if not output or not output.get("model_output"):
+ return Score(name=self._name(), score=0.0, metadata={"reason": "scan produced no output"})
+ after = primary_outcome(output["model_output"])
+ stable = after == spec.get("recorded_primary")
+ return Score(
+ name=self._name(),
+ score=1.0 if stable else 0.0,
+ metadata={"before": spec.get("recorded_primary"), "after": after},
+ )
+
+
+class ScoreAlignment(Scorer):
+ """For scorer scanners: distance from the reference score, normalized by the configured scale.
+
+ The reference is the recorded production score; cases whose recorded run was thumbs-downed
+ carry no spec (a known-bad reference would reward reproducing the mistake)."""
+
+ def _name(self) -> str:
+ return "score_alignment"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ spec = _spec(expected, self._name())
+ if spec is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "not a scorer case with a reference"})
+ span = float(spec["scale_max"]) - float(spec["scale_min"])
+ if span <= 0:
+ # A degenerate scale makes distance meaningless: the scorer is inapplicable, not failing.
+ return Score(name=self._name(), score=None, metadata={"reason": "zero-width scale"})
+ model_output = (output or {}).get("model_output") or {}
+ fresh = model_output.get("score")
+ if not isinstance(fresh, int | float) or isinstance(fresh, bool):
+ return Score(name=self._name(), score=0.0, metadata={"reason": "scan produced no numeric score"})
+ alignment = max(0.0, 1.0 - abs(float(fresh) - float(spec["recorded_score"])) / span)
+ return Score(
+ name=self._name(),
+ score=alignment,
+ metadata={"recorded_score": spec["recorded_score"], "fresh_score": fresh},
+ )
+
+
+_SUMMARY_JUDGE_PROMPT = """
+You are comparing two AI-generated analyses of the same session recording of a user using a product.
+
+The reference analysis was produced earlier and is trusted:
+{{expected}}
+
+The candidate analysis was just produced by a new version of the analyzer:
+{{output}}
+
+Grade how well the candidate captures the same user journey as the reference: the user's intent,
+what happened, the outcome, and any friction encountered. Wording differences are fine; missing or
+invented events, a different outcome, or lost friction points are not.
+
+Answer by selecting exactly one option:
+- perfect: same journey, intent, outcome, and friction; nothing meaningful lost or invented
+- near_perfect: same story with trivial omissions or additions
+- slightly_off: mostly the same story, but one meaningful detail is missing or invented
+- somewhat_misaligned: the story partially matches, but intent, outcome, or major friction diverges
+- strongly_misaligned: the candidate describes a substantially different session
+- useless: the candidate is empty, incoherent, or unrelated
+"""
+
+
+class SummaryAlignment(JudgedScorer):
+ """LLM judge for summarizer cases: does the fresh summary tell the same story as the reference?
+
+ The reference is the recorded output; thumbs-downed references are excluded at case-build time."""
+
+ def __init__(self, **kwargs: Any) -> None:
+ super().__init__(
+ name="summary_alignment",
+ prompt_template=_SUMMARY_JUDGE_PROMPT,
+ choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,
+ model=JUDGE_MODEL,
+ max_completion_tokens=512,
+ **kwargs,
+ )
+
+ def _prepare(self, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> dict[str, Any] | Score:
+ spec = _spec(expected, "summary_alignment")
+ if spec is None:
+ return Score(
+ name=self._name(), score=None, metadata={"reason": "not a summarizer case with a trusted reference"}
+ )
+ model_output = (output or {}).get("model_output")
+ if not model_output:
+ return Score(name=self._name(), score=0.0, metadata={"reason": "scan produced no output"})
+ candidate = {field: model_output.get(field) for field in SUMMARY_FIELDS}
+ return {
+ "output": json.dumps(candidate, indent=2),
+ "expected": json.dumps(spec.get("reference"), indent=2),
+ }
diff --git a/products/replay_vision/evals/test/__init__.py b/products/replay_vision/evals/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/replay_vision/evals/test/test_eval_scanner_quality.py b/products/replay_vision/evals/test/test_eval_scanner_quality.py
new file mode 100644
index 000000000000..121e0b1bcf49
--- /dev/null
+++ b/products/replay_vision/evals/test/test_eval_scanner_quality.py
@@ -0,0 +1,422 @@
+from __future__ import annotations
+
+import time
+import random
+import asyncio
+import datetime as dt
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer
+from products.replay_vision.backend.temporal.activities.call_scanner_provider import apply_known_freeform_tags
+from products.replay_vision.backend.temporal.scanners import ClassifierScanner
+from products.replay_vision.backend.temporal.types import ScannerSnapshot
+from products.replay_vision.evals import collector
+from products.replay_vision.evals.collector import (
+ _VideoAsset,
+ asset_is_recorded_video,
+ build_llm_inputs,
+ order_candidates,
+)
+from products.replay_vision.evals.dataset import GoldenCase, GoldenDataset, ensure_dataset_fresh, parse_utc
+from products.replay_vision.evals.eval_scanner_quality import build_case
+from products.replay_vision.evals.scorers import (
+ LabeledOutcome,
+ OutputStability,
+ ScanCompleted,
+ ScoreAlignment,
+ SummaryAlignment,
+)
+
+
+def _eval(scorer: Scorer, output: dict[str, Any] | None, expected: dict[str, Any] | None) -> Score:
+ # eval_async is the entrypoint the harness dispatches through.
+ score = asyncio.run(scorer.eval_async(output, expected))
+ assert isinstance(score, Score)
+ return score
+
+
+def _monitor_output(verdict: str) -> dict[str, Any]:
+ return {"model_output": {"verdict": verdict, "reasoning": "r", "confidence": 0.9}}
+
+
+def _golden(
+ scanner_type: str,
+ label_is_correct: bool | None,
+ recorded_output: dict[str, Any],
+ case_id: str = "0199aaaa-0000-7000-8000-000000000001",
+ scale: dict[str, Any] | None = None,
+) -> GoldenCase:
+ scanner_config: dict[str, Any] = {"prompt": "watch for rage clicks"}
+ if scanner_type == "classifier":
+ scanner_config["tags"] = ["a", "b"]
+ if scanner_type == "scorer":
+ scanner_config["scale"] = {"min": 1, "max": 5} if scale is None else scale
+ return GoldenCase(
+ case_id=case_id,
+ scanner_id="s1",
+ scanner_name="Test scanner",
+ scanner_type=scanner_type,
+ session_id="sess-1",
+ team_id=2,
+ team_name="Team",
+ snapshot=ScannerSnapshot(
+ name="Test scanner",
+ scanner_type=scanner_type,
+ scanner_version=1,
+ model="gemini-3.6-flash",
+ provider="google",
+ emits_signals=False,
+ scanner_config=scanner_config,
+ ),
+ recorded_output=recorded_output,
+ label_is_correct=label_is_correct,
+ collected_at="2026-07-30T00:00:00+00:00",
+ )
+
+
+ "is_correct,fresh_verdict,expected_score,expected_outcome",
+ [
+ (True, "yes", 1.0, "kept"),
+ (True, "no", 0.0, "regressed"),
+ (False, "no", 1.0, "fixed"),
+ (False, "yes", 0.0, "still_wrong"),
+ ],
+)
+def test_labeled_outcome_scores_thumbs_semantics(
+ is_correct: bool, fresh_verdict: str, expected_score: float, expected_outcome: str
+) -> None:
+ expected = {"labeled_outcome": {"is_correct": is_correct, "recorded_primary": "Verdict: yes"}}
+ score = _eval(LabeledOutcome(), _monitor_output(fresh_verdict), expected)
+ assert score.score == expected_score
+ assert score.metadata["outcome"] == expected_outcome
+
+
+ "scorer",
+ [LabeledOutcome(), OutputStability(), ScoreAlignment()],
+ ids=lambda s: s._name(),
+)
+def test_inapplicable_cases_skip_instead_of_failing(scorer: Any) -> None:
+ # None means "skipped" in the aggregate; returning 0.0 here would silently drag every
+ # experiment's mean down for cases the scorer was never meant to grade.
+ score = _eval(scorer, _monitor_output("yes"), {})
+ assert score.score is None
+
+
+def test_labeled_outcome_fails_when_scan_produced_nothing() -> None:
+ expected = {"labeled_outcome": {"is_correct": True, "recorded_primary": "Verdict: yes"}}
+ score = _eval(LabeledOutcome(), {"model_output": None, "error": "boom"}, expected)
+ assert score.score == 0.0
+
+
+ "fresh,expected_score",
+ [
+ (3.0, 1.0),
+ (4.0, 0.75),
+ (1.0, 0.5),
+ (None, 0.0),
+ ],
+)
+def test_score_alignment_normalizes_distance_by_scale(fresh: float | None, expected_score: float) -> None:
+ expected = {"score_alignment": {"recorded_score": 3.0, "scale_min": 1.0, "scale_max": 5.0}}
+ output = {"model_output": {"score": fresh} if fresh is not None else None}
+ score = _eval(ScoreAlignment(), output, expected)
+ assert score.score == pytest.approx(expected_score)
+
+
+def test_score_alignment_skips_zero_width_scale() -> None:
+ # min == max used to divide by zero and kill the case; a degenerate scale is inapplicable, not failing.
+ expected = {"score_alignment": {"recorded_score": 3.0, "scale_min": 3.0, "scale_max": 3.0}}
+ score = _eval(ScoreAlignment(), {"model_output": {"score": 3.0}}, expected)
+ assert score.score is None
+ assert score.metadata["reason"] == "zero-width scale"
+
+
+ "scale,expected_bounds",
+ [
+ ({}, (0.0, 1.0)),
+ ({"min": 1, "max": 5}, (1, 5)),
+ ({"min": 1}, None),
+ ({"max": 5}, None),
+ ],
+)
+def test_build_case_only_defaults_scale_bounds_as_a_pair(
+ scale: dict[str, Any], expected_bounds: tuple[float, float] | None
+) -> None:
+ case = build_case(_golden("scorer", None, {"score": 3.0}, scale=scale))
+ spec = case.expected.get("score_alignment")
+ if expected_bounds is None:
+ assert spec is None
+ else:
+ assert spec is not None
+ assert (spec["scale_min"], spec["scale_max"]) == expected_bounds
+
+
+def test_output_stability_compares_primary_outcomes() -> None:
+ expected = {"output_stability": {"recorded_primary": "Verdict: yes"}}
+ assert _eval(OutputStability(), _monitor_output("yes"), expected).score == 1.0
+ assert _eval(OutputStability(), _monitor_output("no"), expected).score == 0.0
+
+
+def test_scan_completed_fails_on_schema_breakage() -> None:
+ assert _eval(ScanCompleted(), _monitor_output("yes"), {}).score == 1.0
+ failed = _eval(ScanCompleted(), {"model_output": None, "error": "required step rejected"}, {})
+ assert failed.score == 0.0
+ assert "rejected" in failed.metadata["reason"]
+
+
+def test_summary_alignment_prepare_gates_on_reference() -> None:
+ # _prepare directly: going through eval_async would call the LLM judge.
+ judge = SummaryAlignment()
+ skipped = judge._prepare(_monitor_output("yes"), {})
+ assert isinstance(skipped, Score)
+ assert skipped.score is None
+ spec = {"summary_alignment": {"reference": {"title": "t", "summary": "s"}}}
+ no_output = judge._prepare({"model_output": None}, spec)
+ assert isinstance(no_output, Score)
+ assert no_output.score == 0.0
+ prepared = judge._prepare({"model_output": {"title": "t2", "summary": "s2"}}, spec)
+ assert isinstance(prepared, dict)
+ assert "t2" in prepared["output"]
+ assert "t" in prepared["expected"]
+
+
+ "scanner_type,label_is_correct,recorded_output,expected_key",
+ [
+ ("monitor", True, {"verdict": "yes"}, "labeled_outcome"),
+ ("monitor", None, {"verdict": "yes"}, "output_stability"),
+ ("classifier", False, {"tags": ["a"]}, "labeled_outcome"),
+ ("scorer", None, {"score": 3.0}, "score_alignment"),
+ ("scorer", True, {"score": 3.0}, "score_alignment"),
+ ("summarizer", None, {"title": "t", "summary": "s"}, "summary_alignment"),
+ ],
+)
+def test_build_case_routes_to_the_right_scorer(
+ scanner_type: str, label_is_correct: bool | None, recorded_output: dict[str, Any], expected_key: str
+) -> None:
+ case = build_case(_golden(scanner_type, label_is_correct, recorded_output))
+ assert list(case.expected.keys()) == [expected_key]
+
+
+ "scanner_type,recorded_output",
+ [
+ ("scorer", {"score": 3.0}),
+ ("summarizer", {"title": "t", "summary": "s"}),
+ ],
+)
+def test_build_case_never_trusts_a_thumbs_downed_reference(scanner_type: str, recorded_output: dict[str, Any]) -> None:
+ case = build_case(_golden(scanner_type, False, recorded_output))
+ assert case.expected == {}
+
+
+def test_case_names_do_not_collide_on_shared_uuid_prefix() -> None:
+ # UUIDv7 ids minted in the same minute share their leading characters; a truncated name
+ # collapsed such cases into one dataset entry, scoring one against another session's video.
+ goldens = [
+ _golden("monitor", True, {"verdict": "yes"}, case_id="0199aaaa-0000-7000-8000-000000000001"),
+ _golden("monitor", True, {"verdict": "yes"}, case_id="0199aaaa-0000-7000-8000-000000000002"),
+ ]
+ cases = [build_case(golden) for golden in goldens]
+ assert cases[0].name != cases[1].name
+ golden_by_case_id = {case.metadata["case_id"]: golden for case, golden in zip(cases, goldens)}
+ assert len(golden_by_case_id) == len(goldens)
+
+
+def test_order_candidates_puts_labeled_first_per_type() -> None:
+ def candidate(scanner_type: str, obs_id: str, labeled: bool) -> dict[str, Any]:
+ observation: dict[str, Any] = {"id": obs_id, "label": {"is_correct": True} if labeled else None}
+ return {"observation": observation, "scanner": {}, "scanner_type": scanner_type}
+
+ candidates = [
+ candidate("monitor", "u1", False),
+ candidate("monitor", "l1", True),
+ candidate("monitor", "u2", False),
+ candidate("scorer", "u3", False),
+ candidate("monitor", "l2", True),
+ ]
+ ordered = order_candidates(candidates, random.Random(42))
+ monitor_ids = [c["observation"]["id"] for c in ordered["monitor"]]
+ assert monitor_ids[:2] == ["l1", "l2"]
+ assert sorted(monitor_ids[2:]) == ["u1", "u2"]
+ assert [c["observation"]["id"] for c in ordered["scorer"]] == ["u3"]
+ assert ordered == order_candidates(candidates, random.Random(42))
+
+
+def test_parse_utc_rejects_naive_timestamps() -> None:
+ with pytest.raises(ValueError, match="no timezone"):
+ parse_utc("2026-08-01T12:00:00")
+ assert parse_utc("2026-08-01T12:00:00+12:00") == dt.datetime(2026, 8, 1, 0, 0, 0, tzinfo=dt.UTC)
+
+
[email protected]("age_days,fresh", [(0, True), (29, True), (31, False)])
+def test_ensure_dataset_fresh_enforces_consent_ttl(age_days: int, fresh: bool) -> None:
+ created = (dt.datetime.now(dt.UTC) - dt.timedelta(days=age_days)).isoformat()
+ dataset = GoldenDataset(created_at=created, host="https://us.posthog.com", project_id=2, cases=[])
+ if fresh:
+ ensure_dataset_fresh(dataset, Path("/tmp/dataset"))
+ else:
+ with pytest.raises(RuntimeError, match="re-run collect.py"):
+ ensure_dataset_fresh(dataset, Path("/tmp/dataset"))
+
+
+def test_apply_known_freeform_tags_only_touches_freeform_classifiers() -> None:
+ freeform = ClassifierScanner(prompt="x", tags=["a"], allow_freeform_tags=True)
+ tagged = apply_known_freeform_tags(freeform, ["search_error"])
+ assert isinstance(tagged, ClassifierScanner)
+ assert tagged.known_freeform_tags == ["search_error"]
+ # A fixed-vocab classifier rejects freeform output, so injecting tags there would break its validation.
+ fixed = ClassifierScanner(prompt="x", tags=["a"], allow_freeform_tags=False)
+ assert apply_known_freeform_tags(fixed, ["search_error"]) is fixed
+ assert apply_known_freeform_tags(freeform, []) is freeform
+
+
+def test_asset_is_recorded_video_rejects_rerasterized_assets() -> None:
+ asset = _VideoAsset(asset_id=1, created_at=dt.datetime(2026, 8, 1, tzinfo=dt.UTC))
+ assert asset_is_recorded_video(asset, {"completed_at": "2026-08-01T00:00:01+00:00"})
+ assert not asset_is_recorded_video(asset, {"completed_at": "2026-07-31T23:59:59+00:00"})
+ assert not asset_is_recorded_video(asset, {"completed_at": None})
+
+
+def test_known_freeform_tags_ranks_recent_observations_only() -> None:
+ now = dt.datetime.now(dt.UTC)
+
+ def observation(days_ago: int, model_output: dict[str, Any] | None) -> dict[str, Any]:
+ return {
+ "created_at": (now - dt.timedelta(days=days_ago)).isoformat(),
+ "scanner_result": {"model_output": model_output},
+ }
+
+ observations = [
+ observation(1, {"tags_freeform": ["Search Error", "slow page"]}),
+ observation(2, {"tags_freeform": ["search_error"]}),
+ observation(60, {"tags_freeform": ["ancient_tag"]}),
+ observation(0, None),
+ ]
+ assert collector._known_freeform_tags(observations) == ["search_error", "slow_page"]
+
+
+_SESSION_START = "2026-08-01T12:00:00+12:00"
+_SESSION_END = "2026-08-01T12:05:00+12:00"
+
+
+class _FakeApi:
+ project_id = 2
+
+ def hogql(self, query: str, values: dict[str, Any] | None = None) -> list[list[Any]]:
+ if "session_replay_events" in query:
+ return [["d1", _SESSION_START, _SESSION_END, 3, 4, 5, 60_000, 0, "https://example.com/a"]]
+ # Field order: DEFAULT_EVENT_FIELDS + _EXTRA_FIELDS.
+ return [
+ [
+ "$pageview",
+ "2026-08-01T12:00:10+12:00",
+ "",
+ [],
+ [],
+ "w1",
+ "https://example.com/a",
+ None,
+ "00000000-0000-0000-0000-00000000000a",
+ [],
+ [],
+ [],
+ ],
+ [
+ "$autocapture",
+ "2026-08-01T12:01:10+12:00",
+ "",
+ [],
+ [],
+ "w1",
+ "https://example.com/b",
+ "click",
+ "00000000-0000-0000-0000-00000000000b",
+ [],
+ [],
+ [],
+ ],
+ [
+ "file_uploaded",
+ "2026-08-01T12:02:10+12:00",
+ "",
+ [],
+ [],
+ "w1",
+ "https://example.com/b",
+ None,
+ "00000000-0000-0000-0000-00000000000c",
+ [],
+ [],
+ [],
+ ],
+ ]
+
+
+def test_event_offsets_do_not_depend_on_local_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
+ def offsets_under(tz: str) -> dict[str, int]:
+ monkeypatch.setenv("TZ", tz)
+ time.tzset()
+ inputs = build_llm_inputs(_FakeApi(), 2, "sess-1") # type: ignore[arg-type]
+ assert inputs is not None
+ return inputs.event_timestamps
+
+ try:
+ utc_offsets = offsets_under("UTC")
+ nz_offsets = offsets_under("Pacific/Auckland")
+ finally:
+ monkeypatch.undo()
+ time.tzset()
+ assert utc_offsets == nz_offsets
+ assert utc_offsets["00000000-0000-0000-0000-00000000000a"] == 10_000
+ assert utc_offsets["00000000-0000-0000-0000-00000000000b"] == 70_000
+
+
+class _DefinitionsApi(_FakeApi):
+ def __init__(self) -> None:
+ self.definition_requests = 0
+
+ def paginate(self, path: str, params: dict[str, Any] | None = None, max_items: int | None = None) -> Any:
+ self.definition_requests += 1
+ yield {"name": "file_uploaded", "description": "User uploaded a file"}
+
+
+def test_build_llm_inputs_carries_prompt_context() -> None:
+ api = _DefinitionsApi()
+ lookup = collector.EventDescriptionLookup(api) # type: ignore[arg-type]
+ for _ in range(2):
+ inputs = build_llm_inputs(api, 2, "sess-1", product_context="Acme sells anvils", event_descriptions=lookup) # type: ignore[arg-type]
+ assert inputs is not None
+ assert inputs.product_context == "Acme sells anvils"
+ assert inputs.event_descriptions == {"file_uploaded": "User uploaded a file"}
+ # The description cache spans sessions, so the second build must not refetch.
+ assert api.definition_requests == 1
+
+
+class _PagedApi:
+ def __init__(self, pages: list[list[list[Any]]]) -> None:
+ self._pages = pages
+ self._served = 0
+
+ def hogql(self, query: str, values: dict[str, Any] | None = None) -> list[list[Any]]:
+ page = self._pages[self._served] if self._served < len(self._pages) else []
+ self._served += 1
+ return page
+
+
+def test_fetch_events_caps_total_rows(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(collector, "_EVENTS_PER_PAGE", 2)
+ monkeypatch.setattr(collector, "_MAX_TOTAL_EVENT_ROWS", 5)
+ row = ["$pageview", _SESSION_START, "u"]
+ api = _PagedApi([[row, row], [row, row], [row, row], [row, row]])
+ start = dt.datetime(2026, 8, 1, 0, 0, 0, tzinfo=dt.UTC)
+ fetched = collector._fetch_events(api, "sess-1", start, start + dt.timedelta(minutes=5)) # type: ignore[arg-type]
+ assert len(fetched.rows) == 5
+ assert fetched.truncated
diff --git a/products/replay_vision/package.json b/products/replay_vision/package.json
index 1b757e5d0efa..b8fd736ed4ba 100644
--- a/products/replay_vision/package.json
+++ b/products/replay_vision/package.json
@@ -1,7 +1,7 @@
{
"name": "@posthog/products-replay-vision",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests evals/test/ -v --tb=short"
},
"dependencies": {
"@posthog/quill-charts": "workspace:*",