: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
fix(replay-vision): refuse experiment scanners and explain missing answers in the workflow step (#118499)
Tue Haulund1c83fd4665a4
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.pyindex 6437dedcbea3..df371338187e 100644--- a/products/replay_vision/backend/facade/api.py+++ b/products/replay_vision/backend/facade/api.py@@ -45,6 +45,10 @@ class StartedObservationRequest:# An experiment scan needs a saved scanner, so a workflow step can't run one inline.INLINE_SCAN_TYPES = (ScannerType.MONITOR, ScannerType.CLASSIFIER, ScannerType.SCORER, ScannerType.SUMMARIZER)+# An experiment scanner samples the experiment's variants evenly, which one session from a workflow trigger can't do.+WORKFLOW_EXPERIMENT_SCANNER_ERROR = (+ "Experiment scanners can't run from a workflow. Choose another scanner or set up the scan in the step."+)@dataclass(frozen=True, kw_only=True)@@ -234,6 +238,8 @@ def start_workflow_observation_request(raise ObservationRequestRejected("No scanner with this ID exists in this project.", "not_found")if not _can_scan_with(access, team.id, scanner):raise ObservationRequestRejected("The workflow's owner can't scan with this scanner.", "forbidden")+ if scanner.scanner_type == ScannerType.EXPERIMENT:+ raise ObservationRequestRejected(WORKFLOW_EXPERIMENT_SCANNER_ERROR, "invalid")elif inline is not None:if not access.check_access_level_for_resource("replay_scanner", required_level="editor"):raise ObservationRequestRejected(@@ -306,6 +312,8 @@ def workflow_scan_editor_error(*, user: User, team: "Team", scanner_id: UUID | Nreturn "No scanner with this ID exists in this project."if not _can_scan_with(access, team.id, scanner):return "You need edit access to this scanner to use it in a workflow."+ if scanner.scanner_type == ScannerType.EXPERIMENT:+ return WORKFLOW_EXPERIMENT_SCANNER_ERRORreturn Nonediff --git a/products/replay_vision/backend/observation_requests.py b/products/replay_vision/backend/observation_requests.pyindex 77339577c971..ce99d2f5e6ce 100644--- a/products/replay_vision/backend/observation_requests.py+++ b/products/replay_vision/backend/observation_requests.py@@ -33,6 +33,7 @@ from products.cdp.backend.internal_events import ()from products.cdp.backend.workflow_step_resume import RESULT_BYTE_CAP, cap_value, emit_workflow_step_resumefrom products.replay_vision.backend.distinct_ids import replay_vision_distinct_id+from products.replay_vision.backend.error_kinds import FailureKind, IneligibleSessionKindfrom products.replay_vision.backend.models.replay_observation import TERMINAL_STATUSES, ReplayObservationfrom products.replay_vision.backend.models.replay_observation_request import (ObservationRequestSource,@@ -625,7 +626,64 @@ def step_result(if observation is not None and session.state == RequestSessionState.SUCCEEDEDelse None)- return _step_answer(session.state.value, output, [])+ return _step_answer(session.state.value, output, _unanswered_reason(session))+++_SKIPPED_REASONS: dict[str, str] = {+ "skipped_quota": "Your organization's Replay Vision credits for this period are used up, so the session wasn't scanned.",+ "skipped_scanner_limit": "This scanner reached its own credit limit for this period, so the session wasn't scanned.",+ "skipped_limit": "Too many Replay Vision scans were already running, so the session wasn't scanned.",+}++# Worded as the scanner UI words them.+_INELIGIBLE_REASONS: dict[str, str] = {+ IneligibleSessionKind.NO_RECORDING: "No recording was found for this session.",+ IneligibleSessionKind.NO_SNAPSHOTS: "This recording has no screen data to play back, so there was no video to watch.",+ IneligibleSessionKind.TOO_SHORT: "The session was too short to analyze.",+ IneligibleSessionKind.TOO_INACTIVE: "The session had too little active interaction to analyze.",+ IneligibleSessionKind.TOO_LONG: "The session was too long to analyze.",+ IneligibleSessionKind.TOO_LARGE: "This recording is too large to render as a video, so there was nothing to watch.",+ IneligibleSessionKind.NO_EVENTS: "The session had no events to analyze.",+}++# These kinds store a measured value worth passing on ("Only 3.2s long; min is 5s"); the others store raw error text.+_INELIGIBLE_KINDS_WITH_DETAIL = frozenset(+ {IneligibleSessionKind.TOO_SHORT, IneligibleSessionKind.TOO_INACTIVE, IneligibleSessionKind.TOO_LONG}+)++_FAILURE_REASONS: dict[str, str] = {+ FailureKind.PROVIDER_TRANSIENT: "The AI provider stayed unreachable across every automatic retry.",+ FailureKind.PROVIDER_REJECTED: "The AI provider wouldn't analyze this recording's video.",+ FailureKind.RASTERIZATION_FAILED: "PostHog could not turn this recording into a video.",+ FailureKind.VALIDATION_FAILED: "The AI could not answer in the requested format.",+ FailureKind.INFRA_TRANSIENT: "A PostHog service was slow or unavailable while preparing this recording.",+ FailureKind.INTERNAL_ERROR: "Something inside PostHog stopped this scan.",+ FailureKind.ORPHANED: "The scan was interrupted before it finished.",+ FailureKind.PII_DETECTED: "The AI's answer included personal data the scan didn't ask for, so it wasn't kept.",+}+++def _unanswered_reason(session: RequestSession) -> list[str]:+ """Why the step got no answer, so a workflow can tell a used-up limit from a session that can't be scanned."""+ state = session.state+ if state == RequestSessionState.SUCCEEDED:+ return []+ if state == RequestSessionState.SKIPPED:+ return [_SKIPPED_REASONS.get(session.scan_outcome or "", "The session wasn't scanned.")]+ if state == RequestSessionState.LOST:+ return ["The scan ran out of time before it finished."]+ # `error_reason` is `kind:message`.+ kind, _, detail = (session.observation.error_reason if session.observation is not None else "").partition(":")+ if state == RequestSessionState.INELIGIBLE:+ reason = _INELIGIBLE_REASONS.get(kind, "Replay Vision can't scan this session.")+ detail = detail.strip()+ return [f"{reason} {detail}." if detail and kind in _INELIGIBLE_KINDS_WITH_DETAIL else reason]+ if state == RequestSessionState.FAILED:+ # No observation means the scan never started: it failed to launch, or the process starting it died.+ if session.observation is None:+ return ["The scan failed to start."]+ return [_FAILURE_REASONS.get(kind, "The scan failed.")]+ return []def _step_answer(state: str, output: Any, warnings: list[str]) -> dict[str, Any]:diff --git a/products/replay_vision/backend/tests/test_facade.py b/products/replay_vision/backend/tests/test_facade.pyindex 8b2876d12feb..109dfef1ea6c 100644--- a/products/replay_vision/backend/tests/test_facade.py+++ b/products/replay_vision/backend/tests/test_facade.py@@ -280,6 +280,7 @@ class TestStartWorkflowObservationRequest(APIBaseTest):{"inline": WorkflowInlineScan(scanner_type="classifier", scanner_config={"prompt": "p"})},"invalid",),+ ("experiment_scanner", {"inline": None}, "invalid"),])def test_refuses(self, name: str, overrides: dict[str, Any], kind: str) -> None:@@ -296,6 +297,14 @@ class TestStartWorkflowObservationRequest(APIBaseTest):]self.organization.save()AccessControl.objects.create(team=self.team, resource="session_recording", access_level="none")+ if name == "experiment_scanner":+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="experiment",+ scanner_type=ScannerType.EXPERIMENT,+ scanner_config={"prompt": "p", "experiment_id": create_experiment(self.team, "workflow-flag").id},+ )+ overrides = {**overrides, "scanner_id": scanner.id}with pytest.raises(ObservationRequestRejected) as error:self._start(**overrides)diff --git a/products/replay_vision/backend/tests/test_observation_requests_api.py b/products/replay_vision/backend/tests/test_observation_requests_api.pyindex b7d60a9230ba..453a7ad48faa 100644--- a/products/replay_vision/backend/tests/test_observation_requests_api.py+++ b/products/replay_vision/backend/tests/test_observation_requests_api.py@@ -26,7 +26,10 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,from products.replay_vision.backend.observation_requests import (_SWEEP_CURSOR_KEY,MAX_SESSION_END_WAIT,+ RequestSession,+ RequestSessionState,_complete_page,+ _unanswered_reason,complete_settled_requests,recording_viewer_access,request_progress,@@ -309,6 +312,58 @@ class TestRequestProgress(APIBaseTest):self.assertEqual(progress.settled, settled)+class TestUnansweredReason:+ @parameterized.expand(+ [+ ("answered", RequestSessionState.SUCCEEDED, "started", "", []),+ (+ "credits_used_up",+ RequestSessionState.SKIPPED,+ "skipped_quota",+ None,+ [+ "Your organization's Replay Vision credits for this period are used up, so the session wasn't scanned."+ ],+ ),+ (+ "too_short_keeps_the_measurement",+ RequestSessionState.INELIGIBLE,+ "started",+ "too_short:Only 3.2s long; min is 5s",+ ["The session was too short to analyze. Only 3.2s long; min is 5s."],+ ),+ (+ "too_large_drops_raw_error_text",+ RequestSessionState.INELIGIBLE,+ "started",+ "too_large:RECORDING_TOO_LARGE blocks=412",+ ["This recording is too large to render as a video, so there was nothing to watch."],+ ),+ (+ "failed_scan",+ RequestSessionState.FAILED,+ "started",+ "provider_rejected:400 from provider",+ ["The AI provider wouldn't analyze this recording's video."],+ ),+ ("never_started", RequestSessionState.FAILED, "failed", None, ["The scan failed to start."]),+ ("lost", RequestSessionState.LOST, "started", "", ["The scan ran out of time before it finished."]),+ ]+ )+ def test_names_why_the_step_got_no_answer(+ self,+ _name: str,+ state: RequestSessionState,+ scan_outcome: str,+ error_reason: str | None,+ expected: list[str],+ ) -> None:+ observation = None if error_reason is None else ReplayObservation(error_reason=error_reason)+ session = RequestSession(session_id="s1", scan_outcome=scan_outcome, state=state, observation=observation)++ assert _unanswered_reason(session) == expected++class TestCompleteSettledRequests(APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/replay_vision/frontend/components/ScannerPicker/scannerPickerLogic.ts b/products/replay_vision/frontend/components/ScannerPicker/scannerPickerLogic.tsindex 3333df4ee26e..ccd85e3551ca 100644--- a/products/replay_vision/frontend/components/ScannerPicker/scannerPickerLogic.ts+++ b/products/replay_vision/frontend/components/ScannerPicker/scannerPickerLogic.ts@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'import { teamLogic } from 'scenes/teamLogic'import { visionScannersList } from 'products/replay_vision/frontend/generated/api'-import type { ReplayScannerApi } from 'products/replay_vision/frontend/generated/api.schemas'+import { type ReplayScannerApi, ScannerTypeEnumApi } from 'products/replay_vision/frontend/generated/api.schemas'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerPickerLogicValues {@@ -58,7 +58,10 @@ export const scannerPickerLogic = kea<scannerPickerLogicType>([})// Stops paging once the picker unmounts or a newer load starts.breakpoint()- scanners.push(...page.results)+ // The workflow step refuses experiment scanners, so they aren't offered.+ scanners.push(+ ...page.results.filter((scanner) => scanner.scanner_type !== ScannerTypeEnumApi.Experiment)+ )if (!page.next || page.results.length === 0) {return scanners}diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex 206428ebd873..3c36885e2b8c 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -36,6 +36,7 @@ from products.cdp.backend.templates.fixtures import template_slackfrom products.cdp.backend.templates.hog_function_template import sync_template_to_dbfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.tests.helpers import create_experimentfrom products.skills.backend.models.skills import LLMSkillfrom products.tasks.backend.facade.contracts import WorkflowLastRunDTOfrom products.workflows.backend.facade.writes import update_workflow@@ -7639,6 +7640,19 @@ class TestReplayVisionActionValidation(APIBaseTest):assert response.status_code == expected, response.json()+ def test_the_step_refuses_an_experiment_scanner(self) -> None:+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="experiment",+ scanner_type="experiment",+ scanner_config={"prompt": "p", "experiment_id": create_experiment(self.team, "workflow-flag").id},+ )++ response = self._save_step({"type": "scanner", "scanner_id": str(scanner.id)})++ assert response.status_code == 400, response.json()+ assert "Experiment scanners can't run from a workflow" in str(response.json())+@parameterized.expand([("recording_and_scanner_scopes", ["hog_flow:write", "session_recording:read", "replay_scanner:write"], 201),diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex 7938153d3ab0..b255499edef2 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -190,10 +190,10 @@ A `function` node with `template_id: "template-posthog-replay-vision"` scans the| `summarizer` | `prompt` | A title, a summary, and chapters. || `scanner` | `scanner_id` (a saved scanner's UUID) | The saved scanner's answer, with its own type and prompt. |-- The inline types take the same optional settings as a saved scanner of that type. See the `creating-replay-vision-scanners` skill. Find saved scanners with the `vision-scanners` tools.+- The inline types take the same optional settings as a saved scanner of that type. See the `creating-replay-vision-scanners` skill. Find saved scanners with the `vision-scanners` tools. The step refuses an experiment scanner, because it samples the experiment's variants evenly, which one triggered session can't do.- `session_id` defaults to `{event.properties.$session_id}`. Leave it unset unless the session ID is in another property.- `wait_for_session_end` defaults to `true`, which scans the recording after the session has been quiet for 35 minutes. Set it to `false` only when the trigger event comes after the session ended.-- The step result is `{"state", "output", "warnings"}`. `state` is `succeeded`, `failed`, `skipped`, `ineligible` or `lost`. `output` is the scanner's answer: `verdict`, `tags` or `score` with `reasoning` for a monitor, classifier or scorer, and `title`, `summary` and `chapters` for a summarizer. Every type also returns `confidence`. Use `output_variable` to keep the result, then branch on it.+- The step result is `{"state", "output", "warnings"}`. `state` is `succeeded`, `failed`, `skipped`, `ineligible` or `lost`. `output` is the scanner's answer: `verdict`, `tags` or `score` with `reasoning` for a monitor, classifier or scorer, and `title`, `summary` and `chapters` for a summarizer. Every type also returns `confidence`. Use `output_variable` to keep the result, then branch on it. When `output` is null, `warnings` says why: used-up credits, a session too short or too long to scan, or a failed scan.- **Main environment only.** The server refuses the step in a child environment of a project.- **Daily caps.** Each workflow can start 100 scans a day, and the project 500, unless the project settings change `replay_vision_scan_rate_limit_per_day` and `replay_vision_scan_team_rate_limit_per_day`. Past a cap the step returns `state: "skipped"` and the workflow continues.- **Access.** The token needs `session_recording:read` (or `:write`) and `replay_scanner:write`, and the user needs access to recordings and to the saved scanner. Without them, the save fails with a message that names what is missing.