: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): API validation + lens_result row column (#58685)
Tue Haulund28e24e9b6ca8
diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.pyindex bf9a4529889f..263247a6abf6 100644--- a/products/replay_vision/backend/admin.py+++ b/products/replay_vision/backend/admin.py@@ -27,6 +27,7 @@ class ReplayObservationAdmin(admin.ModelAdmin):"triggered_by","triggered_by_user","lens_snapshot",+ "lens_result","workflow_id","started_at","completed_at",diff --git a/products/replay_vision/backend/api/lenses.py b/products/replay_vision/backend/api/lenses.pyindex 9afbf0ea9487..f44773aa98e2 100644--- a/products/replay_vision/backend/api/lenses.py+++ b/products/replay_vision/backend/api/lenses.py@@ -9,7 +9,8 @@ import structlogimport django_filtersfrom asgiref.sync import async_to_syncfrom django_filters.rest_framework import DjangoFilterBackend-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import extend_schema, extend_schema_field+from pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied@@ -17,6 +18,8 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.schema import RecordingsQuery+from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.models.user import User@@ -31,8 +34,12 @@ from products.replay_vision.backend.temporal.constants import (MAX_SESSION_ID_LENGTH,build_apply_lens_workflow_id,)+from products.replay_vision.backend.temporal.lenses import validate_lens_configfrom products.replay_vision.backend.temporal.types import ApplyLensInputs+# Date is set by the schedule at trigger time, not by the user — strip on save.+_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")+logger = structlog.get_logger(__name__)@@ -50,14 +57,17 @@ class ReplayLensSerializer(serializers.ModelSerializer):choices=LensType.choices,help_text="What the lens does: monitor, classifier, scorer, summarizer, or indexer.",)- # TODO: validate `lens_config` shape per `lens_type` via Pydantic discriminated union.lens_config = serializers.JSONField(help_text="Type-specific configuration. Always includes `prompt`; classifiers add `tags`, scorers add `scale`, etc.",)- # TODO: type `query` against `posthog.schema.RecordingsQuery`.- query = serializers.JSONField(- required=False,- help_text="Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user.",+ query = extend_schema_field(RecordingsQuery)( # type: ignore[arg-type, type-var]+ serializers.JSONField(+ required=False,+ help_text=(+ "Persisted `RecordingsQuery` shape used to pick candidate sessions. "+ "`date_from`/`date_to` are stripped on save — the schedule controls time, not the user."+ ),+ ))sampling_rate = serializers.FloatField(required=False,@@ -136,8 +146,44 @@ class ReplayLensSerializer(serializers.ModelSerializer):duplicates = duplicates.exclude(pk=self.instance.pk)if duplicates.exists():raise serializers.ValidationError({"name": "A lens with this name already exists in this team."})+ self._validate_lens_config(attrs)+ self._validate_and_strip_query(attrs)return attrs+ def _validate_lens_config(self, attrs: dict[str, Any]) -> None:+ # Skip when neither field is touched on PATCH — the existing combination has already been validated.+ if "lens_config" not in attrs and "lens_type" not in attrs:+ return+ lens_type = attrs.get("lens_type", getattr(self.instance, "lens_type", None))+ lens_config = attrs.get("lens_config", getattr(self.instance, "lens_config", None))+ if lens_type is None:+ return # Upstream `lens_type` ChoiceField rejects this on create; PATCH with no instance is unreachable.+ try:+ validate_lens_config(lens_config=lens_config, lens_type=LensType(lens_type))+ except (ValueError, PydanticValidationError) as exc:+ raise serializers.ValidationError({"lens_config": str(exc)})++ def _validate_and_strip_query(self, attrs: dict[str, Any]) -> None:+ if "query" not in attrs:+ return+ try:+ RecordingsQuery.model_validate(attrs["query"])+ except PydanticValidationError as exc:+ raise serializers.ValidationError({"query": str(exc)})+ # Persist exactly what the user sent (validated), minus the date keys the schedule controls.+ attrs["query"] = {k: v for k, v in attrs["query"].items() if k not in _QUERY_FIELDS_TO_STRIP}++ def to_representation(self, instance: ReplayLens) -> dict[str, Any]:+ data = super().to_representation(instance)+ # `is not None` (not falsy) so empty-dict queries still revalidate against future schema changes.+ if data.get("query") is not None:+ try:+ RecordingsQuery.model_validate(data["query"])+ except PydanticValidationError:+ logger.exception("replay_vision.lens.malformed_query", lens_id=str(instance.id))+ data["query"] = None+ return data+def create(self, validated_data: dict[str, Any]) -> ReplayLens:team = self.context["get_team"]()user = cast(User, self.context["request"].user)diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 04f88755a26b..cd9ddde6f9b8 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -2,9 +2,11 @@ import uuidfrom django.db.models import QuerySet+import structlogimport django_filtersfrom django_filters.rest_framework import DjangoFilterBackend-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import extend_schema, extend_schema_field+from pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import mixins, serializers, viewsetsfrom rest_framework.exceptions import NotFound, PermissionDenied@@ -19,6 +21,9 @@ from products.replay_vision.backend.models.replay_observation import (ObservationTrigger,ReplayObservation,)+from products.replay_vision.backend.temporal.types import LensResult, LensSnapshot++logger = structlog.get_logger(__name__)class LensSnapshotSerializer(serializers.Serializer):@@ -50,6 +55,18 @@ class LensSnapshotSerializer(serializers.Serializer):)+class LensResultSerializer(serializers.Serializer):+ """Mirrors `temporal.types.LensResult` for OpenAPI generation."""++ model_output = serializers.JSONField(+ help_text="Validated lens output. Shape depends on `lens_snapshot.lens_type`; always carries `confidence` and `lens_type`.",+ )+ signals_count = serializers.IntegerField(+ min_value=0,+ help_text="Number of PostHog Signals emitted from this observation.",+ )++class ReplayObservationSerializer(serializers.ModelSerializer):lens_id = serializers.UUIDField(read_only=True, help_text="The lens that produced this observation.")session_id = serializers.CharField(read_only=True, help_text="Session recording id this lens was applied to.")@@ -68,10 +85,33 @@ class ReplayObservationSerializer(serializers.ModelSerializer):allow_blank=True,help_text="Temporal workflow id for progress queries and debugging. Empty until the workflow starts.",)- lens_snapshot = LensSnapshotSerializer(- read_only=True,+ lens_snapshot = serializers.SerializerMethodField(help_text="Frozen view of the lens at run time; lens edits do not retroactively mutate this observation.",)+ lens_result = serializers.SerializerMethodField(+ help_text="Result data persisted on success; null until the observation succeeds.",+ )++ @extend_schema_field(LensSnapshotSerializer(allow_null=True))+ def get_lens_snapshot(self, obj: ReplayObservation) -> dict | None:+ if not obj.lens_snapshot:+ return None # Snapshot is supposed to be populated at create; an empty blob is a write-side bug.+ try:+ return LensSnapshot.model_validate(obj.lens_snapshot).model_dump(mode="json")+ except PydanticValidationError:+ logger.exception("replay_vision.observation.malformed_lens_snapshot", observation_id=str(obj.id))+ return None++ @extend_schema_field(LensResultSerializer(allow_null=True))+ def get_lens_result(self, obj: ReplayObservation) -> dict | None:+ if not obj.lens_result:+ return None+ try:+ return LensResult.model_validate(obj.lens_result).model_dump(mode="json")+ except PydanticValidationError:+ logger.exception("replay_vision.observation.malformed_lens_result", observation_id=str(obj.id))+ return None+triggered_by = serializers.ChoiceField(choices=ObservationTrigger.choices,read_only=True,@@ -93,6 +133,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):"error_reason","workflow_id","lens_snapshot",+ "lens_result","triggered_by","triggered_by_user","started_at",diff --git a/products/replay_vision/backend/logic/__init__.py b/products/replay_vision/backend/logic/__init__.pydeleted file mode 100644index f8ef276416a3..000000000000--- a/products/replay_vision/backend/logic/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""-Business logic for replay_vision.--Validation, calculations, business rules, ORM queries.-Called by facade/api.py.--Split into submodules (e.g. logic/queries.py, logic/rules.py)-as this grows.-"""diff --git a/products/replay_vision/backend/migrations/0004_replayobservation_lens_result.py b/products/replay_vision/backend/migrations/0004_replayobservation_lens_result.pynew file mode 100644index 000000000000..d8b7a9353f6c--- /dev/null+++ b/products/replay_vision/backend/migrations/0004_replayobservation_lens_result.py@@ -0,0 +1,23 @@+# Generated by Django 5.2.13 on 2026-05-17 12:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ (+ "replay_vision",+ "0003_remove_replayobservation_lens_config_snapshot_and_more",+ ),+ ]++ operations = [+ migrations.AddField(+ model_name="replayobservation",+ name="lens_result",+ field=models.JSONField(+ default=dict,+ help_text="Result data persisted on success (model output, signals count); see `temporal.types.LensResult`.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 1611312c691f..a4ea1593a0eb 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_remove_replayobservation_lens_config_snapshot_and_more+0004_replayobservation_lens_resultdiff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex c9bd501f1efe..a78edb1683e6 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -40,6 +40,10 @@ class ReplayObservation(UUIDModel):default=dict,help_text="Frozen view of the lens at observation-create time; see `temporal.types.LensSnapshot`.",)+ lens_result = models.JSONField(+ default=dict,+ help_text="Result data persisted on success (model output, signals count); see `temporal.types.LensResult`.",+ )triggered_by = models.CharField(max_length=16,diff --git a/products/replay_vision/backend/presentation/__init__.py b/products/replay_vision/backend/presentation/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/replay_vision/backend/presentation/serializers.py b/products/replay_vision/backend/presentation/serializers.pydeleted file mode 100644index 8441903995d1..000000000000--- a/products/replay_vision/backend/presentation/serializers.py+++ /dev/null@@ -1,8 +0,0 @@-"""-DRF serializers for replay_vision.--Converts frozen dataclasses to/from JSON. Can be auto-generated from-dataclasses using DataclassSerializer.-"""--# from ..facade.contracts import ...diff --git a/products/replay_vision/backend/presentation/urls.py b/products/replay_vision/backend/presentation/urls.pydeleted file mode 100644index 7c866e1a0bee..000000000000--- a/products/replay_vision/backend/presentation/urls.py+++ /dev/null@@ -1,8 +0,0 @@-"""URL routes for replay_vision."""--from rest_framework.routers import DefaultRouter--# from .views import ...--router = DefaultRouter()-urlpatterns = router.urlsdiff --git a/products/replay_vision/backend/presentation/views.py b/products/replay_vision/backend/presentation/views.pydeleted file mode 100644index 861520004179..000000000000--- a/products/replay_vision/backend/presentation/views.py+++ /dev/null@@ -1,14 +0,0 @@-"""-DRF views for replay_vision.--Responsibilities:-- Validate incoming JSON (via serializers)-- Convert JSON to frozen dataclasses-- Call facade methods (facade/api.py)-- Convert frozen dataclasses to JSON responses--No business logic here - that belongs in logic.py via the facade.-"""---# from ..facade import apidiff --git a/products/replay_vision/backend/temporal/activities/call_lens_provider.py b/products/replay_vision/backend/temporal/activities/call_lens_provider.pyindex 07a7e97c8ad5..7a3bf34d2fc2 100644--- a/products/replay_vision/backend/temporal/activities/call_lens_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_lens_provider.py@@ -55,7 +55,7 @@ async def call_lens_provider_activity(inputs: CallLensProviderInputs) -> LensCalfinalized = await _call_with_retry(lens=lens, model=snapshot.model.value, prompt_parts=prompt_parts, team_id=inputs.team_id)- return LensCallOutput(model_output=finalized.model_dump())+ return LensCallOutput(model_output=finalized)def _load_snapshot(observation_id: UUID, team_id: int) -> LensSnapshot:@@ -91,6 +91,7 @@ async def _call_with_retry(*, lens: BaseLens, model: str, prompt_parts: list[typ"""One Gemini call, plus at most one retry that appends the validation error to the prompt."""client = genai.AsyncClient(api_key=settings.GEMINI_API_KEY)schema_class = lens.llm_response_schema+ response_schema = schema_class.model_json_schema()parts = list(prompt_parts)last_error: str | None = None@@ -100,7 +101,7 @@ async def _call_with_retry(*, lens: BaseLens, model: str, prompt_parts: list[typcontents=parts,config=types.GenerateContentConfig(response_mime_type="application/json",- response_json_schema=schema_class.model_json_schema(),+ response_json_schema=response_schema,),posthog_distinct_id=replay_vision_distinct_id(team_id),posthog_groups={"project": str(team_id)},diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.pyindex b646fce7d986..d8324d91c618 100644--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py@@ -51,7 +51,7 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:"provider_used": snapshot.provider.value,"emits_signals": snapshot.emits_signals,# Flatten lens output so HogQL can query individual fields without a JSON extract.- **{f"lens_output_{k}": v for k, v in inputs.model_output.items()},+ **inputs.model_output.to_event_properties(),}distinct_id = (str(observation.triggered_by_user_id)diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.pyindex 98439cce294f..a307c1b0a8e7 100644--- a/products/replay_vision/backend/temporal/activities/observation_state.py+++ b/products/replay_vision/backend/temporal/activities/observation_state.py@@ -37,11 +37,12 @@ def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> Non@activity.defndef mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs) -> None:- """Flip pending/running → succeeded. Idempotent: SUCCEEDED is not in the source filter."""+ """Flip pending/running → succeeded and persist the lens result. Idempotent: SUCCEEDED is not in the source filter."""ReplayObservation.objects.filter(pk=inputs.observation_id,status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],).update(status=ObservationStatus.SUCCEEDED,completed_at=timezone.now(),+ lens_result=inputs.lens_result.model_dump(mode="json"),)diff --git a/products/replay_vision/backend/temporal/lenses/__init__.py b/products/replay_vision/backend/temporal/lenses/__init__.pyindex 7dfd860cb92b..665054acf853 100644--- a/products/replay_vision/backend/temporal/lenses/__init__.py+++ b/products/replay_vision/backend/temporal/lenses/__init__.py@@ -12,7 +12,7 @@ from products.replay_vision.backend.temporal.lenses.indexer import IndexerLens,from products.replay_vision.backend.temporal.lenses.monitor import MonitorLens, MonitorOutputfrom products.replay_vision.backend.temporal.lenses.scorer import ScorerLens, ScorerOutput, ScoreScalefrom products.replay_vision.backend.temporal.lenses.summarizer import SummarizerLens, SummarizerOutput-from products.replay_vision.backend.temporal.types import LensSnapshot+from products.replay_vision.backend.temporal.types import AnyLensOutput, LensSnapshotAnyLens = Annotated[ClassifierLens | IndexerLens | MonitorLens | ScorerLens | SummarizerLens,@@ -21,16 +21,24 @@ AnyLens = Annotated[_LENS_ADAPTER: TypeAdapter[AnyLens] = TypeAdapter(AnyLens)-def _build_lens(*, lens_config: Any, lens_type: LensType, emits_signals: bool, source: str) -> AnyLens:+def validate_lens_config(*, lens_config: Any, lens_type: LensType, emits_signals: bool = False) -> AnyLens:+ """Validate `lens_config` against the per-`lens_type` Pydantic schema.++ Raises `ValueError` if `lens_config` isn't a dict, or `pydantic.ValidationError`+ on a type-specific schema failure. Callers in activity/workflow contexts wrap+ these as `ApplicationError(non_retryable=True)`; callers in DRF contexts wrap+ them as `serializers.ValidationError`.+ """if not isinstance(lens_config, dict):- raise ApplicationError(- f"{source}.lens_config must be a JSON object, got {type(lens_config).__name__}",- non_retryable=True,- )+ raise ValueError(f"lens_config must be a JSON object, got {type(lens_config).__name__}")# Spread `lens_config` first so the trusted top-level columns override anything that leaked into the JSON.+ return _LENS_ADAPTER.validate_python({**lens_config, "lens_type": lens_type, "emits_signals": emits_signals})+++def _build_lens(*, lens_config: Any, lens_type: LensType, emits_signals: bool, source: str) -> AnyLens:try:- return _LENS_ADAPTER.validate_python({**lens_config, "lens_type": lens_type, "emits_signals": emits_signals})- except ValidationError as exc:+ return validate_lens_config(lens_config=lens_config, lens_type=lens_type, emits_signals=emits_signals)+ except (ValueError, ValidationError) as exc:raise ApplicationError(f"{source}.lens_config is invalid: {exc}", non_retryable=True) from exc@@ -56,6 +64,7 @@ def lens_from_snapshot(snapshot: LensSnapshot) -> AnyLens:__all__ = ["AnyLens",+ "AnyLensOutput","BaseLens","BaseLensOutput","ClassifierLens",@@ -71,4 +80,5 @@ __all__ = ["SummarizerOutput","lens_from_db","lens_from_snapshot",+ "validate_lens_config",]diff --git a/products/replay_vision/backend/temporal/lenses/base.py b/products/replay_vision/backend/temporal/lenses/base.pyindex 2bf9bccedf23..20d805e019f1 100644--- a/products/replay_vision/backend/temporal/lenses/base.py+++ b/products/replay_vision/backend/temporal/lenses/base.py@@ -1,10 +1,12 @@"""Base class for all Replay Vision lens types."""import json+from typing import TYPE_CHECKING, Anyfrom pydantic import BaseModel, Field-from products.replay_vision.backend.temporal.types import EventTable+if TYPE_CHECKING:+ from products.replay_vision.backend.temporal.types import EventTable_PROMPT_TEMPLATE = """\You are applying a configured lens to a recorded user session of {team_name}.@@ -34,6 +36,13 @@ class BaseLensOutput(BaseModel, frozen=True):description="Your confidence in this answer, 0 to 1. 0.5 means uncertain; 1.0 means absolutely sure.",)+ def to_event_properties(self) -> dict[str, Any]:+ """Flatten with `lens_output_*` keys for the `$recording_observed` event.++ `lens_type` is excluded because it's already a top-level event property via the snapshot.+ """+ return {f"lens_output_{k}": v for k, v in self.model_dump(mode="json", exclude={"lens_type"}).items()}+class BaseLens(BaseModel, frozen=True):"""Common shape for every concrete lens; subclasses bind a `Literal` `lens_type` discriminator and override `task_instruction` + `llm_response_schema`."""@@ -60,7 +69,7 @@ class BaseLens(BaseModel, frozen=True):"""Lens-specific checks beyond Pydantic schema validation; return `None` when valid, otherwise an error string suitable to feed back into a re-prompt."""return None- def build_prompt(self, *, team_name: str, events: EventTable) -> str:+ def build_prompt(self, *, team_name: str, events: "EventTable") -> str:return _PROMPT_TEMPLATE.format(team_name=team_name,user_prompt=self.prompt,@@ -69,7 +78,7 @@ class BaseLens(BaseModel, frozen=True):)-def _render_events(events: EventTable) -> str:+def _render_events(events: "EventTable") -> str:if not events.rows:return "(no events captured during the session)"# Compact separators: Gemini parses fine without whitespace, and indent=2 burns thousands of prompt tokens.diff --git a/products/replay_vision/backend/temporal/lenses/classifier.py b/products/replay_vision/backend/temporal/lenses/classifier.pyindex 93d027470ac1..8a088306cb6f 100644--- a/products/replay_vision/backend/temporal/lenses/classifier.py+++ b/products/replay_vision/backend/temporal/lenses/classifier.py@@ -10,6 +10,7 @@ from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLeclass ClassifierOutput(BaseLensOutput, frozen=True):+ lens_type: Literal[LensType.CLASSIFIER] = LensType.CLASSIFIERtags: list[str] = Field(description="Subset of the lens's configured tag vocabulary.")reasoning: str = Field(description="One paragraph grounding the tag choice in concrete moments.")diff --git a/products/replay_vision/backend/temporal/lenses/indexer.py b/products/replay_vision/backend/temporal/lenses/indexer.pyindex bd5682153749..358a672e3cb6 100644--- a/products/replay_vision/backend/temporal/lenses/indexer.py+++ b/products/replay_vision/backend/temporal/lenses/indexer.py@@ -9,6 +9,7 @@ from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLeclass IndexerOutput(BaseLensOutput, frozen=True):+ lens_type: Literal[LensType.INDEXER] = LensType.INDEXERsummary: 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.")diff --git a/products/replay_vision/backend/temporal/lenses/monitor.py b/products/replay_vision/backend/temporal/lenses/monitor.pyindex 0e2683666de4..b3e14b205490 100644--- a/products/replay_vision/backend/temporal/lenses/monitor.py+++ b/products/replay_vision/backend/temporal/lenses/monitor.py@@ -9,6 +9,7 @@ from products.replay_vision.backend.temporal.lenses.base import BaseLens, BaseLeclass MonitorOutput(BaseLensOutput, frozen=True):+ lens_type: Literal[LensType.MONITOR] = LensType.MONITORverdict: 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."diff --git a/products/replay_vision/backend/temporal/lenses/scorer.py b/products/replay_vision/backend/temporal/lenses/scorer.pyindex d74efc81b11d..089d7a499f88 100644--- a/products/replay_vision/backend/temporal/lenses/scorer.py+++ b/products/replay_vision/backend/temporal/lenses/scorer.py@@ -21,6 +21,7 @@ class ScoreScale(BaseModel, frozen=True):class ScorerOutput(BaseLensOutput, frozen=True):+ lens_type: Literal[LensType.SCORER] = LensType.SCORERscore: float = Field(description="Numeric score on the configured scale.")reasoning: str = Field(description="One paragraph grounding the score in concrete moments.")label: str | None = Field(diff --git a/products/replay_vision/backend/temporal/lenses/summarizer.py b/products/replay_vision/backend/temporal/lenses/summarizer.pyindex 45b8ea8ba6c1..3fc14c4aff92 100644--- a/products/replay_vision/backend/temporal/lenses/summarizer.py+++ b/products/replay_vision/backend/temporal/lenses/summarizer.py@@ -17,6 +17,7 @@ _LENGTH_GUIDANCE: dict[SummaryLength, str] = {class SummarizerOutput(BaseLensOutput, frozen=True):+ lens_type: Literal[LensType.SUMMARIZER] = LensType.SUMMARIZERtitle: 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.")diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex 59e9b4816067..6b6efb691fff 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -1,5 +1,5 @@import datetime as dt-from typing import Any+from typing import Annotated, Anyfrom uuid import UUIDfrom pydantic import BaseModel, Field, ValidationError, model_validator@@ -8,6 +8,16 @@ from temporalio.exceptions import ApplicationErrorfrom products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensTypefrom products.replay_vision.backend.models.replay_observation import ObservationTriggerfrom products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.temporal.lenses.classifier import ClassifierOutput+from products.replay_vision.backend.temporal.lenses.indexer import IndexerOutput+from products.replay_vision.backend.temporal.lenses.monitor import MonitorOutput+from products.replay_vision.backend.temporal.lenses.scorer import ScorerOutput+from products.replay_vision.backend.temporal.lenses.summarizer import SummarizerOutput++AnyLensOutput = Annotated[+ ClassifierOutput | IndexerOutput | MonitorOutput | ScorerOutput | SummarizerOutput,+ Field(discriminator="lens_type"),+]class LensSnapshot(BaseModel, frozen=True):@@ -32,6 +42,13 @@ class LensSnapshot(BaseModel, frozen=True):) from exc+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)++class ApplyLensInputs(BaseModel, frozen=True):"""Input to ApplyLensWorkflow."""@@ -126,9 +143,9 @@ class CallLensProviderInputs(BaseModel, frozen=True):class LensCallOutput(BaseModel, frozen=True):- """Result of one `call_lens_provider` invocation; `model_output` is the lens-specific dict (shape varies per `LensType`)."""+ """Result of one `call_lens_provider` invocation."""- model_output: dict[str, Any]+ model_output: AnyLensOutputclass CleanupGeminiFileInputs(BaseModel, frozen=True):@@ -137,10 +154,11 @@ class CleanupGeminiFileInputs(BaseModel, frozen=True):class MarkObservationSucceededInputs(BaseModel, frozen=True):observation_id: UUID+ lens_result: LensResultclass EmitObservationEventInputs(BaseModel, frozen=True):- """Payload for the `$recording_observed` capture; this is the only place lens output lives outside of ClickHouse."""+ """Payload for the `$recording_observed` capture."""observation_id: UUID- model_output: dict[str, Any]+ model_output: AnyLensOutputdiff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 1cb33b30a2c8..380a9bf0b061 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -37,6 +37,7 @@ from products.replay_vision.backend.temporal.types import (EnsureSessionAssetOutput,FetchSessionEventsInputs,LensCallOutput,+ LensResult,MarkObservationFailedInputs,MarkObservationRunningInputs,MarkObservationSucceededInputs,@@ -149,7 +150,10 @@ class ApplyLensWorkflow(PostHogWorkflow):)await wf.execute_activity(mark_observation_succeeded_activity,- MarkObservationSucceededInputs(observation_id=observation_id),+ MarkObservationSucceededInputs(+ observation_id=observation_id,+ lens_result=LensResult(model_output=call_output.model_output),+ ),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.pyindex 3933c0075151..4ad5a54fc8b1 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1,4 +1,5 @@from datetime import timedelta+from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -173,6 +174,125 @@ class TestReplayLensViewSet(_VisionAPITestCase):self.assertEqual(resp.status_code, 200)self.assertEqual(resp.json()["lens_version"], 1)+ @parameterized.expand(+ [+ ("monitor", LensType.MONITOR, {"prompt": "p"}),+ ("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"}),+ ]+ )+ def test_create_accepts_valid_lens_config_per_type(+ self, label: str, lens_type: LensType, lens_config: dict+ ) -> None:+ resp = self.client.post(+ self.lenses_url,+ data={+ "name": f"valid-{label}",+ "lens_type": lens_type,+ "lens_config": lens_config,+ "model": LensModel.GEMINI_3_FLASH,+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 201, resp.json())++ @parameterized.expand(+ [+ ("classifier_without_tags", LensType.CLASSIFIER, {"prompt": "p"}),+ ("classifier_empty_tags", LensType.CLASSIFIER, {"prompt": "p", "tags": []}),+ ("scorer_inverted_scale", LensType.SCORER, {"prompt": "p", "scale": {"min": 10, "max": 0}}),+ ("monitor_missing_prompt", LensType.MONITOR, {}),+ ("not_a_dict", LensType.MONITOR, "just a string"),+ ]+ )+ def test_create_rejects_invalid_lens_config_per_type(+ self, label: str, lens_type: LensType, lens_config: Any+ ) -> None:+ resp = self.client.post(+ self.lenses_url,+ data={+ "name": f"invalid-{label}",+ "lens_type": lens_type,+ "lens_config": lens_config,+ "model": LensModel.GEMINI_3_FLASH,+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertEqual(resp.json()["attr"], "lens_config")++ def test_patch_lens_type_validates_against_existing_config(self) -> None:+ # Existing monitor lens has {"prompt": "..."}; switching to classifier without tags must 400.+ lens = self._create_lens()+ resp = self.client.patch(+ f"{self.lenses_url}{lens.id}/",+ data={"lens_type": LensType.CLASSIFIER},+ format="json",+ )+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertEqual(resp.json()["attr"], "lens_config")++ def test_patch_can_change_lens_type_with_matching_config(self) -> None:+ lens = self._create_lens()+ resp = self.client.patch(+ f"{self.lenses_url}{lens.id}/",+ data={"lens_type": LensType.CLASSIFIER, "lens_config": {"prompt": "p", "tags": ["x"]}},+ format="json",+ )+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(resp.json()["lens_type"], LensType.CLASSIFIER)++ def test_create_accepts_valid_query(self) -> None:+ resp = self.client.post(+ self.lenses_url,+ data={+ "name": "with-query",+ "lens_type": LensType.MONITOR,+ "lens_config": {"prompt": "p"},+ "model": LensModel.GEMINI_3_FLASH,+ "query": {"filter_test_accounts": True},+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 201, resp.json())+ self.assertEqual(resp.json()["query"], {"filter_test_accounts": True})++ def test_create_strips_date_fields_from_query(self) -> None:+ # The schedule controls time, not the user.+ resp = self.client.post(+ self.lenses_url,+ data={+ "name": "stripped",+ "lens_type": LensType.MONITOR,+ "lens_config": {"prompt": "p"},+ "model": LensModel.GEMINI_3_FLASH,+ "query": {"date_from": "-7d", "date_to": "-1d", "filter_test_accounts": True},+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 201, resp.json())+ body_query = resp.json()["query"]+ self.assertNotIn("date_from", body_query)+ self.assertNotIn("date_to", body_query)+ self.assertEqual(body_query["filter_test_accounts"], True)++ def test_create_rejects_invalid_query(self) -> None:+ resp = self.client.post(+ self.lenses_url,+ data={+ "name": "bad-query",+ "lens_type": LensType.MONITOR,+ "lens_config": {"prompt": "p"},+ "model": LensModel.GEMINI_3_FLASH,+ "query": {"this_field_does_not_exist": True},+ },+ format="json",+ )+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertEqual(resp.json()["attr"], "query")+def test_delete(self) -> None:lens = self._create_lens()resp = self.client.delete(f"{self.lenses_url}{lens.id}/")@@ -287,6 +407,28 @@ class TestReplayObservationViewSet(_VisionAPITestCase):resp = self.client.get(f"{self.observations_url(str(self.lens.id))}{obs.id}/")self.assertEqual(resp.status_code, 200)self.assertEqual(resp.json()["session_id"], obs.session_id)+ self.assertIsNone(resp.json()["lens_result"]) # null until succeeded++ def test_retrieve_observation_exposes_lens_result_when_succeeded(self) -> None:+ obs = self._create_observation(+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ lens_result={+ "model_output": {+ "lens_type": "monitor",+ "verdict": True,+ "reasoning": "user completed checkout",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ resp = self.client.get(f"{self.observations_url(str(self.lens.id))}{obs.id}/")+ self.assertEqual(resp.status_code, 200)+ body = resp.json()+ self.assertEqual(body["lens_result"]["signals_count"], 0)+ self.assertEqual(body["lens_result"]["model_output"]["verdict"], True)+ self.assertEqual(body["lens_result"]["model_output"]["confidence"], 0.9)@parameterized.expand([diff --git a/products/replay_vision/backend/tests/test_lenses.py b/products/replay_vision/backend/tests/test_lenses.pyindex 110340d7414f..d21c0935be17 100644--- a/products/replay_vision/backend/tests/test_lenses.py+++ b/products/replay_vision/backend/tests/test_lenses.py@@ -351,3 +351,21 @@ 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)+++class TestToEventProperties:+ def test_flattens_with_lens_output_prefix(self) -> None:+ out = MonitorOutput(verdict=True, reasoning="found it", confidence=0.9)+ props = out.to_event_properties()+ assert props == {+ "lens_output_verdict": True,+ "lens_output_reasoning": "found it",+ "lens_output_confidence": 0.9,+ }++ def test_excludes_lens_type_discriminator(self) -> None:+ # `lens_type` lives at the top-level event property; flattening it would duplicate.+ out = MonitorOutput(verdict=False, reasoning="nope", confidence=0.5)+ props = out.to_event_properties()+ assert "lens_output_lens_type" not in props+ assert "lens_type" not in propsdiff --git a/products/replay_vision/backend/tests/test_logic.py b/products/replay_vision/backend/tests/test_logic.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/replay_vision/backend/tests/test_presentation.py b/products/replay_vision/backend/tests/test_presentation.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex b04320b6620e..be25b394143c 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -38,6 +38,7 @@ from products.replay_vision.backend.temporal.activities.observation_state importmark_observation_succeeded_activity,)from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity+from products.replay_vision.backend.temporal.lenses.monitor import MonitorOutputfrom products.replay_vision.backend.temporal.state import (StateActivitiesEnum,generate_state_key,@@ -54,6 +55,7 @@ from products.replay_vision.backend.temporal.types import (FetchSessionEventsInputs,LensCallOutput,LensLlmInputs,+ LensResult,MarkObservationFailedInputs,MarkObservationRunningInputs,MarkObservationSucceededInputs,@@ -298,15 +300,19 @@ class TestObservationStateActivities:observation.refresh_from_db()assert observation.started_at == first_started_at- def test_mark_succeeded_stamps_lifecycle_metadata(self) -> None:+ def test_mark_succeeded_stamps_lifecycle_metadata_and_persists_result(self) -> None:lens = _make_lens()observation = _make_observation(lens, status=ObservationStatus.RUNNING, started_at=timezone.now())+ result = LensResult(model_output=MonitorOutput(verdict=True, reasoning="ok", confidence=0.9))- mark_observation_succeeded_activity(MarkObservationSucceededInputs(observation_id=observation.id))+ mark_observation_succeeded_activity(+ MarkObservationSucceededInputs(observation_id=observation.id, lens_result=result)+ )observation.refresh_from_db()assert observation.status == ObservationStatus.SUCCEEDEDassert observation.completed_at is not None+ assert observation.lens_result == result.model_dump(mode="json")def test_mark_succeeded_does_not_overwrite_terminal_status(self) -> None:# Bounded UPDATE: failed/succeeded rows are sticky.@@ -314,12 +320,16 @@ class TestObservationStateActivities:observation = _make_observation(lens, status=ObservationStatus.FAILED, error_reason="prior", completed_at=timezone.now())+ result = LensResult(model_output=MonitorOutput(verdict=True, reasoning="late", confidence=0.9))- mark_observation_succeeded_activity(MarkObservationSucceededInputs(observation_id=observation.id))+ mark_observation_succeeded_activity(+ MarkObservationSucceededInputs(observation_id=observation.id, lens_result=result)+ )observation.refresh_from_db()assert observation.status == ObservationStatus.FAILEDassert observation.completed_at is not None+ assert observation.lens_result == {} # not overwritten@pytest.mark.django_db(transaction=True)@@ -614,7 +624,7 @@ async def _run_workflow(inputs: ApplyLensInputs, mocks: _WorkflowMocks, workflow@pytest.mark.asyncioasync def test_apply_lens_workflow_drives_full_success_pipeline() -> None:new_observation_id = uuid.uuid4()- model_output = {"verdict": True, "reasoning": "user exported", "confidence": 0.9}+ model_output = MonitorOutput(verdict=True, reasoning="user exported", confidence=0.9)mocks = _WorkflowMocks(activity_results={create_observation_activity: CreateObservationOutput(observation_id=new_observation_id, was_created=True),@@ -714,7 +724,7 @@ async def test_apply_lens_workflow_succeeds_even_when_cleanup_fails() -> None:file_uri="gemini://files/x", mime_type="video/mp4", gemini_file_name="files/x"),call_lens_provider_activity: LensCallOutput(- model_output={"verdict": True, "reasoning": "ok", "confidence": 0.9},+ model_output=MonitorOutput(verdict=True, reasoning="ok", confidence=0.9),),},activity_errors={cleanup_gemini_file_activity: RuntimeError("cleanup failed")},diff --git a/products/replay_vision/frontend/generated/.gitkeep b/products/replay_vision/frontend/generated/.gitkeepdeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex d335ba17760c..9bea9dce55f6 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -204,6 +204,19 @@ export interface LensSnapshotApi {lens_config: unknown}+/**+ * Mirrors `temporal.types.LensResult` for OpenAPI generation.+ */+export interface LensResultApi {+ /** Validated lens output. Shape depends on `lens_snapshot.lens_type`; always carries `confidence` and `lens_type`. */+ model_output: unknown+ /**+ * Number of PostHog Signals emitted from this observation.+ * @minimum 0+ */+ signals_count: number+}+/*** * `schedule` - Schedule* `on_demand` - On demand@@ -233,7 +246,9 @@ export interface ReplayObservationApi {/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */readonly workflow_id: string/** Frozen view of the lens at run time; lens edits do not retroactively mutate this observation. */- readonly lens_snapshot: LensSnapshotApi+ readonly lens_snapshot: LensSnapshotApi | null+ /** Result data persisted on success; null until the observation succeeds. */+ readonly lens_result: LensResultApi | null/** Whether this observation came from the schedule or an on-demand request.* `schedule` - Schedulediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d540a552f285..90d8e1cd3a2f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19776,6 +19776,19 @@ export namespace Schemas {Google: 'google',} as const;+ /**+ * Mirrors `temporal.types.LensResult` for OpenAPI generation.+ */+ export interface LensResult {+ /** Validated lens output. Shape depends on `lens_snapshot.lens_type`; always carries `confidence` and `lens_type`. */+ model_output: unknown;+ /**+ * Number of PostHog Signals emitted from this observation.+ * @minimum 0+ */+ signals_count: number;+ }+/*** * `monitor` - Monitor* `classifier` - Classifier@@ -22821,7 +22834,9 @@ export namespace Schemas {/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */readonly workflow_id: string;/** Frozen view of the lens at run time; lens edits do not retroactively mutate this observation. */- readonly lens_snapshot: LensSnapshot;+ readonly lens_snapshot: LensSnapshot | null;+ /** Result data persisted on success; null until the observation succeeds. */+ readonly lens_result: LensResult | null;/** Whether this observation came from the schedule or an on-demand request.* `schedule` - Schedule