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.

fix(replay-vision): classify scan failures honestly and spend the retry budget (#74977)

Arno Hillen296c7f4351b4
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
index 771f976020bb..23f92ff30a0b 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
@@ -28,6 +28,13 @@ jest.mock('@temporalio/common', () => ({
;(err as any)._isNonRetryable = true
return err
}),
+ retryable: jest.fn().mockImplementation((message, type, cause) => {
+ const err = new Error(message)
+ ;(err as any).type = type
+ ;(err as any).cause = cause
+ ;(err as any)._isNonRetryable = false
+ return err
+ }),
},
}))
@@ -202,17 +209,33 @@ describe('rasterizeRecordingActivity', () => {
await expect(rasterizeRecordingActivity(baseInput())).rejects.toThrow('No snapshot data')
- expect(ApplicationFailure.nonRetryable).toHaveBeenCalledWith('No snapshot data', 'NON_RETRYABLE', error)
+ // Callers classify on the code to tell an unrenderable recording apart from a render that ran out of
+ // retries, so it has to travel as the failure type.
+ expect(ApplicationFailure.nonRetryable).toHaveBeenCalledWith('No snapshot data', 'NO_SNAPSHOTS', error)
})
- it('re-throws retryable RasterizationError as plain Error (Temporal retries)', async () => {
+ it('wraps retryable RasterizationError as ApplicationFailure.retryable, keeping the code', async () => {
const error = new RasterizationError('browser crashed', true, 'TIMEOUT')
mockedRasterizeRecording.mockRejectedValue(error)
- const rejection = rasterizeRecordingActivity(baseInput())
- await expect(rejection).rejects.toThrow('browser crashed')
- await expect(rejection).rejects.toBeInstanceOf(RasterizationError)
+ await expect(rasterizeRecordingActivity(baseInput())).rejects.toThrow('browser crashed')
+
+ expect(ApplicationFailure.retryable).toHaveBeenCalledWith('browser crashed', 'TIMEOUT', error)
+ expect(ApplicationFailure.nonRetryable).not.toHaveBeenCalled()
+ })
+
+ it('keeps a retryable NO_SNAPSHOTS retryable so an ingestion race gets another render', async () => {
+ const error = new RasterizationError('No snapshots after processing', true, 'NO_SNAPSHOTS')
+ mockedRasterizeRecording.mockRejectedValue(error)
+
+ await expect(rasterizeRecordingActivity(baseInput())).rejects.toThrow('No snapshots after processing')
+ // The code still travels, so the caller can classify once the retries are spent, but the attempts happen.
+ expect(ApplicationFailure.retryable).toHaveBeenCalledWith(
+ 'No snapshots after processing',
+ 'NO_SNAPSHOTS',
+ error
+ )
expect(ApplicationFailure.nonRetryable).not.toHaveBeenCalled()
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
index ec9b6899a0bc..6e0aeff6d5f9 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
@@ -153,6 +153,26 @@ describe('PlayerController', () => {
await expect(startPromise).rejects.toBeInstanceOf(RasterizationError)
})
+ it('waitForStart() keeps a retryable NO_SNAPSHOTS retryable', async () => {
+ // A scan can start once replay metadata exists but before the snapshot blocks are readable, and that render
+ // succeeds on a later attempt. Downgrading NO_SNAPSHOTS to non-retryable here would strand those recordings as
+ // permanently ineligible, so the player's own verdict has to survive.
+ const mp = mockCapturePage()
+ const controller = new PlayerController(mp.capturePage, mockBlockProxy, jest.fn())
+ await controller.load(basePlayerConfig())
+
+ const startPromise = controller.waitForStart(basePlayerConfig(), 5000)
+
+ mp._emit({
+ type: 'error',
+ code: 'NO_SNAPSHOTS',
+ message: 'No snapshots after processing',
+ retryable: true,
+ })
+
+ await expect(startPromise).rejects.toMatchObject({ code: 'NO_SNAPSHOTS', retryable: true })
+ })
+
it('isEnded() returns true after ended message', async () => {
const mp = mockCapturePage()
const controller = new PlayerController(mp.capturePage, mockBlockProxy, jest.fn())
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
index dba92d8422ea..c4149b44c266 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
@@ -21,8 +21,14 @@ import {
import { elapsed } from '~/session-replay/recording-rasterizer/utils'
function toActivityError(err: unknown): Error {
- if (err instanceof RasterizationError && !err.retryable) {
- return ApplicationFailure.nonRetryable(err.message, 'NON_RETRYABLE', err)
+ if (err instanceof RasterizationError) {
+ // The code travels as the failure type either way, so a caller can tell a recording that can never render
+ // (NO_SNAPSHOTS) from one that merely ran out of retries. Retryability stays the player's call: NO_SNAPSHOTS is
+ // retryable while a recording is still being ingested, so the code is only conclusive once Temporal has spent
+ // the attempts.
+ return err.retryable
+ ? ApplicationFailure.retryable(err.message, err.code, err)
+ : ApplicationFailure.nonRetryable(err.message, err.code, err)
}
return err instanceof Error ? err : new Error(String(err))
}
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 58204ce316d3..522bb0cc6a7c 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -49,6 +49,7 @@ from products.replay_vision.backend.api.trigger import (
start_apply_scanner_workflow,
)
from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.enqueue_claims import release_enqueue_claim
from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
@@ -175,7 +176,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
triggered_by = serializers.ChoiceField(
choices=ObservationTrigger.choices,
read_only=True,
- help_text="Whether this observation came from the schedule, an on-demand request, or a retry of a failed observation.",
+ help_text="Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.",
)
triggered_by_user = UserBasicSerializer(
read_only=True,
@@ -907,7 +908,7 @@ class ReplayObservationViewSet(
)
@action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])
def retry(self, request: Request, **kwargs: Any) -> Response:
- """Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle."""
+ """Delete a failed or ineligible observation and re-run its scanner on the same recording. Returns 202 with the workflow handle."""
observation = self.get_object()
# The nested route already resolved the scanner for RBAC; the session route pays one FK fetch.
scanner = getattr(self, "_scanner_for_url_cache", None) or observation.scanner
@@ -916,8 +917,18 @@ class ReplayObservationViewSet(
session_id = observation.session_id
original_pk = observation.pk
original_created_at = observation.created_at
- if observation.status != ObservationStatus.FAILED:
- raise ValidationError("Only failed observations can be retried.")
+ # Ineligible is retryable because some gates are timing artifacts: the recording or its snapshots can
+ # finish ingesting after the scan ran (see IneligibleSessionKind.NO_SNAPSHOTS). Without this, the
+ # UNIQUE(scanner, session_id) row would lock the session out of that scanner forever.
+ if observation.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):
+ raise ValidationError("Only failed or ineligible observations can be retried.")
+ # Gate consent before deleting the row: the replacement workflow fails closed at create time when
+ # consent is off, and the sweep never revisits past sessions, so the delete would leave nothing behind.
+ if not is_ai_data_processing_approved(self.team.id):
+ raise ValidationError(
+ "AI data processing is turned off for this organization, so the scan can't run. "
+ "An organization admin can turn it on in organization settings."
+ )
# Advisory, and deliberately outside the lock below: the atomic claim is the authoritative gate,
# and these two read enough to be worth keeping off a held row lock.
check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))
@@ -925,8 +936,8 @@ class ReplayObservationViewSet(
# Locked so two concurrent retries can't both pass the status check and both delete the row.
with transaction.atomic():
locked = ReplayObservation.objects.select_for_update().get(pk=original_pk, team_id=self.team_id)
- if locked.status != ObservationStatus.FAILED:
- raise ValidationError("Only failed observations can be retried.")
+ if locked.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):
+ raise ValidationError("Only failed or ineligible observations can be retried.")
# Captured before the delete cascades it away: a run that never starts has to put the team's
# rating back with the row, not just the row.
original_label = ReplayObservationLabel.objects.filter(
@@ -956,7 +967,7 @@ class ReplayObservationViewSet(
slot_already_claimed=True,
)
if outcome is not WorkflowStartOutcome.STARTED:
- # The replacement run never started, so restore the failed row and its rating instead of leaving
+ # The replacement run never started, so restore the original row and its rating instead of leaving
# the recording looking unscanned and the team's feedback gone.
try:
with transaction.atomic():
diff --git a/products/replay_vision/backend/error_kinds.py b/products/replay_vision/backend/error_kinds.py
index e1ae68628336..ee2986ea30c2 100644
--- a/products/replay_vision/backend/error_kinds.py
+++ b/products/replay_vision/backend/error_kinds.py
@@ -11,21 +11,27 @@ class IneligibleSessionKind(StrEnum):
TOO_INACTIVE = "too_inactive"
TOO_LONG = "too_long"
NO_EVENTS = "no_events"
+ # Replay metadata exists but the snapshot blocks hold nothing renderable, so there is no video to analyze.
+ # Usually a property of the recording, but it can be a timing artifact (snapshots still ingesting, a
+ # backfill landing late), so the retry endpoint accepts ineligible rows and the UI offers a retry here.
+ NO_SNAPSHOTS = "no_snapshots"
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_TRANSIENT = "provider_transient" # AI provider outage / rate limit / 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
+ INFRA_TRANSIENT = "infra_transient" # PostHog-side dependency was slow or at capacity; retry usually helps
INTERNAL_ERROR = "internal_error" # Unclassified / bug paths — user can't fix
ORPHANED = "orphaned" # Workflow died without reaching a terminal state (timeout, terminate); set by the reaper
@property
def is_retryable(self) -> bool:
- return self is FailureKind.PROVIDER_TRANSIENT
+ """Whether Temporal should re-run the activity that raised this. Only the two transient kinds recover on their own."""
+ return self in (FailureKind.PROVIDER_TRANSIENT, FailureKind.INFRA_TRANSIENT)
# Shared by the model field and the API serializer so the documented vocabulary can't drift from the enums.
diff --git a/products/replay_vision/backend/migrations/0056_alter_replayobservation_help_texts.py b/products/replay_vision/backend/migrations/0056_alter_replayobservation_help_texts.py
new file mode 100644
index 000000000000..b6da1110b151
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0056_alter_replayobservation_help_texts.py
@@ -0,0 +1,30 @@
+# Generated by Django 5.2.14 on 2026-07-29 17:03
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0055_alter_replayscanner_model"),
+ ]
+
+ operations = [
+ 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 / no_snapshots. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned.",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="replayobservation",
+ name="triggered_by",
+ field=models.CharField(
+ choices=[("schedule", "Schedule"), ("on_demand", "On demand"), ("retry", "Retry")],
+ help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, or a retry of a failed or ineligible observation.",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 771710fc070a..fde6cd028dfc 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0055_alter_replayscanner_model
+0056_alter_replayobservation_help_texts
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index a3aeddecbfa3..47313c4009fc 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -74,7 +74,7 @@ class ReplayObservation(UUIDModel):
triggered_by = models.CharField(
max_length=16,
choices=ObservationTrigger.choices,
- help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, or a retry of a failed observation.",
+ help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, or a retry of a failed or ineligible observation.",
)
triggered_by_user = models.ForeignKey(
"posthog.User",
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 3e30dc035019..74ccd32258c5 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -10,6 +10,7 @@ import re
import time
import asyncio
import functools
+from dataclasses import dataclass
from typing import Any, TypeVar
from uuid import UUID
@@ -33,8 +34,8 @@ from products.replay_vision.backend.temporal.conversation import function_calls,
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.events_tool import build_events_index, dispatch_events_tool, events_tool
-from products.replay_vision.backend.temporal.gemini import gemini_api_key
-from products.replay_vision.backend.temporal.metrics import record_provider_call
+from products.replay_vision.backend.temporal.gemini import classify_gemini_error, describe_gemini_error, gemini_api_key
+from products.replay_vision.backend.temporal.metrics import record_mission_pass, record_provider_call
from products.replay_vision.backend.temporal.scanners import scanner_from_snapshot
from products.replay_vision.backend.temporal.scanners.base import (
TIMESTAMP_CITATION_RE,
@@ -57,19 +58,47 @@ from products.replay_vision.backend.temporal.types import (
logger = structlog.get_logger(__name__)
_MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation error appended per step
+# One clean re-ask after a validation failure. The per-step re-prompt above retries inside the same conversation,
+# where the model stays anchored on the answer it just got wrong; a fresh conversation is an independent draw.
+_MAX_MISSION_ATTEMPTS = 2
# Cache TTL: a scan is a handful of turns and finishes in minutes; well under this.
_VIDEO_CACHE_TTL = "900s"
_OutputT = TypeVar("_OutputT", bound=BaseModel)
+@dataclass(frozen=True)
+class _StepResult:
+ """One mission step's outcome: the validated output, or, when exhausted, whether the provider refused to answer."""
+
+ output: BaseModel | None
+ provider_refused: bool = False
+
+
@activity.defn
@track_activity()
async def call_scanner_provider_activity(inputs: CallScannerProviderInputs) -> ScannerCallOutput:
"""Run the scanner conversation against the uploaded video + cached events; validate, finalize, return the output."""
- # Background heartbeats let Temporal detect a dead worker in ~2 min instead of the full 10-min timeout.
+ # Background heartbeats let Temporal detect a dead worker in ~2 min instead of the full 20-min timeout.
async with Heartbeater(factor=4):
- return await _call_scanner_provider(inputs)
+ try:
+ return await _call_scanner_provider(inputs)
+ except Exception as e:
+ # Classify at the activity boundary, not inside the mission, so the cached-run fallback below can
+ # inspect the raw provider error and decide which layer owns the retry.
+ kind = classify_gemini_error(e)
+ if kind is None:
+ raise
+ # The raw error body can quote request content (prompt text), so it stays out of both the
+ # user-visible error_reason and the logs; code + status carry the diagnostic signal.
+ logger.warning(
+ "replay_vision.call_scanner_provider.provider_error",
+ kind=kind.value,
+ error_type=type(e).__name__,
+ code=getattr(e, "code", None),
+ status=getattr(e, "status", None),
+ )
+ raise ScannerFailureError(describe_gemini_error(e), kind=kind) from e
async def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCallOutput:
@@ -238,25 +267,7 @@ async def _run_mission(
metric_labels=metric_labels,
)
try:
- if cache is None:
- step_outputs = await run(cache_name=None)
- else:
- try:
- step_outputs = await run(cache_name=cache.name)
- except ScannerFailureError:
- raise # a required step genuinely couldn't be satisfied — re-running won't help.
- except Exception as exc:
- # The cached request failed (a bad cache reference, or a transient provider error) — retry inline once.
- # Capture the cause: this fallback fires often enough that we need to know whether it's the
- # cached-content + response-schema combination, a stale cache reference, or a transient provider error.
- logger.warning(
- "replay_vision.video_cache.run_failed_retrying_inline",
- model=snapshot.model,
- error=str(exc),
- error_type=type(exc).__name__,
- exc_info=True,
- )
- step_outputs = await run(cache_name=None)
+ step_outputs = await _run_mission_attempts(run=run, cache=cache, model=snapshot.model)
finally:
if cache is not None:
await _delete_video_cache(cache_client, cache.name)
@@ -264,6 +275,53 @@ async def _run_mission(
return scanner.assemble(step_outputs)
+async def _run_mission_attempts(*, run: Any, cache: Any | None, model: str) -> dict[str, BaseModel]:
+ """Run the mission, re-asking once from a clean conversation when a required step failed validation."""
+ for attempt in range(1, _MAX_MISSION_ATTEMPTS):
+ try:
+ return await _run_pass(run=run, cache=cache, model=model)
+ except ScannerFailureError as exc:
+ if exc.kind is not FailureKind.VALIDATION_FAILED:
+ raise
+ logger.warning(
+ "replay_vision.call_scanner_provider.mission_retry_after_validation_failure",
+ model=model,
+ attempt=attempt,
+ error=str(exc),
+ )
+ return await _run_pass(run=run, cache=cache, model=model)
+
+
+async def _run_pass(*, run: Any, cache: Any | None, model: str) -> dict[str, BaseModel]:
+ """One mission pass over the cached prefix, falling back to an inline video when the cached request itself fails."""
+ if cache is None:
+ record_mission_pass(model=model, path="inline")
+ return await run(cache_name=None)
+ record_mission_pass(model=model, path="cached")
+ try:
+ return await run(cache_name=cache.name)
+ except ScannerFailureError:
+ raise # a required step genuinely couldn't be satisfied, so re-running won't help.
+ except Exception as exc:
+ # Transient provider errors belong to the Temporal activity retry, which backs off across the quota
+ # window; an immediate inline re-run would just re-spend the video tokens against a provider that is
+ # still rate-limiting or down, and would multiply with the other retry layers.
+ if classify_gemini_error(exc) is FailureKind.PROVIDER_TRANSIENT:
+ raise
+ # The cached request failed some other way (a stale cache reference, an unrecognized error), so retry
+ # inline once. Capture the cause: this fallback fires often enough that we need to know whether it's
+ # the cached-content + response-schema combination or something new.
+ logger.warning(
+ "replay_vision.video_cache.run_failed_retrying_inline",
+ model=model,
+ error=str(exc),
+ error_type=type(exc).__name__,
+ exc_info=True,
+ )
+ record_mission_pass(model=model, path="inline_fallback")
+ return await run(cache_name=None)
+
+
async def _run_steps(
*,
client: Any,
@@ -283,7 +341,7 @@ async def _run_steps(
for step in steps:
checkpoint = len(convo)
convo.append(types.Part(text=step.instruction))
- parsed = await _run_step(
+ result = await _run_step(
client=client,
model=model,
step=step,
@@ -293,20 +351,32 @@ async def _run_steps(
team_id=team_id,
metric_labels=metric_labels,
)
- if parsed is None:
+ if result.output is None:
# Roll the failed step's half-finished exchange back so the next instruction follows the last good
# model turn, not a dangling correction/tool call (which would leave two user turns in a row).
del convo[checkpoint:]
if step.required:
- raise ScannerFailureError(
- f"Required step '{step.name}' rejected after {_MAX_LLM_ATTEMPTS} attempts",
- kind=FailureKind.VALIDATION_FAILED,
- )
+ raise _exhausted_step_error(step, result)
continue
- step_outputs[step.name] = parsed
+ step_outputs[step.name] = result.output
return step_outputs
+def _exhausted_step_error(step: MissionStep, result: "_StepResult") -> ScannerFailureError:
+ """Why a required step ran out of attempts, kept distinct so the user gets advice that matches the cause."""
+ if result.provider_refused:
+ # An empty candidate list is the provider declining to answer about this video (safety or content policy).
+ # Telling the user to reword their prompt would send them editing something that was never the problem.
+ return ScannerFailureError(
+ f"Provider returned no answer for required step '{step.name}' after {_MAX_LLM_ATTEMPTS} attempts",
+ kind=FailureKind.PROVIDER_REJECTED,
+ )
+ return ScannerFailureError(
+ f"Required step '{step.name}' rejected after {_MAX_LLM_ATTEMPTS} attempts",
+ kind=FailureKind.VALIDATION_FAILED,
+ )
+
+
async def _run_step(
*,
client: Any,
@@ -317,8 +387,8 @@ async def _run_step(
dispatch: Any,
team_id: int,
metric_labels: dict[str, str],
-) -> BaseModel | None:
- """Run one step's tool loop with one re-prompt on failure. Returns the validated output, or None when exhausted.
+) -> "_StepResult":
+ """Run one step's tool loop with one re-prompt on failure. Returns the validated output, or why it was exhausted.
On success the model's answer is appended to `convo` so the next step sees it; on failure a correction is
appended and we retry.
@@ -336,6 +406,9 @@ async def _run_step(
)
last_error: str | None = None
+ # Whether the final attempt came back with no candidate at all, which reads as a provider refusal rather
+ # than a schema problem. Tracked on the last attempt only: that is the state we ended up reporting.
+ last_was_empty = False
for attempt in range(_MAX_LLM_ATTEMPTS):
started = time.monotonic()
try:
@@ -360,9 +433,11 @@ async def _run_step(
if not response.candidates:
# No candidate (safety filter / content policy): record a failed attempt and retry without indexing [0].
last_error = "model returned no candidates"
+ last_was_empty = True
record_provider_call(**metric_labels, outcome="validation_failed", seconds=time.monotonic() - started)
logger.warning("replay_vision.call_scanner_provider.empty_response", step=step.name, attempt=attempt + 1)
continue
+ last_was_empty = False
text = (response.text or "").strip()
parsed, error = _parse_and_validate(step, text)
@@ -374,7 +449,7 @@ async def _run_step(
if error is None:
convo.append(response.candidates[0].content) # carry the answer into the next turn
- return parsed
+ return _StepResult(output=parsed)
last_error = error
logger.warning(
@@ -403,8 +478,9 @@ async def _run_step(
step=step.name,
required=step.required,
error=last_error,
+ provider_refused=last_was_empty,
)
- return None
+ return _StepResult(output=None, provider_refused=last_was_empty)
_OUT_OF_LOOKUPS_NUDGE = (
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 9e32d1c47597..e9557d4bd16b 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
@@ -20,7 +20,7 @@ from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureError
-from products.replay_vision.backend.temporal.gemini import gemini_api_key
+from products.replay_vision.backend.temporal.gemini import classify_gemini_error, describe_gemini_error, gemini_api_key
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import track_uploaded_file
from products.replay_vision.backend.temporal.types import UploadedVideo, UploadVideoToGeminiInputs
@@ -36,7 +36,22 @@ 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."""
# Background heartbeats let Temporal detect a dead worker in ~2 min instead of the full 10-min timeout.
async with Heartbeater(factor=4):
- return await _upload_video(inputs)
+ try:
+ return await _upload_video(inputs)
+ except Exception as e:
+ kind = classify_gemini_error(e)
+ if kind is None:
+ raise
+ # The raw error body can quote request content, so it stays out of both the user-visible
+ # error_reason and the logs; code + status carry the diagnostic signal.
+ logger.warning(
+ "replay_vision.upload_video_to_gemini.provider_error",
+ kind=kind.value,
+ error_type=type(e).__name__,
+ code=getattr(e, "code", None),
+ status=getattr(e, "status", None),
+ )
+ raise ScannerFailureError(describe_gemini_error(e), kind=kind) from e
async def _upload_video(inputs: UploadVideoToGeminiInputs) -> UploadedVideo:
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 251932a82c17..722420fa386c 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -5,10 +5,17 @@ APPLY_SCANNER_WORKFLOW_NAME = "replay-vision-apply-scanner"
SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"
# Shared by the sweep's children and the on-demand /observe/ trigger; the orphan cutoff below leans on it.
-APPLY_SCANNER_EXECUTION_TIMEOUT = dt.timedelta(hours=1)
-
-# Pending/running rows older than twice the apply execution timeout are provably orphaned.
-OBSERVATION_ORPHAN_CUTOFF = APPLY_SCANNER_EXECUTION_TIMEOUT * 2
+# Must exceed the worst-case failure chain in `workflow.py`, where every phase spends its full schedule_to_close
+# budget before the terminal mark runs: create 3m + mark running 3m + fetch 5m + rasterize 40m + upload 20m +
+# provider 25m + terminal mark 3m + cleanup 1m = 100m. The 10m headroom covers task-queue scheduling latency
+# between phases. If this timeout wins instead of an activity, the workflow's except block never runs and the
+# row is stranded in `running` until the reaper's cutoff below.
+APPLY_SCANNER_EXECUTION_TIMEOUT = dt.timedelta(minutes=110)
+
+# A pending/running row is created inside its workflow, and the workflow cannot outlive its execution timeout
+# (which spans Temporal-level retries), so any such row older than the timeout plus a margin for clock skew
+# and late state writes is provably orphaned.
+OBSERVATION_ORPHAN_CUTOFF = APPLY_SCANNER_EXECUTION_TIMEOUT + dt.timedelta(minutes=30)
# Bounds one reaper pass; a backlog beyond this drains across subsequent reconciler ticks.
REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE = 500
REAP_ORPHANED_OBSERVATIONS_TIMEOUT = dt.timedelta(minutes=3)
diff --git a/products/replay_vision/backend/temporal/gemini.py b/products/replay_vision/backend/temporal/gemini.py
index 03200e65d060..38862d96ce6c 100644
--- a/products/replay_vision/backend/temporal/gemini.py
+++ b/products/replay_vision/backend/temporal/gemini.py
@@ -1,8 +1,59 @@
-"""Gemini API key resolution for Replay Vision."""
+"""Gemini API key resolution and error classification for Replay Vision."""
from django.conf import settings
+import httpx
+import aiohttp
+from google.genai.errors import APIError
+
+from products.replay_vision.backend.error_kinds import FailureKind
+
def gemini_api_key() -> str:
"""Replay Vision's dedicated key (own GCP project), falling back to the shared key where unset."""
return settings.REPLAY_VISION_GEMINI_API_KEY or settings.GEMINI_API_KEY
+
+
+# 408 request timeout and 409 conflict join the usual rate-limit/5xx set: all clear on their own.
+_TRANSIENT_STATUS_CODES = frozenset({408, 409, 429, 500, 502, 503, 504})
+
+# Connection-level failures raised before any HTTP response exists (DNS, TLS, resets, read timeouts). The
+# google-genai SDK uses aiohttp when installed and httpx otherwise, and lets both stacks' transport errors
+# propagate raw; an unreachable provider is the same user story as a 5xx. Anything outside these two
+# hierarchies stays unclassified on purpose, because it can come from our own code.
+_PROVIDER_TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (
+ httpx.TransportError,
+ aiohttp.ClientConnectionError,
+)
+
+
+def describe_gemini_error(error: BaseException) -> str:
+ """Fixed-shape summary for user-visible error reasons.
+
+ The raw error can quote parts of the request (prompt text, file references), so it must never reach
+ `error_reason`; callers log the full error and show the user only the shape of the failure.
+ """
+ if isinstance(error, APIError):
+ status = f" {error.status}" if error.status else ""
+ return f"The AI provider returned HTTP {error.code}{status}"
+ return f"PostHog could not reach the AI provider ({type(error).__name__})"
+
+
+def classify_gemini_error(error: BaseException) -> FailureKind | None:
+ """Map a `google-genai` provider error onto a failure kind, or None when it isn't one.
+
+ Without this every provider hiccup (a 429 during a quota window, a 503 mid-outage, a dropped connection)
+ reaches the workflow as an unrecognized exception and lands as `internal_error`, which tells the user to
+ contact support about an outage they can just retry. Errors we can't place stay None so they keep the
+ unclassified path rather than claiming to be transient and burning the retry budget.
+ """
+ if isinstance(error, _PROVIDER_TRANSPORT_ERRORS):
+ return FailureKind.PROVIDER_TRANSIENT
+ if not isinstance(error, APIError):
+ return None
+ if error.code in _TRANSIENT_STATUS_CODES:
+ return FailureKind.PROVIDER_TRANSIENT
+ # A 4xx we didn't list is the provider refusing this input (unsupported video, too large, safety block).
+ if isinstance(error.code, int) and 400 <= error.code < 500:
+ return FailureKind.PROVIDER_REJECTED
+ return None
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index d6d2862a7b07..308237b9604a 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -52,6 +52,12 @@ REPLAY_VISION_PROVIDER_CALL = Histogram(
buckets=_PROVIDER_CALL_BUCKETS,
)
+REPLAY_VISION_MISSION_PASSES = Counter(
+ "replay_vision_mission_passes_total",
+ "Full mission passes sent to the provider; rate against observations shows how hard the retry layers multiply",
+ ["model", "path"],
+)
+
REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS = Counter(
"replay_vision_quota_exhausted_skips_total",
"Observations skipped because the org's monthly credit quota was exhausted",
@@ -148,6 +154,12 @@ def record_provider_call(provider: str, model: str, scanner_type: str, outcome:
_otel.record_histogram_twin(REPLAY_VISION_PROVIDER_CALL, seconds, labels)
+def record_mission_pass(model: str, path: str) -> None:
+ labels = {"model": model, "path": path}
+ REPLAY_VISION_MISSION_PASSES.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_MISSION_PASSES, 1, labels)
+
+
def record_quota_exhausted_skip(scanner_type: str) -> None:
REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS.labels(scanner_type=scanner_type).inc()
_otel.record_counter_twin(REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS, 1, {"scanner_type": scanner_type})
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index f17321e9fb29..56ee6006d05f 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -41,6 +41,8 @@ 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
@@ -77,6 +79,10 @@ _STATE_ACTIVITY_RETRY = common.RetryPolicy(
maximum_attempts=5,
)
+# Bounds each state write's whole retry chain, backoff included, so the failure path provably fits inside
+# APPLY_SCANNER_EXECUTION_TIMEOUT (see the arithmetic on that constant).
+_STATE_ACTIVITY_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=3)
+
# Create's `ValueError` paths (scanner missing, user not in org) won't recover on retry.
_CREATE_OBSERVATION_RETRY = common.RetryPolicy(
initial_interval=dt.timedelta(seconds=1),
@@ -100,17 +106,24 @@ _ENSURE_ASSET_RETRY = common.RetryPolicy(
)
# Deterministic failures opt out via ScannerFailureError's non_retryable flag; only transient kinds re-run.
+# Attempts land at ~0s/15s/75s so the third clears a per-minute provider quota window.
_UPLOAD_RETRY = common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=2),
- maximum_interval=dt.timedelta(seconds=30),
+ initial_interval=dt.timedelta(seconds=15),
+ backoff_coefficient=4.0,
+ maximum_interval=dt.timedelta(seconds=60),
maximum_attempts=3,
)
# Workflow-level retries only cover transient transport failures; schema/semantic errors are non-retryable.
+# A provider rate limit or 5xx arrives classified (see `classify_gemini_error`), which is what makes these attempts
+# reachable at all. The spacing must outlast a per-minute quota window: attempts land at ~0s/15s/75s/135s, so the
+# last two run in later windows instead of burning out inside the one that rate-limited us. `schedule_to_close`
+# on the call site keeps four long attempts from eating the whole workflow budget.
_PROVIDER_CALL_RETRY = common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=2),
- maximum_interval=dt.timedelta(seconds=30),
- maximum_attempts=3,
+ initial_interval=dt.timedelta(seconds=15),
+ backoff_coefficient=4.0,
+ maximum_interval=dt.timedelta(seconds=60),
+ maximum_attempts=4,
)
# Cleanup is best-effort; the cleanup sweep handles persistent failures.
@@ -137,19 +150,34 @@ _PROVIDER_TIMEOUT_ACTIVITY_TYPES = frozenset(
{"replay_vision_upload_video_to_gemini_activity", "call_scanner_provider_activity"}
)
+# The rasterizer sends its own `RasterizationError.code` as the ApplicationError type. This one means the recording
+# holds no renderable snapshots. It stays retryable over there (blocks can still be landing), so by the time it
+# surfaces here the render attempts are spent and the emptiness is a property of the recording, not of one attempt.
+_RASTERIZER_NO_SNAPSHOTS_TYPE = "NO_SNAPSHOTS"
+
def _activity_timeout_kind(e: BaseException) -> str | None:
- """Map a start-to-close/heartbeat timeout of a provider-facing activity to `provider_transient`."""
- if not isinstance(e, ActivityError) or e.activity_type not in _PROVIDER_TIMEOUT_ACTIVITY_TYPES:
+ """Map an activity start-to-close/heartbeat timeout onto whichever side ran out of time."""
+ if not isinstance(e, ActivityError) or not isinstance(e.cause, TemporalTimeoutError):
return None
- return FailureKind.PROVIDER_TRANSIENT.value if isinstance(e.cause, TemporalTimeoutError) else None
+ if e.activity_type in _PROVIDER_TIMEOUT_ACTIVITY_TYPES:
+ return FailureKind.PROVIDER_TRANSIENT.value
+ # Every other activity here talks to our own dependencies (ClickHouse, Postgres, Redis, object storage). A
+ # timeout against those is capacity, so it recovers on a retry; `internal_error` would send the user to support.
+ return FailureKind.INFRA_TRANSIENT.value
+
+
+def _failure_type(e: BaseException) -> str | None:
+ """The `type` off an ApplicationError, surviving Temporal's ActivityError / ChildWorkflowError wrapping."""
+ cause = unwrap_temporal_cause(e) or e
+ return getattr(cause, "type", None)
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:
+ if _failure_type(e) != expected_type:
return None
+ cause = unwrap_temporal_cause(e) or e
details = getattr(cause, "details", None)
return details[0] if details else None
@@ -211,6 +239,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
workflow_id=workflow_id,
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_CREATE_OBSERVATION_RETRY,
)
if not create_result.was_created or create_result.observation_id is None:
@@ -226,6 +255,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
mark_observation_running_activity,
MarkObservationRunningInputs(observation_id=observation_id),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_STATE_ACTIVITY_RETRY,
)
self._advance_phase("fetching")
@@ -237,6 +267,8 @@ class ApplyScannerWorkflow(PostHogWorkflow):
upload_video_to_gemini_activity,
UploadVideoToGeminiInputs(asset_id=asset_result.asset_id),
start_to_close_timeout=dt.timedelta(minutes=10),
+ # Bounds the whole retry chain, so three slow attempts can't consume the phases behind this one.
+ schedule_to_close_timeout=dt.timedelta(minutes=20),
heartbeat_timeout=dt.timedelta(minutes=2),
retry_policy=_UPLOAD_RETRY,
)
@@ -249,8 +281,12 @@ class ApplyScannerWorkflow(PostHogWorkflow):
file_uri=uploaded.file_uri,
mime_type=uploaded.mime_type,
),
- # Multi-turn tool conversation (video + on-demand event lookups) needs more headroom than a single call.
- start_to_close_timeout=dt.timedelta(minutes=10),
+ # Multi-turn tool conversation (video + on-demand event lookups) needs more headroom than a single
+ # call, and must cover both mission passes: a second pass that overruns would surface as a Temporal
+ # timeout labeled provider_transient when the real problem is the scanner's prompt.
+ start_to_close_timeout=dt.timedelta(minutes=20),
+ # Bounds the whole retry chain, so slow attempts can't overrun the workflow's own timeout.
+ schedule_to_close_timeout=dt.timedelta(minutes=25),
heartbeat_timeout=dt.timedelta(minutes=2),
retry_policy=_PROVIDER_CALL_RETRY,
)
@@ -286,6 +322,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
scanner_result=ScannerResult(model_output=call_output.model_output, signals_count=signals_count),
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_STATE_ACTIVITY_RETRY,
)
try:
@@ -293,6 +330,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
emit_observation_event_activity,
EmitObservationEventInputs(observation_id=observation_id, model_output=call_output.model_output),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_STATE_ACTIVITY_RETRY,
)
except Exception:
@@ -334,12 +372,15 @@ class ApplyScannerWorkflow(PostHogWorkflow):
session_id=inputs.session_id,
),
start_to_close_timeout=dt.timedelta(minutes=2),
+ # Bounds the whole retry chain: six 2m attempts with backoff would otherwise stretch past 13m.
+ schedule_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=_FETCH_RETRY,
)
asset_task = wf.execute_activity(
ensure_session_asset_activity,
EnsureSessionAssetInputs(team_id=inputs.team_id, session_id=inputs.session_id),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_ENSURE_ASSET_RETRY,
)
_, asset_result = await asyncio.gather(fetch_task, asset_task)
@@ -354,7 +395,11 @@ class ApplyScannerWorkflow(PostHogWorkflow):
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),
+ # Temporal counts the whole retry chain against this, and the child's own render activity is allowed
+ # 30 minutes. Must exceed that 30m start-to-close, or a first render that fails fast leaves no room to
+ # schedule a retry at all. Held below a second full 30m render on purpose, to stay within the parent's
+ # phase budget.
+ execution_timeout=dt.timedelta(minutes=40),
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
@@ -363,6 +408,11 @@ class ApplyScannerWorkflow(PostHogWorkflow):
),
)
except Exception as e:
+ if _failure_type(e) == _RASTERIZER_NO_SNAPSHOTS_TYPE:
+ # Replay metadata exists but the snapshot blocks hold nothing to draw. That is the same class of
+ # "nothing to analyze" as a session with no events, which we already gate as ineligible, so calling
+ # it a failure would point the user at support over a recording that can never produce a video.
+ raise IneligibleSessionError(_root_cause_message(e), kind=IneligibleSessionKind.NO_SNAPSHOTS) from 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
@@ -375,6 +425,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
error_reason=_encode_reason(kind, message),
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_STATE_ACTIVITY_RETRY,
)
@@ -387,6 +438,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
error_reason=_encode_reason(kind, message),
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_STATE_ACTIVITY_RETRY,
)
@@ -417,6 +469,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
model_output=model_output,
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=dt.timedelta(minutes=2),
retry_policy=_SIDE_EFFECT_RETRY,
)
except Exception:
@@ -433,6 +486,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
classifier_output=model_output,
),
start_to_close_timeout=dt.timedelta(seconds=30),
+ schedule_to_close_timeout=dt.timedelta(minutes=2),
retry_policy=_SIDE_EFFECT_RETRY,
)
except Exception:
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 205df48a5ed2..95ac451a897a 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -35,6 +35,7 @@ from products.replay_vision.backend.models.vision_action import VisionAction
from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds
from products.replay_vision.backend.temporal.constants import (
+ APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
)
@@ -1688,7 +1689,7 @@ class TestObserveAction(_VisionAPITestCase):
args, kwargs = start_workflow.call_args
self.assertEqual(args[0], APPLY_SCANNER_WORKFLOW_NAME)
self.assertEqual(kwargs["id"], expected_workflow_id)
- self.assertEqual(kwargs["execution_timeout"], timedelta(hours=1))
+ self.assertEqual(kwargs["execution_timeout"], APPLY_SCANNER_EXECUTION_TIMEOUT)
inputs = args[1]
self.assertEqual(inputs.scanner_id, self.scanner.id)
self.assertEqual(inputs.session_id, "sess-42")
@@ -2068,7 +2069,47 @@ class TestRetryActions(_VisionAPITestCase):
self.assertEqual(inputs.triggered_by, ObservationTrigger.RETRY)
self.assertEqual(inputs.triggered_by_user_id, self.user.id)
- def test_retry_rejects_non_failed_statuses(
+ def test_retry_accepts_ineligible_observation(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # Ineligibility can be a timing artifact (snapshots that finished ingesting after the scan), and the
+ # UNIQUE(scanner, session_id) row would otherwise lock the session out of this scanner forever.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ observation = ReplayObservation.objects.create(
+ scanner=self.scanner,
+ session_id="sess-ineligible",
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ status=ObservationStatus.INELIGIBLE,
+ error_reason="no_snapshots:No snapshots after processing",
+ completed_at=timezone.now(),
+ )
+
+ resp = self.client.post(self.retry_url(str(observation.id)))
+ self.assertEqual(resp.status_code, 202, resp.json())
+ self.assertFalse(ReplayObservation.objects.filter(id=observation.id).exists())
+ args, _kwargs = start_workflow.call_args
+ self.assertEqual(args[1].triggered_by, ObservationTrigger.RETRY)
+
+ def test_retry_keeps_row_when_ai_consent_is_off(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The replacement workflow fails closed at create time when consent is off, so letting the retry
+ # delete the row first would leave the recording looking unscanned with no way to get a row back.
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ observation = self._create_failed("sess-no-consent")
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+
+ resp = self.client.post(self.retry_url(str(observation.id)))
+ self.assertEqual(resp.status_code, 400, resp.json())
+ self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())
+ start_workflow.assert_not_called()
+
+ def test_retry_rejects_non_terminal_statuses(
self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
) -> None:
# Plain loop, not @parameterized: class-level @patch mis-orders expanded args.
@@ -2076,8 +2117,8 @@ class TestRetryActions(_VisionAPITestCase):
mock_async_to_sync.return_value = start_workflow
cases = [
(ObservationStatus.SUCCEEDED, timezone.now()),
- (ObservationStatus.INELIGIBLE, timezone.now()),
(ObservationStatus.PENDING, None),
+ (ObservationStatus.RUNNING, None),
]
for status_value, completed_at in cases:
with self.subTest(status=status_value):
@@ -2087,7 +2128,7 @@ class TestRetryActions(_VisionAPITestCase):
scanner_snapshot=_snapshot_for(self.scanner),
triggered_by=ObservationTrigger.SCHEDULE,
status=status_value,
- error_reason="kind:msg" if status_value == ObservationStatus.INELIGIBLE else "",
+ error_reason="",
completed_at=completed_at,
)
diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.py
index 8a43e24fa6aa..33c845a15819 100644
--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py
+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py
@@ -2,14 +2,18 @@ from typing import Any, cast
import pytest
+import httpx
+from google.genai.errors import APIError
from pydantic import BaseModel
from products.replay_vision.backend.temporal.activities.call_scanner_provider import (
_maybe_create_video_cache,
+ _run_mission_attempts,
+ _run_pass,
_run_steps,
_step_config,
)
-from products.replay_vision.backend.temporal.errors import ScannerFailureError
+from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.scanners.base import MissionStep
_LABELS = {"provider": "gemini", "model": "gemini-3-flash-preview", "scanner_type": "monitor"}
@@ -195,8 +199,24 @@ async def test_failed_non_required_step_is_rolled_back_so_the_next_step_stays_cl
async def test_required_step_failure_raises_validation_error() -> None:
steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
client = _FakeClient([_Resp(text="bad"), _Resp(text="still bad")])
- with pytest.raises(ScannerFailureError, match="Required step 'core'"):
+ with pytest.raises(ScannerFailureError, match="Required step 'core'") as caught:
await _run(client, steps)
+ assert caught.value.kind is FailureKind.VALIDATION_FAILED
+
+
+async def test_required_step_with_no_candidates_blames_the_provider_not_the_prompt() -> None:
+ # Zero candidates is the provider declining to answer about this video, not a schema problem. Reporting it as
+ # a validation failure would tell the user to rewrite a prompt that was never involved.
+ class _Empty:
+ candidates: list[Any] = []
+ text = None
+
+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
+ client = _FakeClient([_Empty(), _Empty()]) # type: ignore[list-item]
+ with pytest.raises(ScannerFailureError) as caught:
+ await _run(client, steps)
+ assert caught.value.kind is FailureKind.PROVIDER_REJECTED
@pytest.mark.asyncio
@@ -210,6 +230,98 @@ async def test_semantic_validate_hook_triggers_a_re_prompt() -> None:
assert out["core"].verdict == "yes"
+class TestMissionAttempts:
+ """The per-step re-prompt argues with the model inside one conversation; this is the clean-slate re-ask around it."""
+
+ @staticmethod
+ def _failing_run(kind: FailureKind, fail_times: int) -> tuple[Any, list[str | None]]:
+ calls: list[str | None] = []
+
+ async def run(*, cache_name: str | None) -> dict[str, BaseModel]:
+ calls.append(cache_name)
+ if len(calls) <= fail_times:
+ raise ScannerFailureError("rejected", kind=kind)
+ return {"core": _Core(verdict="yes")}
+
+ return run, calls
+
+ @pytest.mark.asyncio
+ async def test_validation_failure_gets_one_clean_re_ask(self) -> None:
+ run, calls = self._failing_run(FailureKind.VALIDATION_FAILED, fail_times=1)
+ out = await _run_mission_attempts(run=run, cache=None, model="m")
+ assert cast(_Core, out["core"]).verdict == "yes"
+ assert len(calls) == 2
+
+ @pytest.mark.asyncio
+ async def test_re_asking_is_bounded(self) -> None:
+ run, calls = self._failing_run(FailureKind.VALIDATION_FAILED, fail_times=99)
+ with pytest.raises(ScannerFailureError):
+ await _run_mission_attempts(run=run, cache=None, model="m")
+ assert len(calls) == 2
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "kind",
+ [FailureKind.PROVIDER_REJECTED, FailureKind.PROVIDER_TRANSIENT, FailureKind.INTERNAL_ERROR],
+ )
+ async def test_other_kinds_are_not_re_asked(self, kind: FailureKind) -> None:
+ # Re-asking these would double the video spend for nothing: the provider isn't going to change its mind
+ # mid-activity, and Temporal already owns the retry for the transient ones.
+ run, calls = self._failing_run(kind, fail_times=1)
+ with pytest.raises(ScannerFailureError):
+ await _run_mission_attempts(run=run, cache=None, model="m")
+ assert len(calls) == 1
+
+
+class TestRunPass:
+ """Which retry layer owns a cached-run failure. Transients belong to the Temporal activity retry (it backs
+ off across the quota window); only cache-shaped failures get the one inline fallback. A blanket inline retry
+ here would multiply with the other layers into many video re-sends per observation."""
+
+ class _Cache:
+ name = "cache-1"
+
+ @staticmethod
+ def _cached_run_failing_with(error: Exception) -> tuple[Any, list[str | None]]:
+ calls: list[str | None] = []
+
+ async def run(*, cache_name: str | None) -> dict[str, BaseModel]:
+ calls.append(cache_name)
+ if cache_name is not None:
+ raise error
+ return {"core": _Core(verdict="yes")}
+
+ return run, calls
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "error",
+ [
+ APIError(429, {"error": {"message": "quota", "status": "RESOURCE_EXHAUSTED"}}),
+ httpx.ConnectError("connection reset by peer"),
+ ],
+ )
+ async def test_transient_provider_error_is_not_retried_inline(self, error: Exception) -> None:
+ run, calls = self._cached_run_failing_with(error)
+ with pytest.raises(type(error)):
+ await _run_pass(run=run, cache=self._Cache(), model="m")
+ assert calls == ["cache-1"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "error",
+ [
+ APIError(403, {"error": {"message": "CachedContent not found"}}),
+ ValueError("unrecognized SDK failure"),
+ ],
+ )
+ async def test_cache_shaped_failure_falls_back_inline_once(self, error: Exception) -> None:
+ run, calls = self._cached_run_failing_with(error)
+ out = await _run_pass(run=run, cache=self._Cache(), model="m")
+ assert cast(_Core, out["core"]).verdict == "yes"
+ assert calls == ["cache-1", None]
+
+
class TestStepConfig:
def test_inline_path_carries_tools_and_no_cache(self) -> None:
config = _step_config(MissionStep(name="core", instruction="c", response_model=_Core), cache_name=None)
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 07c9026067d2..e3406ffe09fd 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -10,6 +10,8 @@ from django.conf import settings
from django.db import IntegrityError
from django.utils import timezone
+import httpx
+import aiohttp
import psycopg.errors
from asgiref.sync import sync_to_async
from google.genai.errors import APIError
@@ -19,6 +21,7 @@ from structlog.testing import capture_logs
from temporalio.exceptions import (
ActivityError,
ApplicationError,
+ ChildWorkflowError,
TimeoutError as TemporalTimeoutError,
TimeoutType,
)
@@ -83,6 +86,7 @@ from products.replay_vision.backend.temporal.errors import (
IneligibleSessionKind,
ScannerFailureError,
)
+from products.replay_vision.backend.temporal.gemini import classify_gemini_error
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants import (
REDIS_INDEX_KEY as _GEMINI_REDIS_INDEX_KEY,
REDIS_KEY_PREFIX as _GEMINI_REDIS_KEY_PREFIX,
@@ -128,6 +132,7 @@ from products.replay_vision.backend.temporal.types import (
from products.replay_vision.backend.temporal.workflow import (
_activity_timeout_kind,
_extract_kind_for_type,
+ _failure_type,
_root_cause_message,
)
from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
@@ -1640,9 +1645,11 @@ class _WorkflowMocks:
*,
activity_results: dict[Any, Any] | None = None,
activity_errors: dict[Any, Exception] | None = None,
+ child_error: Exception | None = None,
) -> None:
self.activity_results = activity_results or {}
self.activity_errors = activity_errors or {}
+ self.child_error = child_error
self.activity_calls: list[tuple[Any, Any]] = []
self.child_calls: list[tuple[tuple, dict]] = []
@@ -1654,6 +1661,8 @@ class _WorkflowMocks:
async def execute_child_workflow(self, *args: Any, **kwargs: Any) -> Any:
self.child_calls.append((args, kwargs))
+ if self.child_error is not None:
+ raise self.child_error
return None
@@ -1743,6 +1752,53 @@ async def test_apply_scanner_workflow_marks_failed_when_fetch_raises() -> None:
assert "no events" in failed_input.error_reason.lower()
+ "rasterizer_type,expect_ineligible,expected_kind",
+ [
+ # An unrenderable recording is a gate, so it must not land on the failed path telling the user to retry.
+ ("NO_SNAPSHOTS", True, "no_snapshots"),
+ ("CAPTURE_ABORTED", False, "rasterization_failed"),
+ (None, False, "rasterization_failed"),
+ ],
+)
+async def test_apply_scanner_workflow_splits_rasterizer_failures_by_cause(
+ rasterizer_type: str | None, expect_ineligible: bool, expected_kind: str
+) -> None:
+ new_observation_id = uuid.uuid4()
+ leaf = (
+ # `non_retryable=False` is the real arrival shape: the rasterizer keeps NO_SNAPSHOTS retryable while blocks may
+ # still be landing, so it only reaches us once the attempts are spent. Classification keys off the type alone.
+ ApplicationError("No snapshots after processing", type=rasterizer_type, non_retryable=False)
+ if rasterizer_type
+ else RuntimeError("browser pod vanished")
+ )
+ mocks = _WorkflowMocks(
+ activity_results={
+ create_observation_activity: CreateObservationOutput(
+ observation_id=new_observation_id, was_created=True, scanner_type=ScannerType.MONITOR
+ ),
+ ensure_session_asset_activity: EnsureSessionAssetOutput(asset_id=42),
+ },
+ # Mirrors how the rasterizer's own error reaches the parent: wrapped twice by Temporal.
+ child_error=_wrap_in_child_workflow_error(_wrap_in_activity_error(leaf))
+ if isinstance(leaf, ApplicationError)
+ else leaf,
+ )
+
+ with pytest.raises(Exception):
+ await _run_workflow(_build_inputs(session_id="sess-raster"), mocks)
+
+ called = {fn for fn, _ in mocks.activity_calls}
+ terminal = mark_observation_ineligible_activity if expect_ineligible else mark_observation_failed_activity
+ other = mark_observation_failed_activity if expect_ineligible else mark_observation_ineligible_activity
+ assert terminal in called
+ assert other not in called
+ assert mocks.activity_calls[-1][1].error_reason.startswith(f"{expected_kind}:")
+ # The video is never uploaded when the render fails, so there is nothing to bill or clean up.
+ assert upload_video_to_gemini_activity not in called
+
+
@pytest.mark.asyncio
async def test_apply_scanner_workflow_cleans_up_gemini_file_when_call_provider_fails() -> None:
new_observation_id = uuid.uuid4()
@@ -2257,6 +2313,107 @@ def _wrap_in_activity_error(cause: ApplicationError) -> ActivityError:
return activity_err
+def _wrap_in_child_workflow_error(cause: BaseException) -> ChildWorkflowError:
+ """Same idea one level up: what a failing child workflow raises into the parent's `except` block."""
+ child_err = ChildWorkflowError.__new__(ChildWorkflowError)
+ child_err.__cause__ = cause
+ return child_err
+
+
+class TestClassifyGeminiError:
+ """An unclassified provider error lands as `internal_error`, which sends the user to support over an outage they
+ could just retry. These cases pin the mapping that keeps it out of that bucket."""
+
+ @parameterized.expand(
+ [
+ ("rate_limited", 429, FailureKind.PROVIDER_TRANSIENT),
+ ("server_error", 500, FailureKind.PROVIDER_TRANSIENT),
+ ("bad_gateway", 502, FailureKind.PROVIDER_TRANSIENT),
+ ("unavailable", 503, FailureKind.PROVIDER_TRANSIENT),
+ ("gateway_timeout", 504, FailureKind.PROVIDER_TRANSIENT),
+ ("request_timeout", 408, FailureKind.PROVIDER_TRANSIENT),
+ ("bad_request", 400, FailureKind.PROVIDER_REJECTED),
+ ("permission_denied", 403, FailureKind.PROVIDER_REJECTED),
+ ("payload_too_large", 413, FailureKind.PROVIDER_REJECTED),
+ ]
+ )
+ def test_maps_api_error_status_codes(self, _label: str, code: int, expected: FailureKind) -> None:
+ assert classify_gemini_error(APIError(code, {"error": {"message": "boom"}})) is expected
+
+ @parameterized.expand(
+ [
+ ("httpx_connect", httpx.ConnectError("connection reset by peer")),
+ ("httpx_read_timeout", httpx.ReadTimeout("timed out")),
+ ("aiohttp_disconnected", aiohttp.ServerDisconnectedError()),
+ ]
+ )
+ def test_maps_transport_errors_to_provider_transient(self, _label: str, error: Exception) -> None:
+ # These carry no HTTP response, so the status-code mapping can't see them; an unreachable provider is
+ # the same user story as a 5xx and must not land as internal_error.
+ assert classify_gemini_error(error) is FailureKind.PROVIDER_TRANSIENT
+
+ def test_leaves_non_provider_exceptions_unclassified(self) -> None:
+ # Claiming a kind here would be worse than the status quo: a PostHog bug would be blamed on the provider,
+ # and for the transient kinds it would burn the retry budget before failing anyway.
+ assert classify_gemini_error(ValueError("bad arg")) is None
+
+
+class TestGeminiErrorRedaction:
+ """`error_reason` is shown to the user verbatim, and a Gemini error body can quote request content
+ (prompt text, file references). The provider-facing activities must surface only the fixed summary."""
+
+ _BODY = {
+ "error": {"message": "invalid prompt: 'the user's confidential prompt text'", "status": "INVALID_ARGUMENT"}
+ }
+
+ @pytest.mark.asyncio
+ async def test_provider_activity_redacts_the_error_body(self) -> None:
+ with patch(
+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._call_scanner_provider",
+ side_effect=APIError(400, self._BODY),
+ ):
+ with pytest.raises(ScannerFailureError) as exc_info:
+ await ActivityEnvironment().run(
+ call_scanner_provider_activity,
+ CallScannerProviderInputs(
+ team_id=1, observation_id=uuid.uuid4(), file_uri="gemini://files/x", mime_type="video/mp4"
+ ),
+ )
+ assert exc_info.value.kind is FailureKind.PROVIDER_REJECTED
+ assert exc_info.value.message == "The AI provider returned HTTP 400 INVALID_ARGUMENT"
+
+ @pytest.mark.asyncio
+ async def test_upload_activity_redacts_the_error_body(self) -> None:
+ with patch(
+ "products.replay_vision.backend.temporal.activities.upload_video_to_gemini._upload_video",
+ side_effect=APIError(
+ 429, {"error": {"message": "quota for 'wf-secret-name'", "status": "RESOURCE_EXHAUSTED"}}
+ ),
+ ):
+ with pytest.raises(ScannerFailureError) as exc_info:
+ await ActivityEnvironment().run(upload_video_to_gemini_activity, UploadVideoToGeminiInputs(asset_id=1))
+ assert exc_info.value.kind is FailureKind.PROVIDER_TRANSIENT
+ assert exc_info.value.message == "The AI provider returned HTTP 429 RESOURCE_EXHAUSTED"
+
+ @pytest.mark.asyncio
+ async def test_provider_activity_classifies_transport_errors_as_transient(self) -> None:
+ # A dropped connection has no HTTP response, so it would otherwise escape unclassified and land as
+ # internal_error with contact-support copy for what is a retryable provider outage.
+ with patch(
+ "products.replay_vision.backend.temporal.activities.call_scanner_provider._call_scanner_provider",
+ side_effect=httpx.ConnectError("connection reset by peer"),
+ ):
+ with pytest.raises(ScannerFailureError) as exc_info:
+ await ActivityEnvironment().run(
+ call_scanner_provider_activity,
+ CallScannerProviderInputs(
+ team_id=1, observation_id=uuid.uuid4(), file_uri="gemini://files/x", mime_type="video/mp4"
+ ),
+ )
+ assert exc_info.value.kind is FailureKind.PROVIDER_TRANSIENT
+ assert exc_info.value.message == "PostHog could not reach the AI provider (ConnectError)"
+
+
class TestWorkflowErrorHelpers:
"""Unit tests for the workflow's exception-classification helpers."""
@@ -2294,15 +2451,22 @@ class TestWorkflowErrorHelpers:
def test_root_cause_message_falls_back_to_str_for_bare_exceptions(self) -> None:
assert _root_cause_message(ValueError("bad arg")) == "bad arg"
+ def test_failure_type_survives_a_child_workflow_wrap(self) -> None:
+ # The rasterizer's code reaches the parent through ChildWorkflowError -> ActivityError -> ApplicationError.
+ # Losing it to that wrapping is what makes an unrenderable recording look like a generic render failure.
+ leaf = ApplicationError("No snapshots after processing", type="NO_SNAPSHOTS", non_retryable=True)
+ wrapped = _wrap_in_child_workflow_error(_wrap_in_activity_error(leaf))
+ assert _failure_type(wrapped) == "NO_SNAPSHOTS"
+
@parameterized.expand(
[
("provider_call_timeout", "call_scanner_provider_activity", True, "provider_transient"),
("upload_timeout", "replay_vision_upload_video_to_gemini_activity", True, "provider_transient"),
- ("other_activity_timeout", "replay_vision_fetch_session_events_activity", True, None),
+ ("other_activity_timeout", "replay_vision_fetch_session_events_activity", True, "infra_transient"),
("provider_call_non_timeout", "call_scanner_provider_activity", False, None),
]
)
- def test_activity_timeout_kind_maps_provider_activity_timeouts(
+ def test_activity_timeout_kind_separates_provider_from_our_own_infra(
self, _label: str, activity_type: str, timed_out: bool, expected: str | None
) -> None:
err = ActivityError(
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index ab635dab2ce3..667b12d93ec3 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -1,6 +1,6 @@
import { useValues } from 'kea'
-import { IconCopy, IconRefresh, IconRewindPlay, IconSparkles } from '@posthog/icons'
+import { IconCopy, IconRewindPlay, IconSparkles } from '@posthog/icons'
import { LemonButton, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
@@ -19,9 +19,9 @@ import {
parseIneligibleReason,
scannerTypeLabel,
} from '../replay_scanners/types'
-import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { citedTextToPlainText, parseCitedSegments } from '../utils/citations'
import { ObservationProgressBar } from './ObservationProgressBar'
+import { ObservationRetryButton } from './ObservationRetryButton'
export function ObservationStatusTag({
status,
@@ -432,23 +432,32 @@ export function ObservationDockCard({
<div className="space-y-2">
<FailureDetail errorReason={observation.error_reason} />
{onRetry && (
- <LemonButton
- size="xsmall"
- type="secondary"
- icon={<IconRefresh />}
- onClick={onRetry}
+ <ObservationRetryButton
+ status={observation.status}
+ errorReason={observation.error_reason}
+ onRetry={onRetry}
loading={retrying}
- disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}
- data-attr="vision-dock-retry-observation"
- >
- Retry scan
- </LemonButton>
+ userAccessLevel={scanner?.user_access_level}
+ dataAttr="vision-dock-retry-observation"
+ />
)}
</div>
)}
{observation.status === 'ineligible' && observation.error_reason && (
- <IneligibleDetail errorReason={observation.error_reason} />
+ <div className="space-y-2">
+ <IneligibleDetail errorReason={observation.error_reason} />
+ {onRetry && (
+ <ObservationRetryButton
+ status={observation.status}
+ errorReason={observation.error_reason}
+ onRetry={onRetry}
+ loading={retrying}
+ userAccessLevel={scanner?.user_access_level}
+ dataAttr="vision-dock-retry-observation"
+ />
+ )}
+ </div>
)}
{observation.status === 'succeeded' && snapshot && result && (
diff --git a/products/replay_vision/frontend/components/ObservationRetryButton.tsx b/products/replay_vision/frontend/components/ObservationRetryButton.tsx
new file mode 100644
index 000000000000..c7df2950e6e4
--- /dev/null
+++ b/products/replay_vision/frontend/components/ObservationRetryButton.tsx
@@ -0,0 +1,57 @@
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AccessControlLevel } from '~/types'
+
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { observationRetryOffer } from '../replay_scanners/types'
+import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
+
+/**
+ * Retry control for a terminal observation, shared by the dock card, the observations table, and the detail scene.
+ *
+ * Renders nothing when a retry isn't offered for the observation's status and kind (see `observationRetryOffer`).
+ * Where it is offered, what varies per kind is how hard we push it: kinds that recover on their own keep the
+ * caller's emphasis, and the rest drop to secondary and use the tooltip to say why a plain retry probably isn't
+ * the next step.
+ */
+export function ObservationRetryButton({
+ status,
+ errorReason,
+ onRetry,
+ loading = false,
+ userAccessLevel,
+ emphasis = 'secondary',
+ size = 'xsmall',
+ iconOnly = false,
+ dataAttr,
+}: {
+ status: ReplayObservationApi['status']
+ errorReason: string
+ onRetry: () => void
+ loading?: boolean
+ userAccessLevel?: AccessControlLevel | null
+ emphasis?: 'primary' | 'secondary'
+ size?: 'xsmall' | 'small'
+ iconOnly?: boolean
+ dataAttr: string
+}): JSX.Element | null {
+ const { show, worthwhile, hint } = observationRetryOffer(status, errorReason)
+ if (!show) {
+ return null
+ }
+ return (
+ <LemonButton
+ size={size}
+ type={worthwhile ? emphasis : 'secondary'}
+ icon={<IconRefresh />}
+ onClick={onRetry}
+ loading={loading}
+ disabledReason={getReplayVisionEditDisabledReason(userAccessLevel)}
+ tooltip={hint ?? 'Retry scan'}
+ data-attr={dataAttr}
+ >
+ {iconOnly ? undefined : 'Retry scan'}
+ </LemonButton>
+ )
+}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 162603a0ffaa..e0ef2e6eb928 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -615,7 +615,7 @@ export interface ReplayObservationApi {
* * `failed` - Failed
* * `ineligible` - Ineligible */
readonly status: ObservationStatusEnumApi
- /** 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 / orphaned. */
+ /** 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 / no_snapshots. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */
readonly error_reason: string
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string
@@ -623,7 +623,7 @@ export interface ReplayObservationApi {
readonly scanner_snapshot: ScannerSnapshotApi | null
/** Result data persisted on success; null until the observation succeeds. */
readonly scanner_result: ScannerResultApi | null
- /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed observation.
+ /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.
*
* * `schedule` - Schedule
* * `on_demand` - On demand
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index f33c48023b25..05911ea22eba 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -379,7 +379,7 @@ export const getVisionObservationsRetryCreateUrl = (projectId: string, id: strin
}
/**
- * Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.
+ * Delete a failed or ineligible observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.
*/
export const visionObservationsRetryCreate = async (
projectId: string,
@@ -757,7 +757,7 @@ export const getVisionScannersObservationsRetryCreateUrl = (projectId: string, s
}
/**
- * Delete a failed observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.
+ * Delete a failed or ineligible observation and re-run its scanner on the same recording. Returns 202 with the workflow handle.
*/
export const visionScannersObservationsRetryCreate = async (
projectId: string,
diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsx
index 1ebbd56f6cc2..a02da61f277f 100644
--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx
+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx
@@ -10,7 +10,6 @@ import {
IconExpand,
IconGear,
IconInfo,
- IconRefresh,
IconSparkles,
IconThoughtBubble,
IconVideoCamera,
@@ -49,6 +48,7 @@ import {
readResult,
} from '../components/ObservationCard'
import { ObservationProgressBar } from '../components/ObservationProgressBar'
+import { ObservationRetryButton } from '../components/ObservationRetryButton'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
import { replayScannerLogic } from '../replay_scanners/replayScannerLogic'
@@ -66,7 +66,6 @@ import {
OBSERVATION_TRIGGER_TAG,
type ScannerType,
} from '../replay_scanners/types'
-import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { ObservationLabelControl } from './ObservationLabelControl'
import { neighborFilterParams, observationDetailUrl, replayObservationLogic } from './replayObservationLogic'
import { replayObservationSceneLogic } from './replayObservationSceneLogic'
@@ -353,17 +352,16 @@ export function ReplayObservationSceneComponent(): JSX.Element {
</LabeledRow>
)}
<div>
- <LemonButton
- type="primary"
- size="small"
- icon={<IconRefresh />}
- onClick={() => retryObservation()}
+ <ObservationRetryButton
+ status={observation.status}
+ errorReason={observation.error_reason}
+ onRetry={() => retryObservation()}
loading={retrying}
- disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}
- data-attr="vision-observation-detail-retry"
- >
- Retry scan
- </LemonButton>
+ userAccessLevel={scanner?.user_access_level}
+ emphasis="primary"
+ size="small"
+ dataAttr="vision-observation-detail-retry"
+ />
</div>
</div>
)}
@@ -387,6 +385,17 @@ export function ReplayObservationSceneComponent(): JSX.Element {
<p className="text-sm text-default m-0 leading-snug">{ineligibleMessage}</p>
</LabeledRow>
)}
+ <div>
+ <ObservationRetryButton
+ status={observation.status}
+ errorReason={observation.error_reason}
+ onRetry={() => retryObservation()}
+ loading={retrying}
+ userAccessLevel={scanner?.user_access_level}
+ size="small"
+ dataAttr="vision-observation-detail-retry"
+ />
+ </div>
</div>
)}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
index e2403a96eb29..1fb7540d28e9 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
@@ -13,9 +13,9 @@ import { DateMappingOption } from '~/types'
import { FilterPill } from '../../components/FilterPill'
import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'
+import { ObservationRetryButton } from '../../components/ObservationRetryButton'
import type { ReplayObservationApi } from '../../generated/api.schemas'
import { observationDetailUrl } from '../../observations/replayObservationLogic'
-import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import {
OBSERVATIONS_PAGE_SIZE,
ObservationStatusValue,
@@ -153,18 +153,15 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
render: (_, obs) => (
<div className="flex items-center gap-1">
<ObservationStatusTag status={obs.status} errorReason={obs.error_reason} />
- {obs.status === 'failed' && (
- <LemonButton
- size="xsmall"
- type="secondary"
- icon={<IconRefresh />}
- onClick={() => retryObservation(obs.id)}
- loading={retryingObservationIds.includes(obs.id)}
- disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}
- tooltip="Retry scan"
- data-attr="vision-observation-retry"
- />
- )}
+ <ObservationRetryButton
+ status={obs.status}
+ errorReason={obs.error_reason}
+ onRetry={() => retryObservation(obs.id)}
+ loading={retryingObservationIds.includes(obs.id)}
+ userAccessLevel={scanner?.user_access_level}
+ iconOnly
+ dataAttr="vision-observation-retry"
+ />
</div>
),
},
diff --git a/products/replay_vision/frontend/replay_scanners/types.test.ts b/products/replay_vision/frontend/replay_scanners/types.test.ts
new file mode 100644
index 000000000000..6425801b2a1e
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/types.test.ts
@@ -0,0 +1,63 @@
+import { type FailureKind, failureRetryGuidance, observationRetryOffer } from './types'
+
+describe('retry guidance', () => {
+ describe('failureRetryGuidance', () => {
+ // The retry button is always rendered; this is what decides whether we push it. Getting a kind into the wrong
+ // bucket either discourages the retry that fixes it, or promises one that can only fail the same way.
+ const cases: [FailureKind, boolean, boolean][] = [
+ // kind, worthwhile, carries a hint
+ ['provider_transient', true, false],
+ ['infra_transient', true, false],
+ ['rasterization_failed', true, false],
+ ['orphaned', true, false],
+ ['internal_error', true, false],
+ ['provider_rejected', false, true],
+ ['validation_failed', false, true],
+ ]
+
+ it.each(cases)('classifies %s', (kind, worthwhile, hasHint) => {
+ const guidance = failureRetryGuidance(kind)
+ expect(guidance.worthwhile).toBe(worthwhile)
+ expect(guidance.hint !== null).toBe(hasHint)
+ })
+
+ it('offers the retry for a kind it cannot parse', () => {
+ // A reason the backend added and this build doesn't know yet parses to null. Withholding the retry on no
+ // evidence would strand the user, so the unknown case has to stay encouraging.
+ expect(failureRetryGuidance(null)).toEqual({ worthwhile: true, hint: null })
+ })
+ })
+
+ describe('observationRetryOffer', () => {
+ it.each<[string, Parameters<typeof observationRetryOffer>[0], string, boolean, boolean]>([
+ // label, status, error_reason, show, worthwhile
+ ['any failed observation', 'failed', 'internal_error:boom', true, true],
+ ['a failed observation with an unknown kind', 'failed', 'future_kind:msg', true, true],
+ ['a discouraged failure kind, softly', 'failed', 'provider_rejected:declined', true, false],
+ // no_snapshots can be a timing artifact (snapshots that finished ingesting after the scan), and the
+ // backend retry endpoint accepts ineligible rows; withholding the button would strand the session.
+ [
+ 'an ineligible observation with no snapshots',
+ 'ineligible',
+ 'no_snapshots:nothing to render',
+ true,
+ false,
+ ],
+ // no_ai_consent offers a retry too: consent can be turned on after the scan, and without the
+ // button the unique (scanner, session) row would lock the session out permanently.
+ ['an ineligible observation without AI consent', 'ineligible', 'no_ai_consent:consent off', true, false],
+ ['a deterministic ineligibility gate', 'ineligible', 'too_short:12s long', false, false],
+ ['an unknown ineligible kind', 'ineligible', 'future_gate:msg', false, false],
+ ['a succeeded observation', 'succeeded', '', false, false],
+ ['a running observation', 'running', '', false, false],
+ ])('handles %s', (_label, status, errorReason, show, worthwhile) => {
+ const offer = observationRetryOffer(status, errorReason)
+ expect(offer.show).toBe(show)
+ expect(offer.worthwhile).toBe(worthwhile)
+ })
+
+ it('carries a hint for the ineligible kinds it offers, so the button can say why retrying might work', () => {
+ expect(observationRetryOffer('ineligible', 'no_snapshots:nothing to render').hint).not.toBeNull()
+ })
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index c4af91721d06..1ef462c5bee1 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -46,17 +46,43 @@ export const OBSERVATION_LIST_FILTER_KEYS: readonly (keyof VisionObservationsRet
export type EnabledFilter = 'enabled' | 'disabled'
-export type IneligibleKind = 'no_recording' | 'too_short' | 'too_inactive' | 'too_long' | 'no_events' | 'no_ai_consent'
+export type IneligibleKind =
+ | 'no_recording'
+ | 'no_snapshots'
+ | 'too_short'
+ | 'too_inactive'
+ | 'too_long'
+ | 'no_events'
+ | 'no_ai_consent'
+
+type IneligibleKindInfo = {
+ label: string
+ description: string
+ /** Set where the gate can be a timing artifact rather than a property of the session, so a retry is offered. */
+ retryable?: boolean
+ /** Why a retry might change the outcome. Shown on the retry control. */
+ retryHint?: string
+}
-const INELIGIBLE_KINDS: Record<IneligibleKind, { label: string; description: string }> = {
+const INELIGIBLE_KINDS: Record<IneligibleKind, IneligibleKindInfo> = {
no_recording: { label: 'No recording', description: 'No recording was found for this session.' },
+ no_snapshots: {
+ label: 'Nothing to play back',
+ description:
+ 'This recording has no screen data to play back, so there was no video for the AI to watch. If you expect this recording to have visuals, its screen data may still be ingesting. Retry the scan later.',
+ retryable: true,
+ retryHint: 'Screen data can finish ingesting after a scan. Retry if you expect this recording to play back.',
+ },
too_short: { label: 'Too short', description: 'The session was too short to analyze.' },
too_inactive: { label: 'Too inactive', description: 'The session had too little active interaction to analyze.' },
too_long: { label: 'Too long', description: 'The session was too long to analyze.' },
no_events: { label: 'No events', description: 'The session had no events to analyze.' },
no_ai_consent: {
label: 'AI analysis not allowed',
- description: 'AI data processing is turned off for this organization, so this recording was not analyzed.',
+ description:
+ 'AI data processing is turned off for this organization, so this recording was not analyzed. An organization admin can turn it on in organization settings.',
+ retryable: true,
+ retryHint: 'If AI data processing has been turned on since, retry the scan.',
},
}
@@ -65,37 +91,59 @@ export type FailureKind =
| 'provider_rejected'
| 'rasterization_failed'
| 'validation_failed'
+ | 'infra_transient'
| 'internal_error'
| 'orphaned'
-const FAILURE_KINDS: Record<FailureKind, { label: string; description: string }> = {
+type FailureKindInfo = {
+ label: string
+ description: string
+ /** Whether one more attempt at the same recording can plausibly land differently. Drives how retry is offered. */
+ retryWorthwhile: boolean
+ /** Why a plain retry probably isn't the next step. Shown on the retry control when set. */
+ retryHint?: string
+}
+
+const FAILURE_KINDS: Record<FailureKind, FailureKindInfo> = {
provider_transient: {
label: 'AI provider unavailable',
- description:
- "The AI provider was temporarily unreachable. PostHog will retry on the scanner's next scheduled run.",
+ description: 'The AI provider stayed unreachable across every automatic retry. Retry the scan.',
+ retryWorthwhile: true,
},
provider_rejected: {
- label: 'AI provider rejected video',
- description: "The AI provider couldn't process this recording. Try a different one.",
+ label: 'AI provider rejected the video',
+ description:
+ "The AI provider wouldn't analyze this recording's video. Retrying reaches the same answer, so run the scanner on a different recording.",
+ retryWorthwhile: false,
+ retryHint: 'The provider already declined this video, so a retry will most likely fail the same way.',
},
rasterization_failed: {
label: 'Recording video failed',
description:
- "PostHog couldn't render this recording into a video for the AI. Try again, or run the scanner on a different recording.",
+ 'PostHog could not turn this recording into a video for the AI. Retry the scan, and contact support if it fails again.',
+ retryWorthwhile: true,
},
validation_failed: {
- label: 'AI output invalid',
+ label: 'AI output did not fit the scanner',
description:
- 'The AI returned malformed output after several attempts. Try simplifying or rephrasing the scanner prompt.',
+ "The AI could not answer in this scanner's format, across two separate attempts. Simplify or rephrase the scanner prompt, then retry.",
+ retryWorthwhile: false,
+ retryHint: "A retry runs the scanner's current prompt. Edit the prompt first if you haven't changed it yet.",
+ },
+ infra_transient: {
+ label: 'PostHog timed out',
+ description: 'A PostHog service took too long while preparing this recording. Retry the scan in a few minutes.',
+ retryWorthwhile: true,
},
internal_error: {
label: 'Internal error',
- description: 'An unexpected PostHog error occurred. Please contact support.',
+ description: 'Something inside PostHog stopped this scan. Retry it, and contact support if it fails again.',
+ retryWorthwhile: true,
},
orphaned: {
label: 'Interrupted',
- description:
- 'The analysis was interrupted before finishing and has been cleaned up. Run the scanner on this recording again if needed.',
+ description: 'The scan was interrupted before it finished, and PostHog cleaned it up. Retry the scan.',
+ retryWorthwhile: true,
},
}
@@ -133,6 +181,41 @@ export function failureKindDescription(kind: FailureKind): string {
return FAILURE_KINDS[kind].description
}
+/**
+ * How to offer a retry for a given failure. An unparseable or unknown kind gets the encouraging default, since
+ * the alternative is discouraging a retry we have no evidence against.
+ */
+export function failureRetryGuidance(kind: FailureKind | null): { worthwhile: boolean; hint: string | null } {
+ const info = kind ? FAILURE_KINDS[kind] : null
+ return { worthwhile: info?.retryWorthwhile ?? true, hint: info?.retryHint ?? null }
+}
+
+export type ObservationRetryOffer = { show: boolean; worthwhile: boolean; hint: string | null }
+
+/**
+ * Whether and how to offer a retry for an observation. Failed observations always offer it, because the user can
+ * know things we don't (that they just rewrote the scanner prompt, say). The retry endpoint accepts any failed or
+ * ineligible observation; the UI additionally narrows ineligible offers to kinds whose outcome can change (late
+ * snapshots, consent turned on), so deterministic gates like too_short don't grow a pointless button.
+ */
+export function observationRetryOffer(
+ status: ReplayObservationApi['status'],
+ errorReason: string | null | undefined
+): ObservationRetryOffer {
+ if (status === 'failed') {
+ const kind = errorReason ? (parseFailureReason(errorReason)?.kind ?? null) : null
+ return { show: true, ...failureRetryGuidance(kind) }
+ }
+ if (status === 'ineligible' && errorReason) {
+ const parsed = parseIneligibleReason(errorReason)
+ const info = parsed ? INELIGIBLE_KINDS[parsed.kind] : null
+ if (info?.retryable) {
+ return { show: true, worthwhile: false, hint: info.retryHint ?? null }
+ }
+ }
+ return { show: false, worthwhile: false, hint: null }
+}
+
export function ineligibleKindDescription(kind: IneligibleKind): string {
return INELIGIBLE_KINDS[kind].description
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c4f3f06b8b4b..00ba16d5c834 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45035,7 +45035,7 @@ export namespace Schemas {
* * `failed` - Failed
* * `ineligible` - Ineligible */
readonly status: ObservationStatusEnum;
- /** 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 / orphaned. */
+ /** 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 / no_snapshots. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */
readonly error_reason: string;
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string;
@@ -45043,7 +45043,7 @@ export namespace Schemas {
readonly scanner_snapshot: ScannerSnapshot | null;
/** Result data persisted on success; null until the observation succeeds. */
readonly scanner_result: ScannerResult | null;
- /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed observation.
+ /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.
*
* * `schedule` - Schedule
* * `on_demand` - On demand