: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): add /observe/ endpoint and stub ApplyLensWorkflow (#58273)
Tue Haulund898f0d77e836
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex f52e52112562..cea6269fd3b4 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -267,6 +267,11 @@ jobs:run: |echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/session_replay/|^ee/hogai/session_summaries|^posthog/temporal/common|^products/signals/backend/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT+ - name: Check for changes that affect replay vision temporal worker+ id: check_changes_replay_vision_temporal_worker+ run: |+ echo "changed=$((git diff --name-only HEAD^ HEAD | grep -qE '^products/replay_vision/backend/temporal/|^products/replay_vision/backend/models/|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$' && echo true) || echo false)" >> $GITHUB_OUTPUT+- name: Check for changes that affect weekly digest temporal workerid: check_changes_weekly_digest_temporal_workerrun: |@@ -364,6 +369,27 @@ jobs:"timestamp": "${{ github.event.head_commit.timestamp }}"}+ - name: Trigger Replay Vision Temporal Worker Cloud deployment+ if: steps.check_changes_replay_vision_temporal_worker.outputs.changed == 'true'+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1+ with:+ token: ${{ steps.deployer.outputs.token }}+ repository: PostHog/charts+ event-type: commit_state_update+ client-payload: |+ {+ "values": {+ "image": {+ "sha": "${{ steps.build.outputs.digest }}"+ }+ },+ "release": "temporal-worker-replay-vision",+ "commit": ${{ toJson(github.event.head_commit) }},+ "repository": ${{ toJson(github.repository) }},+ "labels": ${{ steps.labels.outputs.labels }},+ "timestamp": "${{ github.event.head_commit.timestamp }}"+ }+- name: Trigger Weekly Digest Temporal Worker Cloud deploymentif: steps.check_changes_weekly_digest_temporal_worker.outputs.changed == 'true'uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex fabb1a3f8125..f978c2bc2b03 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -169,6 +169,10 @@ from products.logs.backend.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,)+from products.replay_vision.backend.temporal import (+ ACTIVITIES as REPLAY_VISION_ACTIVITIES,+ WORKFLOWS as REPLAY_VISION_WORKFLOWS,+)from products.signals.backend.temporal import (ACTIVITIES as SIGNALS_PRODUCT_ACTIVITIES,WORKFLOWS as SIGNALS_PRODUCT_WORKFLOWS,@@ -301,6 +305,11 @@ _task_queue_specs = [+ SESSION_SUMMARY_GROUP_ACTIVITIES+ SUMMARIZATION_SWEEP_ACTIVITIES,),+ (+ settings.REPLAY_VISION_TASK_QUEUE,+ REPLAY_VISION_WORKFLOWS,+ REPLAY_VISION_ACTIVITIES,+ ),(settings.MESSAGING_TASK_QUEUE,MESSAGING_WORKFLOWS + WA_DIGEST_WORKFLOWS,diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 889eb93a9e7a..43b2d582525a 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -459,6 +459,14 @@ if get_from_env("POSTHOG_SESSION_RECORDING_REDIS_HOST", ""):os.getenv("POSTHOG_SESSION_RECORDING_REDIS_PORT", "6379"),)+REPLAY_VISION_REDIS_URL = REDIS_URL++if get_from_env("POSTHOG_REPLAY_VISION_REDIS_HOST", ""):+ REPLAY_VISION_REDIS_URL = "redis://{}:{}/".format(+ os.getenv("POSTHOG_REPLAY_VISION_REDIS_HOST", ""),+ os.getenv("POSTHOG_REPLAY_VISION_REDIS_PORT", "6379"),+ )+if not REDIS_URL:raise ImproperlyConfigured("Env var REDIS_URL or POSTHOG_REDIS_HOST is absolutely required to run this software.\n"diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 5c22a3b20e41..0cd678f8c5f5 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -99,6 +99,7 @@ VIDEO_EXPORT_TASK_QUEUE = _set_temporal_task_queue("video-export-task-queue")MESSAGING_TASK_QUEUE = _set_temporal_task_queue("messaging-task-queue")ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")+REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")WEEKLY_DIGEST_TASK_QUEUE = _set_temporal_task_queue("weekly-digest-task-queue")LLMA_EVALS_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-evals-task-queue")LLMA_SENTIMENT_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-sentiment-task-queue")diff --git a/products/replay_vision/backend/api/constants.py b/products/replay_vision/backend/api/constants.pynew file mode 100644index 000000000000..19295cbe68b4--- /dev/null+++ b/products/replay_vision/backend/api/constants.py@@ -0,0 +1 @@+VISION_TAG = "replay_vision"diff --git a/products/replay_vision/backend/api/lenses.py b/products/replay_vision/backend/api/lenses.pyindex e9201c14c959..9afbf0ea9487 100644--- a/products/replay_vision/backend/api/lenses.py+++ b/products/replay_vision/backend/api/lenses.py@@ -1,21 +1,39 @@+import datetime as dtfrom typing import Any, NoReturn, cast+from django.conf import settingsfrom django.db import IntegrityErrorfrom django.db.models import QuerySet+import structlogimport django_filters+from asgiref.sync import async_to_syncfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema-from rest_framework import serializers, viewsets+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import PermissionDenied+from rest_framework.request import Request+from rest_framework.response import Response+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.models.user import User+from posthog.temporal.common.client import sync_connect+from products.replay_vision.backend.api.constants import VISION_TAGfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_lens import LensModel, LensProvider, LensType, ReplayLens+from products.replay_vision.backend.models.replay_observation import ObservationTrigger+from products.replay_vision.backend.temporal.constants import (+ APPLY_LENS_WORKFLOW_NAME,+ MAX_SESSION_ID_LENGTH,+ build_apply_lens_workflow_id,+)+from products.replay_vision.backend.temporal.types import ApplyLensInputs-VISION_TAG = "replay_vision"+logger = structlog.get_logger(__name__)class ReplayLensSerializer(serializers.ModelSerializer):@@ -32,11 +50,11 @@ 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 (deferred to follow-up PR)+ # 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` (deferred to follow-up PR)+ # 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.",@@ -171,11 +189,33 @@ class ReplayLensFilter(django_filters.FilterSet):fields = ["enabled", "lens_type", "emits_signals"]+class ObserveRequestSerializer(serializers.Serializer):+ """Body of POST /vision/lenses/{id}/observe/."""++ session_id = serializers.CharField(+ max_length=MAX_SESSION_ID_LENGTH,+ help_text="ID of the session recording to apply the lens to.",+ )+++class ObserveResponseSerializer(serializers.Serializer):+ """Async-accepted response for POST /vision/lenses/{id}/observe/."""++ workflow_id = serializers.CharField(+ help_text=(+ "Temporal workflow id for this lens application. Look up the resulting "+ "ReplayObservation via GET /vision/lenses/{id}/observations/?session_id=<session_id>."+ ),+ )++@extend_schema(tags=[VISION_TAG])class ReplayLensViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""CRUD for Replay Vision lenses."""scope_object = "replay_lens"+ # Custom actions must be listed explicitly or personal-API-key callers 403 silently.+ scope_object_write_actions = ["create", "update", "partial_update", "destroy", "observe"]permission_classes = [ReplayVisionEnabledPermission]serializer_class = ReplayLensSerializerqueryset = ReplayLens.objects.all()@@ -185,3 +225,62 @@ class ReplayLensViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def safely_get_queryset(self, queryset: QuerySet[ReplayLens]) -> QuerySet[ReplayLens]:return queryset.filter(team_id=self.team_id).select_related("created_by").order_by("name", "id")++ @extend_schema(+ request=ObserveRequestSerializer,+ responses={202: ObserveResponseSerializer},+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="observe",+ required_scopes=["replay_lens:write", "session_recording:read"],+ )+ def observe(self, request: Request, **kwargs: Any) -> Response:+ """Apply this lens to one specific session, on demand. Returns 202 with the workflow handle."""+ lens = self.get_object()+ # Observation output exposes recording contents, so observe requires session_recording read.+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Triggering an on-demand observation requires session_recording read access.")++ body = ObserveRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ session_id: str = body.validated_data["session_id"]+ user = cast(User, request.user)++ workflow_id = build_apply_lens_workflow_id(lens.id, session_id)+ try:+ client = sync_connect()+ async_to_sync(client.start_workflow)( # type: ignore[misc]+ APPLY_LENS_WORKFLOW_NAME, # type: ignore[arg-type]+ ApplyLensInputs( # type: ignore[arg-type]+ lens_id=lens.id,+ session_id=session_id,+ team_id=lens.team_id,+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=user.id,+ ),+ id=workflow_id,+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,+ execution_timeout=dt.timedelta(hours=1),+ )+ except WorkflowAlreadyStartedError as exc:+ # Pin to our own workflow_id so a future id_reuse_policy change can't silently 202 an unrelated run.+ if exc.workflow_id != workflow_id:+ logger.exception("replay_vision.observe.workflow_id_mismatch", workflow_id=workflow_id)+ return Response(+ {"error": "Failed to start observation workflow"},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ logger.info("replay_vision.observe.workflow_already_started", workflow_id=workflow_id)+ except Exception:+ logger.exception("replay_vision.observe.workflow_start_failed", workflow_id=workflow_id)+ return Response(+ {"error": "Failed to start observation workflow"},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ return Response(+ ObserveResponseSerializer({"workflow_id": workflow_id}).data,+ status=status.HTTP_202_ACCEPTED,+ )diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 602a5a9c99ce..8d5f752d706d 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -11,7 +11,7 @@ from rest_framework.exceptions import NotFound, PermissionDeniedfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from products.replay_vision.backend.api.lenses import VISION_TAG+from products.replay_vision.backend.api.constants import VISION_TAGfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_lens import ReplayLensfrom products.replay_vision.backend.models.replay_observation import (@@ -43,7 +43,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):read_only=True,help_text="The `ReplayLens.lens_version` value at the moment the workflow ran.",)- # TODO: type against the same Pydantic shape used to validate `ReplayLens.lens_config` (deferred to follow-up PR)+ # TODO: type against the same Pydantic shape used to validate `ReplayLens.lens_config`.lens_config_snapshot = serializers.JSONField(read_only=True,help_text="Snapshot of `ReplayLens.lens_config` at run time. Lens edits do not retroactively mutate observations.",@@ -145,8 +145,7 @@ class ReplayObservationViewSet(lens = ReplayLens.objects.filter(team_id=self.team_id, id=lens_id).first()if lens is None:raise NotFound()- # Inherit RBAC denies on the parent lens, plus require session_recording read since- # observations expose session_id and model output derived from the recording.+ # Observations expose recording-derived output, so observe inherits the lens's RBAC and also requires session_recording read.self.check_object_permissions(self.request, lens)if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):raise PermissionDenied("Reading replay observations requires session_recording read access.")diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex e69de29bb2d1..4cdd8b4eae33 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -0,0 +1,25 @@+from collections.abc import Callable+from typing import Any++from products.replay_vision.backend.temporal.activities import (+ create_observation_activity,+ mark_observation_failed_activity,+ mark_observation_running_activity,+)+from products.replay_vision.backend.temporal.workflow import ApplyLensWorkflow++WORKFLOWS = [ApplyLensWorkflow]+ACTIVITIES: list[Callable[..., Any]] = [+ create_observation_activity,+ mark_observation_running_activity,+ mark_observation_failed_activity,+]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "ApplyLensWorkflow",+ "create_observation_activity",+ "mark_observation_failed_activity",+ "mark_observation_running_activity",+]diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pynew file mode 100644index 000000000000..f7d527fbda7c--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -0,0 +1,11 @@+from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity+from products.replay_vision.backend.temporal.activities.observation_state import (+ mark_observation_failed_activity,+ mark_observation_running_activity,+)++__all__ = [+ "create_observation_activity",+ "mark_observation_failed_activity",+ "mark_observation_running_activity",+]diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pynew file mode 100644index 000000000000..3baee21e58dd--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -0,0 +1,60 @@+import copy++from django.db import IntegrityError, transaction++import psycopg.errors+from temporalio import activity+from temporalio.exceptions import ApplicationError++from posthog.models.organization import OrganizationMembership++from products.replay_vision.backend.models.replay_lens import ReplayLens+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.temporal.types import CreateObservationInputs, CreateObservationOutput+++def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservationOutput:+ """Snapshot the lens config + version and INSERT the row in `pending`. Returns `was_created=False` on UNIQUE conflict."""+ lens = ReplayLens.objects.filter(pk=inputs.lens_id, team_id=inputs.team_id).select_related("team").first()+ if lens is None:+ raise ValueError(f"ReplayLens {inputs.lens_id} not found for team {inputs.team_id}")++ if inputs.triggered_by_user_id is not None:+ # The activity is the persistence boundary, so re-check team membership rather than trusting the trigger.+ is_member = OrganizationMembership.objects.filter(+ user_id=inputs.triggered_by_user_id,+ organization_id=lens.team.organization_id,+ ).exists()+ if not is_member:+ raise ValueError(+ f"User {inputs.triggered_by_user_id} is not a member of lens {inputs.lens_id}'s organization"+ )++ try:+ with transaction.atomic():+ observation = ReplayObservation.objects.create(+ lens=lens,+ team=lens.team,+ session_id=inputs.session_id,+ status=ObservationStatus.PENDING,+ workflow_id=inputs.workflow_id,+ lens_version=lens.lens_version,+ lens_config_snapshot=copy.deepcopy(lens.lens_config),+ triggered_by=inputs.triggered_by,+ triggered_by_user_id=inputs.triggered_by_user_id,+ )+ except IntegrityError as e:+ # Only swallow the dedup case; FK / CHECK violations should fail the activity.+ if not isinstance(e.__cause__, psycopg.errors.UniqueViolation):+ raise+ existing = ReplayObservation.objects.filter(lens_id=inputs.lens_id, session_id=inputs.session_id).first()+ if existing is None:+ # Conflicting row was deleted between INSERT and SELECT; let Temporal retry the INSERT.+ raise ApplicationError(+ f"Observation for ({inputs.lens_id}, {inputs.session_id}) was deleted mid-create",+ non_retryable=False,+ )+ return CreateObservationOutput(observation_id=existing.id, was_created=False)++ return CreateObservationOutput(observation_id=observation.id, was_created=True)diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.pynew file mode 100644index 000000000000..4765c8fb63e3--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/observation_state.py@@ -0,0 +1,31 @@+from django.utils import timezone++from temporalio import activity++from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation+from products.replay_vision.backend.temporal.types import MarkObservationFailedInputs, MarkObservationRunningInputs+++def mark_observation_running_activity(inputs: MarkObservationRunningInputs) -> None:+ """Flip pending → running. Idempotent: an at-least-once retry against the now-RUNNING row is a no-op."""+ ReplayObservation.objects.filter(+ pk=inputs.observation_id,+ status=ObservationStatus.PENDING,+ ).update(+ status=ObservationStatus.RUNNING,+ started_at=timezone.now(),+ )+++def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> None:+ """Flip pending/running → failed. Idempotent: FAILED is not in the source filter."""+ ReplayObservation.objects.filter(+ pk=inputs.observation_id,+ status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],+ ).update(+ status=ObservationStatus.FAILED,+ error_reason=inputs.error_reason,+ completed_at=timezone.now(),+ )diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pynew file mode 100644index 000000000000..8c83c1685369--- /dev/null+++ b/products/replay_vision/backend/temporal/constants.py@@ -0,0 +1,11 @@+from uuid import UUID++APPLY_LENS_WORKFLOW_NAME = "replay-vision-apply-lens"++# Capped so `replay-vision-apply-lens-{lens_uuid:36}-{session_id}` fits the 255-char `ReplayObservation.workflow_id` column.+MAX_SESSION_ID_LENGTH = 128+++def build_apply_lens_workflow_id(lens_id: UUID, session_id: str) -> str:+ """Deterministic Temporal workflow id for one (lens, session) application."""+ return f"{APPLY_LENS_WORKFLOW_NAME}-{lens_id}-{session_id}"diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pynew file mode 100644index 000000000000..beb7742f3689--- /dev/null+++ b/products/replay_vision/backend/temporal/types.py@@ -0,0 +1,41 @@+from uuid import UUID++from pydantic import BaseModel, Field++from products.replay_vision.backend.models.replay_observation import ObservationTrigger+from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+++class ApplyLensInputs(BaseModel, frozen=True):+ """Input to ApplyLensWorkflow."""++ lens_id: UUID+ session_id: str = Field(min_length=1, max_length=MAX_SESSION_ID_LENGTH)+ team_id: int+ triggered_by: ObservationTrigger+ triggered_by_user_id: int | None = None+++class CreateObservationInputs(BaseModel, frozen=True):+ lens_id: UUID+ team_id: int+ session_id: str = Field(min_length=1, max_length=MAX_SESSION_ID_LENGTH)+ triggered_by: ObservationTrigger+ triggered_by_user_id: int | None+ workflow_id: str+++class CreateObservationOutput(BaseModel, frozen=True):+ """`was_created=False` means the row already existed; the caller should no-op."""++ observation_id: UUID+ was_created: bool+++class MarkObservationRunningInputs(BaseModel, frozen=True):+ observation_id: UUID+++class MarkObservationFailedInputs(BaseModel, frozen=True):+ observation_id: UUID+ error_reason: strdiff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pynew file mode 100644index 000000000000..e4ab54fc0399--- /dev/null+++ b/products/replay_vision/backend/temporal/workflow.py@@ -0,0 +1,83 @@+import datetime as dt++import temporalio.workflow as wf+from temporalio import common++from posthog.temporal.common.base import PostHogWorkflow++from products.replay_vision.backend.temporal.activities import (+ create_observation_activity,+ mark_observation_failed_activity,+ mark_observation_running_activity,+)+from products.replay_vision.backend.temporal.constants import APPLY_LENS_WORKFLOW_NAME+from products.replay_vision.backend.temporal.types import (+ ApplyLensInputs,+ CreateObservationInputs,+ CreateObservationOutput,+ MarkObservationFailedInputs,+ MarkObservationRunningInputs,+)++_STATE_ACTIVITY_RETRY = common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=1),+ maximum_interval=dt.timedelta(seconds=10),+ maximum_attempts=5,+)++# Create's `ValueError` paths (lens missing, user not in org) won't recover on retry.+_CREATE_OBSERVATION_RETRY = common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=1),+ maximum_interval=dt.timedelta(seconds=10),+ maximum_attempts=5,+ non_retryable_error_types=["ValueError"],+)++_STUB_NOT_IMPLEMENTED_REASON = (+ "ApplyLensWorkflow is a stub: the rasterize → upload → call-provider → emit-event pipeline "+ "is not implemented yet. The observation row is exercised end-to-end so wiring can be verified."+)++[email protected](name=APPLY_LENS_WORKFLOW_NAME)+class ApplyLensWorkflow(PostHogWorkflow):+ """Apply one lens to one session. STUB: marks the row failed; the real pipeline replaces that step."""++ inputs_cls = ApplyLensInputs++ @wf.run+ async def run(self, inputs: ApplyLensInputs) -> None:+ workflow_id = wf.info().workflow_id++ create_result: CreateObservationOutput = await wf.execute_activity(+ create_observation_activity,+ CreateObservationInputs(+ lens_id=inputs.lens_id,+ team_id=inputs.team_id,+ session_id=inputs.session_id,+ triggered_by=inputs.triggered_by,+ triggered_by_user_id=inputs.triggered_by_user_id,+ workflow_id=workflow_id,+ ),+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_CREATE_OBSERVATION_RETRY,+ )+ if not create_result.was_created:+ return # Existing observation owns this (lens, session_id); its workflow drives it.++ observation_id = create_result.observation_id+ await wf.execute_activity(+ mark_observation_running_activity,+ MarkObservationRunningInputs(observation_id=observation_id),+ start_to_close_timeout=dt.timedelta(seconds=30),+ retry_policy=_STATE_ACTIVITY_RETRY,+ )+ await wf.execute_activity(+ mark_observation_failed_activity,+ MarkObservationFailedInputs(+ observation_id=observation_id,+ error_reason=_STUB_NOT_IMPLEMENTED_REASON,+ ),+ 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 4127e9f001f6..d840a930056d 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1,9 +1,12 @@+from datetime import timedelta+from posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.utils import timezonefrom parameterized import parameterized+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import Organization, Team@@ -13,6 +16,7 @@ from products.replay_vision.backend.models.replay_observation import (ObservationTrigger,ReplayObservation,)+from products.replay_vision.backend.temporal.constants import APPLY_LENS_WORKFLOW_NAME, build_apply_lens_workflow_idclass _VisionAPITestCase(APIBaseTest):@@ -327,3 +331,157 @@ class TestReplayObservationViewSet(_VisionAPITestCase):body = resp.json()self.assertEqual(len(body["results"]), 2)self.assertIsNotNone(body.get("next"))+++@patch("products.replay_vision.backend.api.lenses.async_to_sync")+@patch("products.replay_vision.backend.api.lenses.sync_connect")+class TestObserveAction(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.lens = self._create_lens()++ def observe_url(self, lens_id: str) -> str:+ return f"{self.lenses_url}{lens_id}/observe/"++ def test_observe_returns_workflow_id_and_starts_workflow(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_client = MagicMock()+ mock_sync_connect.return_value = mock_client+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(self.observe_url(str(self.lens.id)), data={"session_id": "sess-42"}, format="json")+ self.assertEqual(resp.status_code, 202, resp.json())++ expected_workflow_id = build_apply_lens_workflow_id(self.lens.id, "sess-42")+ self.assertEqual(resp.json(), {"workflow_id": expected_workflow_id})++ self.assertFalse(ReplayObservation.objects.filter(lens=self.lens, session_id="sess-42").exists())++ mock_async_to_sync.assert_called_once_with(mock_client.start_workflow)+ args, kwargs = start_workflow.call_args+ self.assertEqual(args[0], APPLY_LENS_WORKFLOW_NAME)+ self.assertEqual(kwargs["id"], expected_workflow_id)+ self.assertEqual(kwargs["execution_timeout"], timedelta(hours=1))+ inputs = args[1]+ self.assertEqual(inputs.lens_id, self.lens.id)+ self.assertEqual(inputs.session_id, "sess-42")+ self.assertEqual(inputs.team_id, self.team.id)+ self.assertEqual(inputs.triggered_by, ObservationTrigger.ON_DEMAND)+ self.assertEqual(inputs.triggered_by_user_id, self.user.id)++ def test_observe_dedup_uses_deterministic_workflow_id(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow++ first = self.client.post(self.observe_url(str(self.lens.id)), data={"session_id": "sess-dup"}, format="json")+ second = self.client.post(self.observe_url(str(self.lens.id)), data={"session_id": "sess-dup"}, format="json")+ self.assertEqual(first.json()["workflow_id"], second.json()["workflow_id"])++ def test_observe_rejects_missing_session_id(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ resp = self.client.post(self.observe_url(str(self.lens.id)), data={}, format="json")+ self.assertEqual(resp.status_code, 400)+ self.assertEqual(resp.json()["attr"], "session_id")++ def test_observe_rejects_too_long_session_id(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ resp = self.client.post(+ self.observe_url(str(self.lens.id)),+ data={"session_id": "x" * 129},+ format="json",+ )+ self.assertEqual(resp.status_code, 400)+ self.assertEqual(resp.json()["attr"], "session_id")++ def test_observe_workflow_id_fits_observation_column_at_max_input(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Catches widening session_id without re-checking the workflow_id column ceiling.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ max_session_id = "x" * 128++ resp = self.client.post(self.observe_url(str(self.lens.id)), data={"session_id": max_session_id}, format="json")+ self.assertEqual(resp.status_code, 202, resp.json())+ workflow_id = resp.json()["workflow_id"]+ max_length = ReplayObservation._meta.get_field("workflow_id").max_length+ assert max_length is not None+ self.assertLessEqual(len(workflow_id), max_length)++ def test_observe_dispatch_failure_returns_503(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock(side_effect=RuntimeError("temporal unavailable"))+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(self.observe_url(str(self.lens.id)), data={"session_id": "sess-broken"}, format="json")+ self.assertEqual(resp.status_code, 503)+ self.assertFalse(ReplayObservation.objects.filter(lens=self.lens, session_id="sess-broken").exists())++ def test_observe_workflow_already_started_is_treated_as_success(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ coalesced_workflow_id = build_apply_lens_workflow_id(self.lens.id, "sess-coalesce")+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock(+ side_effect=WorkflowAlreadyStartedError(+ workflow_id=coalesced_workflow_id,+ workflow_type=APPLY_LENS_WORKFLOW_NAME,+ )+ )+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(+ self.observe_url(str(self.lens.id)), data={"session_id": "sess-coalesce"}, format="json"+ )+ self.assertEqual(resp.status_code, 202, resp.json())+ self.assertEqual(resp.json(), {"workflow_id": coalesced_workflow_id})++ def test_observe_workflow_already_started_with_mismatched_id_returns_503(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Mismatched workflow_id must not silently 202 under a future id_reuse_policy.+ mock_sync_connect.return_value = MagicMock()+ start_workflow = MagicMock(+ side_effect=WorkflowAlreadyStartedError(+ workflow_id="some-unrelated-workflow-id",+ workflow_type=APPLY_LENS_WORKFLOW_NAME,+ )+ )+ mock_async_to_sync.return_value = start_workflow++ resp = self.client.post(+ self.observe_url(str(self.lens.id)), data={"session_id": "sess-mismatch"}, format="json"+ )+ self.assertEqual(resp.status_code, 503, resp.json())+++@patch("products.replay_vision.backend.api.lenses.async_to_sync")+@patch("products.replay_vision.backend.api.lenses.sync_connect")+class TestObserveActionFeatureFlag(APIBaseTest):+ def test_flag_off_returns_404(self, _mock_sync_connect: MagicMock, _mock_async_to_sync: MagicMock) -> None:+ with patch(+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",+ return_value=False,+ ):+ lens = ReplayLens.objects.create(+ team=self.team,+ name="off",+ lens_type=LensType.MONITOR,+ lens_config={"prompt": "p"},+ model=LensModel.GEMINI_3_FLASH,+ )+ resp = self.client.post(+ f"/api/environments/{self.team.id}/vision/lenses/{lens.id}/observe/",+ data={"session_id": "s"},+ format="json",+ )+ self.assertEqual(resp.status_code, 404)diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex e69de29bb2d1..c8f9655be29c 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -0,0 +1,489 @@+import uuid+from collections.abc import AsyncIterator, Callable, Iterator+from concurrent.futures import ThreadPoolExecutor+from typing import Any++import pytest+from unittest.mock import patch++from django.db import IntegrityError+from django.utils import timezone++import psycopg.errors+import pytest_asyncio+from asgiref.sync import sync_to_async+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.models import Organization, Team+from posthog.models.user import User++from products.replay_vision.backend.models.replay_lens import LensModel, LensType, ReplayLens+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.temporal import ACTIVITIES, ApplyLensWorkflow+from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity+from products.replay_vision.backend.temporal.activities.observation_state import (+ mark_observation_failed_activity,+ mark_observation_running_activity,+)+from products.replay_vision.backend.temporal.constants import build_apply_lens_workflow_id+from products.replay_vision.backend.temporal.types import (+ ApplyLensInputs,+ CreateObservationInputs,+ CreateObservationOutput,+ MarkObservationFailedInputs,+ MarkObservationRunningInputs,+)+++def _make_lens() -> ReplayLens:+ org = Organization.objects.create(name="vision-test-org")+ team = Team.objects.create(organization=org, name="vision-test-team")+ return ReplayLens.objects.create(+ team=team,+ name="t",+ lens_type=LensType.MONITOR,+ lens_config={"prompt": "p"},+ model=LensModel.GEMINI_3_FLASH,+ )+++def _make_observation(lens: ReplayLens, **overrides) -> ReplayObservation:+ defaults: dict = {+ "lens": lens,+ "team": lens.team,+ "session_id": "sess-1",+ "triggered_by": ObservationTrigger.ON_DEMAND,+ "lens_version": lens.lens_version,+ "lens_config_snapshot": lens.lens_config,+ }+ defaults.update(overrides)+ return ReplayObservation.objects.create(**defaults)+++@pytest_asyncio.fixture(scope="module")+async def workflow_env() -> AsyncIterator[WorkflowEnvironment]:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ yield env++[email protected](scope="module")+def thread_pool_executor() -> Iterator[ThreadPoolExecutor]:+ with ThreadPoolExecutor(max_workers=4) as executor:+ yield executor++[email protected]_db(transaction=True)+class TestCreateObservationActivity:+ def test_creates_row_in_pending_with_workflow_id_and_snapshot(self) -> None:+ lens = _make_lens()+ result = create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ workflow_id="wf-xyz",+ )+ )++ assert result.was_created is True+ observation = ReplayObservation.objects.get(id=result.observation_id)+ assert observation.status == ObservationStatus.PENDING+ assert observation.workflow_id == "wf-xyz"+ assert observation.session_id == "sess-1"+ assert observation.triggered_by == ObservationTrigger.ON_DEMAND+ assert observation.lens_version == lens.lens_version+ assert observation.lens_config_snapshot == lens.lens_config+ assert observation.started_at is None # set when transitioning to running, not here+ assert observation.completed_at is None++ def test_snapshot_is_frozen_against_later_lens_edits(self) -> None:+ lens = _make_lens()+ original_config = dict(lens.lens_config)+ result = create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id="wf-1",+ )+ )++ lens.lens_config = {"prompt": "completely different prompt"}+ lens.save()++ observation = ReplayObservation.objects.get(id=result.observation_id)+ assert observation.lens_config_snapshot == original_config++ def test_returns_existing_observation_on_unique_conflict(self) -> None:+ lens = _make_lens()+ existing = _make_observation(lens, session_id="sess-dup")++ result = create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-dup",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ workflow_id="wf-second",+ )+ )++ assert result == CreateObservationOutput(observation_id=existing.id, was_created=False)+ # The original row wasn't touched.+ existing.refresh_from_db()+ assert existing.workflow_id != "wf-second"++ def test_propagates_non_unique_integrity_errors(self) -> None:+ # FK/CHECK violations must surface as activity failures, not silently fall into the dedup path.+ lens = _make_lens()+ fk_error = IntegrityError("insert or update on table violates foreign key constraint")+ fk_error.__cause__ = psycopg.errors.ForeignKeyViolation("violation")++ with patch.object(ReplayObservation.objects, "create", side_effect=fk_error):+ with pytest.raises(IntegrityError):+ create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-fk",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ workflow_id="wf-fk",+ )+ )++ assert not ReplayObservation.objects.filter(lens=lens, session_id="sess-fk").exists()++ @pytest.mark.parametrize(+ "use_real_lens_id, team_id_offset",+ [+ pytest.param(False, 0, id="lens_does_not_exist"),+ pytest.param(True, 999, id="lens_belongs_to_other_team"),+ ],+ )+ def test_raises_when_lens_not_found_for_team(self, use_real_lens_id: bool, team_id_offset: int) -> None:+ lens = _make_lens()+ lens_id = lens.id if use_real_lens_id else uuid.uuid4()+ team_id = lens.team_id + team_id_offset++ with pytest.raises(ValueError):+ create_observation_activity(+ CreateObservationInputs(+ lens_id=lens_id,+ team_id=team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ workflow_id="wf-1",+ )+ )++ def test_raises_when_user_is_not_in_lens_organization(self) -> None:+ lens = _make_lens()+ outsider_org = Organization.objects.create(name="other-org")+ outsider = User.objects.create_and_join(organization=outsider_org, email="[email protected]", password=None)++ with pytest.raises(ValueError, match="not a member"):+ create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=outsider.id,+ workflow_id="wf-1",+ )+ )++ def test_accepts_user_in_lens_organization(self) -> None:+ lens = _make_lens()+ member = User.objects.create_and_join(organization=lens.team.organization, email="[email protected]", password=None)++ result = create_observation_activity(+ CreateObservationInputs(+ lens_id=lens.id,+ team_id=lens.team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=member.id,+ workflow_id="wf-1",+ )+ )+ assert result.was_created is True++[email protected]_db(transaction=True)+class TestObservationStateActivities:+ def test_mark_running_stamps_started_at(self) -> None:+ lens = _make_lens()+ observation = _make_observation(lens, workflow_id="wf-1")+ assert observation.status == ObservationStatus.PENDING++ mark_observation_running_activity(MarkObservationRunningInputs(observation_id=observation.id))++ observation.refresh_from_db()+ assert observation.status == ObservationStatus.RUNNING+ assert observation.workflow_id == "wf-1"+ assert observation.started_at is not None++ def test_mark_failed_records_reason_and_completed_at(self) -> None:+ lens = _make_lens()+ observation = _make_observation(lens)+ observation.status = ObservationStatus.RUNNING+ observation.started_at = timezone.now()+ observation.save(update_fields=["status", "started_at"])++ mark_observation_failed_activity(+ MarkObservationFailedInputs(observation_id=observation.id, error_reason="bad output")+ )++ observation.refresh_from_db()+ assert observation.status == ObservationStatus.FAILED+ assert observation.error_reason == "bad output"+ assert observation.completed_at is not None++ @pytest.mark.parametrize("terminal_status", [ObservationStatus.SUCCEEDED, ObservationStatus.FAILED])+ def test_terminal_status_is_not_overwritten_by_state_activities(self, terminal_status: str) -> None:+ # Bounded UPDATE protects against retries that race past a settled row.+ lens = _make_lens()+ observation = _make_observation(lens)+ observation.status = terminal_status+ observation.completed_at = timezone.now()+ observation.error_reason = "original"+ observation.save(update_fields=["status", "completed_at", "error_reason"])++ mark_observation_running_activity(MarkObservationRunningInputs(observation_id=observation.id))+ mark_observation_failed_activity(+ MarkObservationFailedInputs(observation_id=observation.id, error_reason="late failure")+ )++ observation.refresh_from_db()+ assert observation.status == terminal_status+ assert observation.error_reason == "original"++ def test_mark_running_is_idempotent_against_already_running_rows(self) -> None:+ # `started_at` must survive at-least-once retries; duration metrics depend on it.+ lens = _make_lens()+ observation = _make_observation(lens)+ mark_observation_running_activity(MarkObservationRunningInputs(observation_id=observation.id))+ observation.refresh_from_db()+ first_started_at = observation.started_at+ assert first_started_at is not None++ mark_observation_running_activity(MarkObservationRunningInputs(observation_id=observation.id))+ observation.refresh_from_db()+ assert observation.started_at == first_started_at++[email protected]_db(transaction=True)+async def test_apply_lens_workflow_creates_row_then_marks_failed_with_stub_reason(+ workflow_env: WorkflowEnvironment, thread_pool_executor: ThreadPoolExecutor+) -> None:+ lens = await sync_to_async(_make_lens)()+ workflow_id = build_apply_lens_workflow_id(lens.id, "sess-1")+ task_queue = f"vision-test-{uuid.uuid4()}"++ async with Worker(+ workflow_env.client,+ task_queue=task_queue,+ workflows=[ApplyLensWorkflow],+ activities=ACTIVITIES,+ activity_executor=thread_pool_executor,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await workflow_env.client.execute_workflow(+ ApplyLensWorkflow.run,+ ApplyLensInputs(+ lens_id=lens.id,+ session_id="sess-1",+ team_id=lens.team_id,+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ ),+ id=workflow_id,+ task_queue=task_queue,+ )++ @sync_to_async+ def _reload() -> ReplayObservation:+ return ReplayObservation.objects.get(lens=lens, session_id="sess-1")++ final = await _reload()+ assert final.status == ObservationStatus.FAILED+ assert "stub" in final.error_reason.lower()+ assert final.workflow_id == workflow_id+ assert final.started_at is not None+ assert final.completed_at is not None++[email protected]_db(transaction=True)+async def test_apply_lens_workflow_no_ops_when_observation_already_exists(+ workflow_env: WorkflowEnvironment, thread_pool_executor: ThreadPoolExecutor+) -> None:+ lens = await sync_to_async(_make_lens)()+ existing = await sync_to_async(_make_observation)(+ lens,+ session_id="sess-dup",+ workflow_id="prior-workflow",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ )++ workflow_id = build_apply_lens_workflow_id(lens.id, "sess-dup")+ task_queue = f"vision-test-{uuid.uuid4()}"++ async with Worker(+ workflow_env.client,+ task_queue=task_queue,+ workflows=[ApplyLensWorkflow],+ activities=ACTIVITIES,+ activity_executor=thread_pool_executor,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await workflow_env.client.execute_workflow(+ ApplyLensWorkflow.run,+ ApplyLensInputs(+ lens_id=lens.id,+ session_id="sess-dup",+ team_id=lens.team_id,+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ ),+ id=workflow_id,+ task_queue=task_queue,+ )++ # Existing row stays exactly as it was — no new rows created.+ @sync_to_async+ def _check() -> tuple[int, ReplayObservation]:+ rows = ReplayObservation.objects.filter(lens=lens, session_id="sess-dup")+ return rows.count(), rows.get()++ count, observation = await _check()+ assert count == 1+ assert observation.id == existing.id+ assert observation.workflow_id == "prior-workflow"+ assert observation.status == ObservationStatus.SUCCEEDED+++async def test_apply_lens_workflow_orchestrates_activities_in_order(workflow_env: WorkflowEnvironment) -> None:+ calls: list[tuple[str, dict]] = []+ new_observation_id = uuid.uuid4()++ @activity.defn(name="create_observation_activity")+ async def stub_create(inputs: CreateObservationInputs) -> CreateObservationOutput:+ calls.append(+ (+ "create",+ {+ "lens_id": inputs.lens_id,+ "session_id": inputs.session_id,+ "triggered_by": inputs.triggered_by,+ "workflow_id": inputs.workflow_id,+ },+ )+ )+ return CreateObservationOutput(observation_id=new_observation_id, was_created=True)++ @activity.defn(name="mark_observation_running_activity")+ async def stub_running(inputs: MarkObservationRunningInputs) -> None:+ calls.append(("running", {"observation_id": inputs.observation_id}))++ @activity.defn(name="mark_observation_failed_activity")+ async def stub_failed(inputs: MarkObservationFailedInputs) -> None:+ calls.append(("failed", {"observation_id": inputs.observation_id, "error_reason": inputs.error_reason}))++ lens_id = uuid.uuid4()+ workflow_id = build_apply_lens_workflow_id(lens_id, "sess-x")+ task_queue = f"vision-test-{uuid.uuid4()}"+ activities: list[Callable[..., Any]] = [stub_create, stub_running, stub_failed]++ async with Worker(+ workflow_env.client,+ task_queue=task_queue,+ workflows=[ApplyLensWorkflow],+ activities=activities,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await workflow_env.client.execute_workflow(+ ApplyLensWorkflow.run,+ ApplyLensInputs(+ lens_id=lens_id,+ session_id="sess-x",+ team_id=1,+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ ),+ id=workflow_id,+ task_queue=task_queue,+ )++ assert [name for name, _ in calls] == ["create", "running", "failed"]+ assert calls[0][1] == {+ "lens_id": lens_id,+ "session_id": "sess-x",+ "triggered_by": ObservationTrigger.SCHEDULE,+ "workflow_id": workflow_id,+ }+ assert calls[1][1] == {"observation_id": new_observation_id}+ assert calls[2][1]["observation_id"] == new_observation_id+ assert "stub" in calls[2][1]["error_reason"].lower()+++async def test_apply_lens_workflow_exits_when_create_returns_was_created_false(+ workflow_env: WorkflowEnvironment,+) -> None:+ calls: list[str] = []++ @activity.defn(name="create_observation_activity")+ async def stub_create(inputs: CreateObservationInputs) -> CreateObservationOutput:+ calls.append("create")+ return CreateObservationOutput(observation_id=uuid.uuid4(), was_created=False)++ @activity.defn(name="mark_observation_running_activity")+ async def stub_running(inputs: MarkObservationRunningInputs) -> None:+ calls.append("running")++ @activity.defn(name="mark_observation_failed_activity")+ async def stub_failed(inputs: MarkObservationFailedInputs) -> None:+ calls.append("failed")++ activities: list[Callable[..., Any]] = [stub_create, stub_running, stub_failed]+ task_queue = f"vision-test-{uuid.uuid4()}"++ async with Worker(+ workflow_env.client,+ task_queue=task_queue,+ workflows=[ApplyLensWorkflow],+ activities=activities,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ await workflow_env.client.execute_workflow(+ ApplyLensWorkflow.run,+ ApplyLensInputs(+ lens_id=uuid.uuid4(),+ session_id="sess-y",+ team_id=1,+ triggered_by=ObservationTrigger.ON_DEMAND,+ triggered_by_user_id=None,+ ),+ id="wf-y",+ task_queue=task_queue,+ )++ assert calls == ["create"]diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex bfdfd4c801f6..595f9b103773 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -282,6 +282,25 @@ export interface PatchedReplayLensApi {readonly updated_at?: string}+/**+ * Body of POST /vision/lenses/{id}/observe/.+ */+export interface ObserveRequestApi {+ /**+ * ID of the session recording to apply the lens to.+ * @maxLength 128+ */+ session_id: string+}++/**+ * Async-accepted response for POST /vision/lenses/{id}/observe/.+ */+export interface ObserveResponseApi {+ /** Temporal workflow id for this lens application. Look up the resulting ReplayObservation via GET /vision/lenses/{id}/observations/?session_id=<session_id>. */+ workflow_id: string+}+export type VisionLensesListParams = {/*** Filter to lenses that emit Signals.diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex f9aaf7394923..2cdbe7c45cfd 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ObserveRequestApi,+ ObserveResponseApi,PaginatedReplayLensListApi,PaginatedReplayObservationListApi,PatchedReplayLensApi,@@ -194,3 +196,24 @@ export const visionLensesDestroy = async (projectId: string, id: string, optionsmethod: 'DELETE',})}++export const getVisionLensesObserveCreateUrl = (projectId: string, id: string) => {+ return `/api/environments/${projectId}/vision/lenses/${id}/observe/`+}++/**+ * Apply this lens to one specific session, on demand. Returns 202 with the workflow handle.+ */+export const visionLensesObserveCreate = async (+ projectId: string,+ id: string,+ observeRequestApi: ObserveRequestApi,+ options?: RequestInit+): Promise<ObserveResponseApi> => {+ return apiMutator<ObserveResponseApi>(getVisionLensesObserveCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(observeRequestApi),+ })+}diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex be9946cb0fb4..1ce98d104cff 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -133,3 +133,17 @@ export const VisionLensesPartialUpdateBody = /* @__PURE__ */ zod.object({'When true, the prompt is augmented with the Signal side mission and the lens emits PostHog Signals.'),})++/**+ * Apply this lens to one specific session, on demand. Returns 202 with the workflow handle.+ */+export const visionLensesObserveCreateBodySessionIdMax = 128++export const VisionLensesObserveCreateBody = /* @__PURE__ */ zod+ .object({+ session_id: zod+ .string()+ .max(visionLensesObserveCreateBodySessionIdMax)+ .describe('ID of the session recording to apply the lens to.'),+ })+ .describe('Body of POST \/vision\/lenses\/{id}\/observe\/.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cd10b45f7ff0..ff79df530e69 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20347,6 +20347,25 @@ export namespace Schemas {OnDemand: 'on_demand',} as const;+ /**+ * Body of POST /vision/lenses/{id}/observe/.+ */+ export interface ObserveRequest {+ /**+ * ID of the session recording to apply the lens to.+ * @maxLength 128+ */+ session_id: string;+ }++ /**+ * Async-accepted response for POST /vision/lenses/{id}/observe/.+ */+ export interface ObserveResponse {+ /** Temporal workflow id for this lens application. Look up the resulting ReplayObservation via GET /vision/lenses/{id}/observations/?session_id=<session_id>. */+ workflow_id: string;+ }+export interface OfflineExperimentItemsRequest {/** `$ai_experiment_id` whose offline-evaluation items to return. */experiment_id: string;