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): lens output quality — citations, indexer search, confidence calibration (#59269)

Tue Haulund3a5ef92b5b03
diff --git a/products/replay_vision/backend/api/lenses.py b/products/replay_vision/backend/api/lenses.py
index f44773aa98e2..69642bbe635e 100644
--- a/products/replay_vision/backend/api/lenses.py
+++ b/products/replay_vision/backend/api/lenses.py
@@ -58,7 +58,10 @@ class ReplayLensSerializer(serializers.ModelSerializer):
help_text="What the lens does: monitor, classifier, scorer, summarizer, or indexer.",
)
lens_config = serializers.JSONField(
- help_text="Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.",
+ help_text=(
+ "Type-specific configuration. Monitor/classifier/scorer/summarizer require `prompt`; "
+ "classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`."
+ ),
)
query = extend_schema_field(RecordingsQuery)( # type: ignore[arg-type, type-var]
serializers.JSONField(
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index cd9ddde6f9b8..f7febd1a38a7 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -65,6 +65,13 @@ class LensResultSerializer(serializers.Serializer):
min_value=0,
help_text="Number of PostHog Signals emitted from this observation.",
)
+ event_id_mapping = serializers.DictField(
+ child=serializers.JSONField(),
+ help_text=(
+ "Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: "
+ "`{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited."
+ ),
+ )
class ReplayObservationSerializer(serializers.ModelSerializer):
diff --git a/products/replay_vision/backend/migrations/0005_alter_replaylens_model.py b/products/replay_vision/backend/migrations/0005_alter_replaylens_model.py
new file mode 100644
index 000000000000..93f04ea4afdf
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0005_alter_replaylens_model.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.14 on 2026-05-21 05:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0004_replayobservation_lens_result"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="replaylens",
+ name="model",
+ field=models.CharField(
+ choices=[
+ ("gemini-3-flash-preview", "Gemini 3 Flash"),
+ ("gemini-3.1-flash-lite-preview", "Gemini 3 Flash Lite"),
+ ],
+ max_length=64,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index a4ea1593a0eb..c01a533b2047 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_replayobservation_lens_result
+0005_alter_replaylens_model
diff --git a/products/replay_vision/backend/models/replay_lens.py b/products/replay_vision/backend/models/replay_lens.py
index 56f728d400ce..3945270339ea 100644
--- a/products/replay_vision/backend/models/replay_lens.py
+++ b/products/replay_vision/backend/models/replay_lens.py
@@ -18,8 +18,8 @@ class LensProvider(models.TextChoices):
class LensModel(models.TextChoices):
- GEMINI_3_FLASH = "gemini-3-flash", "Gemini 3 Flash"
- GEMINI_3_FLASH_LITE = "gemini-3-flash-lite", "Gemini 3 Flash Lite"
+ GEMINI_3_FLASH = "gemini-3-flash-preview", "Gemini 3 Flash"
+ GEMINI_3_FLASH_LITE = "gemini-3.1-flash-lite-preview", "Gemini 3 Flash Lite"
class ReplayLens(UUIDModel):
diff --git a/products/replay_vision/backend/temporal/activities/call_lens_provider.py b/products/replay_vision/backend/temporal/activities/call_lens_provider.py
index 02a374ad2d41..bd17df6dc469 100644
--- a/products/replay_vision/backend/temporal/activities/call_lens_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_lens_provider.py
@@ -1,5 +1,6 @@
"""Single Gemini call per lens application; retries once on validation failure with the error fed back."""
+import re
import asyncio
from uuid import UUID
@@ -26,6 +27,7 @@ from products.replay_vision.backend.temporal.state import (
)
from products.replay_vision.backend.temporal.types import (
CallLensProviderInputs,
+ EventCitation,
LensCallOutput,
LensLlmInputs,
LensSnapshot,
@@ -34,6 +36,8 @@ from products.replay_vision.backend.temporal.types import (
logger = structlog.get_logger(__name__)
_MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation error appended
+# Captures the hex hash inside `(event_id <hash>)`; case-insensitive since model output isn't deterministic.
+_EVENT_ID_CITATION_RE = re.compile(r"\(event_id ([0-9a-f]{16})\)", re.IGNORECASE)
@activity.defn
@@ -61,7 +65,39 @@ async def call_lens_provider_activity(inputs: CallLensProviderInputs) -> LensCal
finalized = await _call_with_retry(
lens=lens, model=snapshot.model.value, prompt_parts=prompt_parts, team_id=inputs.team_id
)
- return LensCallOutput(model_output=finalized)
+ finalized, filtered_mapping = _resolve_citations(finalized, lens, llm_inputs.event_id_mapping)
+ return LensCallOutput(model_output=finalized, event_id_mapping=filtered_mapping)
+
+
+def _resolve_citations(
+ finalized: BaseModel,
+ lens: BaseLens,
+ mapping: dict[str, EventCitation],
+) -> tuple[BaseModel, dict[str, EventCitation]]:
+ """Slim event_id_mapping to citations actually used; strip hallucinated `(event_id <hash>)` parens whose hash isn't in `mapping`."""
+ cited_hashes: set[str] = set()
+ field_updates: dict[str, str] = {}
+ for field in lens.citation_fields:
+ text = getattr(finalized, field, None)
+ if not isinstance(text, str):
+ continue
+
+ def _filter(match: re.Match[str]) -> str:
+ hex_hash = match.group(1).lower()
+ if hex_hash not in mapping:
+ return "" # drop dead citation rather than leaving a parenthetical the FE can't resolve
+ cited_hashes.add(hex_hash)
+ # Rewrite with canonical lowercase hex so persisted text matches the mapping keys.
+ return f"(event_id {hex_hash})"
+
+ new_text = _EVENT_ID_CITATION_RE.sub(_filter, text)
+ if new_text != text:
+ field_updates[field] = new_text
+
+ if field_updates:
+ finalized = finalized.model_copy(update=field_updates)
+ filtered_mapping = {h: c for h, c in mapping.items() if h in cited_hashes}
+ return finalized, filtered_mapping
def _load_snapshot(observation_id: UUID, team_id: int) -> LensSnapshot:
@@ -144,7 +180,7 @@ async def _call_with_retry(*, lens: BaseLens, model: str, prompt_parts: list[typ
),
]
- # `non_retryable=True` so the workflow-level retry doesn't re-burn attempts on schema/semantic failures.
+ # non_retryable so workflow-level retries don't re-burn on schema/semantic failures.
raise ApplicationError(
f"Lens call rejected after {_MAX_LLM_ATTEMPTS} attempts: {last_error}",
non_retryable=True,
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
index 66f6fdf67861..6bad9f4d6898 100644
--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py
+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
@@ -1,4 +1,5 @@
import hashlib
+import datetime as dt
from typing import Any
from asgiref.sync import sync_to_async
@@ -19,6 +20,7 @@ from products.replay_vision.backend.temporal.state import (
store_data_in_redis,
)
from products.replay_vision.backend.temporal.types import (
+ EventCitation,
EventTable,
FetchSessionEventsInputs,
LensLlmInputs,
@@ -32,8 +34,10 @@ _MAX_EVENT_PAGES = 5 # Hard cap on prompt size for very chatty sessions; sets `
# Noisy SDK-internal events that add no signal for the LLM.
_EVENTS_TO_IGNORE = ["$feature_flag_called"]
-# `properties.*` is the HogQL-side prefix for JSON-property fields; bare names refer to top-level columns.
+# `properties.*` is the HogQL prefix for JSON properties; bare names are top-level columns.
+# `uuid` lets us map short event_ids back to real events; never sent to the LLM.
_EXTRA_FIELDS = [
+ "uuid",
"elements_chain_ids",
"properties.$exception_types",
"properties.$exception_values",
@@ -120,9 +124,10 @@ def _fetch_payload(team_id: int, session_id: str) -> LensLlmInputs | None:
if columns is None or not all_rows:
return None
- processed_columns, processed_rows, url_mapping, window_mapping = _process_events(columns, all_rows)
- # `RecordingMetadata` doesn't carry inactive_seconds directly; derive from duration minus active.
- # CH data quality can sporadically yield active > duration (tab visibility, clock skew), so clamp at 0.
+ processed_columns, processed_rows, url_mapping, window_mapping, event_id_mapping = _process_events(
+ columns, all_rows, session_start=metadata["start_time"]
+ )
+ # Derive from duration; clamp because CH can yield active > duration (tab visibility, clock skew).
inactive_seconds = max(0.0, duration_seconds - active_seconds)
return LensLlmInputs(
@@ -131,6 +136,7 @@ def _fetch_payload(team_id: int, session_id: str) -> LensLlmInputs | None:
events=EventTable(columns=processed_columns, rows=processed_rows),
url_mapping=url_mapping,
window_mapping=window_mapping,
+ event_id_mapping=event_id_mapping,
metadata=SessionMetadata(
start_time=metadata["start_time"],
end_time=metadata["end_time"],
@@ -148,39 +154,62 @@ def _fetch_payload(team_id: int, session_id: str) -> LensLlmInputs | None:
def _process_events(
- raw_columns: list[str], raw_rows: list[list[Any]]
-) -> tuple[list[str], list[list[Any]], dict[str, str], dict[str, str]]:
- """Dedup by content hash, truncate oversized fields, intern URLs and window IDs; prepend event_id + event_index columns."""
- url_index = raw_columns.index("$current_url") if "$current_url" in raw_columns else None
- window_index = raw_columns.index("$window_id") if "$window_id" in raw_columns else None
+ raw_columns: list[str], raw_rows: list[list[Any]], *, session_start: dt.datetime
+) -> tuple[list[str], list[list[Any]], dict[str, str], dict[str, str], dict[str, EventCitation]]:
+ """Dedup, truncate, intern URLs/windows, project uuid into the event_id mapping."""
+ uuid_index = raw_columns.index("uuid") if "uuid" in raw_columns else None
+ timestamp_index = raw_columns.index("timestamp") if "timestamp" in raw_columns else None
+ # All other indexes are over the LLM-visible column set (uuid stripped); compute once.
+ visible_columns = [c for i, c in enumerate(raw_columns) if i != uuid_index]
+ url_index = visible_columns.index("$current_url") if "$current_url" in visible_columns else None
+ window_index = visible_columns.index("$window_id") if "$window_id" in visible_columns else None
url_tokens: dict[str, str] = {} # actual -> token; flipped at the end for the prompt
window_tokens: dict[str, str] = {}
+ event_id_mapping: dict[str, EventCitation] = {}
seen_hashes: set[str] = set()
processed: list[list[Any]] = []
for row in raw_rows:
- # Hash the raw row first so duplicate-row rejection short-circuits the more expensive work below.
- raw_hash = _row_hash(row)
+ # Hash the LLM-visible projection (uuid is unique per event and would defeat dedup).
+ visible = list(row)
+ uuid_value: Any = None
+ if uuid_index is not None:
+ uuid_value = visible.pop(uuid_index)
+ raw_hash = _row_hash(visible)
if raw_hash in seen_hashes:
continue
seen_hashes.add(raw_hash)
- # Intern URLs and window IDs first so the token map keys on the real value, not a truncated prefix;
- # truncation runs after so any other oversized field still gets clipped.
- simplified = list(row)
+ if uuid_value is not None:
+ # ClickHouse returns `uuid` as `uuid.UUID`, not str.
+ event_id_mapping[raw_hash] = EventCitation(
+ uuid=str(uuid_value),
+ timestamp_ms=_relative_ms(row[timestamp_index] if timestamp_index is not None else None, session_start),
+ )
+
+ # Intern before truncate so the token map keys on the full value, not a clipped prefix.
if url_index is not None:
- simplified[url_index] = _intern(simplified[url_index], url_tokens, _URL_PREFIX)
+ visible[url_index] = _intern(visible[url_index], url_tokens, _URL_PREFIX)
if window_index is not None:
- simplified[window_index] = _intern(simplified[window_index], window_tokens, _WINDOW_PREFIX)
- simplified = [_truncate(v) for v in simplified]
- # event_index is sequential in the deduplicated output, not the raw input.
- processed.append([raw_hash, len(processed), *simplified])
+ visible[window_index] = _intern(visible[window_index], window_tokens, _WINDOW_PREFIX)
+ processed.append([raw_hash, *(_truncate(v) for v in visible)])
- output_columns = ["event_id", "event_index", *raw_columns]
+ output_columns = ["event_id", *visible_columns]
url_mapping = {token: actual for actual, token in url_tokens.items()}
window_mapping = {token: actual for actual, token in window_tokens.items()}
- return output_columns, processed, url_mapping, window_mapping
+ return output_columns, processed, url_mapping, window_mapping, event_id_mapping
+
+
+def _relative_ms(event_timestamp: Any, session_start: dt.datetime) -> int:
+ """Milliseconds since session start; 0 when the timestamp is missing, malformed, earlier than start, or tz-mismatched."""
+ if not isinstance(event_timestamp, dt.datetime):
+ return 0
+ try:
+ return max(0, int((event_timestamp - session_start).total_seconds() * 1000))
+ except TypeError:
+ # Mixed naive/aware datetimes raise here; fall back to 0 like the other defensive branches.
+ return 0
def _intern(value: Any, mapping: dict[str, str], prefix: str) -> Any:
diff --git a/products/replay_vision/backend/temporal/lenses/__init__.py b/products/replay_vision/backend/temporal/lenses/__init__.py
index 573cd9faf294..09eccb3309d5 100644
--- a/products/replay_vision/backend/temporal/lenses/__init__.py
+++ b/products/replay_vision/backend/temporal/lenses/__init__.py
@@ -8,10 +8,14 @@ from temporalio.exceptions import ApplicationError
from products.replay_vision.backend.models.replay_lens import LensType, ReplayLens
from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLensOutput
from products.replay_vision.backend.temporal.lenses.classifier import ClassifierLens, ClassifierOutput
-from products.replay_vision.backend.temporal.lenses.indexer import IndexerLens, IndexerOutput
-from products.replay_vision.backend.temporal.lenses.monitor import MonitorLens, MonitorOutput
+from products.replay_vision.backend.temporal.lenses.indexer import IndexerLens, IndexerLlmResponse, IndexerOutput
+from products.replay_vision.backend.temporal.lenses.monitor import MonitorLens, MonitorLlmResponse, MonitorOutput
from products.replay_vision.backend.temporal.lenses.scorer import ScorerLens, ScorerOutput, ScoreScale
-from products.replay_vision.backend.temporal.lenses.summarizer import SummarizerLens, SummarizerOutput
+from products.replay_vision.backend.temporal.lenses.summarizer import (
+ SummarizerLens,
+ SummarizerLlmResponse,
+ SummarizerOutput,
+)
from products.replay_vision.backend.temporal.types import AnyLensOutput, LensSnapshot
AnyLens = Annotated[
@@ -64,13 +68,16 @@ __all__ = [
"ClassifierLens",
"ClassifierOutput",
"IndexerLens",
+ "IndexerLlmResponse",
"IndexerOutput",
"MonitorLens",
+ "MonitorLlmResponse",
"MonitorOutput",
"ScoreScale",
"ScorerLens",
"ScorerOutput",
"SummarizerLens",
+ "SummarizerLlmResponse",
"SummarizerOutput",
"lens_from_db",
"lens_from_snapshot",
diff --git a/products/replay_vision/backend/temporal/lenses/base.py b/products/replay_vision/backend/temporal/lenses/base.py
index 65c6d7878fed..50c5490f7ae2 100644
--- a/products/replay_vision/backend/temporal/lenses/base.py
+++ b/products/replay_vision/backend/temporal/lenses/base.py
@@ -16,7 +16,12 @@ class BaseLensOutput(BaseModel, frozen=True):
confidence: float = Field(
ge=0,
le=1,
- description="Your confidence in this answer, 0 to 1. 0.5 means uncertain; 1.0 means absolutely sure.",
+ description=(
+ "Calibrated confidence, 0.0 to 1.0 with one decimal; use the full range — most answers fall in 0.6-0.9. "
+ "Ask: could a reasonable alternative answer be defended on the same evidence? If yes, cap at 0.7. "
+ "Reserve 0.9+ for unambiguous evidence with no plausible alternative. "
+ "1.0 should be exceedingly rare — pick 0.95 instead."
+ ),
)
def to_event_properties(self) -> dict[str, Any]:
@@ -25,13 +30,16 @@ class BaseLensOutput(BaseModel, frozen=True):
class BaseLens(BaseModel, frozen=True):
- """Common shape for every concrete lens; subclasses bind a `Literal` `lens_type` discriminator, a `prompt_template`, and an `llm_response_schema`."""
+ """Common shape for every concrete lens; subclasses bind `lens_type`, `prompt_template`, and `llm_response_schema`."""
- prompt: str
emits_signals: bool = False
# Per-lens-type Jinja2 template under `prompts/`. Subclasses set this.
prompt_template: ClassVar[str] = ""
+ # Names of free-text fields on the LLM response that may contain `(event_id <hash>)` citations.
+ citation_fields: ClassVar[tuple[str, ...]] = ()
+ # Persisted output class — subclasses override to stamp their `lens_type` discriminator.
+ output_cls: ClassVar[type["BaseLensOutput"] | None] = None
@property
def llm_response_schema(self) -> type[BaseModel]:
@@ -43,10 +51,10 @@ class BaseLens(BaseModel, frozen=True):
return {}
def finalize(self, llm_response: BaseModel) -> BaseLensOutput:
- """Build the final `BaseLensOutput` from the validated LLM response; default returns it unchanged."""
- if not isinstance(llm_response, BaseLensOutput):
- raise TypeError(f"Expected BaseLensOutput, got {type(llm_response).__name__}")
- return llm_response
+ """Stamp `output_cls` (with its `lens_type` discriminator) onto the validated LLM response."""
+ if self.output_cls is None:
+ raise NotImplementedError(f"{type(self).__name__} must set `output_cls`")
+ return self.output_cls(**llm_response.model_dump())
def validate_semantics(self, output: BaseLensOutput) -> str | None:
"""Lens-specific checks beyond Pydantic schema validation; return `None` when valid, otherwise an error string suitable to feed back into a re-prompt."""
@@ -66,7 +74,8 @@ class BaseLens(BaseModel, frozen=True):
return render_prompt(
self.prompt_template,
team_name=team_name,
- user_prompt=self.prompt,
+ # `prompt` lives on the four lenses that accept it; the indexer doesn't declare one.
+ user_prompt=getattr(self, "prompt", None),
events=events,
url_mapping=url_mapping or {},
window_mapping=window_mapping or {},
diff --git a/products/replay_vision/backend/temporal/lenses/classifier.py b/products/replay_vision/backend/temporal/lenses/classifier.py
index 6ef8dc67aa9f..193c57754d92 100644
--- a/products/replay_vision/backend/temporal/lenses/classifier.py
+++ b/products/replay_vision/backend/temporal/lenses/classifier.py
@@ -17,7 +17,10 @@ class ClassifierOutput(BaseLensOutput, frozen=True):
class ClassifierLens(BaseLens, frozen=True):
lens_type: Literal[LensType.CLASSIFIER] = LensType.CLASSIFIER
+ prompt: str
prompt_template: ClassVar[str] = "classifier.jinja"
+ citation_fields: ClassVar[tuple[str, ...]] = ("reasoning",)
+ output_cls: ClassVar[type[BaseLensOutput]] = ClassifierOutput
tags: list[str] = Field(min_length=1, description="Fixed vocabulary the model picks from.")
multi_label: bool = True
diff --git a/products/replay_vision/backend/temporal/lenses/indexer.py b/products/replay_vision/backend/temporal/lenses/indexer.py
index 807b678395ea..b6503345dc0a 100644
--- a/products/replay_vision/backend/temporal/lenses/indexer.py
+++ b/products/replay_vision/backend/temporal/lenses/indexer.py
@@ -1,25 +1,69 @@
-"""Indexer lens: produces four semantic facets for free-text search via embeddings."""
+"""Indexer lens: produces semantic facets for free-text search via embeddings."""
from typing import ClassVar, Literal
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
from products.replay_vision.backend.models.replay_lens import LensType
from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLensOutput
-class IndexerOutput(BaseLensOutput, frozen=True):
+class IndexerLlmResponse(BaseLensOutput, frozen=True):
+ """LLM-facing schema: the model decides these fields; `lens_type` is stamped by the workflow in `finalize`."""
+
+ intent: str = Field(
+ description=(
+ "One sentence describing what the user was trying to accomplish at the start of the session "
+ "(their goal), regardless of whether they succeeded."
+ )
+ )
+ summary: str = Field(
+ description=(
+ "One or two sentences describing the overall arc — what the user actually did and how the session progressed."
+ )
+ )
+ outcome: str = Field(
+ description=(
+ "One sentence describing the final state — where the user ended up and whether they accomplished "
+ "their intent. Do not restate the summary."
+ )
+ )
+ friction_points: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Named blockers, errors, or frustrations encountered, lowercase phrases "
+ "(e.g. 'login failure', 'buffering during replay', 'empty logs page'). Empty list if friction-free."
+ ),
+ )
+ keywords: list[str] = Field(
+ min_length=1,
+ description=(
+ "5-15 distinctive lowercase keywords for free-text search. Favor concrete action verbs "
+ "(clicked, abandoned, retried, submitted) and specific feature names. "
+ "Avoid generic terms that apply to most sessions ('user', 'session', 'navigation', 'interaction'); "
+ "avoid the team or product brand name."
+ ),
+ )
+
+ @field_validator("keywords", "friction_points", mode="after")
+ @classmethod
+ def _lowercase(cls, value: list[str]) -> list[str]:
+ # Lowercase so embedding similarity isn't fragmented by mixed casing.
+ return [v.lower() for v in value]
+
+
+class IndexerOutput(IndexerLlmResponse, frozen=True):
+ """Persisted output: adds the discriminator for the `AnyLensOutput` union."""
+
lens_type: Literal[LensType.INDEXER] = LensType.INDEXER
- summary: str = Field(description="One-sentence summary of what happened in the session.")
- user_type: str = Field(description="One-sentence characterization of the user (role, intent, behavior).")
- outcome: str = Field(description="One-sentence summary of how the session ended.")
- keywords: list[str] = Field(min_length=1, description="Distinctive keywords for free-text search (5-15 items).")
-class IndexerLens(BaseLens, frozen=True):
+class IndexerLens(BaseLens, frozen=True, extra="forbid"):
+ # `extra='forbid'` surfaces stale config (e.g. legacy `prompt`) instead of ignoring it.
lens_type: Literal[LensType.INDEXER] = LensType.INDEXER
prompt_template: ClassVar[str] = "indexer.jinja"
+ output_cls: ClassVar[type[BaseLensOutput]] = IndexerOutput
@property
def llm_response_schema(self) -> type[BaseModel]:
- return IndexerOutput
+ return IndexerLlmResponse
diff --git a/products/replay_vision/backend/temporal/lenses/monitor.py b/products/replay_vision/backend/temporal/lenses/monitor.py
index 52df2484ca9e..5ad1d1620ef4 100644
--- a/products/replay_vision/backend/temporal/lenses/monitor.py
+++ b/products/replay_vision/backend/temporal/lenses/monitor.py
@@ -8,18 +8,28 @@ from products.replay_vision.backend.models.replay_lens import LensType
from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLensOutput
-class MonitorOutput(BaseLensOutput, frozen=True):
- lens_type: Literal[LensType.MONITOR] = LensType.MONITOR
+class MonitorLlmResponse(BaseLensOutput, frozen=True):
+ """LLM-facing schema: the model decides these fields; `lens_type` is stamped by the workflow in `finalize`."""
+
verdict: bool = Field(description="Did the condition described in the lens intent occur during the session?")
reasoning: str = Field(
description="One paragraph grounding the verdict in concrete moments from the video and events."
)
+class MonitorOutput(MonitorLlmResponse, frozen=True):
+ """Persisted output: adds the discriminator for the `AnyLensOutput` union."""
+
+ lens_type: Literal[LensType.MONITOR] = LensType.MONITOR
+
+
class MonitorLens(BaseLens, frozen=True):
lens_type: Literal[LensType.MONITOR] = LensType.MONITOR
+ prompt: str
prompt_template: ClassVar[str] = "monitor.jinja"
+ citation_fields: ClassVar[tuple[str, ...]] = ("reasoning",)
+ output_cls: ClassVar[type[BaseLensOutput]] = MonitorOutput
@property
def llm_response_schema(self) -> type[BaseModel]:
- return MonitorOutput
+ return MonitorLlmResponse
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/_macros.jinja b/products/replay_vision/backend/temporal/lenses/prompts/_macros.jinja
new file mode 100644
index 000000000000..93d3ae4e4e6e
--- /dev/null
+++ b/products/replay_vision/backend/temporal/lenses/prompts/_macros.jinja
@@ -0,0 +1,4 @@
+{# Citation policy that lenses can opt into. Call as `{{ cite_in('reasoning') }}` or `{{ cite_in('summary') }}`. #}
+{%- macro cite_in(field_name) -%}
+Inside `{{ field_name }}`, cite key events as `(event_id <hex-hash>)`, e.g. `(event_id 030df0f4f45a4d7a)`. One event per parens; max 1–2 citations per paragraph. Cite only turning points, blockers, and climaxes — skip routine navigation. Never cite by ordinal, position, or any identifier other than the hex hash.
+{%- endmacro -%}
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/base.jinja b/products/replay_vision/backend/temporal/lenses/prompts/base.jinja
index 50716c78ccd1..70e466f45969 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/base.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/base.jinja
@@ -1,25 +1,17 @@
-You are an expert analyst of web application user sessions, skilled at reconstructing what users did and didn't accomplish by interpreting recorded session videos alongside analytics event timelines.
-
-Two rules guide every answer:
-- Ground every observation in direct evidence — a specific moment in the video or a specific event in the timeline. When citing a moment, reference the `event_id` of the relevant event so the reader can locate the evidence.
-- When evidence is ambiguous or absent, lower your `confidence` and explain the uncertainty. Better to admit uncertainty than fabricate detail.
-
-Answer the lens intent precisely. Don't expand into adjacent observations the lens didn't ask about.
-
-You're analyzing a session from {{ team_name }}. The video is a recording of the user session, played back at 8x speed with inactive periods skipped — time jumps in the video correspond to those cuts, while the events table preserves real timestamps.
-
-<lens_intent>
-{{ user_prompt }}
-</lens_intent>
+You're analyzing a recorded user session from {{ team_name }}. The video plays at 8× speed with inactive periods cut — time jumps in the video correspond to those cuts; the events table preserves real timestamps.
<task>
{% block task required %}{% endblock %}
</task>
+Approach:
+- Ground every claim in direct evidence — a specific moment in the video or a specific event in the timeline. When evidence is ambiguous or absent, lower `confidence` and say so.
+- Stay on the task. Don't drift into adjacent observations it didn't ask about.
+- Prefer admitting uncertainty over fabricating detail.
+
<events_format>
Each event is an object with these fields:
-- event_id: short hash you can cite in `reasoning` to point at a specific moment
-- event_index: 0-based sequence number in the session
+- event_id: 16-char hex hash; the only identifier you may use to refer to a specific event
- event: type of event (e.g. `$pageview`, `$autocapture`, `$exception`)
- timestamp: when it occurred (ISO 8601)
- elements_chain_href / elements_chain_texts / elements_chain_elements / elements_chain_ids: what was interacted with
@@ -28,7 +20,7 @@ Each event is an object with these fields:
- $event_type: interaction kind (click, submit, etc.)
- $exception_types / $exception_values: exception class + short description, when applicable
-Events are in chronological order; identical consecutive events have been deduplicated; sparse fields may be missing. Very chatty sessions are truncated to the first batch of events — when that happens `session_metadata.events_truncated` is true and you should rely more on the video and lower your `confidence` accordingly.
+Events are in chronological order; identical consecutive events have been deduplicated; sparse fields are omitted per-event. Very chatty sessions are truncated to the first batch of events — when that happens `session_metadata.events_truncated` is true and you should rely more on the video and lower your `confidence` accordingly.
</events_format>
<events>
@@ -45,7 +37,7 @@ Events are in chronological order; identical consecutive events have been dedupl
<session_metadata_format>
Session-level context. Fields (all optional, omitted when unknown):
-- start_time / duration_seconds: when the session ran and how long
+- start_time / end_time / duration_seconds: when the session ran and how long
- active_seconds / inactive_seconds: time the user was / wasn't interacting
- click_count / keypress_count / mouse_activity_count: interaction density
- start_url: where the user entered the session
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/classifier.jinja b/products/replay_vision/backend/temporal/lenses/prompts/classifier.jinja
index 8f5dcbf1a2ca..fad655a1173c 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/classifier.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/classifier.jinja
@@ -1,2 +1,7 @@
{% extends "base.jinja" %}
-{% block task %}Apply the lens intent and choose tags from this fixed vocabulary: [{{ vocabulary }}]. {% if multi_label %}Pick every tag that applies.{% else %}Pick exactly one tag.{% endif %} Use `reasoning` to cite the moments that justify your choice.{% endblock %}
+{% from "_macros.jinja" import cite_in %}
+{% block task %}Categorize this session according to: {{ user_prompt }}
+
+Choose tags from this fixed vocabulary: [{{ vocabulary }}]. {% if multi_label %}Pick every tag that applies.{% else %}Pick exactly one tag.{% endif %} Use `reasoning` to justify your choice.
+
+{{ cite_in('reasoning') }}{% endblock %}
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/indexer.jinja b/products/replay_vision/backend/temporal/lenses/prompts/indexer.jinja
index 37fd9f97cbb8..7b74ab46b927 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/indexer.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/indexer.jinja
@@ -1,2 +1,10 @@
{% extends "base.jinja" %}
-{% block task %}Produce four facets that characterize the session for free-text search. `summary`, `user_type`, and `outcome` are each one sentence. `keywords` is a free-form list of 5-15 distinctive words.{% endblock %}
+{% block task %}Produce facets that characterize this session for free-text search by future users.
+
+- `intent`: one sentence about what the user set out to do (their goal).
+- `summary`: 1-2 sentences on the overall arc.
+- `outcome`: one sentence on the final state — do not restate the summary.
+- `friction_points`: list of named blockers, errors, or frustrations the user hit (empty if none).
+- `keywords`: 5-15 distinctive lowercase terms — favor action verbs and specific feature names; skip generic terms ('user', 'session', 'navigation') and the product/team name.
+
+Do not include any event citations or `event_id` hashes anywhere — this output is consumed by a vector-embedding pipeline and hex tokens would be noise.{% endblock %}
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/monitor.jinja b/products/replay_vision/backend/temporal/lenses/prompts/monitor.jinja
index 4a243180860a..bc7f0e80bf8f 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/monitor.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/monitor.jinja
@@ -1,2 +1,7 @@
{% extends "base.jinja" %}
-{% block task %}Decide whether the condition described in the lens intent occurred. Set `verdict` to true only if there is direct visual or event-level evidence; otherwise false. Use `reasoning` to cite the specific moments that drove your decision.{% endblock %}
+{% from "_macros.jinja" import cite_in %}
+{% block task %}Decide whether the following condition occurred during the session: {{ user_prompt }}
+
+Set `verdict` to true only if there is direct visual or event-level evidence; otherwise false. Use `reasoning` to ground your decision.
+
+{{ cite_in('reasoning') }}{% endblock %}
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/scorer.jinja b/products/replay_vision/backend/temporal/lenses/prompts/scorer.jinja
index 764a0587e7a5..9df9a92bc130 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/scorer.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/scorer.jinja
@@ -1,2 +1,7 @@
{% extends "base.jinja" %}
-{% block task %}Apply the lens intent and rate the session on {% if scale_label %}the '{{ scale_label }}' scale{% else %}the scale{% endif %} from {{ scale_min }} to {{ scale_max }}. Use `reasoning` to cite the moments that drove your score.{% endblock %}
+{% from "_macros.jinja" import cite_in %}
+{% block task %}Rate this session against the following criterion: {{ user_prompt }}
+
+Score it on {% if scale_label %}the '{{ scale_label }}' scale{% else %}the scale{% endif %} from {{ scale_min }} to {{ scale_max }}. Use `reasoning` to explain what drove your score.
+
+{{ cite_in('reasoning') }}{% endblock %}
diff --git a/products/replay_vision/backend/temporal/lenses/prompts/summarizer.jinja b/products/replay_vision/backend/temporal/lenses/prompts/summarizer.jinja
index c5e036f59e3c..418952ad8e01 100644
--- a/products/replay_vision/backend/temporal/lenses/prompts/summarizer.jinja
+++ b/products/replay_vision/backend/temporal/lenses/prompts/summarizer.jinja
@@ -1,2 +1,7 @@
{% extends "base.jinja" %}
-{% block task %}Summarize the session per the lens intent. `title` is at most ~80 characters. `summary` should be {{ length_guidance }}.{% endblock %}
+{% from "_macros.jinja" import cite_in %}
+{% block task %}Summarize this session per these instructions: {{ user_prompt }}
+
+`title` is at most ~80 characters and contains no event citations. `summary` should be {{ length_guidance }}.
+
+{{ cite_in('summary') }}{% endblock %}
diff --git a/products/replay_vision/backend/temporal/lenses/scorer.py b/products/replay_vision/backend/temporal/lenses/scorer.py
index 85fc0010dafb..29c64c332c52 100644
--- a/products/replay_vision/backend/temporal/lenses/scorer.py
+++ b/products/replay_vision/backend/temporal/lenses/scorer.py
@@ -31,7 +31,10 @@ class ScorerOutput(BaseLensOutput, frozen=True):
class ScorerLens(BaseLens, frozen=True):
lens_type: Literal[LensType.SCORER] = LensType.SCORER
+ prompt: str
prompt_template: ClassVar[str] = "scorer.jinja"
+ citation_fields: ClassVar[tuple[str, ...]] = ("reasoning",)
+ output_cls: ClassVar[type[BaseLensOutput]] = ScorerOutput
scale: ScoreScale
@property
diff --git a/products/replay_vision/backend/temporal/lenses/summarizer.py b/products/replay_vision/backend/temporal/lenses/summarizer.py
index 9854a2d3b2b6..264af6f4b291 100644
--- a/products/replay_vision/backend/temporal/lenses/summarizer.py
+++ b/products/replay_vision/backend/temporal/lenses/summarizer.py
@@ -16,20 +16,30 @@ _LENGTH_GUIDANCE: dict[SummaryLength, str] = {
}
-class SummarizerOutput(BaseLensOutput, frozen=True):
- lens_type: Literal[LensType.SUMMARIZER] = LensType.SUMMARIZER
+class SummarizerLlmResponse(BaseLensOutput, frozen=True):
+ """LLM-facing schema: the model decides these fields; `lens_type` is stamped by the workflow in `finalize`."""
+
title: str = Field(max_length=120, description="Short title for the session (~80 chars). Plain text, no quotes.")
summary: str = Field(description="Body text whose length follows the lens's configured length.")
+class SummarizerOutput(SummarizerLlmResponse, frozen=True):
+ """Persisted output: adds the discriminator for the `AnyLensOutput` union."""
+
+ lens_type: Literal[LensType.SUMMARIZER] = LensType.SUMMARIZER
+
+
class SummarizerLens(BaseLens, frozen=True):
lens_type: Literal[LensType.SUMMARIZER] = LensType.SUMMARIZER
+ prompt: str
prompt_template: ClassVar[str] = "summarizer.jinja"
+ citation_fields: ClassVar[tuple[str, ...]] = ("summary",)
+ output_cls: ClassVar[type[BaseLensOutput]] = SummarizerOutput
length: SummaryLength = "medium"
@property
def llm_response_schema(self) -> type[BaseModel]:
- return SummarizerOutput
+ return SummarizerLlmResponse
def prompt_context(self) -> dict[str, Any]:
return {"length_guidance": _LENGTH_GUIDANCE[self.length]}
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 7724d9ff5ce3..55eaf00c1a57 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -42,11 +42,21 @@ class LensSnapshot(BaseModel, frozen=True):
) from exc
+class EventCitation(BaseModel, frozen=True):
+ """One entry in `event_id_mapping`: enough metadata for a UI to render a deep-link to the cited event."""
+
+ uuid: str = Field(description="Real PostHog event UUID; use with `/api/.../events/{uuid}` to fetch the event.")
+ timestamp_ms: int = Field(
+ ge=0, description="Milliseconds since session start; use to seek the session replay player to the moment."
+ )
+
+
class LensResult(BaseModel, frozen=True):
"""Result data of a completed observation, persisted into `ReplayObservation.lens_result`."""
model_output: AnyLensOutput
signals_count: int = Field(default=0, ge=0)
+ event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)
class ApplyLensInputs(BaseModel, frozen=True):
@@ -105,8 +115,16 @@ class EventTable(BaseModel, frozen=True):
return self
def as_dicts(self) -> list[dict[str, Any]]:
- """Zip columns and rows into per-event dicts for prompt-template rendering."""
- return [dict(zip(self.columns, row)) for row in self.rows]
+ """Zip columns and rows into per-event dicts for prompt-template rendering; drops null/empty values so sparse events render compactly."""
+ # Explicit `is None` (not membership) so 0/False are never dropped via `0 == False`.
+ return [
+ {
+ column: value
+ for column, value in zip(self.columns, row)
+ if value is not None and value != "" and value != [] and value != {}
+ }
+ for row in self.rows
+ ]
class SessionMetadata(BaseModel, frozen=True):
@@ -139,6 +157,7 @@ class LensLlmInputs(BaseModel, frozen=True):
# Reverse mappings: `url_1` -> actual URL, `window_1` -> actual window UUID.
url_mapping: dict[str, str] = Field(default_factory=dict)
window_mapping: dict[str, str] = Field(default_factory=dict)
+ event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)
metadata: SessionMetadata
@@ -172,6 +191,8 @@ class LensCallOutput(BaseModel, frozen=True):
"""Result of one `call_lens_provider` invocation."""
model_output: AnyLensOutput
+ # Short event_id (LLM-facing) -> citation metadata, propagated from `LensLlmInputs` for downstream resolution.
+ event_id_mapping: dict[str, EventCitation] = Field(default_factory=dict)
class CleanupGeminiFileInputs(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index 380a9bf0b061..8296d24d45af 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -152,7 +152,10 @@ class ApplyLensWorkflow(PostHogWorkflow):
mark_observation_succeeded_activity,
MarkObservationSucceededInputs(
observation_id=observation_id,
- lens_result=LensResult(model_output=call_output.model_output),
+ lens_result=LensResult(
+ model_output=call_output.model_output,
+ event_id_mapping=call_output.event_id_mapping,
+ ),
),
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=_STATE_ACTIVITY_RETRY,
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 4ad5a54fc8b1..3336da953b95 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -180,7 +180,7 @@ class TestReplayLensViewSet(_VisionAPITestCase):
("classifier", LensType.CLASSIFIER, {"prompt": "p", "tags": ["a", "b"]}),
("scorer", LensType.SCORER, {"prompt": "p", "scale": {"min": 0, "max": 10}}),
("summarizer", LensType.SUMMARIZER, {"prompt": "p"}),
- ("indexer", LensType.INDEXER, {"prompt": "p"}),
+ ("indexer", LensType.INDEXER, {}),
]
)
def test_create_accepts_valid_lens_config_per_type(
diff --git a/products/replay_vision/backend/tests/test_lenses.py b/products/replay_vision/backend/tests/test_lenses.py
index ea545f07cece..0fc9666f939e 100644
--- a/products/replay_vision/backend/tests/test_lenses.py
+++ b/products/replay_vision/backend/tests/test_lenses.py
@@ -10,6 +10,7 @@ from products.replay_vision.backend.temporal.lenses import (
IndexerLens,
IndexerOutput,
MonitorLens,
+ MonitorLlmResponse,
MonitorOutput,
ScorerLens,
ScorerOutput,
@@ -65,7 +66,7 @@ class TestMonitorLens:
assert isinstance(lens, MonitorLens)
assert lens.prompt == "did the user export?"
assert lens.emits_signals is False
- assert lens.llm_response_schema is MonitorOutput
+ assert lens.llm_response_schema is MonitorLlmResponse
def test_lens_from_db_raises_on_missing_prompt(self) -> None:
with pytest.raises(ApplicationError, match="prompt"):
@@ -79,10 +80,29 @@ class TestMonitorLens:
)
assert "session from Acme" in rendered
assert "did the user complete checkout?" in rendered
- assert "Decide whether the condition" in rendered
+ assert "Decide whether the following condition" in rendered
assert '"event":"$pageview"' in rendered
assert '"$current_url":"/cart"' in rendered
+ def test_build_prompt_drops_null_and_empty_fields_per_event(self) -> None:
+ lens = lens_from_db(_build_replay_lens())
+ rendered = lens.build_prompt(
+ team_name="Acme",
+ events=EventTable(
+ columns=["event", "$current_url", "$exception_types", "elements_chain_texts", "$event_type"],
+ rows=[
+ ["$pageview", "/cart", None, [], None],
+ ["$autocapture", "/cart", None, ["Add to cart"], "click"],
+ ],
+ ),
+ )
+ assert '"$exception_types"' not in rendered
+ assert '"elements_chain_texts":[]' not in rendered
+ assert '"$event_type":null' not in rendered
+ assert '"event":"$pageview"' in rendered
+ assert '"elements_chain_texts":["Add to cart"]' in rendered
+ assert '"$event_type":"click"' in rendered
+
def test_build_prompt_escapes_left_angle_to_block_tag_injection(self) -> None:
lens = lens_from_db(_build_replay_lens())
rendered = lens.build_prompt(
@@ -135,10 +155,15 @@ class TestMonitorLens:
assert "<session_metadata>" in rendered
assert '"active_seconds":180' in rendered
- def test_finalize_is_identity_for_monitor(self) -> None:
+ def test_finalize_stamps_lens_type_onto_llm_response(self) -> None:
lens = lens_from_db(_build_replay_lens())
- llm_output = MonitorOutput(verdict=True, reasoning="user clicked Export at 0:42", confidence=0.9)
- assert lens.finalize(llm_output) is llm_output
+ llm_response = MonitorLlmResponse(verdict=True, reasoning="user clicked Export at 0:42", confidence=0.9)
+ finalized = lens.finalize(llm_response)
+ assert isinstance(finalized, MonitorOutput)
+ assert finalized.lens_type == LensType.MONITOR
+ assert finalized.verdict is True
+ assert finalized.reasoning == "user clicked Export at 0:42"
+ assert finalized.confidence == 0.9
def test_validate_semantics_passes_for_well_formed_output(self) -> None:
lens = lens_from_db(_build_replay_lens())
@@ -369,14 +394,19 @@ class TestSummarizerLens:
class TestIndexerLens:
def test_lens_from_db_picks_indexer_subclass(self) -> None:
- lens = lens_from_db(_build_replay_lens(lens_type=LensType.INDEXER, lens_config={"prompt": "index"}))
+ lens = lens_from_db(_build_replay_lens(lens_type=LensType.INDEXER, lens_config={}))
assert isinstance(lens, IndexerLens)
+ def test_lens_from_db_rejects_prompt_on_indexer(self) -> None:
+ with pytest.raises(ApplicationError, match="prompt"):
+ lens_from_db(_build_replay_lens(lens_type=LensType.INDEXER, lens_config={"prompt": "x"}))
+
def test_output_round_trip_includes_all_facets(self) -> None:
out = IndexerOutput(
+ intent="File a regression report",
summary="Bug report",
- user_type="Power user filing a regression",
outcome="Submitted ticket",
+ friction_points=["upload failure"],
keywords=["bug", "regression", "ticket"],
confidence=0.8,
)
@@ -385,7 +415,24 @@ class TestIndexerLens:
def test_output_rejects_empty_keywords(self) -> None:
with pytest.raises(ValidationError):
- IndexerOutput(summary="x", user_type="x", outcome="x", keywords=[], confidence=0.8)
+ IndexerOutput(intent="x", summary="x", outcome="x", keywords=[], confidence=0.8)
+
+ def test_finalize_lowercases_keywords_and_friction_points(self) -> None:
+ lens = lens_from_db(_build_replay_lens(lens_type=LensType.INDEXER, lens_config={}))
+ from products.replay_vision.backend.temporal.lenses import IndexerLlmResponse
+
+ response = IndexerLlmResponse(
+ intent="Authenticate",
+ summary="Tried to log in",
+ outcome="Reached reset page",
+ friction_points=["Invalid Password Error", "Buffering Page"],
+ keywords=["Login", "Failed Attempt", "Reset"],
+ confidence=0.9,
+ )
+ finalized = lens.finalize(response)
+ assert isinstance(finalized, IndexerOutput)
+ assert finalized.friction_points == ["invalid password error", "buffering page"]
+ assert finalized.keywords == ["login", "failed attempt", "reset"]
class TestToEventProperties:
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 22384c5d0f7a..4a01c2dd02c1 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -378,14 +378,12 @@ class TestFetchSessionEventsActivity:
assert stored is not None
assert stored.session_id == "sess-1"
assert stored.team_id == lens.team_id
- assert stored.events.columns == ["event_id", "event_index", "event", "timestamp", "$session_id"]
+ assert stored.events.columns == ["event_id", "event", "timestamp", "$session_id"]
assert stored.metadata.start_time == start
assert stored.metadata.end_time == end
assert stored.metadata.duration_seconds == 300.0
assert len(stored.events.rows) == 1
- # Row is prepended with [event_id (hash), event_index (0), ...original values]
- assert stored.events.rows[0][1] == 0
- assert stored.events.rows[0][2:] == ["$pageview", "2026-05-12T10:00:00Z", "sess-1"]
+ assert stored.events.rows[0][1:] == ["$pageview", "2026-05-12T10:00:00Z", "sess-1"]
@pytest.mark.asyncio
async def test_paginates_through_get_events_until_short_page(self) -> None:
@@ -615,6 +613,48 @@ class TestFetchSessionEventsActivity:
assert stored is not None
assert len(stored.events.rows) == 2 # rageclick collapsed, plus the $pageview
+ @pytest.mark.asyncio
+ async def test_deduplicates_identical_content_despite_distinct_uuids(self) -> None:
+ # `uuid` is fetched per event but excluded from the dedup hash — otherwise identical events never collapse.
+ lens = await sync_to_async(_make_lens)()
+ observation_id = uuid.uuid4()
+ start = dt.datetime(2026, 5, 12, 10, 0, 0, tzinfo=dt.UTC)
+ metadata = {"start_time": start, "end_time": start, "duration": 60, "active_seconds": 30}
+ mock_obj = self._make_session_replay_events_mock(
+ metadata,
+ [
+ (
+ ["event", "timestamp", "uuid"],
+ [
+ ("rageclick", start, "00000000-0000-0000-0000-000000000001"),
+ ("rageclick", start, "00000000-0000-0000-0000-000000000002"), # distinct uuid, same content
+ ("rageclick", start, "00000000-0000-0000-0000-000000000003"),
+ ("$pageview", start, "00000000-0000-0000-0000-000000000004"),
+ ],
+ )
+ ],
+ )
+
+ with patch(
+ "products.replay_vision.backend.temporal.activities.fetch_session_events.SessionReplayEvents",
+ return_value=mock_obj,
+ ):
+ await fetch_session_events_activity(
+ FetchSessionEventsInputs(observation_id=observation_id, team_id=lens.team_id, session_id="sess-1")
+ )
+
+ redis_client = get_async_client(settings.REPLAY_VISION_REDIS_URL)
+ key = generate_state_key(label=StateActivitiesEnum.SESSION_EVENTS, state_id=str(observation_id))
+ stored = await get_data_class_from_redis(redis_client, key, target_class=LensLlmInputs)
+ assert stored is not None
+ assert len(stored.events.rows) == 2 # rageclick collapsed, $pageview kept
+ assert "uuid" not in stored.events.columns # not surfaced to the LLM
+ # The mapping records the FIRST uuid seen for each unique event_id.
+ assert len(stored.event_id_mapping) == 2
+ uuids = {c.uuid for c in stored.event_id_mapping.values()}
+ assert "00000000-0000-0000-0000-000000000001" in uuids
+ assert "00000000-0000-0000-0000-000000000004" in uuids
+
@pytest.mark.asyncio
async def test_session_metadata_round_trips_to_payload(self) -> None:
# `RecordingMetadata` uses `first_url` (not `start_url`) and has no `inactive_seconds` — we derive it from duration.
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 9bea9dce55f6..a067e1123648 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -34,14 +34,14 @@ export const LensProviderEnumApi = {
} as const
/**
- * * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
*/
export type LensModelEnumApi = (typeof LensModelEnumApi)[keyof typeof LensModelEnumApi]
export const LensModelEnumApi = {
- Gemini3Flash: 'gemini-3-flash',
- Gemini3FlashLite: 'gemini-3-flash-lite',
+ Gemini3FlashPreview: 'gemini-3-flash-preview',
+ Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
} as const
/**
@@ -116,7 +116,7 @@ export interface ReplayLensApi {
* `summarizer` - Summarizer
* `indexer` - Indexer */
lens_type: LensTypeEnumApi
- /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ /** Type-specific configuration. Monitor/classifier/scorer/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`. */
lens_config: unknown
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown
@@ -132,8 +132,8 @@ export interface ReplayLensApi {
provider?: LensProviderEnumApi
/** Concrete model to use for this lens.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model: LensModelEnumApi
/** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
enabled?: boolean
@@ -191,8 +191,8 @@ export interface LensSnapshotApi {
lens_version: number
/** Concrete model that ran the observation.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model: LensModelEnumApi
/** Concrete provider that ran the observation.
@@ -204,6 +204,11 @@ export interface LensSnapshotApi {
lens_config: unknown
}
+/**
+ * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.
+ */
+export type LensResultApiEventIdMapping = { [key: string]: unknown }
+
/**
* Mirrors `temporal.types.LensResult` for OpenAPI generation.
*/
@@ -215,6 +220,8 @@ export interface LensResultApi {
* @minimum 0
*/
signals_count: number
+ /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */
+ event_id_mapping: LensResultApiEventIdMapping
}
/**
@@ -289,7 +296,7 @@ export interface PatchedReplayLensApi {
* `summarizer` - Summarizer
* `indexer` - Indexer */
lens_type?: LensTypeEnumApi
- /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ /** Type-specific configuration. Monitor/classifier/scorer/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`. */
lens_config?: unknown
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown
@@ -305,8 +312,8 @@ export interface PatchedReplayLensApi {
provider?: LensProviderEnumApi
/** Concrete model to use for this lens.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model?: LensModelEnumApi
/** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
enabled?: boolean
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 1ce98d104cff..c8c94e270e58 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -31,7 +31,7 @@ export const VisionLensesCreateBody = /* @__PURE__ */ zod.object({
lens_config: zod
.unknown()
.describe(
- 'Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.'
+ 'Type-specific configuration. Monitor\/classifier\/scorer\/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`.'
),
query: zod
.unknown()
@@ -51,10 +51,12 @@ export const VisionLensesCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
model: zod
- .enum(['gemini-3-flash', 'gemini-3-flash-lite'])
- .describe('\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite')
+ .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
.describe(
- 'Concrete model to use for this lens.\n\n\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite'
+ '\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ )
+ .describe(
+ 'Concrete model to use for this lens.\n\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
),
enabled: zod
.boolean()
@@ -96,7 +98,7 @@ export const VisionLensesPartialUpdateBody = /* @__PURE__ */ zod.object({
.unknown()
.optional()
.describe(
- 'Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.'
+ 'Type-specific configuration. Monitor\/classifier\/scorer\/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`.'
),
query: zod
.unknown()
@@ -116,11 +118,13 @@ export const VisionLensesPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('LLM provider. v1 is Google-only.\n\n\* `google` - Google'),
model: zod
- .enum(['gemini-3-flash', 'gemini-3-flash-lite'])
- .describe('\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite')
+ .enum(['gemini-3-flash-preview', 'gemini-3.1-flash-lite-preview'])
+ .describe(
+ '\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
+ )
.optional()
.describe(
- 'Concrete model to use for this lens.\n\n\* `gemini-3-flash` - Gemini 3 Flash\n\* `gemini-3-flash-lite` - Gemini 3 Flash Lite'
+ 'Concrete model to use for this lens.\n\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite'
),
enabled: zod
.boolean()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 277276aa0f36..4d77b6230bc8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19910,15 +19910,15 @@ export namespace Schemas {
}
/**
- * * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
*/
export type LensModelEnum = typeof LensModelEnum[keyof typeof LensModelEnum];
export const LensModelEnum = {
- Gemini3Flash: 'gemini-3-flash',
- Gemini3FlashLite: 'gemini-3-flash-lite',
+ Gemini3FlashPreview: 'gemini-3-flash-preview',
+ Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
} as const;
/**
@@ -19931,6 +19931,11 @@ export namespace Schemas {
Google: 'google',
} as const;
+ /**
+ * Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited.
+ */
+ export type LensResultEventIdMapping = { [key: string]: unknown };
+
/**
* Mirrors `temporal.types.LensResult` for OpenAPI generation.
*/
@@ -19942,6 +19947,8 @@ export namespace Schemas {
* @minimum 0
*/
signals_count: number;
+ /** Maps the short `event_id` the LLM cites in `model_output.reasoning` to citation metadata: `{uuid, timestamp_ms}`. Only includes hashes the LLM actually cited. */
+ event_id_mapping: LensResultEventIdMapping;
}
/**
@@ -19980,8 +19987,8 @@ export namespace Schemas {
lens_version: number;
/** Concrete model that ran the observation.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model: LensModelEnum;
/** Concrete provider that ran the observation.
@@ -23112,7 +23119,7 @@ export namespace Schemas {
* `summarizer` - Summarizer
* `indexer` - Indexer */
lens_type: LensTypeEnum;
- /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ /** Type-specific configuration. Monitor/classifier/scorer/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`. */
lens_config: unknown;
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown;
@@ -23128,8 +23135,8 @@ export namespace Schemas {
provider?: LensProviderEnum;
/** Concrete model to use for this lens.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model: LensModelEnum;
/** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
enabled?: boolean;
@@ -29347,7 +29354,7 @@ export namespace Schemas {
* `summarizer` - Summarizer
* `indexer` - Indexer */
lens_type?: LensTypeEnum;
- /** Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc. */
+ /** Type-specific configuration. Monitor/classifier/scorer/summarizer require `prompt`; classifiers add `tags`, scorers add `scale`. Indexer is fixed-task and rejects `prompt`. */
lens_config?: unknown;
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown;
@@ -29363,8 +29370,8 @@ export namespace Schemas {
provider?: LensProviderEnum;
/** Concrete model to use for this lens.
- * `gemini-3-flash` - Gemini 3 Flash
- * `gemini-3-flash-lite` - Gemini 3 Flash Lite */
+ * `gemini-3-flash-preview` - Gemini 3 Flash
+ * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
model?: LensModelEnum;
/** When false, the reconciler removes the lens's Temporal schedule. On-demand triggers still work. */
enabled?: boolean;