Skip to content

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

feat(replay-vision): INELIGIBLE observation status + better failure messages (#60011)

Tue Haulund6adb390cd426
diff --git a/posthog/temporal/common/errors.py b/posthog/temporal/common/errors.py
index e7171d2554d7..6a28ae1f7933 100644
--- a/posthog/temporal/common/errors.py
+++ b/posthog/temporal/common/errors.py
@@ -1,6 +1,6 @@
import traceback
-from temporalio.exceptions import ActivityError, ApplicationError
+from temporalio.exceptions import ApplicationError, FailureError
# Bound error strings so a multi-MB str(e) (ClickHouse 5xx body, Playwright HTML dump)
# can't blow out Temporal's 2 MiB payload limit.
@@ -15,9 +15,13 @@ def truncate_for_temporal_payload(value: str, limit: int) -> str:
def unwrap_temporal_cause(exc: BaseException) -> ApplicationError | None:
- if isinstance(exc, ActivityError) and isinstance(exc.cause, ApplicationError):
- return exc.cause
- return None
+ """Walk past Temporal's failure wrappers (ActivityError, ChildWorkflowError, …) to the underlying ApplicationError."""
+ if isinstance(exc, ApplicationError):
+ return None # already at the leaf; nothing to unwrap
+ current: BaseException | None = exc
+ while isinstance(current, FailureError) and not isinstance(current, ApplicationError):
+ current = current.cause
+ return current if isinstance(current, ApplicationError) else None
def resolve_exception_class(exc: BaseException) -> str:
diff --git a/posthog/temporal/common/test_errors.py b/posthog/temporal/common/test_errors.py
index 2aa975af8445..572656c1f7cc 100644
--- a/posthog/temporal/common/test_errors.py
+++ b/posthog/temporal/common/test_errors.py
@@ -1,6 +1,13 @@
import pytest
-from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, MAX_ERROR_TRACE_CHARS, truncate_for_temporal_payload
+from temporalio.exceptions import ActivityError, ApplicationError, ChildWorkflowError
+
+from posthog.temporal.common.errors import (
+ MAX_ERROR_MESSAGE_CHARS,
+ MAX_ERROR_TRACE_CHARS,
+ truncate_for_temporal_payload,
+ unwrap_temporal_cause,
+)
@pytest.mark.parametrize(
@@ -26,3 +33,52 @@ def test_default_limits_fit_under_temporal_payload_limit():
# fit inside 1 MiB (worst-case UTF-8: 4 bytes/char) to leave headroom for everything else.
worst_case_error_bytes = (MAX_ERROR_MESSAGE_CHARS + MAX_ERROR_TRACE_CHARS) * 4
assert worst_case_error_bytes < 1 * 1024 * 1024
+
+
+def _activity_error(cause: BaseException) -> ActivityError:
+ err = ActivityError(
+ "activity failed",
+ scheduled_event_id=1,
+ started_event_id=2,
+ identity="worker",
+ activity_type="t",
+ activity_id="a",
+ retry_state=None,
+ )
+ err.__cause__ = cause
+ return err
+
+
+def _child_workflow_error(cause: BaseException) -> ChildWorkflowError:
+ err = ChildWorkflowError(
+ "child failed",
+ namespace="default",
+ workflow_id="w",
+ run_id="r",
+ workflow_type="t",
+ initiated_event_id=1,
+ started_event_id=2,
+ retry_state=None,
+ )
+ err.__cause__ = cause
+ return err
+
+
+class TestUnwrapTemporalCause:
+ def test_returns_none_for_bare_application_error(self) -> None:
+ assert unwrap_temporal_cause(ApplicationError("x", type="X")) is None
+
+ def test_returns_none_for_bare_exception(self) -> None:
+ assert unwrap_temporal_cause(ValueError("x")) is None
+
+ def test_unwraps_activity_error(self) -> None:
+ leaf = ApplicationError("inner", type="X")
+ assert unwrap_temporal_cause(_activity_error(leaf)) is leaf
+
+ def test_unwraps_child_workflow_error_wrapping_activity_error(self) -> None:
+ # Real Temporal chain when a child workflow's activity raises an ApplicationError.
+ leaf = ApplicationError("inner", type="X")
+ assert unwrap_temporal_cause(_child_workflow_error(_activity_error(leaf))) is leaf
+
+ def test_returns_none_when_wrapper_chain_bottoms_out_on_non_application(self) -> None:
+ assert unwrap_temporal_cause(_activity_error(ValueError("not an app error"))) is None
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 4ac5a6dd1ee6..5041131d3ab9 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -85,12 +85,17 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(
choices=ObservationStatus.choices,
read_only=True,
- help_text="Observation status (pending, running, succeeded, failed).",
+ help_text="Observation status (pending, running, succeeded, failed, ineligible).",
)
error_reason = serializers.CharField(
read_only=True,
allow_blank=True,
- help_text="Populated on failure; includes the malformed model response when validation fails.",
+ help_text=(
+ "Populated on terminal non-success statuses; formatted as `kind:human-readable message`. "
+ "For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events. "
+ "For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / "
+ "validation_failed / internal_error."
+ ),
)
workflow_id = serializers.CharField(
read_only=True,
diff --git a/products/replay_vision/backend/migrations/0007_add_ineligible_status.py b/products/replay_vision/backend/migrations/0007_add_ineligible_status.py
new file mode 100644
index 000000000000..83098609a13d
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0007_add_ineligible_status.py
@@ -0,0 +1,62 @@
+# Generated by Django 5.2.14 on 2026-05-26 07:25
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0006_rename_lens_to_scanner"),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="replayobservation",
+ name="replay_observation_completed_at_matches_status",
+ ),
+ migrations.AlterField(
+ model_name="replayobservation",
+ name="error_reason",
+ field=models.TextField(
+ blank=True,
+ default="",
+ help_text=(
+ "Populated on terminal non-success statuses; formatted as `kind:human-readable message`. "
+ "For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events. "
+ "For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / "
+ "validation_failed / internal_error."
+ ),
+ ),
+ ),
+ migrations.AlterField(
+ model_name="replayobservation",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("running", "Running"),
+ ("succeeded", "Succeeded"),
+ ("failed", "Failed"),
+ ("ineligible", "Ineligible"),
+ ],
+ default="pending",
+ max_length=16,
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="replayobservation",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("completed_at__isnull", True),
+ ("status__in", ["pending", "running"]),
+ ),
+ models.Q(
+ ("completed_at__isnull", False),
+ ("status__in", ["succeeded", "failed", "ineligible"]),
+ ),
+ _connector="OR",
+ ),
+ name="replay_observation_completed_at_matches_status",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index e2c0fc136760..e8f4512c4adf 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_rename_lens_to_scanner
+0007_add_ineligible_status
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 85f5aa01389d..33b06e3f2bc3 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -1,5 +1,4 @@
from django.db import models
-from django.utils import timezone
from posthog.models.utils import UUIDModel
@@ -9,6 +8,9 @@ class ObservationStatus(models.TextChoices):
RUNNING = "running", "Running"
SUCCEEDED = "succeeded", "Succeeded"
FAILED = "failed", "Failed"
+ # Terminal state for sessions the scanner can't analyze (no recording, too short, too long, etc.).
+ # The reason kind is stored in `error_reason` formatted as `kind:human message`.
+ INELIGIBLE = "ineligible", "Ineligible"
class ObservationTrigger(models.TextChoices):
@@ -27,7 +29,12 @@ class ReplayObservation(UUIDModel):
error_reason = models.TextField(
blank=True,
default="",
- help_text="Populated on `status='failed'`. Includes the malformed model response on validation failure.",
+ help_text=(
+ "Populated on terminal non-success statuses; formatted as `kind:human-readable message`. "
+ "For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events. "
+ "For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / "
+ "validation_failed / internal_error."
+ ),
)
workflow_id = models.CharField(
max_length=255,
@@ -70,7 +77,7 @@ class ReplayObservation(UUIDModel):
models.CheckConstraint(
condition=(
models.Q(status__in=["pending", "running"], completed_at__isnull=True)
- | models.Q(status__in=["succeeded", "failed"], completed_at__isnull=False)
+ | models.Q(status__in=["succeeded", "failed", "ineligible"], completed_at__isnull=False)
),
name="replay_observation_completed_at_matches_status",
),
@@ -96,16 +103,5 @@ class ReplayObservation(UUIDModel):
self.team_id = scanner_team_id
super().save(*args, **kwargs)
- def mark_succeeded(self) -> None:
- self.status = ObservationStatus.SUCCEEDED
- self.completed_at = timezone.now()
- self.save(update_fields=["status", "completed_at"])
-
- def mark_failed(self, error_reason: str) -> None:
- self.status = ObservationStatus.FAILED
- self.error_reason = error_reason
- self.completed_at = timezone.now()
- self.save(update_fields=["status", "completed_at", "error_reason"])
-
def __str__(self) -> str:
return f"{self.scanner_id}:{self.session_id} [{self.status}]"
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 1576f4057aa1..91b5cc6c7300 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -11,6 +11,7 @@ from products.replay_vision.backend.temporal.activities import (
ensure_session_asset_activity,
fetch_session_events_activity,
mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
upload_video_to_gemini_activity,
@@ -22,6 +23,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
create_observation_activity,
mark_observation_running_activity,
mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
mark_observation_succeeded_activity,
fetch_session_events_activity,
ensure_session_asset_activity,
@@ -46,6 +48,7 @@ __all__ = [
"ensure_session_asset_activity",
"fetch_session_events_activity",
"mark_observation_failed_activity",
+ "mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
"upload_video_to_gemini_activity",
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 3883c10ab36d..3c0bde697347 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -10,6 +10,7 @@ from products.replay_vision.backend.temporal.activities.ensure_session_asset imp
from products.replay_vision.backend.temporal.activities.fetch_session_events import fetch_session_events_activity
from products.replay_vision.backend.temporal.activities.observation_state import (
mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
)
@@ -25,6 +26,7 @@ __all__ = [
"ensure_session_asset_activity",
"fetch_session_events_activity",
"mark_observation_failed_activity",
+ "mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
"upload_video_to_gemini_activity",
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 861fe8526eb1..838cad01bda4 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -12,12 +12,12 @@ from google.genai import types
from posthoganalytics.ai.gemini import genai
from pydantic import BaseModel, ValidationError
from temporalio import activity
-from temporalio.exceptions import ApplicationError
from posthog.models import Team
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.temporal.constants import replay_vision_distinct_id
+from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.scanners import scanner_from_snapshot
from products.replay_vision.backend.temporal.scanners.base import BaseScanner
from products.replay_vision.backend.temporal.state import (
@@ -107,7 +107,9 @@ def _load_snapshot(observation_id: UUID, team_id: int) -> ScannerSnapshot:
.first()
)
if raw is None:
- raise ApplicationError(f"ReplayObservation {observation_id} not found for team {team_id}", non_retryable=True)
+ raise ScannerFailureError(
+ f"ReplayObservation {observation_id} not found for team {team_id}", kind=FailureKind.INTERNAL_ERROR
+ )
return ScannerSnapshot.load_for(observation_id, raw)
@@ -115,7 +117,7 @@ def _load_team_name(team_id: int) -> str:
try:
return Team.objects.values_list("name", flat=True).get(pk=team_id)
except Team.DoesNotExist:
- raise ApplicationError(f"Team {team_id} not found", non_retryable=True)
+ raise ScannerFailureError(f"Team {team_id} not found", kind=FailureKind.INTERNAL_ERROR)
async def _load_llm_inputs(observation_id: UUID) -> ScannerLlmInputs:
@@ -125,8 +127,8 @@ async def _load_llm_inputs(observation_id: UUID) -> ScannerLlmInputs:
)
payload = await get_data_class_from_redis(redis_client, redis_key, target_class=ScannerLlmInputs)
if payload is None:
- raise ApplicationError(
- f"ScannerLlmInputs missing in Redis for observation {observation_id}", non_retryable=True
+ raise ScannerFailureError(
+ f"ScannerLlmInputs missing in Redis for observation {observation_id}", kind=FailureKind.INTERNAL_ERROR
)
return payload
@@ -185,9 +187,9 @@ async def _call_with_retry(
]
# non_retryable so workflow-level retries don't re-burn on schema/semantic failures.
- raise ApplicationError(
+ raise ScannerFailureError(
f"Scanner call rejected after {_MAX_LLM_ATTEMPTS} attempts: {last_error}",
- non_retryable=True,
+ kind=FailureKind.VALIDATION_FAILED,
)
diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
index 33c09312752f..7b16aa46feef 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
@@ -4,7 +4,6 @@ from datetime import UTC, datetime
import structlog
from temporalio import activity
-from temporalio.exceptions import ApplicationError
from posthog.api.capture import capture_internal
from posthog.models.team import Team
@@ -12,6 +11,7 @@ from posthog.sync import database_sync_to_async
from products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservation
from products.replay_vision.backend.temporal.constants import replay_vision_distinct_id
+from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.types import EmitObservationEventInputs, ScannerSnapshot
logger = structlog.get_logger(__name__)
@@ -29,12 +29,16 @@ async def emit_observation_event_activity(inputs: EmitObservationEventInputs) ->
def _emit_event(inputs: EmitObservationEventInputs) -> None:
observation = ReplayObservation.objects.select_related("team").filter(pk=inputs.observation_id).first()
if observation is None:
- raise ApplicationError(f"ReplayObservation {inputs.observation_id} not found", non_retryable=True)
+ raise ScannerFailureError(
+ f"ReplayObservation {inputs.observation_id} not found", kind=FailureKind.INTERNAL_ERROR
+ )
try:
team: Team = observation.team
except Team.DoesNotExist:
- raise ApplicationError(f"Team for observation {inputs.observation_id} not found", non_retryable=True)
+ raise ScannerFailureError(
+ f"Team for observation {inputs.observation_id} not found", kind=FailureKind.INTERNAL_ERROR
+ )
snapshot = ScannerSnapshot.load_for(inputs.observation_id, observation.scanner_snapshot)
properties: dict = {
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
index cd0e0b45f620..a88bd8598cd6 100644
--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py
+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
@@ -4,7 +4,6 @@ from typing import Any
from asgiref.sync import sync_to_async
from temporalio import activity
-from temporalio.exceptions import ApplicationError
from posthog.models import Team
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
@@ -14,6 +13,7 @@ from products.replay_vision.backend.temporal.constants import (
MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S,
)
+from products.replay_vision.backend.temporal.errors import IneligibleSessionError, IneligibleSessionKind
from products.replay_vision.backend.temporal.state import (
StateActivitiesEnum,
get_redis_state_client,
@@ -64,9 +64,9 @@ async def fetch_session_events_activity(inputs: FetchSessionEventsInputs) -> Non
payload = await sync_to_async(_fetch_payload)(inputs.team_id, inputs.session_id)
if payload is None:
- raise ApplicationError(
+ raise IneligibleSessionError(
f"Session {inputs.session_id} has no events to analyze",
- non_retryable=True,
+ kind=IneligibleSessionKind.NO_EVENTS,
)
await store_data_in_redis(redis_client, redis_key, payload.model_dump_json())
@@ -77,24 +77,27 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:
events_obj = SessionReplayEvents()
metadata = events_obj.get_metadata(session_id=session_id, team=team)
if metadata is None:
- raise ApplicationError(f"No replay metadata found for session {session_id}", non_retryable=True)
+ raise IneligibleSessionError(
+ f"No replay metadata found for session {session_id}",
+ kind=IneligibleSessionKind.NO_RECORDING,
+ )
duration_seconds = float(metadata["duration"])
if duration_seconds < MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S:
- raise ApplicationError(
+ raise IneligibleSessionError(
f"Session {session_id} is only {duration_seconds}s long; min is {MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S}s",
- non_retryable=True,
+ kind=IneligibleSessionKind.TOO_SHORT,
)
# `RecordingMetadata` types this as `int` but it can be missing on sparse fixtures; default to 0.
active_seconds = metadata.get("active_seconds") or 0
if active_seconds < MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S:
- raise ApplicationError(
+ raise IneligibleSessionError(
f"Session {session_id} has only {active_seconds}s of active interaction; min is {MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S}s",
- non_retryable=True,
+ kind=IneligibleSessionKind.TOO_INACTIVE,
)
if active_seconds > MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S:
- raise ApplicationError(
+ raise IneligibleSessionError(
f"Session {session_id} has {active_seconds}s of active interaction; max is {MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S}s",
- non_retryable=True,
+ kind=IneligibleSessionKind.TOO_LONG,
)
columns: list[str] | None = None
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index ccb41890c8ac..daa9129809ad 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -5,6 +5,7 @@ from temporalio import activity
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.temporal.types import (
MarkObservationFailedInputs,
+ MarkObservationIneligibleInputs,
MarkObservationRunningInputs,
MarkObservationSucceededInputs,
)
@@ -35,6 +36,19 @@ def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> Non
)
+def mark_observation_ineligible_activity(inputs: MarkObservationIneligibleInputs) -> None:
+ """Flip pending/running → ineligible. Idempotent: INELIGIBLE is not in the source filter."""
+ ReplayObservation.objects.filter(
+ pk=inputs.observation_id,
+ status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],
+ ).update(
+ status=ObservationStatus.INELIGIBLE,
+ error_reason=inputs.error_reason,
+ completed_at=timezone.now(),
+ )
+
+
@activity.defn
def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs) -> None:
"""Flip pending/running → succeeded and persist the scanner result. Idempotent: SUCCEEDED is not in the source filter."""
diff --git a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py
index df02d0617350..a543c8dd5a4a 100644
--- a/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py
+++ b/products/replay_vision/backend/temporal/activities/upload_video_to_gemini.py
@@ -19,6 +19,7 @@ from posthog.models.exported_asset import ExportedAsset
from posthog.storage import object_storage
from posthog.temporal.session_replay.gemini_cleanup_sweep.tracking import track_uploaded_file
+from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.types import UploadedVideo, UploadVideoToGeminiInputs
logger = structlog.get_logger(__name__)
@@ -32,7 +33,7 @@ async def upload_video_to_gemini_activity(inputs: UploadVideoToGeminiInputs) ->
"""Read the asset's MP4 bytes, upload to Gemini, poll until ACTIVE, return the file reference."""
workflow_id = activity.info().workflow_id
if workflow_id is None:
- raise RuntimeError("upload_video_to_gemini_activity has no workflow_id")
+ raise ScannerFailureError("upload_video_to_gemini_activity has no workflow_id", kind=FailureKind.INTERNAL_ERROR)
asset = await ExportedAsset.objects.aget(id=inputs.asset_id)
video_bytes: bytes | None
@@ -41,9 +42,14 @@ async def upload_video_to_gemini_activity(inputs: UploadVideoToGeminiInputs) ->
elif asset.content_location:
video_bytes = await sync_to_async(object_storage.read_bytes, thread_sensitive=False)(asset.content_location)
else:
- raise ValueError(f"ExportedAsset {inputs.asset_id} has neither content nor content_location")
+ raise ScannerFailureError(
+ f"ExportedAsset {inputs.asset_id} has neither content nor content_location",
+ kind=FailureKind.INTERNAL_ERROR,
+ )
if not video_bytes:
- raise ValueError(f"ExportedAsset {inputs.asset_id} produced empty video bytes")
+ raise ScannerFailureError(
+ f"ExportedAsset {inputs.asset_id} produced empty video bytes", kind=FailureKind.INTERNAL_ERROR
+ )
raw_client = RawGenAIClient(api_key=settings.GEMINI_API_KEY)
# `tmp_file.write` / `flush` are blocking disk I/O; offload the whole tempfile+upload block off the event loop.
@@ -52,7 +58,11 @@ async def upload_video_to_gemini_activity(inputs: UploadVideoToGeminiInputs) ->
)
if uploaded_file.name is None:
- raise RuntimeError("Gemini upload returned a file without a name")
+ # Non-retryable: a retry would re-upload before the cleanup sweep can reap the unnamed file Gemini may have created.
+ raise ScannerFailureError(
+ "Gemini upload returned a file without a name",
+ kind=FailureKind.INTERNAL_ERROR,
+ )
gemini_file_name = uploaded_file.name
# Track BEFORE the ACTIVE-wait so a polling timeout still leaves the file visible to the cleanup sweep.
@@ -70,17 +80,24 @@ async def upload_video_to_gemini_activity(inputs: UploadVideoToGeminiInputs) ->
while uploaded_file.state and uploaded_file.state.name == "PROCESSING":
elapsed = time.time() - wait_start
if elapsed >= _MAX_PROCESSING_WAIT_SECONDS:
- raise RuntimeError(
- f"Gemini file {gemini_file_name} stuck in PROCESSING after {elapsed:.1f}s; left for the cleanup sweep"
+ raise ScannerFailureError(
+ f"Gemini file {gemini_file_name} stuck in PROCESSING after {elapsed:.1f}s; left for the cleanup sweep",
+ kind=FailureKind.PROVIDER_TRANSIENT,
)
await asyncio.sleep(0.5)
uploaded_file = await sync_to_async(raw_client.files.get, thread_sensitive=False)(name=gemini_file_name)
final_state = uploaded_file.state.name if uploaded_file.state else None
if final_state != "ACTIVE":
- raise RuntimeError(f"Gemini file {gemini_file_name} reached non-ACTIVE state {final_state!r}")
+ raise ScannerFailureError(
+ f"Gemini file {gemini_file_name} reached non-ACTIVE state {final_state!r}",
+ kind=FailureKind.PROVIDER_REJECTED,
+ )
if not uploaded_file.uri:
- raise RuntimeError(f"Gemini file {gemini_file_name} reached ACTIVE but has no URI")
+ raise ScannerFailureError(
+ f"Gemini file {gemini_file_name} reached ACTIVE but has no URI",
+ kind=FailureKind.PROVIDER_TRANSIENT,
+ )
return UploadedVideo(
file_uri=uploaded_file.uri,
diff --git a/products/replay_vision/backend/temporal/errors.py b/products/replay_vision/backend/temporal/errors.py
new file mode 100644
index 000000000000..7b3fe6404952
--- /dev/null
+++ b/products/replay_vision/backend/temporal/errors.py
@@ -0,0 +1,58 @@
+from enum import StrEnum
+
+from temporalio.exceptions import ApplicationError
+
+# Strings survive Temporal's ActivityError wrapping via ApplicationError.type, so the
+# workflow can dispatch on them without parsing exception messages.
+INELIGIBLE_SESSION_ERROR_TYPE = "IneligibleSession"
+SCANNER_FAILURE_ERROR_TYPE = "ScannerFailure"
+
+
+class IneligibleSessionKind(StrEnum):
+ """Reason a scanner couldn't be applied to a session — not a failure, the session doesn't qualify."""
+
+ NO_RECORDING = "no_recording"
+ TOO_SHORT = "too_short"
+ TOO_INACTIVE = "too_inactive"
+ TOO_LONG = "too_long"
+ NO_EVENTS = "no_events"
+
+
+class FailureKind(StrEnum):
+ """User-facing classification of a failed observation; drives the frontend description + advice."""
+
+ PROVIDER_TRANSIENT = "provider_transient" # AI provider outage / network — retry usually helps
+ PROVIDER_REJECTED = "provider_rejected" # AI provider couldn't process the video — won't recover
+ RASTERIZATION_FAILED = "rasterization_failed" # Rasterizer couldn't render this recording — known issue
+ VALIDATION_FAILED = "validation_failed" # LLM output didn't match the scanner schema after internal retries
+ INTERNAL_ERROR = "internal_error" # Unclassified / bug paths — user can't fix
+
+ @property
+ def is_retryable(self) -> bool:
+ return self is FailureKind.PROVIDER_TRANSIENT
+
+
+class _KindedApplicationError(ApplicationError):
+ """ApplicationError carrying a typed `kind` payload that survives Temporal's serialization.
+
+ `details=(kind,)` is the canonical way to attach a typed payload an outer workflow can read off
+ `cause.details` after Temporal wraps the activity raise in ActivityError.
+ """
+
+ def __init__(self, message: str, *, kind: StrEnum, type: str, non_retryable: bool = True) -> None:
+ super().__init__(message, str(kind), type=type, non_retryable=non_retryable)
+ self.kind = kind
+
+
+class IneligibleSessionError(_KindedApplicationError):
+ """The session doesn't qualify for analysis. Surfaced as ObservationStatus.INELIGIBLE, not FAILED."""
+
+ def __init__(self, message: str, *, kind: IneligibleSessionKind) -> None:
+ super().__init__(message, kind=kind, type=INELIGIBLE_SESSION_ERROR_TYPE)
+
+
+class ScannerFailureError(_KindedApplicationError):
+ """A classified workflow failure. Surfaced as ObservationStatus.FAILED with the kind label on the frontend."""
+
+ def __init__(self, message: str, *, kind: FailureKind) -> None:
+ super().__init__(message, kind=kind, type=SCANNER_FAILURE_ERROR_TYPE, non_retryable=not kind.is_retryable)
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 4b89af51f76e..199c4a2a7833 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -94,6 +94,12 @@ class MarkObservationFailedInputs(BaseModel, frozen=True):
error_reason: str
+class MarkObservationIneligibleInputs(BaseModel, frozen=True):
+ observation_id: UUID
+ # `kind:message` — kind is one of IneligibleSessionKind values.
+ error_reason: str
+
+
class FetchSessionEventsInputs(BaseModel, frozen=True):
observation_id: UUID
team_id: int
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index 144b286c2d48..68072238e3da 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -7,6 +7,7 @@ from temporalio import common
from temporalio.common import SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs
@@ -23,11 +24,18 @@ from products.replay_vision.backend.temporal.activities import (
ensure_session_asset_activity,
fetch_session_events_activity,
mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
upload_video_to_gemini_activity,
)
from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_WORKFLOW_NAME
+from products.replay_vision.backend.temporal.errors import (
+ INELIGIBLE_SESSION_ERROR_TYPE,
+ SCANNER_FAILURE_ERROR_TYPE,
+ FailureKind,
+ ScannerFailureError,
+)
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
from products.replay_vision.backend.temporal.scanners.indexer import IndexerOutput
from products.replay_vision.backend.temporal.types import (
@@ -43,6 +51,7 @@ from products.replay_vision.backend.temporal.types import (
EnsureSessionAssetOutput,
FetchSessionEventsInputs,
MarkObservationFailedInputs,
+ MarkObservationIneligibleInputs,
MarkObservationRunningInputs,
MarkObservationSucceededInputs,
ScannerCallOutput,
@@ -74,12 +83,11 @@ _FETCH_RETRY = common.RetryPolicy(
# Asset get-or-create has no transient failure modes worth retrying.
_ENSURE_ASSET_RETRY = common.RetryPolicy(maximum_attempts=1)
-# Deterministic failures don't retry; a re-upload would leak another Gemini file before the cleanup sweep reaps it.
+# Deterministic failures opt out via ScannerFailureError's non_retryable flag; only transient kinds re-run.
_UPLOAD_RETRY = common.RetryPolicy(
initial_interval=dt.timedelta(seconds=2),
maximum_interval=dt.timedelta(seconds=30),
maximum_attempts=3,
- non_retryable_error_types=["RuntimeError", "ValueError"],
)
# Workflow-level retries only cover transient transport failures; schema/semantic errors are non-retryable.
@@ -100,6 +108,27 @@ _SIDE_EFFECT_RETRY = common.RetryPolicy(
)
+def _extract_kind_for_type(e: BaseException, expected_type: str) -> str | None:
+ """Pull a kind string off a kinded ApplicationError, surviving Temporal's ActivityError wrap."""
+ cause = unwrap_temporal_cause(e) or e
+ if getattr(cause, "type", None) != expected_type:
+ return None
+ details = getattr(cause, "details", None)
+ return details[0] if details else None
+
+
+def _root_cause_message(e: BaseException) -> str:
+ """Bare message from the root cause — no `TypeName:` prefix; the kind label takes that role."""
+ cause = unwrap_temporal_cause(e) or e
+ msg = getattr(cause, "message", None) or str(cause) or type(cause).__name__
+ return truncate_for_temporal_payload(msg, MAX_ERROR_MESSAGE_CHARS)
+
+
+def _encode_reason(kind: str, message: str) -> str:
+ """`kind:message` — the frontend splits on the first colon to render the kind as a badge."""
+ return f"{kind}:{message}"
+
+
@wf.defn(name=APPLY_SCANNER_WORKFLOW_NAME)
class ApplyScannerWorkflow(PostHogWorkflow):
"""Apply one scanner to one session: create row → fetch+rasterize → upload → call provider → emit event → mark succeeded."""
@@ -175,7 +204,12 @@ class ApplyScannerWorkflow(PostHogWorkflow):
retry_policy=_STATE_ACTIVITY_RETRY,
)
except Exception as e:
- await self._mark_failed(observation_id, f"{type(e).__name__}: {e}")
+ ineligible_kind = _extract_kind_for_type(e, INELIGIBLE_SESSION_ERROR_TYPE)
+ if ineligible_kind is not None:
+ await self._mark_ineligible(observation_id, ineligible_kind, _root_cause_message(e))
+ else:
+ failure_kind = _extract_kind_for_type(e, SCANNER_FAILURE_ERROR_TYPE) or FailureKind.INTERNAL_ERROR.value
+ await self._mark_failed(observation_id, failure_kind, _root_cause_message(e))
raise
finally:
if uploaded is not None:
@@ -214,26 +248,38 @@ class ApplyScannerWorkflow(PostHogWorkflow):
async def _run_rasterize_child(self, inputs: ApplyScannerInputs, asset_id: int) -> None:
# Per-scanner child id so concurrent observations of the same session don't collide on WorkflowAlreadyStartedError.
- await wf.execute_child_workflow(
- "rasterize-recording",
- RasterizeRecordingInputs(exported_asset_id=asset_id),
- id=f"replay-vision-rasterize-{inputs.team_id}-{inputs.session_id}-{inputs.scanner_id}",
- task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
- retry_policy=common.RetryPolicy(maximum_attempts=int(settings.TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
- execution_timeout=dt.timedelta(minutes=30),
- search_attributes=TypedSearchAttributes(
- search_attributes=[
- SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
- SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=inputs.session_id),
- ]
- ),
- )
+ try:
+ await wf.execute_child_workflow(
+ "rasterize-recording",
+ RasterizeRecordingInputs(exported_asset_id=asset_id),
+ id=f"replay-vision-rasterize-{inputs.team_id}-{inputs.session_id}-{inputs.scanner_id}",
+ task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
+ retry_policy=common.RetryPolicy(maximum_attempts=int(settings.TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ execution_timeout=dt.timedelta(minutes=30),
+ search_attributes=TypedSearchAttributes(
+ search_attributes=[
+ SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
+ SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=inputs.session_id),
+ ]
+ ),
+ )
+ except Exception as e:
+ # Re-classify the rasterizer's failure so the user sees a rasterizer label, not a generic "internal error".
+ raise ScannerFailureError(_root_cause_message(e), kind=FailureKind.RASTERIZATION_FAILED) from e
- async def _mark_failed(self, observation_id: UUID, error_reason: str) -> None:
+ async def _mark_failed(self, observation_id: UUID, kind: str, message: str) -> None:
await wf.execute_activity(
mark_observation_failed_activity,
- MarkObservationFailedInputs(observation_id=observation_id, error_reason=error_reason),
+ MarkObservationFailedInputs(observation_id=observation_id, error_reason=_encode_reason(kind, message)),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=_STATE_ACTIVITY_RETRY,
+ )
+
+ async def _mark_ineligible(self, observation_id: UUID, kind: str, message: str) -> None:
+ await wf.execute_activity(
+ mark_observation_ineligible_activity,
+ MarkObservationIneligibleInputs(observation_id=observation_id, error_reason=_encode_reason(kind, message)),
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=_STATE_ACTIVITY_RETRY,
)
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 807f215cf5a3..725c6d441a23 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -266,21 +266,3 @@ class TestReplayObservation(BaseTest):
scanner.save()
obs.refresh_from_db()
self.assertEqual(obs.scanner_snapshot["scanner_config"], {"prompt": "original"})
-
- def test_mark_succeeded_sets_completed_at(self) -> None:
- scanner = self._create_scanner()
- obs = self._create_observation(scanner, session_id="mark-ok")
- self.assertIsNone(obs.completed_at)
- obs.mark_succeeded()
- obs.refresh_from_db()
- self.assertEqual(obs.status, ObservationStatus.SUCCEEDED)
- self.assertIsNotNone(obs.completed_at)
-
- def test_mark_failed_sets_completed_at_and_error(self) -> None:
- scanner = self._create_scanner()
- obs = self._create_observation(scanner, session_id="mark-fail")
- obs.mark_failed("provider timeout after retries")
- obs.refresh_from_db()
- self.assertEqual(obs.status, ObservationStatus.FAILED)
- self.assertIsNotNone(obs.completed_at)
- self.assertEqual(obs.error_reason, "provider timeout after retries")
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 056c4fab63ae..394d656a2bfb 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -11,7 +11,7 @@ from django.utils import timezone
import psycopg.errors
from asgiref.sync import sync_to_async
-from temporalio.exceptions import ApplicationError
+from temporalio.exceptions import ActivityError, ApplicationError
from posthog.models import Organization, Team
from posthog.models.exported_asset import ExportedAsset
@@ -38,10 +38,19 @@ from products.replay_vision.backend.temporal.activities.ensure_session_asset imp
from products.replay_vision.backend.temporal.activities.fetch_session_events import fetch_session_events_activity
from products.replay_vision.backend.temporal.activities.observation_state import (
mark_observation_failed_activity,
+ mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_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.errors import (
+ INELIGIBLE_SESSION_ERROR_TYPE,
+ SCANNER_FAILURE_ERROR_TYPE,
+ FailureKind,
+ IneligibleSessionError,
+ IneligibleSessionKind,
+ ScannerFailureError,
+)
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
from products.replay_vision.backend.temporal.scanners.indexer import IndexerOutput
from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput
@@ -62,6 +71,7 @@ from products.replay_vision.backend.temporal.types import (
EventTable,
FetchSessionEventsInputs,
MarkObservationFailedInputs,
+ MarkObservationIneligibleInputs,
MarkObservationRunningInputs,
MarkObservationSucceededInputs,
ScannerCallOutput,
@@ -70,6 +80,7 @@ from products.replay_vision.backend.temporal.types import (
SessionMetadata,
UploadedVideo,
)
+from products.replay_vision.backend.temporal.workflow import _extract_kind_for_type, _root_cause_message
from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
@@ -277,7 +288,23 @@ class TestObservationStateActivities:
assert observation.error_reason == "bad output"
assert observation.completed_at is not None
- @pytest.mark.parametrize("terminal_status", [ObservationStatus.SUCCEEDED, ObservationStatus.FAILED])
+ def test_mark_ineligible_records_kind_reason_and_completed_at(self) -> None:
+ scanner = _make_scanner()
+ observation = _make_observation(scanner, status=ObservationStatus.RUNNING, started_at=timezone.now())
+
+ mark_observation_ineligible_activity(
+ MarkObservationIneligibleInputs(observation_id=observation.id, error_reason="too_short:only 5s long")
+ )
+
+ observation.refresh_from_db()
+ assert observation.status == ObservationStatus.INELIGIBLE
+ assert observation.error_reason == "too_short:only 5s long"
+ assert observation.completed_at is not None
+
+ @pytest.mark.parametrize(
+ "terminal_status",
+ [ObservationStatus.SUCCEEDED, ObservationStatus.FAILED, ObservationStatus.INELIGIBLE],
+ )
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.
scanner = _make_scanner()
@@ -470,33 +497,70 @@ class TestFetchSessionEventsActivity:
mock_obj.get_metadata.assert_not_called()
mock_obj.get_events.assert_not_called()
+ @pytest.mark.parametrize(
+ "metadata,expected_kind,expected_substring",
+ [
+ (None, "no_recording", "No replay metadata"),
+ (
+ {
+ "start_time": dt.datetime(2026, 5, 12, tzinfo=dt.UTC),
+ "end_time": dt.datetime(2026, 5, 12, 0, 0, 5, tzinfo=dt.UTC),
+ "duration": 5, # under 15s floor
+ "active_seconds": 5,
+ },
+ "too_short",
+ "is only 5",
+ ),
+ (
+ {
+ "start_time": dt.datetime(2026, 5, 12, tzinfo=dt.UTC),
+ "end_time": dt.datetime(2026, 5, 12, 0, 5, tzinfo=dt.UTC),
+ "duration": 300,
+ "active_seconds": 3, # under 10s floor
+ },
+ "too_inactive",
+ "has only 3",
+ ),
+ (
+ {
+ "start_time": dt.datetime(2026, 5, 12, tzinfo=dt.UTC),
+ "end_time": dt.datetime(2026, 5, 12, 2, tzinfo=dt.UTC),
+ "duration": 7200,
+ "active_seconds": 5000, # over 3600 cap
+ },
+ "too_long",
+ "has 5000",
+ ),
+ ],
+ )
@pytest.mark.asyncio
- async def test_raises_non_retryable_when_session_active_seconds_exceeds_max(self) -> None:
+ async def test_raises_ineligible_session_error_with_kind(
+ self, metadata: dict | None, expected_kind: str, expected_substring: str
+ ) -> None:
scanner = await sync_to_async(_make_scanner)()
observation_id = uuid.uuid4()
- metadata = {
- "start_time": dt.datetime(2026, 5, 12, tzinfo=dt.UTC),
- "end_time": dt.datetime(2026, 5, 12, 2, tzinfo=dt.UTC),
- "duration": 7200,
- "active_seconds": 5000, # over the 3600 cap
- }
mock_obj = self._make_session_replay_events_mock(metadata, [(["event"], [("$pageview",)])])
with patch(
"products.replay_vision.backend.temporal.activities.fetch_session_events.SessionReplayEvents",
return_value=mock_obj,
):
- with pytest.raises(ApplicationError) as exc_info:
+ with pytest.raises(IneligibleSessionError) as exc_info:
await fetch_session_events_activity(
FetchSessionEventsInputs(
- observation_id=observation_id, team_id=scanner.team_id, session_id="sess-long"
+ observation_id=observation_id, team_id=scanner.team_id, session_id="sess-x"
)
)
- assert exc_info.value.non_retryable is True
- assert "5000" in str(exc_info.value)
+
+ assert exc_info.value.non_retryable is True
+ assert exc_info.value.type == INELIGIBLE_SESSION_ERROR_TYPE
+ assert exc_info.value.kind == expected_kind
+ # Kind is also in `details[0]` so the workflow can read it off the wire-serialized ApplicationError.
+ assert exc_info.value.details == (expected_kind,)
+ assert expected_substring in str(exc_info.value)
@pytest.mark.asyncio
- async def test_raises_non_retryable_when_session_has_no_events(self) -> None:
+ async def test_raises_ineligible_no_events_when_session_returns_empty_pages(self) -> None:
scanner = await sync_to_async(_make_scanner)()
observation_id = uuid.uuid4()
metadata = {
@@ -505,21 +569,23 @@ class TestFetchSessionEventsActivity:
"duration": 300,
"active_seconds": 200,
}
+ # Empty columns + no rows triggers `_fetch_payload` to return None.
mock_obj = self._make_session_replay_events_mock(metadata, [([], [])])
with patch(
"products.replay_vision.backend.temporal.activities.fetch_session_events.SessionReplayEvents",
return_value=mock_obj,
):
- with pytest.raises(ApplicationError) as exc_info:
+ with pytest.raises(IneligibleSessionError) as exc_info:
await fetch_session_events_activity(
FetchSessionEventsInputs(
- observation_id=observation_id,
- team_id=scanner.team_id,
- session_id="sess-empty",
+ observation_id=observation_id, team_id=scanner.team_id, session_id="sess-empty"
)
)
- assert exc_info.value.non_retryable is True
+
+ assert exc_info.value.non_retryable is True
+ assert exc_info.value.kind == "no_events"
+ assert exc_info.value.details == ("no_events",)
@pytest.mark.asyncio
async def test_requests_extra_fields_and_event_blocklist(self) -> None:
@@ -1330,3 +1396,48 @@ async def test_apply_scanner_workflow_marks_failed_when_side_effect_raises() ->
assert mark_observation_succeeded_activity not in called
assert mark_observation_failed_activity in called
assert cleanup_gemini_file_activity in called
+
+
+def _wrap_in_activity_error(cause: ApplicationError) -> ActivityError:
+ """Build a minimal ActivityError shaped like what Temporal raises into a workflow's `except` block."""
+ activity_err = ActivityError.__new__(ActivityError)
+ activity_err.__cause__ = cause
+ return activity_err
+
+
+class TestWorkflowErrorHelpers:
+ """Unit tests for the workflow's exception-classification helpers."""
+
+ def test_extract_ineligible_kind_returns_kind_for_direct_ineligible_session_error(self) -> None:
+ err = IneligibleSessionError("session is too short", kind=IneligibleSessionKind.TOO_SHORT)
+ assert _extract_kind_for_type(err, INELIGIBLE_SESSION_ERROR_TYPE) == "too_short"
+
+ def test_extract_ineligible_kind_unwraps_activity_error_from_worker(self) -> None:
+ leaf = IneligibleSessionError("no recording", kind=IneligibleSessionKind.NO_RECORDING)
+ wrapped = _wrap_in_activity_error(leaf)
+ assert _extract_kind_for_type(wrapped, INELIGIBLE_SESSION_ERROR_TYPE) == "no_recording"
+
+ def test_extract_ineligible_kind_returns_none_for_unrelated_application_error(self) -> None:
+ err = ApplicationError("something broke", type="RuntimeError", non_retryable=True)
+ assert _extract_kind_for_type(err, INELIGIBLE_SESSION_ERROR_TYPE) is None
+
+ def test_extract_failure_kind_returns_kind_for_scanner_failure_error(self) -> None:
+ err = ScannerFailureError("gemini rejected", kind=FailureKind.PROVIDER_REJECTED)
+ assert _extract_kind_for_type(err, SCANNER_FAILURE_ERROR_TYPE) == "provider_rejected"
+
+ def test_extract_failure_kind_unwraps_activity_error_from_worker(self) -> None:
+ leaf = ScannerFailureError("missing asset", kind=FailureKind.INTERNAL_ERROR)
+ wrapped = _wrap_in_activity_error(leaf)
+ assert _extract_kind_for_type(wrapped, SCANNER_FAILURE_ERROR_TYPE) == "internal_error"
+
+ def test_extract_failure_kind_returns_none_for_unrelated_application_error(self) -> None:
+ err = ApplicationError("something broke", type="RuntimeError", non_retryable=True)
+ assert _extract_kind_for_type(err, SCANNER_FAILURE_ERROR_TYPE) is None
+
+ def test_root_cause_message_strips_temporal_wrapper(self) -> None:
+ leaf = ApplicationError("Gemini file files/abc reached state FAILED", type="RuntimeError")
+ wrapped = _wrap_in_activity_error(leaf)
+ assert _root_cause_message(wrapped) == "Gemini file files/abc reached state FAILED"
+
+ def test_root_cause_message_falls_back_to_str_for_bare_exceptions(self) -> None:
+ assert _root_cause_message(ValueError("bad arg")) == "bad arg"
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index e3f1a084ff77..e1109a0b18ad 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -4,6 +4,7 @@ import { LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import type { ScannerTypeEnumApi, ReplayObservationApi } from '../generated/api.schemas'
+import { failureKindDescription, parseFailureReason, parseIneligibleReason } from '../replay_scanners/types'
const SCANNER_TYPE_LABEL: Record<ScannerTypeEnumApi, string> = {
monitor: 'Monitor',
@@ -20,6 +21,10 @@ export function ObservationStatusTag({ status }: { status: ReplayObservationApi[
if (status === 'failed') {
return <LemonTag type="danger">Failed</LemonTag>
}
+ if (status === 'ineligible') {
+ // Muted, not danger — the session was skipped at the gate, not a scanner failure.
+ return <LemonTag type="muted">Ineligible</LemonTag>
+ }
if (status === 'running') {
return (
<LemonTag type="warning">
@@ -37,11 +42,26 @@ function readResult(observation: ReplayObservationApi): Record<string, unknown>
/** Compact, single-cell preview of an observation result for the Vision scene's observations table. */
export function ObservationResultSummary({ observation }: { observation: ReplayObservationApi }): JSX.Element {
+ if (observation.status === 'ineligible') {
+ const parsed = parseIneligibleReason(observation.error_reason)
+ const label = parsed?.label ?? 'Ineligible'
+ const detail = parsed?.message ?? observation.error_reason
+ return (
+ <Tooltip title={detail || label}>
+ <span className="text-muted text-sm">{label}</span>
+ </Tooltip>
+ )
+ }
if (observation.status === 'failed') {
+ const parsed = parseFailureReason(observation.error_reason)
+ const label = parsed?.label ?? 'Failed'
+ const description = parsed ? failureKindDescription(parsed.kind) : null
+ const detail = parsed?.message ?? observation.error_reason
+ const tooltip = [description, detail].filter(Boolean).join('\n\n') || 'Unknown error'
return (
- <Tooltip title={observation.error_reason || 'Unknown error'}>
+ <Tooltip title={tooltip}>
<span className="inline-flex items-center gap-1 text-danger text-sm">
- <IconWarning /> {observation.error_reason || 'Failed'}
+ <IconWarning /> {label}
</span>
</Tooltip>
)
@@ -154,6 +174,33 @@ function ObservationResult({
)
}
+function FailureDetail({ errorReason }: { errorReason: string }): JSX.Element {
+ const parsed = parseFailureReason(errorReason)
+ if (!parsed) {
+ return <div className="text-danger text-sm">{errorReason}</div>
+ }
+ return (
+ <div className="space-y-1">
+ <div className="font-semibold text-danger text-sm">{parsed.label}</div>
+ <div className="text-muted text-xs">{failureKindDescription(parsed.kind)}</div>
+ {parsed.message && <div className="text-muted text-xs font-mono">{parsed.message}</div>}
+ </div>
+ )
+}
+
+function IneligibleDetail({ errorReason }: { errorReason: string }): JSX.Element {
+ const parsed = parseIneligibleReason(errorReason)
+ if (!parsed) {
+ return <div className="text-muted text-sm">{errorReason}</div>
+ }
+ return (
+ <div className="space-y-1">
+ <div className="font-semibold text-sm">{parsed.label}</div>
+ {parsed.message && <div className="text-muted text-xs">{parsed.message}</div>}
+ </div>
+ )
+}
+
/** In-progress state for a pending/running observation. */
function ObservationProgress({ observation }: { observation: ReplayObservationApi }): JSX.Element {
return (
@@ -183,7 +230,11 @@ export function ObservationCard({ observation }: { observation: ReplayObservatio
</div>
{observation.status === 'failed' && observation.error_reason && (
- <div className="text-danger text-sm">{observation.error_reason}</div>
+ <FailureDetail errorReason={observation.error_reason} />
+ )}
+
+ {observation.status === 'ineligible' && observation.error_reason && (
+ <IneligibleDetail errorReason={observation.error_reason} />
)}
{observation.status === 'succeeded' && scannerType && result && (
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 56d082be5444..6480cd77c785 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -12,6 +12,7 @@
* `running` - Running
* `succeeded` - Succeeded
* `failed` - Failed
+ * `ineligible` - Ineligible
*/
export type ObservationStatusEnumApi = (typeof ObservationStatusEnumApi)[keyof typeof ObservationStatusEnumApi]
@@ -20,6 +21,7 @@ export const ObservationStatusEnumApi = {
Running: 'running',
Succeeded: 'succeeded',
Failed: 'failed',
+ Ineligible: 'ineligible',
} as const
/**
@@ -182,14 +184,15 @@ export interface ReplayObservationApi {
readonly scanner_id: string
/** Session recording id this scanner was applied to. */
readonly session_id: string
- /** Observation status (pending, running, succeeded, failed).
+ /** Observation status (pending, running, succeeded, failed, ineligible).
* `pending` - Pending
* `running` - Running
* `succeeded` - Succeeded
- * `failed` - Failed */
+ * `failed` - Failed
+ * `ineligible` - Ineligible */
readonly status: ObservationStatusEnumApi
- /** Populated on failure; includes the malformed model response when validation fails. */
+ /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / internal_error. */
readonly error_reason: string
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string
@@ -477,6 +480,7 @@ export type VisionScannersObservationsListParams = {
* `running` - Running
* `succeeded` - Succeeded
* `failed` - Failed
+* `ineligible` - Ineligible
*/
status?: VisionScannersObservationsListStatus
/**
@@ -493,6 +497,7 @@ export type VisionScannersObservationsListStatus =
export const VisionScannersObservationsListStatus = {
Failed: 'failed',
+ Ineligible: 'ineligible',
Pending: 'pending',
Running: 'running',
Succeeded: 'succeeded',
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
index d6efc694a719..500fa2b3b689 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
@@ -23,15 +23,18 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri
acc.succeeded += 1
} else if (o.status === 'failed') {
acc.failed += 1
+ } else if (o.status === 'ineligible') {
+ acc.ineligible += 1
} else {
acc.inFlight += 1
}
return acc
},
- { total: 0, succeeded: 0, failed: 0, inFlight: 0 }
+ { total: 0, succeeded: 0, failed: 0, ineligible: 0, inFlight: 0 }
)
- const completed = stats.succeeded + stats.failed
- const successRate = completed > 0 ? Math.round((stats.succeeded / completed) * 100) : null
+ // Success rate excludes ineligible — those weren't scanner failures, they were skipped at the gate.
+ const scored = stats.succeeded + stats.failed
+ const successRate = scored > 0 ? Math.round((stats.succeeded / scored) * 100) : null
const columns: LemonTableColumns<ReplayObservationApi> = [
{
@@ -103,6 +106,12 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri
<div className="text-muted">Failed</div>
</div>
)}
+ {stats.ineligible > 0 && (
+ <div className="text-center">
+ <div className="font-semibold text-lg">{stats.ineligible}</div>
+ <div className="text-muted">Ineligible</div>
+ </div>
+ )}
{stats.inFlight > 0 && (
<div className="text-center">
<div className="font-semibold text-lg">{stats.inFlight}</div>
@@ -138,7 +147,8 @@ export function ScannerObservationsTable({ scannerId, tabId }: { scannerId: stri
pagination={{ pageSize: 50 }}
nouns={['observation', 'observations']}
expandable={{
- rowExpandable: (obs) => obs.status === 'succeeded' || obs.status === 'failed',
+ rowExpandable: (obs) =>
+ obs.status === 'succeeded' || obs.status === 'failed' || obs.status === 'ineligible',
expandedRowRender: (obs) => (
<div className="p-2">
<ObservationCard observation={obs} />
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index bc35c89b2f16..ea3a2d285f04 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -6,6 +6,82 @@ export type ScannerType = 'monitor' | 'classifier' | 'scorer' | 'summarizer' | '
export type EnabledFilter = 'enabled' | 'disabled'
+export type IneligibleKind = 'no_recording' | 'too_short' | 'too_inactive' | 'too_long' | 'no_events'
+
+const INELIGIBLE_KIND_LABELS: Record<IneligibleKind, string> = {
+ no_recording: 'No recording',
+ too_short: 'Too short',
+ too_inactive: 'Too inactive',
+ too_long: 'Too long',
+ no_events: 'No events',
+}
+
+export type FailureKind =
+ | 'provider_transient'
+ | 'provider_rejected'
+ | 'rasterization_failed'
+ | 'validation_failed'
+ | 'internal_error'
+
+const FAILURE_KINDS: Record<FailureKind, { label: string; description: string }> = {
+ provider_transient: {
+ label: 'AI provider unavailable',
+ description: 'The AI provider was temporarily unreachable. PostHog will retry on the next schedule fire.',
+ },
+ provider_rejected: {
+ label: 'AI provider rejected video',
+ description: "The AI provider couldn't process this recording. Other recordings should work.",
+ },
+ rasterization_failed: {
+ label: 'Rasterization failed',
+ description: "PostHog couldn't render this recording into a video. Other recordings should work.",
+ },
+ validation_failed: {
+ label: 'AI output invalid',
+ description:
+ "The AI's response didn't match the scanner schema after several attempts. Try simplifying the scanner prompt.",
+ },
+ internal_error: {
+ label: 'Internal error',
+ description: 'An unexpected PostHog error occurred. Please contact support.',
+ },
+}
+
+const FAILURE_KIND_LABELS = Object.fromEntries(
+ Object.entries(FAILURE_KINDS).map(([kind, meta]) => [kind, meta.label])
+) as Record<FailureKind, string>
+
+export type ParsedReason<K extends string> = { kind: K; label: string; message: string }
+
+function parseKindReason<K extends string>(error_reason: string, labels: Record<K, string>): ParsedReason<K> | null {
+ // The backend formats `error_reason` as `kind:human message`; fall back to a generic label on drift.
+ const idx = error_reason.indexOf(':')
+ if (idx <= 0) {
+ return null
+ }
+ const kind = error_reason.slice(0, idx)
+ if (!(kind in labels)) {
+ return null
+ }
+ return {
+ kind: kind as K,
+ label: labels[kind as K],
+ message: error_reason.slice(idx + 1).trim(),
+ }
+}
+
+export function parseIneligibleReason(error_reason: string): ParsedReason<IneligibleKind> | null {
+ return parseKindReason(error_reason, INELIGIBLE_KIND_LABELS)
+}
+
+export function parseFailureReason(error_reason: string): ParsedReason<FailureKind> | null {
+ return parseKindReason(error_reason, FAILURE_KIND_LABELS)
+}
+
+export function failureKindDescription(kind: FailureKind): string {
+ return FAILURE_KINDS[kind].description
+}
+
export const DEFAULT_PROVIDER = 'google'
export const DEFAULT_MODEL = 'gemini-3-flash'
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fa7dfd075c98..a74b64af6ffc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21696,6 +21696,7 @@ export namespace Schemas {
* `running` - Running
* `succeeded` - Succeeded
* `failed` - Failed
+ * `ineligible` - Ineligible
*/
export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
@@ -21705,6 +21706,7 @@ export namespace Schemas {
Running: 'running',
Succeeded: 'succeeded',
Failed: 'failed',
+ Ineligible: 'ineligible',
} as const;
/**
@@ -23549,14 +23551,15 @@ export namespace Schemas {
readonly scanner_id: string;
/** Session recording id this scanner was applied to. */
readonly session_id: string;
- /** Observation status (pending, running, succeeded, failed).
+ /** Observation status (pending, running, succeeded, failed, ineligible).
* `pending` - Pending
* `running` - Running
* `succeeded` - Succeeded
- * `failed` - Failed */
+ * `failed` - Failed
+ * `ineligible` - Ineligible */
readonly status: ObservationStatusEnum;
- /** Populated on failure; includes the malformed model response when validation fails. */
+ /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / internal_error. */
readonly error_reason: string;
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string;
@@ -41782,6 +41785,7 @@ export namespace Schemas {
* `running` - Running
* `succeeded` - Succeeded
* `failed` - Failed
+ * `ineligible` - Ineligible
*/
status?: VisionScannersObservationsListStatus;
/**
@@ -41798,6 +41802,7 @@ export namespace Schemas {
export const VisionScannersObservationsListStatus = {
Failed: 'failed',
+ Ineligible: 'ineligible',
Pending: 'pending',
Running: 'running',
Succeeded: 'succeeded',