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): backend review hardening and cleanups (#67744)

Tue Haulund588437d4bfa9
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.md
index 179bc36a523e..71f4f0cde119 100644
--- a/products/replay_vision/README.md
+++ b/products/replay_vision/README.md
@@ -4,14 +4,22 @@ A sub-product of Session Replay. Users configure named **scanners** that PostHog
## Concepts
-**Scanner** — a configured probe scoped to a team. Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, and a sampling rate. Each enabled scanner has a Temporal schedule that fires every 5 minutes. Summarizers always emit per-facet embeddings for downstream free-text search.
+**Scanner** — a configured probe scoped to a team. Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, and a sampling rate. Each enabled scanner has a Temporal schedule that fires every 5 minutes and sweeps for newly settled recordings past the scanner's watermark (`last_swept_at`); disabling a scanner removes its schedule, and re-enabling restarts the sweep from now rather than backfilling the gap. Summarizers always emit per-facet embeddings for downstream free-text search.
-**Observation** — one application of a scanner to a session. Created in `pending` when triggered (by the scanner's schedule or the `/observe/` action), transitions to `running` while `ApplyScannerWorkflow` executes, and lands in `succeeded` (with content emitted as a `$recording_observed` event) or `failed`. Each observation snapshots the full scanner state (`scanner_snapshot`) that produced it, so subsequent edits to the scanner don't retro-mutate history.
+**Observation** — one application of a scanner to a session, unique per (scanner, session). Created in `pending` when triggered (by the scanner's schedule or the `/observe/` action), transitions to `running` while `ApplyScannerWorkflow` executes (rasterize the recording to video → upload to Gemini → multi-turn scan), and lands in `succeeded` (result persisted, then a `$recording_observed` event plus embeddings/tags emitted fail-soft), `failed` (with a `kind:message` `error_reason`), or `ineligible` (the session doesn't qualify — too short, too idle, no recording). Each observation snapshots the full scanner state (`scanner_snapshot`) that produced it, so subsequent edits to the scanner don't retro-mutate history. Rows stranded in `pending`/`running` by a dead workflow are failed as `orphaned` by a reaper on the reconciler tick.
+
+**Quota** — succeeded observations write an immutable usage receipt; usage (receipts + in-flight rows) is counted against a monthly per-organization quota, with per-scanner volume estimates summed into a projected-usage prognosis shown at configuration time.
## Layout
-- `backend/models/` — `ReplayScanner`, `ReplayObservation`, and their enums.
-- `backend/api/` — DRF viewsets, serializers, URL routing.
+- `backend/models/` — `ReplayScanner`, `ReplayObservation`, usage receipts, quota grants.
+- `backend/api/` — DRF viewsets and serializers (scanners, observations, stats, live progress over SSE).
+- `backend/queries/` — ClickHouse candidate selection (watermark + settle window + eligibility + sampling) and volume estimates.
+- `backend/temporal/` — the apply workflow and its activities, per-scanner sweep, schedule reconciler (+ observation reaper), estimate refresher, and the Gemini file cleanup sweep.
+- `backend/quota.py` — monthly quota accounting.
+- `backend/embeddings.py` — the embedding identity shared by the write and search sides.
+- `backend/max_tools.py` — Max AI tools (draft a scanner prompt, digest summaries, semantic search over observations).
- `backend/feature_flag.py` — `replay-vision` flag check + permission.
-- `backend/admin.py` — Django admin registrations for both models.
+- `backend/admin.py` — Django admin registrations.
+- `backend/temporal/vision_actions/` + `backend/api/vision_actions.py` — scheduled follow-up actions over observations (under active development).
- `frontend/` — kea-first scenes and logics for the scanner management UI.
diff --git a/products/replay_vision/backend/api/observation_stats.py b/products/replay_vision/backend/api/observation_stats.py
index 23b0e0ade21d..82eecd4f3934 100644
--- a/products/replay_vision/backend/api/observation_stats.py
+++ b/products/replay_vision/backend/api/observation_stats.py
@@ -6,7 +6,7 @@ summary+histogram via raw SQL (`jsonb_array_elements_text`, `PERCENTILE_CONT`).
import math
from datetime import timedelta
-from typing import Any
+from typing import Any, get_args
from django.db import connection
from django.db.models import Count, Q, QuerySet
@@ -15,6 +15,7 @@ from django.utils import timezone
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
_DEFAULT_RECENT_DAYS = 14
_MAX_RECENT_DAYS = 365
@@ -87,7 +88,7 @@ def _coverage(queryset: QuerySet[ReplayObservation], recent_days: int) -> dict[s
def _monitor_stats(queryset: QuerySet[ReplayObservation]) -> dict[str, Any]:
- counts = {"yes": 0, "no": 0, "inconclusive": 0}
+ counts = dict.fromkeys(get_args(MonitorVerdict), 0)
rows = (
queryset.filter(status=ObservationStatus.SUCCEEDED)
.annotate(verdict=KeyTextTransform("verdict", KeyTextTransform("model_output", "scanner_result")))
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 71378af84f37..41cd63436939 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -1,5 +1,5 @@
import uuid
-from typing import Any
+from typing import Any, get_args
from django.conf import settings
from django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, When
@@ -26,18 +26,15 @@ from posthog.renderers import ServerSentEventRenderer
from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum
from products.replay_vision.backend.api.observation_progress import stream_observation_progress
from products.replay_vision.backend.api.observation_stats import compute_observation_stats
+from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
ReplayObservation,
)
-from products.replay_vision.backend.models.replay_scanner import (
- ReplayScanner,
- ScannerModel,
- ScannerProvider,
- ScannerType,
-)
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
from products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshot
logger = structlog.get_logger(__name__)
@@ -60,13 +57,11 @@ class ScannerSnapshotSerializer(serializers.Serializer):
scanner_version = serializers.IntegerField(
help_text="The `ReplayScanner.scanner_version` value at the moment the workflow ran.",
)
- model = serializers.ChoiceField(
- choices=ScannerModel.choices,
- help_text="Concrete model that ran the observation.",
+ model = serializers.CharField(
+ help_text="Concrete model that ran the observation; historical rows may carry since-retired model ids.",
)
- provider = serializers.ChoiceField(
- choices=ScannerProvider.choices,
- help_text="Concrete provider that ran the observation.",
+ provider = serializers.CharField(
+ help_text="Concrete provider that ran the observation; historical rows may carry since-retired providers.",
)
emits_signals = serializers.BooleanField(
help_text="Whether the observation was run with Signal emission enabled.",
@@ -96,16 +91,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Observation status (pending, running, succeeded, failed, ineligible).",
)
- error_reason = serializers.CharField(
- read_only=True,
- allow_blank=True,
- 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."
- ),
- )
+ error_reason = serializers.CharField(read_only=True, allow_blank=True, help_text=ERROR_REASON_HELP_TEXT)
workflow_id = serializers.CharField(
read_only=True,
allow_blank=True,
@@ -300,7 +286,8 @@ _JSONB_ORDER_KEYS = ("result_score", "result_verdict", "scanner_version")
_ALL_ORDER_KEYS = OBSERVATION_ORDER_FIELDS + _JSONB_ORDER_KEYS + ("recording_subject_email",)
-_MONITOR_VERDICTS = frozenset({"yes", "no", "inconclusive"})
+# Derived from the scanner output schema so the filter can never drift from what monitors emit.
+_MONITOR_VERDICTS = frozenset(get_args(MonitorVerdict))
class _ObservationOrderByFilter(OrderByFilter):
@@ -309,6 +296,9 @@ class _ObservationOrderByFilter(OrderByFilter):
_allowed_keys = frozenset(_ALL_ORDER_KEYS)
def _handle(self, qs: QuerySet[ReplayObservation], key: str, descending: bool) -> QuerySet[ReplayObservation]:
+ if key in ("started_at", "completed_at"):
+ # Null until the row starts/settles — keep in-flight rows out of the way regardless of direction.
+ return self._order_nulls_last(qs, key, descending)
if key in OBSERVATION_ORDER_FIELDS:
return self._order_plain(qs, key, descending)
if key == "recording_subject_email":
@@ -382,7 +372,8 @@ class ReplayObservationFilter(django_filters.FilterSet):
help_text=(
"Sort observations by created_at, started_at, completed_at, status, recording_subject_email, "
"result_score, result_verdict, or scanner_version. Prefix with `-` for descending. Keys that can be "
- "null (recording_subject_email, result_*, scanner_version) sort nulls last regardless of direction."
+ "null (started_at, completed_at, recording_subject_email, result_*, scanner_version) sort nulls "
+ "last regardless of direction."
),
)
@@ -433,7 +424,7 @@ class ReplayObservationFilter(django_filters.FilterSet):
description=(
"Sort observations. Plain keys: created_at, started_at, completed_at, status, "
"recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), "
- "scanner_version. Prefix with `-` for descending."
+ "scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way."
),
)
]
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 471102a95f9e..1a38bc96dcf2 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -1,4 +1,3 @@
-import datetime as dt
from typing import Any, NoReturn, cast
from django.conf import settings
@@ -52,13 +51,16 @@ from products.replay_vision.backend.models.replay_scanner import (
from products.replay_vision.backend.queries import (
ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,
ESTIMATE_STALE_AFTER,
+ MIN_SAMPLING_RATE,
estimate_scanner_session_volume,
project_monthly_observations,
refresh_scanner_estimate,
)
from products.replay_vision.backend.quota import compute_quota_snapshot, sum_enabled_scanner_estimates
from products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags
+from products.replay_vision.backend.tags import slugify_tag
from products.replay_vision.backend.temporal.constants import (
+ APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
MAX_SESSION_ID_LENGTH,
build_apply_scanner_workflow_id,
@@ -69,6 +71,12 @@ from products.replay_vision.backend.temporal.types import ApplyScannerInputs
# Date is set by the schedule at trigger time, not by the user — strip on save.
_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
+# Size caps enforced at the write boundary; scanner_config is copied into every observation's snapshot.
+_MAX_PROMPT_LENGTH = 20_000
+_MAX_TAGS = 100
+_MAX_TAG_LENGTH = 100
+_MAX_DESCRIPTION_LENGTH = 1_000
+
logger = structlog.get_logger(__name__)
@@ -86,15 +94,27 @@ def _scanner_config_error_message(scanner_type: ScannerType, scanner_config: Any
prompt = scanner_config.get("prompt")
if not isinstance(prompt, str) or not prompt.strip():
return "Prompt is required."
+ if len(prompt) > _MAX_PROMPT_LENGTH:
+ return f"Prompt can be at most {_MAX_PROMPT_LENGTH:,} characters."
if scanner_type == ScannerType.CLASSIFIER:
tags = scanner_config.get("tags") or []
if len(tags) == 0:
return "Tag vocabulary must have at least one tag."
+ if len(tags) > _MAX_TAGS:
+ return f"Tag vocabulary can have at most {_MAX_TAGS} tags."
if any(not isinstance(t, str) or not t.strip() for t in tags):
return "Tags can't be blank."
- normalized = {t.strip().lower() for t in tags}
- if len(normalized) != len(tags):
- return "Tags must be unique."
+ if any(len(t) > _MAX_TAG_LENGTH for t in tags):
+ return f"Tags can be at most {_MAX_TAG_LENGTH} characters."
+ # Uniqueness on the slug, since filtering/stripping/search all compare slugified tags downstream.
+ slugged: dict[str, str] = {}
+ for t in tags:
+ slug = slugify_tag(t)
+ if not slug:
+ return "Tags must contain letters or numbers."
+ if slug in slugged:
+ return f"Tags must be unique: '{slugged[slug]}' and '{t}' are the same tag."
+ slugged[slug] = t
if scanner_type == ScannerType.SCORER:
scale = scanner_config.get("scale")
if not isinstance(scale, dict):
@@ -105,9 +125,13 @@ def _scanner_config_error_message(scanner_type: ScannerType, scanner_config: Any
if min_v >= max_v:
return "Scale max must be greater than min."
try:
- validate_scanner_config(scanner_config=scanner_config, scanner_type=scanner_type)
+ scanner = validate_scanner_config(scanner_config=scanner_config, scanner_type=scanner_type)
except (ValueError, PydanticValidationError):
return "Scanner configuration is invalid."
+ # The pydantic models ignore extra keys — reject here so typos and junk don't snapshot onto every observation.
+ unknown = set(scanner_config) - set(type(scanner).model_fields)
+ if unknown:
+ return f"Unknown scanner configuration keys: {', '.join(sorted(unknown))}."
return None
@@ -119,6 +143,7 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
description = serializers.CharField(
required=False,
allow_blank=True,
+ max_length=_MAX_DESCRIPTION_LENGTH,
help_text="Free-form description shown in the scanner management UI.",
)
scanner_type = serializers.ChoiceField(
@@ -144,7 +169,11 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
required=False,
min_value=0.0,
max_value=1.0,
- help_text="0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).",
+ help_text=(
+ "0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). "
+ "Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below "
+ "the sampling precision."
+ ),
)
provider = serializers.ChoiceField(
choices=ScannerProvider.choices,
@@ -229,6 +258,14 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
self._validate_and_strip_query(attrs)
return attrs
+ def validate_sampling_rate(self, value: float) -> float:
+ # Below one modulo bucket the candidate query samples nothing — reject instead of silently scanning zero.
+ if 0 < value < MIN_SAMPLING_RATE:
+ raise serializers.ValidationError(
+ f"Sampling rate must be 0 (paused) or at least {MIN_SAMPLING_RATE} (0.01%)."
+ )
+ return value
+
def _reject_scanner_type_change(self, attrs: dict[str, Any]) -> None:
if self.instance is None or "scanner_type" not in attrs:
return
@@ -711,7 +748,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
),
id=workflow_id,
task_queue=settings.REPLAY_VISION_TASK_QUEUE,
- execution_timeout=dt.timedelta(hours=1),
+ execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,
# Stamp the scanner id so on-demand applies count toward the sweep's in-flight cap.
search_attributes=TypedSearchAttributes(
search_attributes=[
diff --git a/products/replay_vision/backend/embeddings.py b/products/replay_vision/backend/embeddings.py
new file mode 100644
index 000000000000..ecdf6b741621
--- /dev/null
+++ b/products/replay_vision/backend/embeddings.py
@@ -0,0 +1,11 @@
+"""Embedding identity shared by the write side (embed_observation) and the search side (max_tools).
+
+A search only finds rows written with the same (model, product, document_type) triple, so both sides must
+import from here rather than defining their own copies.
+"""
+
+from posthog.schema import EmbeddingModelName
+
+OBSERVATION_EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072
+EMBEDDING_PRODUCT = "replay-vision"
+EMBEDDING_DOCUMENT_TYPE = "replay-observation"
diff --git a/products/replay_vision/backend/error_kinds.py b/products/replay_vision/backend/error_kinds.py
new file mode 100644
index 000000000000..e1ae68628336
--- /dev/null
+++ b/products/replay_vision/backend/error_kinds.py
@@ -0,0 +1,36 @@
+"""Terminal-observation error taxonomy; sited outside `temporal/` so the model can import it without temporalio."""
+
+from enum import StrEnum
+
+
+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
+ 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
+
+
+# Shared by the model field and the API serializer so the documented vocabulary can't drift from the enums.
+ERROR_REASON_HELP_TEXT = (
+ "Populated on terminal non-success statuses; formatted as `kind:human-readable message`. "
+ f"For `ineligible`, kind is one of {' / '.join(IneligibleSessionKind)}. "
+ f"For `failed`, kind is one of {' / '.join(FailureKind)}."
+)
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 2d2d2afe1eaa..ed04cee19c7b 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -8,8 +8,6 @@ import structlog
from posthoganalytics import capture_exception
from pydantic import BaseModel, Field
-from posthog.schema import EmbeddingModelName
-
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
@@ -19,6 +17,11 @@ from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
from posthog.sync import database_sync_to_async
+from products.replay_vision.backend.embeddings import (
+ EMBEDDING_DOCUMENT_TYPE,
+ EMBEDDING_PRODUCT,
+ OBSERVATION_EMBEDDING_MODEL,
+)
from products.replay_vision.backend.feature_flag import is_replay_vision_enabled
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
@@ -114,9 +117,9 @@ SEARCH_OBSERVATIONS_TOOL_DESCRIPTION = dedent("""
- The user wants recordings whose observed reasoning mentions a concept, even if worded differently
# Scope
- - If a `scanner_id` is available (the user is looking at a specific scanner), the search is scoped to it.
- - Otherwise the search spans every Replay Vision scanner the user can read — use this to find recordings
- across the whole project. Leave `scanner_id` unset for a project-wide search.
+ - Pass a `scanner_id` to search one specific scanner.
+ - When `scanner_id` is unset, the search defaults to the scanner the user is currently viewing; if they
+ aren't on a scanner page it spans every Replay Vision scanner they can read.
Works for every scanner type (monitor, classifier, scorer, summarizer).
@@ -137,10 +140,6 @@ SEARCH_OBSERVATIONS_TOOL_DESCRIPTION = dedent("""
synthesize the reasons rather than restating each row.
""").strip()
-# Reasoning/summary embeddings are written with the large model; the query must be embedded with the same one.
-SEARCH_EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072
-_EMBEDDING_PRODUCT = "replay-vision"
-_EMBEDDING_DOCUMENT_TYPE = "replay-observation"
# Default and hard cap on how many observations the search returns to Max's context.
DEFAULT_SEARCH_LIMIT = 20
MAX_SEARCH_LIMIT = 50
@@ -225,12 +224,8 @@ class SummarizeReplayVisionSummariesTool(MaxTool):
e,
properties={"team_id": self._team.id, "user_id": self._user.id, "scanner_id": str(resolved_id)},
)
- # Generic content — Max may relay it to the user, so don't surface the raw exception.
- # Raw detail stays in the artifact (not user-visible) for debugging.
- return "Something went wrong loading the summaries. Please try again.", {
- "error": "fetch_failed",
- "details": str(e),
- }
+ # Generic content and artifact — the raw exception goes to error tracking above, not the conversation.
+ return "Something went wrong loading the summaries. Please try again.", {"error": "fetch_failed"}
@database_sync_to_async
def _fetch_and_format(self, scanner_id: str) -> tuple[str, dict[str, Any]]:
@@ -360,7 +355,10 @@ class SearchObservationsArgs(BaseModel):
)
scanner_id: str | None = Field(
default=None,
- description="Scope the search to a single scanner. Omit to search across every scanner the user can read.",
+ description=(
+ "Scope the search to a single scanner. When omitted, defaults to the scanner the user is viewing, "
+ "or every scanner they can read when not on a scanner page."
+ ),
)
verdict: list[str] | None = Field(
default=None,
@@ -404,8 +402,8 @@ class SearchReplayVisionObservationsTool(MaxTool):
max_score: float | None = None,
limit: int | None = None,
) -> tuple[str, dict[str, Any]]:
- # A scanner in scene context scopes the search; otherwise it spans every scanner the user can read.
- resolved_id = self.context.get("scanner_id") or scanner_id
+ # Explicit argument wins; scene context is only the default scope when the model passed nothing.
+ resolved_id = scanner_id or self.context.get("scanner_id")
if not query or not query.strip():
return "No search query provided. Please describe what to look for.", {"error": "empty_query"}
@@ -443,7 +441,9 @@ class SearchReplayVisionObservationsTool(MaxTool):
scanner_ids, scope_label, cross_scanner, capped_limit = resolved_scope
try:
- embedding_response = await async_generate_embedding(self._team, query, model=SEARCH_EMBEDDING_MODEL.value)
+ embedding_response = await async_generate_embedding(
+ self._team, query, model=OBSERVATION_EMBEDDING_MODEL.value
+ )
except Exception:
logger.warning("replay_vision.observation_search.embedding_failed", team_id=self._team.id, exc_info=True)
# Could be a timeout, a transport error, or (commonly) the org not having opted into AI data processing.
@@ -572,9 +572,9 @@ class SearchReplayVisionObservationsTool(MaxTool):
"""
placeholders: dict[str, ast.Expr] = {
"embedding": ast.Constant(value=query_vector),
- "model_name": ast.Constant(value=SEARCH_EMBEDDING_MODEL.value),
- "product": ast.Constant(value=_EMBEDDING_PRODUCT),
- "document_type": ast.Constant(value=_EMBEDDING_DOCUMENT_TYPE),
+ "model_name": ast.Constant(value=OBSERVATION_EMBEDDING_MODEL.value),
+ "product": ast.Constant(value=EMBEDDING_PRODUCT),
+ "document_type": ast.Constant(value=EMBEDDING_DOCUMENT_TYPE),
"team_id": ast.Constant(value=self._team.id),
"scanner_ids": ast.Constant(value=scanner_ids),
"candidate_cap": ast.Constant(value=_MAX_CANDIDATE_ROWS),
diff --git a/products/replay_vision/backend/migrations/0025_alter_replayobservation_error_reason.py b/products/replay_vision/backend/migrations/0025_alter_replayobservation_error_reason.py
new file mode 100644
index 000000000000..289d710db0cf
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0025_alter_replayobservation_error_reason.py
@@ -0,0 +1,19 @@
+# Generated by Django 5.2.14 on 2026-07-01 21:05
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("replay_vision", "0024_visionaction_max_observations")]
+
+ 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. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / internal_error / orphaned.",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index e176a6e78da7..a798a41867d0 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0024_visionaction_max_observations
+0025_alter_replayobservation_error_reason
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index e224c87c563e..11402d1af761 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -2,6 +2,8 @@ from django.db import models
from posthog.models.utils import UUIDModel
+from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
+
class ObservationStatus(models.TextChoices):
PENDING = "pending", "Pending"
@@ -42,16 +44,7 @@ class ReplayObservation(UUIDModel):
)
status = models.CharField(max_length=16, choices=ObservationStatus.choices, default=ObservationStatus.PENDING)
- error_reason = 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."
- ),
- )
+ error_reason = models.TextField(blank=True, default="", help_text=ERROR_REASON_HELP_TEXT)
workflow_id = models.CharField(
max_length=255,
blank=True,
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index c9e63ca11b05..5ef92d51bec3 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -132,13 +132,20 @@ class ReplayScanner(UUIDModel):
update_fields = kwargs.get("update_fields")
if update_fields is not None:
relevant = [f for f in self._VERSION_TRACKED_FIELDS if f in update_fields]
+ track_enabled = "enabled" in update_fields
else:
relevant = list(self._VERSION_TRACKED_FIELDS)
- if self.pk and relevant:
+ track_enabled = True
+ # `_state.adding`, not `self.pk` — UUIDModel assigns the pk in __init__, so pk is truthy even on creates.
+ if not self._state.adding and (relevant or track_enabled):
# SELECT FOR UPDATE so concurrent saves can't both bump scanner_version from the same baseline.
with transaction.atomic():
old = (
- type(self).objects.select_for_update().filter(pk=self.pk).only("scanner_version", *relevant).first()
+ type(self)
+ .objects.select_for_update()
+ .filter(pk=self.pk)
+ .only("scanner_version", "enabled", *relevant)
+ .first()
)
if old is not None:
changed = {f for f in relevant if getattr(old, f) != getattr(self, f)}
@@ -149,6 +156,11 @@ class ReplayScanner(UUIDModel):
if changed & self._ESTIMATE_FIELDS:
self.estimated_at = None
extra_fields.append("estimated_at")
+ if track_enabled and not old.enabled and self.enabled:
+ # Re-enabling restarts the sweep from now — don't backfill (and bill) the disabled gap.
+ self.last_swept_at = initial_watermark()
+ self.last_seen_session_id = ""
+ extra_fields.extend(["last_swept_at", "last_seen_session_id"])
if update_fields is not None and extra_fields:
kwargs["update_fields"] = [*update_fields, *extra_fields]
super().save(*args, **kwargs)
diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.py
index d527f4128f73..ff787bc329b6 100644
--- a/products/replay_vision/backend/queries/__init__.py
+++ b/products/replay_vision/backend/queries/__init__.py
@@ -1,6 +1,7 @@
from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
DEFAULT_MAX_EXECUTION_SECONDS,
+ MIN_SAMPLING_RATE,
SAMPLE_RATE_PRECISION,
SETTLE_INTERVAL,
CandidateSession,
@@ -20,6 +21,7 @@ __all__ = [
"DEFAULT_MAX_EXECUTION_SECONDS",
"ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS",
"ESTIMATE_STALE_AFTER",
+ "MIN_SAMPLING_RATE",
"SAMPLE_RATE_PRECISION",
"SETTLE_INTERVAL",
"CandidateSession",
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index e8a2d8a96a9d..8846a583abbd 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -19,6 +19,7 @@ from posthog.session_recordings.queries.session_recording_list_from_query import
from products.replay_vision.backend.temporal.constants import (
MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
+ MAX_SESSION_ID_LENGTH,
MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,
MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S,
)
@@ -33,12 +34,11 @@ SETTLE_INTERVAL = dt.timedelta(minutes=35)
_PARTITION_LOOKBACK = dt.timedelta(hours=26)
SAMPLE_RATE_PRECISION = 10_000
+# Smallest non-zero rate the modulo bucketing can express (one bucket); the API rejects non-zero rates below it.
+MIN_SAMPLING_RATE = 1 / SAMPLE_RATE_PRECISION
DEFAULT_CANDIDATE_LIMIT = 5_000
DEFAULT_MAX_EXECUTION_SECONDS = 180
-# Excludes attacker-supplied over-length session_ids that would later wedge wire-payload validation.
-_MAX_SESSION_ID_LENGTH = 128
-
def eligibility_predicates() -> list[ast.Expr]:
# Mirror the scan-time eligibility gate (fetch_session_events) on the same ClickHouse aggregates the scan reads, so
@@ -80,6 +80,8 @@ class ScannerCandidateQuery:
query: RecordingsQuery,
last_swept_at: dt.datetime,
sampling_rate: float,
+ # Per-scanner sampling salt (pass the scanner id); must stay stable across sweeps of the same scanner.
+ sampling_salt: str,
last_seen_session_id: str | None = None,
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,
@@ -97,6 +99,7 @@ class ScannerCandidateQuery:
self._last_swept_at = last_swept_at
self._last_seen_session_id = last_seen_session_id
self._sampling_rate = max(0.0, min(1.0, sampling_rate))
+ self._sampling_salt = sampling_salt
self._candidate_limit = candidate_limit
self._max_execution_time_seconds = max_execution_time_seconds
@@ -139,10 +142,11 @@ class ScannerCandidateQuery:
left=ast.Field(chain=["sessions", "end_time"]),
right=ast.Constant(value=dt.datetime.now(dt.UTC) - SETTLE_INTERVAL),
),
+ # Excludes attacker-supplied over-length session_ids that would later wedge wire-payload validation.
ast.CompareOperation(
op=ast.CompareOperationOp.LtEq,
left=ast.Call(name="length", args=[ast.Field(chain=["sessions", "session_id"])]),
- right=ast.Constant(value=_MAX_SESSION_ID_LENGTH),
+ right=ast.Constant(value=MAX_SESSION_ID_LENGTH),
),
]
@@ -176,7 +180,8 @@ class ScannerCandidateQuery:
def _sampling_predicate(self) -> ast.Expr | None:
if self._sampling_rate >= 1.0:
return None
- threshold = max(0, int(self._sampling_rate * SAMPLE_RATE_PRECISION))
+ # round(), not int(): float error puts e.g. 0.29 * 10_000 at 2899.999…, and truncation would shave a bucket.
+ threshold = max(0, round(self._sampling_rate * SAMPLE_RATE_PRECISION))
if threshold <= 0:
return ast.Constant(value=False)
return ast.CompareOperation(
@@ -184,7 +189,16 @@ class ScannerCandidateQuery:
left=ast.Call(
name="modulo",
args=[
- ast.Call(name="cityHash64", args=[ast.Field(chain=["s", "session_id"])]),
+ # concat rather than a second cityHash64 arg — HogQL pins cityHash64 to a single argument.
+ ast.Call(
+ name="cityHash64",
+ args=[
+ ast.Call(
+ name="concat",
+ args=[ast.Field(chain=["s", "session_id"]), ast.Constant(value=self._sampling_salt)],
+ )
+ ],
+ ),
ast.Constant(value=SAMPLE_RATE_PRECISION),
],
),
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 2dd3fbcba0c6..5d256cdf38e3 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -25,6 +25,9 @@ ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS = 10
# The estimate always projects a calendar month from a fixed 30-day lookback.
ESTIMATE_WINDOW_DAYS = 30
+# The earliest-recording probe scans at most this far back; anything older clamps the divisor to the full window.
+_EARLIEST_PROBE_LOOKBACK_DAYS = 3 * ESTIMATE_WINDOW_DAYS
+
# Persisted per-scanner estimates older than this are recomputed by the sweep.
ESTIMATE_STALE_AFTER = dt.timedelta(hours=24)
@@ -43,11 +46,14 @@ def estimate_scanner_session_volume(
Reuses `SessionRecordingListFromQuery`'s filter compilation verbatim and wraps it in a
COUNT, so the estimate and the real recordings list agree on what "matches". The team's
- earliest recording is fetched in the same round trip via a CROSS JOIN so the cost-preview
- widget never pays for two sequential HogQL queries.
+ earliest recent recording is fetched in the same round trip via a CROSS JOIN so the
+ cost-preview widget never pays for two sequential HogQL queries.
"""
+ now = dt.datetime.now(dt.UTC)
+ window_start = now - dt.timedelta(days=ESTIMATE_WINDOW_DAYS)
windowed = query.model_copy(deep=True)
- windowed.date_from = f"-{ESTIMATE_WINDOW_DAYS}d"
+ # Exact timestamp — the relative "-30d" form truncates to start-of-day, counting up to 31 days against a /30 divisor.
+ windowed.date_from = window_start.isoformat()
windowed.date_to = None
# Count only sessions the sweep would actually observe, so the forecast matches the eligible set the candidate query selects.
@@ -69,6 +75,12 @@ def estimate_scanner_session_volume(
)
],
select_from=ast.JoinExpr(table=ast.Field(chain=["raw_session_replay_events"])),
+ # Bounded so the probe partition-prunes; older data would clamp the divisor to the full window anyway.
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["min_first_timestamp"]),
+ right=ast.Constant(value=now - dt.timedelta(days=_EARLIEST_PROBE_LOOKBACK_DAYS)),
+ ),
)
combined_query = ast.SelectQuery(
select=[
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 7a71ef80d667..fb792de4d2fc 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -9,7 +9,6 @@ from products.replay_vision.backend.temporal.activities import (
create_observation_activity,
delete_scanner_schedule_activity,
embed_observation_activity,
- embed_summarizer_observation_activity,
emit_classifier_tags_activity,
emit_observation_event_activity,
emit_observation_signal_activity,
@@ -23,6 +22,7 @@ from products.replay_vision.backend.temporal.activities import (
mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
+ reap_orphaned_observations_activity,
refresh_scanner_estimate_activity,
upload_video_to_gemini_activity,
upsert_scanner_schedule_activity,
@@ -64,7 +64,6 @@ ACTIVITIES: list[Callable[..., Any]] = [
upload_video_to_gemini_activity,
call_scanner_provider_activity,
embed_observation_activity,
- embed_summarizer_observation_activity,
emit_classifier_tags_activity,
emit_observation_event_activity,
emit_observation_signal_activity,
@@ -78,6 +77,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
delete_scanner_schedule_activity,
list_stale_scanner_estimates_activity,
refresh_scanner_estimate_activity,
+ reap_orphaned_observations_activity,
sweep_gemini_files_activity,
evaluate_due_vision_actions_activity,
create_vision_action_run_activity,
@@ -109,7 +109,6 @@ __all__ = [
"create_observation_activity",
"delete_scanner_schedule_activity",
"embed_observation_activity",
- "embed_summarizer_observation_activity",
"emit_classifier_tags_activity",
"emit_observation_event_activity",
"emit_observation_signal_activity",
@@ -123,6 +122,7 @@ __all__ = [
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "reap_orphaned_observations_activity",
"refresh_scanner_estimate_activity",
"sweep_gemini_files_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 1200494da8f1..1bd945479707 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -5,10 +5,7 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
from products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activity
from products.replay_vision.backend.temporal.activities.count_in_flight_applies import count_in_flight_applies_activity
from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity
-from products.replay_vision.backend.temporal.activities.embed_observation import (
- embed_observation_activity,
- embed_summarizer_observation_activity,
-)
+from products.replay_vision.backend.temporal.activities.embed_observation import embed_observation_activity
from products.replay_vision.backend.temporal.activities.emit_classifier_tags import emit_classifier_tags_activity
from products.replay_vision.backend.temporal.activities.emit_observation_event import emit_observation_event_activity
from products.replay_vision.backend.temporal.activities.emit_observation_signal import emit_observation_signal_activity
@@ -24,6 +21,9 @@ from products.replay_vision.backend.temporal.activities.observation_state import
mark_observation_running_activity,
mark_observation_succeeded_activity,
)
+from products.replay_vision.backend.temporal.activities.reap_orphaned_observations import (
+ reap_orphaned_observations_activity,
+)
from products.replay_vision.backend.temporal.activities.reconciler_activities import (
delete_scanner_schedule_activity,
list_enabled_scanners_activity,
@@ -43,7 +43,6 @@ __all__ = [
"create_observation_activity",
"delete_scanner_schedule_activity",
"embed_observation_activity",
- "embed_summarizer_observation_activity",
"emit_classifier_tags_activity",
"emit_observation_event_activity",
"emit_observation_signal_activity",
@@ -57,6 +56,7 @@ __all__ = [
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "reap_orphaned_observations_activity",
"refresh_scanner_estimate_activity",
"upload_video_to_gemini_activity",
"upsert_scanner_schedule_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 e866ca88561f..5d630fc3350c 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -24,6 +24,7 @@ from pydantic import BaseModel, ValidationError
from temporalio import activity
from posthog.models import Team
+from posthog.temporal.common.heartbeat import Heartbeater
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.temporal.constants import replay_vision_distinct_id
@@ -66,6 +67,12 @@ _OutputT = TypeVar("_OutputT", bound=BaseModel)
@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.
+ async with Heartbeater(factor=4):
+ return await _call_scanner_provider(inputs)
+
+
+async def _call_scanner_provider(inputs: CallScannerProviderInputs) -> ScannerCallOutput:
snapshot, team_name, llm_inputs = await asyncio.gather(
sync_to_async(_load_snapshot)(inputs.observation_id, inputs.team_id),
sync_to_async(_load_team_name)(inputs.team_id),
@@ -186,10 +193,10 @@ async def _run_mission(
},
)
cache_client = GoogleGenAIClient(api_key=api_key)
- model = f"models/{snapshot.model.value}"
+ model = f"models/{snapshot.model}"
metric_labels = {
- "provider": snapshot.provider.value,
- "model": snapshot.model.value,
+ "provider": snapshot.provider,
+ "model": snapshot.model,
"scanner_type": snapshot.scanner_type.value,
}
@@ -224,7 +231,7 @@ async def _run_mission(
# 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.value,
+ model=snapshot.model,
error=str(exc),
error_type=type(exc).__name__,
exc_info=True,
diff --git a/products/replay_vision/backend/temporal/activities/cleanup_gemini_file.py b/products/replay_vision/backend/temporal/activities/cleanup_gemini_file.py
index 4ebfb1c7b39a..522ae0287544 100644
--- a/products/replay_vision/backend/temporal/activities/cleanup_gemini_file.py
+++ b/products/replay_vision/backend/temporal/activities/cleanup_gemini_file.py
@@ -1,35 +1,17 @@
"""Best-effort cleanup of a Gemini file uploaded by `upload_video_to_gemini_activity`."""
-import structlog
-from asgiref.sync import sync_to_async
from google.genai import Client as RawGenAIClient
from temporalio import activity
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.gemini import gemini_api_key
-from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import (
- is_gemini_file_gone,
- untrack_uploaded_file,
-)
+from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import delete_and_untrack
from products.replay_vision.backend.temporal.types import CleanupGeminiFileInputs
-logger = structlog.get_logger(__name__)
-
@activity.defn(name="replay_vision_cleanup_gemini_file_activity")
@track_activity()
async def cleanup_gemini_file_activity(inputs: CleanupGeminiFileInputs) -> None:
"""Best-effort delete of the uploaded Gemini file; the cleanup sweep retries on transient failure via the tracking key."""
- try:
- raw_client = RawGenAIClient(api_key=gemini_api_key())
- await sync_to_async(raw_client.files.delete, thread_sensitive=False)(name=inputs.gemini_file_name)
- except Exception as e:
- if not is_gemini_file_gone(e):
- logger.exception(
- "replay_vision.cleanup_gemini_file.delete_failed", gemini_file_name=inputs.gemini_file_name
- )
- return
- # File already gone — untrack so the sweep doesn't retry a doomed delete forever.
- logger.info("replay_vision.cleanup_gemini_file.already_gone", gemini_file_name=inputs.gemini_file_name)
-
- await untrack_uploaded_file(inputs.gemini_file_name)
+ raw_client = RawGenAIClient(api_key=gemini_api_key())
+ await delete_and_untrack(raw_client, inputs.gemini_file_name, log_source="replay_vision.cleanup_gemini_file")
diff --git a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
index 18237589a144..bccbfcdcd775 100644
--- a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
+++ b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
@@ -3,12 +3,14 @@ from temporalio import activity
from posthog.temporal.common.client import async_connect
+from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs
logger = structlog.get_logger(__name__)
@activity.defn
+@track_activity()
async def count_in_flight_applies_activity(inputs: CountInFlightAppliesInputs) -> int:
"""Count this scanner's running apply-scanner workflows (PostHogScannerId is stamped only on those).
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 35cf36dffd91..15331b5b4086 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -34,7 +34,7 @@ def _build_scanner_snapshot(scanner: ReplayScanner) -> dict[str, Any]:
@activity.defn
@track_activity()
def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservationOutput:
- """Snapshot the full scanner state and INSERT the row in `pending`. Returns `was_created=False` on UNIQUE conflict."""
+ """Snapshot the full scanner state and INSERT the row in `pending`; UNIQUE conflicts return `was_created=False` unless the row is this workflow's own lost-result insert, which is reclaimed."""
scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()
if scanner is None:
raise ValueError(f"ReplayScanner {inputs.scanner_id} not found for team {inputs.team_id}")
@@ -86,9 +86,11 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv
)
# Route through the validator so a malformed legacy snapshot surfaces as a tagged non-retryable error.
existing_snapshot = ScannerSnapshot.load_for(existing.id, existing.scanner_snapshot)
+ # A still-PENDING row stamped with our own workflow id is our earlier lost-result insert — reclaim it.
+ reclaimed = existing.workflow_id == inputs.workflow_id and existing.status == ObservationStatus.PENDING
return CreateObservationOutput(
observation_id=existing.id,
- was_created=False,
+ was_created=reclaimed,
scanner_type=existing_snapshot.scanner_type,
)
diff --git a/products/replay_vision/backend/temporal/activities/embed_observation.py b/products/replay_vision/backend/temporal/activities/embed_observation.py
index 4a80acbea304..bd9b1bc2f90d 100644
--- a/products/replay_vision/backend/temporal/activities/embed_observation.py
+++ b/products/replay_vision/backend/temporal/activities/embed_observation.py
@@ -3,8 +3,8 @@
Fires `emit_embedding_request` calls so the text lands as rows in `document_embeddings`, scoped to the
scanner via `metadata.scanner_id` for later natural-language search. monitor/classifier/scorer embed their
`reasoning` paragraph under `rendering="reasoning"`; the summarizer embeds its facets (`intent`, `outcome`,
-`friction_points`, `keywords`) under per-facet renderings. Empty content is skipped. Any failure surfaces to
-the workflow and fails the observation.
+`friction_points`, `keywords`) under per-facet renderings. Empty content is skipped. Failures surface to the
+workflow, which logs and swallows them — the observation is already marked succeeded.
The structured result (monitor `verdict`, scorer `score`, classifier `tags`) is stamped into `metadata` so
search can filter by exact outcome inside the same ClickHouse ranking query, with no second-pass lookup.
@@ -17,33 +17,27 @@ import structlog
from asgiref.sync import sync_to_async
from temporalio import activity
-from posthog.schema import EmbeddingModelName
-
from posthog.api.embedding_worker import emit_embedding_request
from posthog.kafka_client.client import ProduceResult
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC
+from products.replay_vision.backend.embeddings import (
+ EMBEDDING_DOCUMENT_TYPE,
+ EMBEDDING_PRODUCT,
+ OBSERVATION_EMBEDDING_MODEL,
+)
from products.replay_vision.backend.tags import slugify_tag
+from products.replay_vision.backend.temporal.constants import KAFKA_DELIVERY_TIMEOUT_S
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
from products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput
from products.replay_vision.backend.temporal.scanners.scorer import ScorerOutput
from products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput
-from products.replay_vision.backend.temporal.types import (
- AnyScannerOutput,
- EmbedObservationInputs,
- EmbedSummarizerObservationInputs,
-)
+from products.replay_vision.backend.temporal.types import AnyScannerOutput, EmbedObservationInputs
logger = structlog.get_logger(__name__)
-OBSERVATION_EMBEDDING_MODEL = EmbeddingModelName.TEXT_EMBEDDING_3_LARGE_3072
-_PRODUCT = "replay-vision"
-_DOCUMENT_TYPE = "replay-observation"
-# Bounded so broker errors surface as activity failures instead of getting lost in the producer buffer.
-_KAFKA_DELIVERY_TIMEOUT_S = 10.0
-
def _renderings_for(model_output: AnyScannerOutput) -> list[tuple[str, str]]:
"""Map a scanner output to `(rendering, content)` pairs to embed; the summarizer splits into facets,
@@ -80,15 +74,15 @@ async def _emit_embeddings(
def emit_all() -> None:
results: list[tuple[str, ProduceResult]] = []
- with producer_scope(topic=KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC, flush_timeout=_KAFKA_DELIVERY_TIMEOUT_S):
+ with producer_scope(topic=KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC, flush_timeout=KAFKA_DELIVERY_TIMEOUT_S):
for rendering, content in renderings:
if not content.strip():
continue
result = emit_embedding_request(
content=content,
team_id=team_id,
- product=_PRODUCT,
- document_type=_DOCUMENT_TYPE,
+ product=EMBEDDING_PRODUCT,
+ document_type=EMBEDDING_DOCUMENT_TYPE,
rendering=rendering,
document_id=str(observation_id),
models=[OBSERVATION_EMBEDDING_MODEL.value],
@@ -136,30 +130,4 @@ async def embed_observation_activity(inputs: EmbedObservationInputs) -> None:
)
-# TODO: remove this back-compat alias after the deploy window (see REMOVAL CRITERION below).
-@track_activity()
-async def embed_summarizer_observation_activity(inputs: EmbedSummarizerObservationInputs) -> None:
- """Back-compat alias under the pre-rename activity name, so summarizer workflows already in flight when the
- activity was renamed can still resolve their scheduled task. Mirrors the old behavior (facet embeddings,
- no `scanner_id`/result metadata).
-
- REMOVAL CRITERION: ApplyScannerWorkflow runs are short (≤1h execution timeout), so once a deploy shipping the
- rename has been live for >1h, no pre-rename run can still be in flight. A follow-up PR after that window
- should delete this alias and `EmbedSummarizerObservationInputs`, and drop it from the worker activity lists.
- """
- metadata = {
- "session_id": inputs.session_id,
- "team_id": inputs.team_id,
- "observation_id": str(inputs.observation_id),
- }
- await _emit_embeddings(
- team_id=inputs.team_id,
- session_id=inputs.session_id,
- observation_id=inputs.observation_id,
- metadata=metadata,
- renderings=_renderings_for(inputs.summarizer_output),
- )
-
-
-__all__ = ["embed_observation_activity", "embed_summarizer_observation_activity"]
+__all__ = ["embed_observation_activity"]
diff --git a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
index 07e30c068935..d0c6d6afda2f 100644
--- a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
+++ b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
@@ -20,14 +20,12 @@ from posthog.models.event.util import format_clickhouse_timestamp
from posthog.sync import database_sync_to_async
from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.temporal.constants import KAFKA_DELIVERY_TIMEOUT_S
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.types import EmitClassifierTagsInputs
logger = structlog.get_logger(__name__)
-# Bounded so broker errors surface as activity failures instead of getting lost in the producer buffer.
-_KAFKA_DELIVERY_TIMEOUT_S = 10.0
-
def _load_session_identity(observation_id: UUID) -> tuple[str | None, datetime | None] | None:
return ReplayObservation.objects.filter(pk=observation_id).values_list("distinct_id", "session_started_at").first()
@@ -77,7 +75,7 @@ async def emit_classifier_tags_activity(inputs: EmitClassifierTagsInputs) -> Non
def emit() -> None:
with producer_scope(
- topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, flush_timeout=_KAFKA_DELIVERY_TIMEOUT_S
+ topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, flush_timeout=KAFKA_DELIVERY_TIMEOUT_S
) as producer:
result = producer.produce(topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, data=payload)
result.get(timeout=0)
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 90e2af9fb4b8..4a91f251f39e 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
@@ -61,8 +61,8 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:
"recording_subject_email": recording_subject_email,
"triggered_by": str(observation.triggered_by),
"triggered_by_user_id": observation.triggered_by_user_id,
- "model_used": snapshot.model.value,
- "provider_used": snapshot.provider.value,
+ "model_used": snapshot.model,
+ "provider_used": snapshot.provider,
"emits_signals": snapshot.emits_signals,
# Flatten scanner output so HogQL can query individual fields without a JSON extract.
**inputs.model_output.to_event_properties(),
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index c950be74c115..0ec9ce20da5c 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -48,6 +48,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
query=query,
last_swept_at=scanner.last_swept_at,
sampling_rate=scanner.sampling_rate,
+ sampling_salt=str(scanner.id),
last_seen_session_id=scanner.last_seen_session_id or None,
candidate_limit=limit,
)
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index a557b6afc165..45bc5544468c 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -1,4 +1,5 @@
-from collections.abc import Container
+from collections.abc import Callable, Container
+from uuid import UUID
from django.db import transaction
from django.utils import timezone
@@ -51,29 +52,50 @@ def mark_observation_running_activity(inputs: MarkObservationRunningInputs) -> N
)
-@track_activity()
-def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> None:
- """Flip pending/running → failed. Idempotent: FAILED is not in the source filter."""
+def mark_observation_terminal(
+ *,
+ observation_id: UUID,
+ status: ObservationStatus,
+ error_reason: str,
+ scanner_type: str,
+ valid_kinds: Container[str],
+ count_kind: Callable[[str], None],
+) -> bool:
+ """Flip pending/running → `status` and record metrics/logs; idempotent no-op against already-terminal rows."""
updated = ReplayObservation.objects.filter(
- pk=inputs.observation_id,
+ pk=observation_id,
status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],
).update(
- status=ObservationStatus.FAILED,
- error_reason=inputs.error_reason,
+ status=status,
+ error_reason=error_reason,
completed_at=timezone.now(),
)
if not updated:
- return # No state transition — retry against an already-terminal row.
- kind = _kind_from_error_reason(inputs.error_reason, _FAILURE_KIND_VALUES)
- REPLAY_VISION_OBSERVATIONS.labels(status="failed", scanner_type=inputs.scanner_type).inc()
- REPLAY_VISION_FAILURE_KINDS.labels(kind=kind, scanner_type=inputs.scanner_type).inc()
+ return False # No state transition — retry against an already-terminal row.
+ kind = _kind_from_error_reason(error_reason, valid_kinds)
+ REPLAY_VISION_OBSERVATIONS.labels(status=status.value, scanner_type=scanner_type).inc()
+ count_kind(kind)
logger.info(
- "replay_vision.observation.failed",
- observation_id=str(inputs.observation_id),
- scanner_type=inputs.scanner_type,
+ f"replay_vision.observation.{status.value}",
+ observation_id=str(observation_id),
+ scanner_type=scanner_type,
kind=kind,
+ error_reason=error_reason,
+ )
+ return True
+
+
+@track_activity()
+def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> None:
+ """Flip pending/running → failed. Idempotent: FAILED is not in the source filter."""
+ mark_observation_terminal(
+ observation_id=inputs.observation_id,
+ status=ObservationStatus.FAILED,
error_reason=inputs.error_reason,
+ scanner_type=inputs.scanner_type,
+ valid_kinds=_FAILURE_KIND_VALUES,
+ count_kind=lambda kind: REPLAY_VISION_FAILURE_KINDS.labels(kind=kind, scanner_type=inputs.scanner_type).inc(),
)
@@ -81,25 +103,13 @@ def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> Non
@track_activity()
def mark_observation_ineligible_activity(inputs: MarkObservationIneligibleInputs) -> None:
"""Flip pending/running → ineligible. Idempotent: INELIGIBLE is not in the source filter."""
- updated = ReplayObservation.objects.filter(
- pk=inputs.observation_id,
- status__in=[ObservationStatus.PENDING, ObservationStatus.RUNNING],
- ).update(
+ mark_observation_terminal(
+ observation_id=inputs.observation_id,
status=ObservationStatus.INELIGIBLE,
error_reason=inputs.error_reason,
- completed_at=timezone.now(),
- )
- if not updated:
- return # No state transition — retry against an already-terminal row.
- kind = _kind_from_error_reason(inputs.error_reason, _INELIGIBLE_KIND_VALUES)
- REPLAY_VISION_OBSERVATIONS.labels(status="ineligible", scanner_type=inputs.scanner_type).inc()
- REPLAY_VISION_INELIGIBLE_KINDS.labels(kind=kind).inc()
- logger.info(
- "replay_vision.observation.ineligible",
- observation_id=str(inputs.observation_id),
scanner_type=inputs.scanner_type,
- kind=kind,
- error_reason=inputs.error_reason,
+ valid_kinds=_INELIGIBLE_KIND_VALUES,
+ count_kind=lambda kind: REPLAY_VISION_INELIGIBLE_KINDS.labels(kind=kind).inc(),
)
diff --git a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
new file mode 100644
index 000000000000..439098f7d8f1
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
@@ -0,0 +1,100 @@
+"""Marks provably-orphaned pending/running observations as failed so they stop blocking re-scans and eating quota."""
+
+from datetime import UTC, datetime
+from typing import Any, cast
+from uuid import UUID
+
+import structlog
+from temporalio import activity
+from temporalio.client import Client, WorkflowExecutionStatus
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.client import async_connect
+
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.temporal.activities.observation_state import mark_observation_terminal
+from products.replay_vision.backend.temporal.constants import (
+ OBSERVATION_ORPHAN_CUTOFF,
+ REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE,
+)
+from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.errors import FailureKind
+from products.replay_vision.backend.temporal.metrics import REPLAY_VISION_FAILURE_KINDS
+
+logger = structlog.get_logger(__name__)
+
+_LIVE_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
+_ORPHANED_ERROR_REASON = f"{FailureKind.ORPHANED.value}:The analysis stopped without recording an outcome."
+
+
+def _list_stale_observations() -> list[dict[str, Any]]:
+ cutoff = datetime.now(UTC) - OBSERVATION_ORPHAN_CUTOFF
+ rows = (
+ ReplayObservation.objects.filter(status__in=_LIVE_STATUSES, created_at__lt=cutoff)
+ .order_by("created_at")
+ .values("id", "workflow_id", "scanner_snapshot")[:REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE]
+ )
+ # cast: django-stubs types `.values()` rows as a TypedDict, which mypy won't widen to dict[str, Any].
+ return cast(list[dict[str, Any]], list(rows))
+
+
+async def _workflow_is_open(temporal: Client, workflow_id: str) -> bool | None:
+ """Whether the latest run of `workflow_id` is still open; `None` when Temporal couldn't answer."""
+ try:
+ desc = await temporal.get_workflow_handle(workflow_id).describe()
+ except RPCError as e:
+ if e.status == RPCStatusCode.NOT_FOUND:
+ return False
+ return None
+ except Exception:
+ return None
+ return desc.status == WorkflowExecutionStatus.RUNNING
+
+
+def _mark_orphaned(observation_id: UUID, scanner_type: str) -> bool:
+ return mark_observation_terminal(
+ observation_id=observation_id,
+ status=ObservationStatus.FAILED,
+ error_reason=_ORPHANED_ERROR_REASON,
+ scanner_type=scanner_type,
+ valid_kinds={FailureKind.ORPHANED.value},
+ count_kind=lambda kind: REPLAY_VISION_FAILURE_KINDS.labels(kind=kind, scanner_type=scanner_type).inc(),
+ )
+
+
+@track_activity()
+async def reap_orphaned_observations_activity() -> int:
+ """Fail pending/running rows past the orphan cutoff whose workflow is no longer open; returns the count reaped.
+
+ The describe check protects rows reclaimed by a live re-trigger of the same deterministic workflow id.
+ """
+ rows = await database_sync_to_async(_list_stale_observations, thread_sensitive=False)()
+ if not rows:
+ return 0
+ temporal = await async_connect()
+ reaped = 0
+ skipped_open = 0
+ skipped_temporal_error = 0
+ for row in rows:
+ if row["workflow_id"]:
+ is_open = await _workflow_is_open(temporal, row["workflow_id"])
+ if is_open:
+ skipped_open += 1
+ continue
+ if is_open is None:
+ skipped_temporal_error += 1 # Can't prove it's closed — leave it for the next tick.
+ continue
+ snapshot = row["scanner_snapshot"] or {}
+ scanner_type = snapshot.get("scanner_type") or "unknown"
+ if await database_sync_to_async(_mark_orphaned, thread_sensitive=False)(row["id"], scanner_type):
+ reaped += 1
+ logger.info(
+ "replay_vision.reap_orphaned_observations",
+ scanned=len(rows),
+ reaped=reaped,
+ skipped_open=skipped_open,
+ skipped_temporal_error=skipped_temporal_error,
+ )
+ return reaped
diff --git a/products/replay_vision/backend/temporal/activities/reconciler_activities.py b/products/replay_vision/backend/temporal/activities/reconciler_activities.py
index ed5fbe538294..8a9c8177c21c 100644
--- a/products/replay_vision/backend/temporal/activities/reconciler_activities.py
+++ b/products/replay_vision/backend/temporal/activities/reconciler_activities.py
@@ -12,6 +12,7 @@ from products.replay_vision.backend.temporal.constants import (
SCANNER_SCHEDULE_TYPE,
SWEEP_SCANNER_WORKFLOW_NAME,
)
+from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.reconciler_types import (
DeleteScannerScheduleActivityInputs,
EnabledScannerEntry,
@@ -28,6 +29,7 @@ logger = structlog.get_logger(__name__)
@activity.defn
+@track_activity()
async def list_enabled_scanners_activity() -> list[EnabledScannerEntry]:
"""Every enabled ReplayScanner with its current fingerprint."""
rows = await database_sync_to_async(load_enabled_scanner_fingerprints)()
@@ -51,6 +53,7 @@ def _schedule_fingerprint(listing: object) -> str | None:
@activity.defn
+@track_activity()
async def list_scanner_schedules_activity() -> list[ScannerScheduleEntry]:
"""Existing per-scanner schedules in Temporal; fingerprint is None for legacy schedules."""
client = await async_connect()
@@ -71,10 +74,12 @@ async def list_scanner_schedules_activity() -> list[ScannerScheduleEntry]:
@activity.defn
+@track_activity()
async def upsert_scanner_schedule_activity(inputs: UpsertScannerScheduleActivityInputs) -> None:
await a_upsert_scanner_schedule(inputs.scanner_id, inputs.team_id)
@activity.defn
+@track_activity()
async def delete_scanner_schedule_activity(inputs: DeleteScannerScheduleActivityInputs) -> None:
await a_delete_scanner_schedule(inputs.scanner_id)
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 552e9b532b0a..342e8a08c0c0 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
@@ -14,6 +14,7 @@ from google.genai import (
from temporalio import activity
from posthog.storage import object_storage
+from posthog.temporal.common.heartbeat import Heartbeater
from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -32,6 +33,12 @@ _MAX_PROCESSING_WAIT_SECONDS = 300
@track_activity()
async def upload_video_to_gemini_activity(inputs: UploadVideoToGeminiInputs) -> UploadedVideo:
"""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)
+
+
+async def _upload_video(inputs: UploadVideoToGeminiInputs) -> UploadedVideo:
workflow_id = activity.info().workflow_id
if workflow_id is None:
raise ScannerFailureError("upload_video_to_gemini_activity has no workflow_id", kind=FailureKind.INTERNAL_ERROR)
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 49aadd76a22e..2adffac486e5 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -4,6 +4,15 @@ from uuid import UUID
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
+# 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)
+
# Per-action vision-action child, fire-and-forgot by the sweep. Name + timeout live here (not in the
# workflow-def module) so the sweep can start it without cross-importing another @wf.defn module.
PROCESS_VISION_ACTION_WORKFLOW_NAME = "process-vision-action"
@@ -45,6 +54,9 @@ RECONCILE_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)
# Capped so `replay-vision-apply-scanner-{scanner_uuid:36}-{session_id}` fits the 255-char `ReplayObservation.workflow_id` column.
MAX_SESSION_ID_LENGTH = 128
+# Bounded so broker errors surface as activity failures instead of getting lost in the producer buffer.
+KAFKA_DELIVERY_TIMEOUT_S = 10.0
+
# Sessions shorter than this don't carry enough signal for the LLM to analyze.
MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S = 15
diff --git a/products/replay_vision/backend/temporal/errors.py b/products/replay_vision/backend/temporal/errors.py
index 7b3fe6404952..a6567865a826 100644
--- a/products/replay_vision/backend/temporal/errors.py
+++ b/products/replay_vision/backend/temporal/errors.py
@@ -2,36 +2,23 @@ from enum import StrEnum
from temporalio.exceptions import ApplicationError
+from products.replay_vision.backend.error_kinds import FailureKind, IneligibleSessionKind
+
+__all__ = [
+ "INELIGIBLE_SESSION_ERROR_TYPE",
+ "SCANNER_FAILURE_ERROR_TYPE",
+ "FailureKind",
+ "IneligibleSessionError",
+ "IneligibleSessionKind",
+ "ScannerFailureError",
+]
+
# 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.
diff --git a/products/replay_vision/backend/temporal/events_tool.py b/products/replay_vision/backend/temporal/events_tool.py
index cef69aba3aee..561e98821065 100644
--- a/products/replay_vision/backend/temporal/events_tool.py
+++ b/products/replay_vision/backend/temporal/events_tool.py
@@ -116,11 +116,30 @@ def events_tool() -> types.Tool:
)
+def _parse_seconds(value: Any) -> int | None:
+ """Coerce a model-sent tool argument to whole seconds; `None` when it isn't numeric."""
+ try:
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, str):
+ return int(float(value.strip()))
+ except (ValueError, OverflowError):
+ return None
+ return None
+
+
def dispatch_events_tool(function_call: Any, index: EventsIndex) -> dict[str, Any]:
"""Execute a model `get_events_around` call against the prebuilt events index."""
if getattr(function_call, "name", None) != GET_EVENTS_TOOL_NAME:
return {"error": f"unknown tool: {getattr(function_call, 'name', None)}"}
args = dict(getattr(function_call, "args", None) or {})
- rec_t = int(args.get("rec_t", 0))
- window_s = int(args.get("window_s", _DEFAULT_WINDOW_S))
+ # Errors go back to the model as tool output — a malformed call must not fail the billed conversation.
+ rec_t = _parse_seconds(args.get("rec_t", 0))
+ if rec_t is None:
+ return {"error": "rec_t must be a number of recording seconds (the footer's REC_T value)"}
+ window_s = _parse_seconds(args.get("window_s", _DEFAULT_WINDOW_S))
+ if window_s is None:
+ window_s = _DEFAULT_WINDOW_S
return {"events": get_events_around(index, rec_t, window_s)}
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
index b82f27b6bae5..ce1c96b0a8dc 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
@@ -2,14 +2,15 @@ import asyncio
from datetime import UTC, datetime
import structlog
-from asgiref.sync import sync_to_async
from google.genai import Client as RawGenAIClient
from temporalio import activity
from temporalio.client import Client, WorkflowExecutionStatus
from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.heartbeat import Heartbeater
+from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.gemini import gemini_api_key
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants import (
DELETE_CONCURRENCY,
@@ -18,10 +19,9 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants impo
SWEEP_MIN_AGE,
)
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import (
+ delete_and_untrack,
index_size,
- is_gemini_file_gone,
iter_tracked_files,
- untrack_uploaded_file,
)
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import (
CleanupSweepInputs,
@@ -59,8 +59,15 @@ async def _classify_workflow(temporal: Client, workflow_id: str) -> str:
@activity.defn(name="replay_vision_sweep_gemini_files_activity")
+@track_activity()
async def sweep_gemini_files_activity(inputs: CleanupSweepInputs) -> CleanupSweepResult:
"""Reclaims orphaned Gemini files. Failures counted, never raised."""
+ # Continuous background heartbeats — a degraded-API delete fan-out otherwise outlives the heartbeat timeout.
+ async with Heartbeater(factor=4):
+ return await _sweep_gemini_files(inputs)
+
+
+async def _sweep_gemini_files(inputs: CleanupSweepInputs) -> CleanupSweepResult:
raw_client = RawGenAIClient(api_key=gemini_api_key())
temporal = await async_connect()
cutoff = datetime.now(UTC) - SWEEP_MIN_AGE
@@ -110,28 +117,14 @@ async def sweep_gemini_files_activity(inputs: CleanupSweepInputs) -> CleanupSwee
async def _delete(tracked: TrackedFile) -> bool:
async with delete_sem:
- try:
- await sync_to_async(raw_client.files.delete, thread_sensitive=False)(name=tracked.gemini_file_name)
- except Exception as e:
- if not is_gemini_file_gone(e):
- # Key kept for next-cycle retry; 48h TTL backstops.
- logger.exception(
- "replay_vision.cleanup_sweep.delete_failed",
- gemini_file_name=tracked.gemini_file_name,
- workflow_id=tracked.workflow_id,
- signals_type="cleanup-sweep",
- )
- return False
- # File already gone (e.g., a previous untrack failed). Drop the key so we
- # don't keep retrying a doomed delete.
- logger.info(
- "replay_vision.cleanup_sweep.delete_already_gone",
- gemini_file_name=tracked.gemini_file_name,
- workflow_id=tracked.workflow_id,
- signals_type="cleanup-sweep",
- )
- await untrack_uploaded_file(tracked.gemini_file_name)
- return True
+ # On transient failure the key is kept for next-cycle retry; the 48h TTL backstops.
+ return await delete_and_untrack(
+ raw_client,
+ tracked.gemini_file_name,
+ log_source="replay_vision.cleanup_sweep",
+ workflow_id=tracked.workflow_id,
+ signals_type="cleanup-sweep",
+ )
delete_results = await asyncio.gather(*(_delete(t) for t in to_delete))
deleted = sum(1 for r in delete_results if r)
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/schedule.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/schedule.py
index 2bd5f05680b6..bc22a33d6ae9 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/schedule.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/schedule.py
@@ -1,18 +1,6 @@
-from django.conf import settings
-
-from temporalio import common
-from temporalio.client import (
- Client,
- Schedule,
- ScheduleActionStartWorkflow,
- ScheduleIntervalSpec,
- ScheduleOverlapPolicy,
- SchedulePolicy,
- ScheduleSpec,
-)
+from temporalio.client import Client
from temporalio.common import SearchAttributePair, TypedSearchAttributes
-from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants import (
@@ -24,34 +12,19 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants impo
WORKFLOW_NAME,
)
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import CleanupSweepInputs
+from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule
async def create_replay_vision_gemini_cleanup_sweep_schedule(client: Client) -> None:
- schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- WORKFLOW_NAME,
- CleanupSweepInputs(),
- id=WORKFLOW_ID,
- task_queue=settings.REPLAY_VISION_TASK_QUEUE,
- execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
- retry_policy=common.RetryPolicy(maximum_attempts=1),
+ await upsert_interval_schedule(
+ client,
+ schedule_id=SCHEDULE_ID,
+ workflow_name=WORKFLOW_NAME,
+ workflow_id=WORKFLOW_ID,
+ inputs=CleanupSweepInputs(),
+ interval=SCHEDULE_INTERVAL,
+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
+ search_attributes=TypedSearchAttributes(
+ search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]
),
- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]),
- policy=SchedulePolicy(
- overlap=ScheduleOverlapPolicy.SKIP,
- catchup_window=SCHEDULE_INTERVAL,
- ),
- )
- search_attributes = TypedSearchAttributes(
- search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]
)
- if await a_schedule_exists(client, SCHEDULE_ID):
- await a_update_schedule(client, SCHEDULE_ID, schedule, search_attributes=search_attributes)
- else:
- await a_create_schedule(
- client,
- SCHEDULE_ID,
- schedule,
- trigger_immediately=True,
- search_attributes=search_attributes,
- )
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/tracking.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/tracking.py
index b416b5d49677..b3a874de5896 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/tracking.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/tracking.py
@@ -3,13 +3,18 @@
import json
from collections.abc import AsyncIterator
from datetime import datetime
+from typing import TYPE_CHECKING, Any
from django.conf import settings
import structlog
+from asgiref.sync import sync_to_async
from google.genai.errors import APIError
from redis import asyncio as aioredis
+if TYPE_CHECKING:
+ from google.genai import Client as RawGenAIClient
+
from posthog.redis import get_async_client
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants import (
@@ -30,6 +35,22 @@ def is_gemini_file_gone(error: Exception) -> bool:
return isinstance(error, APIError) and error.code in (403, 404)
+async def delete_and_untrack(
+ raw_client: "RawGenAIClient", gemini_file_name: str, *, log_source: str, **log_kwargs: Any
+) -> bool:
+ """Delete the Gemini file and drop its tracking key; returns False (key kept for retry) on transient failure."""
+ try:
+ await sync_to_async(raw_client.files.delete, thread_sensitive=False)(name=gemini_file_name)
+ except Exception as e:
+ if not is_gemini_file_gone(e):
+ logger.exception(f"{log_source}.delete_failed", gemini_file_name=gemini_file_name, **log_kwargs)
+ return False
+ # File already gone (e.g. a previous untrack failed) — drop the key so we don't retry a doomed delete.
+ logger.info(f"{log_source}.delete_already_gone", gemini_file_name=gemini_file_name, **log_kwargs)
+ await untrack_uploaded_file(gemini_file_name)
+ return True
+
+
def _redis() -> aioredis.Redis:
return get_async_client(settings.REPLAY_VISION_REDIS_URL)
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index ca0d62797854..6db145b9bf71 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -1,4 +1,4 @@
-"""Syncs per-scanner schedules with the ReplayScanner table on every tick."""
+"""Syncs per-scanner schedules with the ReplayScanner table on every tick, and reaps orphaned observations."""
import asyncio
from collections.abc import Awaitable, Callable
@@ -14,6 +14,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from products.replay_vision.backend.temporal.constants import (
LIST_ENABLED_SCANNERS_TIMEOUT,
LIST_SCANNER_SCHEDULES_TIMEOUT,
+ REAP_ORPHANED_OBSERVATIONS_TIMEOUT,
RECONCILE_SCHEDULE_OP_TIMEOUT,
RECONCILER_EXECUTION_TIMEOUT,
RECONCILER_INTERVAL,
@@ -37,6 +38,7 @@ with workflow.unsafe.imports_passed_through():
delete_scanner_schedule_activity,
list_enabled_scanners_activity,
list_scanner_schedules_activity,
+ reap_orphaned_observations_activity,
upsert_scanner_schedule_activity,
)
@@ -48,6 +50,16 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: ReconcileScannerSchedulesInputs) -> ReconcileScannerSchedulesResult:
+ # Best-effort and first: a schedule-sync failure below must not starve the reaper, and vice versa.
+ try:
+ await workflow.execute_activity(
+ reap_orphaned_observations_activity,
+ start_to_close_timeout=REAP_ORPHANED_OBSERVATIONS_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ except Exception:
+ workflow.logger.exception("replay_vision.reap_orphaned_observations_failed")
+
# A scanner toggled between the two listings recovers on the next tick.
enabled_entries, existing_entries = await asyncio.gather(
workflow.execute_activity(
diff --git a/products/replay_vision/backend/temporal/schedule.py b/products/replay_vision/backend/temporal/schedule.py
index d5c55527dd19..265b66f587b8 100644
--- a/products/replay_vision/backend/temporal/schedule.py
+++ b/products/replay_vision/backend/temporal/schedule.py
@@ -110,6 +110,7 @@ async def upsert_interval_schedule(
inputs: BaseModel,
interval: dt.timedelta,
execution_timeout: dt.timedelta,
+ search_attributes: TypedSearchAttributes | None = None,
) -> None:
"""Create or update a singleton interval schedule with SKIP overlap; first creation triggers immediately."""
schedule = Schedule(
@@ -125,9 +126,11 @@ async def upsert_interval_schedule(
policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=interval),
)
if await a_schedule_exists(client, schedule_id):
- await a_update_schedule(client, schedule_id, schedule)
+ await a_update_schedule(client, schedule_id, schedule, search_attributes=search_attributes)
else:
- await a_create_schedule(client, schedule_id, schedule, trigger_immediately=True)
+ await a_create_schedule(
+ client, schedule_id, schedule, trigger_immediately=True, search_attributes=search_attributes
+ )
async def a_upsert_scanner_schedule(scanner_id: UUID, team_id: int) -> None:
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index e62588840453..f826d46912ea 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -25,6 +25,7 @@ from products.replay_vision.backend.temporal.activities import (
find_scanner_candidates_activity,
)
from products.replay_vision.backend.temporal.constants import (
+ APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
@@ -162,8 +163,7 @@ class SweepScannerWorkflow(PostHogWorkflow):
task_queue=settings.REPLAY_VISION_TASK_QUEUE,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
parent_close_policy=wf.ParentClosePolicy.ABANDON,
- # Matches the on-demand /observe/ ceiling.
- execution_timeout=dt.timedelta(hours=1),
+ execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.py
index 2f9fe7fb0a8d..a3fed230f71e 100644
--- a/products/replay_vision/backend/temporal/types.py
+++ b/products/replay_vision/backend/temporal/types.py
@@ -6,7 +6,7 @@ from pydantic import BaseModel, Field, ValidationError, model_validator
from temporalio.exceptions import ApplicationError
from products.replay_vision.backend.models.replay_observation import ObservationTrigger
-from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerProvider, ScannerType
+from products.replay_vision.backend.models.replay_scanner import ScannerType
from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH
from products.replay_vision.backend.temporal.scanners.base import SignalFinding
from products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutput
@@ -26,8 +26,9 @@ class ScannerSnapshot(BaseModel, frozen=True):
name: str
scanner_type: ScannerType
scanner_version: int = Field(ge=1)
- model: ScannerModel
- provider: ScannerProvider
+ # Plain strings, not live enums: retiring a ScannerModel/ScannerProvider member must not break old-row loads.
+ model: str
+ provider: str
emits_signals: bool
scanner_config: dict[str, Any]
@@ -223,16 +224,6 @@ class EmbedObservationInputs(BaseModel, frozen=True):
model_output: AnyScannerOutput
-class EmbedSummarizerObservationInputs(BaseModel, frozen=True):
- """Back-compat input for the pre-rename `embed_summarizer_observation_activity`. Kept only so summarizer
- workflows already in flight when the activity was renamed can still resolve their scheduled activity."""
-
- team_id: int
- session_id: str
- observation_id: UUID
- summarizer_output: SummarizerOutput
-
-
class EmitClassifierTagsInputs(BaseModel, frozen=True):
"""Input to the classifier-side-effect activity that writes ai_tags_fixed/freeform via Kafka."""
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index 96ce8199d618..243bf3eee26a 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -6,6 +6,10 @@ from uuid import UUID
import temporalio.workflow as wf
from temporalio import common
from temporalio.common import SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
+from temporalio.exceptions import (
+ ActivityError,
+ TimeoutError as TemporalTimeoutError,
+)
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause
@@ -128,6 +132,19 @@ def _has_embeddable_text(model_output: object) -> bool:
return bool(reasoning and reasoning.strip())
+# Provider-facing activities whose Temporal timeout means "provider slow", not a PostHog bug.
+_PROVIDER_TIMEOUT_ACTIVITY_TYPES = frozenset(
+ {"replay_vision_upload_video_to_gemini_activity", "call_scanner_provider_activity"}
+)
+
+
+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:
+ return None
+ return FailureKind.PROVIDER_TRANSIENT.value if isinstance(e.cause, TemporalTimeoutError) else 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
@@ -156,7 +173,7 @@ def _rasterizer_workflow_id(inputs: ApplyScannerInputs) -> str:
@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."""
+ """Apply one scanner to one session: create row → fetch+rasterize → upload → call provider → mark succeeded → emit event."""
inputs_cls = ApplyScannerInputs
@@ -201,16 +218,17 @@ class ApplyScannerWorkflow(PostHogWorkflow):
observation_id = create_result.observation_id
scanner_type = create_result.scanner_type
- await wf.execute_activity(
- mark_observation_running_activity,
- MarkObservationRunningInputs(observation_id=observation_id),
- start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_STATE_ACTIVITY_RETRY,
- )
- self._advance_phase("fetching")
uploaded: UploadedVideo | None = None
try:
+ # Inside the try so an exhausted retry still lands the row in FAILED instead of stranding it PENDING.
+ await wf.execute_activity(
+ mark_observation_running_activity,
+ MarkObservationRunningInputs(observation_id=observation_id),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=_STATE_ACTIVITY_RETRY,
+ )
+ self._advance_phase("fetching")
asset_result = await self._fetch_and_ensure_asset(inputs, observation_id)
self._advance_phase("rendering", rasterizer_workflow_id=_rasterizer_workflow_id(inputs))
await self._run_rasterize_child(inputs, asset_result.asset_id)
@@ -219,6 +237,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
upload_video_to_gemini_activity,
UploadVideoToGeminiInputs(asset_id=asset_result.asset_id),
start_to_close_timeout=dt.timedelta(minutes=10),
+ heartbeat_timeout=dt.timedelta(minutes=2),
retry_policy=_UPLOAD_RETRY,
)
self._advance_phase("analyzing")
@@ -232,10 +251,10 @@ class ApplyScannerWorkflow(PostHogWorkflow):
),
# Multi-turn tool conversation (video + on-demand event lookups) needs more headroom than a single call.
start_to_close_timeout=dt.timedelta(minutes=10),
+ heartbeat_timeout=dt.timedelta(minutes=2),
retry_policy=_PROVIDER_CALL_RETRY,
)
self._advance_phase("finalizing")
- await self._apply_scanner_side_effects(inputs, observation_id, call_output.model_output)
signals_count = 0
if call_output.signals:
# The activity fails soft (returns 0 on any error), so there's nothing to retry. The local
@@ -255,12 +274,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
)
except Exception:
wf.logger.exception("Signal emission activity failed for observation %s", observation_id)
- await wf.execute_activity(
- emit_observation_event_activity,
- EmitObservationEventInputs(observation_id=observation_id, model_output=call_output.model_output),
- start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_STATE_ACTIVITY_RETRY,
- )
+ # Persist the billed result first — everything past this point is fail-soft delivery.
await wf.execute_activity(
mark_observation_succeeded_activity,
MarkObservationSucceededInputs(
@@ -271,12 +285,26 @@ class ApplyScannerWorkflow(PostHogWorkflow):
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=_STATE_ACTIVITY_RETRY,
)
+ try:
+ await wf.execute_activity(
+ emit_observation_event_activity,
+ EmitObservationEventInputs(observation_id=observation_id, model_output=call_output.model_output),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=_STATE_ACTIVITY_RETRY,
+ )
+ except Exception:
+ wf.logger.exception("Event emission failed for succeeded observation %s", observation_id)
+ await self._apply_scanner_side_effects(inputs, observation_id, call_output.model_output)
except Exception as e:
ineligible_kind = _extract_kind_for_type(e, INELIGIBLE_SESSION_ERROR_TYPE)
if ineligible_kind is not None:
await self._mark_ineligible(observation_id, scanner_type, ineligible_kind, _root_cause_message(e))
else:
- failure_kind = _extract_kind_for_type(e, SCANNER_FAILURE_ERROR_TYPE) or FailureKind.INTERNAL_ERROR.value
+ failure_kind = (
+ _extract_kind_for_type(e, SCANNER_FAILURE_ERROR_TYPE)
+ or _activity_timeout_kind(e)
+ or FailureKind.INTERNAL_ERROR.value
+ )
await self._mark_failed(observation_id, scanner_type, failure_kind, _root_cause_message(e))
raise
finally:
@@ -365,40 +393,44 @@ class ApplyScannerWorkflow(PostHogWorkflow):
observation_id: UUID,
model_output: object,
) -> None:
- """Dispatch scanner-type-specific side-effects after the LLM call; failure aborts the workflow.
-
- DEPLOY NOTE (accepted in-flight breakage): this dispatch was changed — the summarizer embed activity was
- renamed and an embed step was added for every scanner type. We deliberately do NOT gate it behind
- `workflow.patched()` (a pattern this codebase doesn't otherwise use). ApplyScannerWorkflow runs are short
- (≤1h timeout), so the only affected runs are the handful in flight *past this step* at the deploy instant:
- they may hit a replay non-determinism error and stall until their timeout, costing at most a few
- re-runnable observations. The `embed_summarizer_observation_activity` alias additionally lets any
- already-scheduled old-name task resolve. This trade-off is accepted over carrying a permanent patch gate.
+ """Dispatch scanner-type-specific side-effects after the observation is marked succeeded.
+
+ Each fails soft — the result is already persisted, and one effect's outage must not abort the rest.
+
+ Dispatch changes here are deliberately NOT gated behind `workflow.patched()`: runs are short (≤1h
+ timeout), so a deploy strands at most the handful of in-flight runs past this step, which the reaper
+ then fails as re-runnable — accepted over carrying permanent patch gates.
"""
# Embed the observation's explanation text (reasoning, or summarizer facets) for natural-language search.
if _has_embeddable_text(model_output):
- await wf.execute_activity(
- embed_observation_activity,
- EmbedObservationInputs(
- team_id=inputs.team_id,
- session_id=inputs.session_id,
- observation_id=observation_id,
- scanner_id=inputs.scanner_id,
- model_output=model_output,
- ),
- start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_SIDE_EFFECT_RETRY,
- )
+ try:
+ await wf.execute_activity(
+ embed_observation_activity,
+ EmbedObservationInputs(
+ team_id=inputs.team_id,
+ session_id=inputs.session_id,
+ observation_id=observation_id,
+ scanner_id=inputs.scanner_id,
+ model_output=model_output,
+ ),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=_SIDE_EFFECT_RETRY,
+ )
+ except Exception:
+ wf.logger.exception("Embedding emission failed for succeeded observation %s", observation_id)
# Classifiers additionally fan their tags out onto the recording.
if isinstance(model_output, ClassifierOutput):
- await wf.execute_activity(
- emit_classifier_tags_activity,
- EmitClassifierTagsInputs(
- team_id=inputs.team_id,
- session_id=inputs.session_id,
- observation_id=observation_id,
- classifier_output=model_output,
- ),
- start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_SIDE_EFFECT_RETRY,
- )
+ try:
+ await wf.execute_activity(
+ emit_classifier_tags_activity,
+ EmitClassifierTagsInputs(
+ team_id=inputs.team_id,
+ session_id=inputs.session_id,
+ observation_id=observation_id,
+ classifier_output=model_output,
+ ),
+ start_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=_SIDE_EFFECT_RETRY,
+ )
+ except Exception:
+ wf.logger.exception("Classifier tag emission failed for succeeded observation %s", observation_id)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 3e6a044500a8..58e8af4e2f0e 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -134,7 +134,7 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 201)
self.assertEqual(resp.json()["provider"], ScannerProvider.GOOGLE)
- @parameterized.expand([("below", -0.1), ("above", 1.5)])
+ @parameterized.expand([("below", -0.1), ("above", 1.5), ("below_sampling_precision", 0.00005)])
def test_create_rejects_out_of_range_sampling_rate(self, _label: str, value: float) -> None:
resp = self.client.post(
self.scanners_url,
@@ -150,6 +150,22 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 400)
self.assertEqual(resp.json()["attr"], "sampling_rate")
+ @parameterized.expand([("paused", 0.0), ("precision_floor", 0.0001)])
+ def test_create_accepts_sampling_rate_boundaries(self, _label: str, value: float) -> None:
+ resp = self.client.post(
+ self.scanners_url,
+ data={
+ "name": f"rate-ok-{value}",
+ "scanner_type": ScannerType.MONITOR,
+ "scanner_config": {"prompt": "p"},
+ "model": ScannerModel.GEMINI_3_FLASH,
+ "sampling_rate": value,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 201)
+ self.assertEqual(resp.json()["sampling_rate"], value)
+
def test_create_duplicate_name_rejected(self) -> None:
self._create_scanner(name="dup")
resp = self.client.post(
@@ -280,7 +296,19 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
"classifier_duplicate_tags",
ScannerType.CLASSIFIER,
{"prompt": "p", "tags": ["Bug", "bug"]},
- "Tags must be unique.",
+ "Tags must be unique: 'Bug' and 'bug' are the same tag.",
+ ),
+ (
+ "classifier_slug_colliding_tags",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": ["login issue", "login_issue"]},
+ "Tags must be unique: 'login issue' and 'login_issue' are the same tag.",
+ ),
+ (
+ "classifier_tag_without_alphanumerics",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": ["!!!"]},
+ "Tags must contain letters or numbers.",
),
(
"monitor_missing_prompt",
@@ -312,6 +340,30 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
"just a string",
"Scanner configuration must be a JSON object.",
),
+ (
+ "oversized_prompt",
+ ScannerType.MONITOR,
+ {"prompt": "p" * 20_001},
+ "Prompt can be at most 20,000 characters.",
+ ),
+ (
+ "too_many_tags",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": [f"tag-{i}" for i in range(101)]},
+ "Tag vocabulary can have at most 100 tags.",
+ ),
+ (
+ "overlong_tag",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": ["ok", "x" * 101]},
+ "Tags can be at most 100 characters.",
+ ),
+ (
+ "unknown_config_key",
+ ScannerType.MONITOR,
+ {"prompt": "p", "alow_inconclusive": True},
+ "Unknown scanner configuration keys: alow_inconclusive.",
+ ),
]
)
def test_validation_returns_specific_message_per_invalid_config(
@@ -841,6 +893,20 @@ class TestReplayObservationViewSet(_VisionAPITestCase):
resp = self.client.get(f"{self.observations_url(str(self.scanner.id))}?order_by=recording_subject_email")
self.assertEqual([r["session_id"] for r in resp.json()["results"]], ["s2", "s1", "s3"])
+ def test_order_by_completed_at_descending_sorts_in_flight_rows_last(self) -> None:
+ now = timezone.now()
+ self._create_observation(
+ session_id="done-old",
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=now - timedelta(hours=2),
+ )
+ self._create_observation(session_id="done-new", status=ObservationStatus.SUCCEEDED, completed_at=now)
+ self._create_observation(
+ session_id="in-flight"
+ ) # pending, completed_at null — Postgres puts nulls first on DESC by default
+ resp = self.client.get(f"{self.observations_url(str(self.scanner.id))}?order_by=-completed_at")
+ self.assertEqual([r["session_id"] for r in resp.json()["results"]], ["done-new", "done-old", "in-flight"])
+
def test_retrieve_observation_exposes_scanner_result_when_succeeded(self) -> None:
obs = self._create_observation(
status=ObservationStatus.SUCCEEDED,
diff --git a/products/replay_vision/backend/tests/test_events_tool.py b/products/replay_vision/backend/tests/test_events_tool.py
index 931c720da825..a3035aa7fd9a 100644
--- a/products/replay_vision/backend/tests/test_events_tool.py
+++ b/products/replay_vision/backend/tests/test_events_tool.py
@@ -1,6 +1,8 @@
import datetime as dt
from typing import Any
+from parameterized import parameterized
+
from products.replay_vision.backend.temporal.events_tool import (
EventsIndex,
build_events_index,
@@ -135,3 +137,33 @@ class TestDispatchEventsTool:
def test_rejects_unknown_tool(self) -> None:
result = dispatch_events_tool(_Call("something_else", {}), _index([], {}))
assert "error" in result
+
+ @parameterized.expand(
+ [
+ ("float_string", "30.7"),
+ ("float", 30.0),
+ ("int_string", "30"),
+ ]
+ )
+ def test_coerces_numeric_rec_t_variants(self, _label: str, rec_t: Any) -> None:
+ rows = [_row("u1", "$rageclick", None, "url_1", None, "click", [])]
+ result = dispatch_events_tool(_Call("get_events_around", {"rec_t": rec_t}), _index(rows, {"u1": 30_000}))
+ assert [e["rec_t"] for e in result["events"]] == [30]
+
+ @parameterized.expand(
+ [
+ ("null", None),
+ ("prose", "about 30"),
+ ("boolean", True),
+ ("nan", "nan"),
+ ]
+ )
+ def test_malformed_rec_t_returns_error_to_model_instead_of_raising(self, _label: str, rec_t: Any) -> None:
+ result = dispatch_events_tool(_Call("get_events_around", {"rec_t": rec_t}), _index([], {}))
+ assert "rec_t" in result["error"]
+
+ def test_malformed_window_falls_back_to_default(self) -> None:
+ rows = [_row("u1", "$rageclick", None, "url_1", None, "click", [])]
+ index = _index(rows, {"u1": 30_000})
+ result = dispatch_events_tool(_Call("get_events_around", {"rec_t": 30, "window_s": "wide"}), index)
+ assert len(result["events"]) == 1
diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.py
index 07381a21ba4d..cb7c5616a5e4 100644
--- a/products/replay_vision/backend/tests/test_max_tools.py
+++ b/products/replay_vision/backend/tests/test_max_tools.py
@@ -13,6 +13,7 @@ from parameterized import parameterized
from products.replay_vision.backend.max_tools import (
DraftReplayVisionScannerPromptTool,
SearchReplayVisionObservationsTool,
+ SummarizeReplayVisionSummariesTool,
_ObservationFilters,
)
from products.replay_vision.backend.models.replay_observation import (
@@ -210,6 +211,25 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
assert artifact["result_count"] == 1
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_explicit_scanner_id_argument_overrides_scene_context(self):
+ context_scanner = await self._scanner(name="context-scanner")
+ target_scanner = await self._scanner(name="target-scanner")
+ obs = await self._observation(target_scanner, "sess-t", "broken button", score=0)
+
+ with (
+ patch(_FLAG_PATH, return_value=True),
+ patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),
+ patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1)])),
+ ):
+ _, artifact = await self._tool(context={"scanner_id": str(context_scanner.id)})._arun_impl(
+ query="button", scanner_id=str(target_scanner.id)
+ )
+
+ # Context-wins precedence would scope to context-scanner and drop the target scanner's row.
+ assert artifact["result_count"] == 1
+
@pytest.mark.django_db
@pytest.mark.asyncio
async def test_returns_empty_when_no_matches(self):
@@ -425,6 +445,22 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
assert "not enabled" in content
+class TestSummarizeReplayVisionSummariesTool(BaseTest):
+ def _tool(self) -> SummarizeReplayVisionSummariesTool:
+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}
+ return SummarizeReplayVisionSummariesTool(team=self.team, user=self.user, config=config)
+
+ @pytest.mark.django_db
+ @pytest.mark.asyncio
+ async def test_internal_error_details_stay_out_of_content_and_artifact(self):
+ # The raw exception may carry connection strings; it belongs in error tracking, not the conversation.
+ with patch(_FLAG_PATH, side_effect=RuntimeError("postgres://user:hunter2@db/prod")):
+ content, artifact = await self._tool()._arun_impl(scanner_id=str(uuid.uuid4()))
+
+ assert artifact == {"error": "fetch_failed"}
+ assert "hunter2" not in content
+
+
class TestObservationFiltersTagClause:
"""Pure-logic clause construction — no DB/ClickHouse, so it runs without the full test stack."""
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index 725c6d441a23..d0153dfc8e87 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
from posthog.test.base import BaseTest
from django.db import IntegrityError
@@ -130,6 +132,36 @@ class TestReplayScanner(BaseTest):
self.assertEqual(scanner.scanner_version, 2)
self.assertEqual(scanner.scanner_config, {"prompt": "persisted"})
+ @parameterized.expand([("full_save", None), ("update_fields_save", ["enabled"])])
+ def test_reenabling_resets_sweep_watermark(self, _label: str, update_fields: list[str] | None) -> None:
+ # Without the reset, a re-enabled scanner backfills every session since it was disabled.
+ stale = timezone.now() - timedelta(days=21)
+ scanner = self._create_scanner(enabled=False, last_swept_at=stale, last_seen_session_id="sess-tie")
+ scanner.enabled = True
+ scanner.save(update_fields=update_fields)
+ scanner.refresh_from_db()
+ self.assertGreater(scanner.last_swept_at, timezone.now() - timedelta(hours=1))
+ self.assertEqual(scanner.last_seen_session_id, "")
+
+ @parameterized.expand(
+ [
+ ("disable", True, False),
+ ("stays_enabled", True, True),
+ ("stays_disabled", False, False),
+ ]
+ )
+ def test_watermark_is_kept_unless_reenabled(self, label: str, enabled_before: bool, enabled_after: bool) -> None:
+ stale = timezone.now() - timedelta(days=21)
+ scanner = self._create_scanner(
+ name=label, enabled=enabled_before, last_swept_at=stale, last_seen_session_id="sess-tie"
+ )
+ scanner.enabled = enabled_after
+ scanner.description = "touched"
+ scanner.save()
+ scanner.refresh_from_db()
+ self.assertEqual(scanner.last_swept_at, stale)
+ self.assertEqual(scanner.last_seen_session_id, "sess-tie")
+
class TestReplayObservation(BaseTest):
def _create_scanner(self, **overrides) -> ReplayScanner:
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index 2f95d9755237..1d43f85d5fbf 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -1,4 +1,5 @@
import uuid
+import datetime as dt
from collections.abc import Callable
from typing import Any
@@ -6,24 +7,33 @@ import pytest
from unittest.mock import AsyncMock, patch
from django.conf import settings
+from django.utils import timezone
from asgiref.sync import sync_to_async
from parameterized import parameterized
-from temporalio.client import ScheduleOverlapPolicy
+from temporalio.client import ScheduleOverlapPolicy, WorkflowExecutionStatus
from temporalio.common import SearchAttributePair, TypedSearchAttributes
from temporalio.exceptions import ApplicationError
+from temporalio.service import RPCError, RPCStatusCode
from posthog.models import Organization, Team
from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_FINGERPRINT_KEY
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.temporal.activities import (
delete_scanner_schedule_activity,
list_enabled_scanners_activity,
list_scanner_schedules_activity,
+ reap_orphaned_observations_activity,
upsert_scanner_schedule_activity,
)
from products.replay_vision.backend.temporal.constants import (
+ OBSERVATION_ORPHAN_CUTOFF,
RECONCILER_EXECUTION_TIMEOUT,
RECONCILER_INTERVAL,
RECONCILER_SCHEDULE_ID,
@@ -199,15 +209,23 @@ class _ReconcileMocks:
existing: list[ScannerScheduleEntry],
upsert_errors_for_ids: set[uuid.UUID] | None = None,
delete_errors_for_ids: set[uuid.UUID] | None = None,
+ reap_error: Exception | None = None,
) -> None:
self.enabled = enabled
self.existing = existing
self.upsert_errors = upsert_errors_for_ids or set()
self.delete_errors = delete_errors_for_ids or set()
+ self.reap_error = reap_error
+ self.reap_calls = 0
self.upserted: list[uuid.UUID] = []
self.deleted: list[uuid.UUID] = []
async def execute_activity(self, activity_fn: Any, activity_input: Any = None, **_: Any) -> Any:
+ if activity_fn is reap_orphaned_observations_activity:
+ self.reap_calls += 1
+ if self.reap_error:
+ raise self.reap_error
+ return 0
if activity_fn is list_enabled_scanners_activity:
return self.enabled
if activity_fn is list_scanner_schedules_activity:
@@ -227,7 +245,11 @@ class _ReconcileMocks:
async def _run_reconcile(mocks: _ReconcileMocks):
# `workflow.logger` reaches into the workflow runtime, which isn't set up here.
- fake_logger = type("Logger", (), {"warning": staticmethod(lambda *_a, **_kw: None)})()
+ fake_logger = type(
+ "Logger",
+ (),
+ {"warning": staticmethod(lambda *_a, **_kw: None), "exception": staticmethod(lambda *_a, **_kw: None)},
+ )()
with (
patch("temporalio.workflow.execute_activity", side_effect=mocks.execute_activity),
patch("temporalio.workflow.logger", fake_logger),
@@ -353,6 +375,22 @@ async def test_reconcile_workflow(_name: str, build: Callable[[], tuple[_Reconci
assert result.failed_delete == expected.get("failed_delete", [])
+async def test_reconcile_workflow_survives_reap_failure() -> None:
+ # The reaper is best-effort: its failure must not block schedule sync (and vice versa — it runs first).
+ sid = uuid.uuid4()
+ fp = compute_schedule_fingerprint({"sample_rate": 0.5})
+ mocks = _ReconcileMocks(
+ enabled=_enabled((sid, 1, fp)),
+ existing=_existing(),
+ reap_error=RuntimeError("reap boom"),
+ )
+ result = await _run_reconcile(mocks)
+ assert mocks.reap_calls == 1
+ assert result.upserted == [sid]
+ assert result.failed_upsert == []
+
+
def test_reconcile_parse_inputs() -> None:
assert ReconcileScannerSchedulesWorkflow.parse_inputs([]) == ReconcileScannerSchedulesInputs()
@@ -384,3 +422,104 @@ async def test_create_reconciler_schedule_routes_by_existence(_name: str, exists
assert called.call_args.kwargs["trigger_immediately"] is True
else:
assert "trigger_immediately" not in called.call_args.kwargs
+
+
+class _StubReapHandle:
+ def __init__(self, outcome: str) -> None:
+ self._outcome = outcome
+
+ async def describe(self):
+ if self._outcome == "not_found":
+ raise RPCError("not found", RPCStatusCode.NOT_FOUND, b"")
+ if self._outcome == "rpc_error":
+ raise RPCError("boom", RPCStatusCode.INTERNAL, b"")
+
+ class _Desc:
+ status = WorkflowExecutionStatus.RUNNING if self._outcome == "open" else WorkflowExecutionStatus.TIMED_OUT
+
+ return _Desc()
+
+
+class _StubReapTemporal:
+ def __init__(self, outcomes: dict[str, str]) -> None:
+ self._outcomes = outcomes
+ self.described: list[str] = []
+
+ def get_workflow_handle(self, workflow_id: str) -> _StubReapHandle:
+ self.described.append(workflow_id)
+ return _StubReapHandle(self._outcomes[workflow_id])
+
+
+def _make_observation(scanner: ReplayScanner, *, session_id: str, status: str, workflow_id: str, age: dt.timedelta):
+ observation = ReplayObservation.objects.create(
+ scanner=scanner,
+ team=scanner.team,
+ session_id=session_id,
+ status=status,
+ workflow_id=workflow_id,
+ scanner_snapshot={"scanner_type": "monitor"},
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+ ReplayObservation.objects.filter(pk=observation.pk).update(created_at=timezone.now() - age)
+ return observation
+
+
[email protected]_db(transaction=True)
+async def test_reap_orphaned_observations_activity(org_team) -> None:
+ _, team = org_team
+ scanner = await sync_to_async(_make_scanner)(team)
+ stale = OBSERVATION_ORPHAN_CUTOFF + dt.timedelta(minutes=5)
+
+ def _setup() -> dict[str, ReplayObservation]:
+ return {
+ "pending_gone": _make_observation(
+ scanner, session_id="s-pending", status=ObservationStatus.PENDING, workflow_id="wf-gone-1", age=stale
+ ),
+ "running_timed_out": _make_observation(
+ scanner, session_id="s-running", status=ObservationStatus.RUNNING, workflow_id="wf-timed-out", age=stale
+ ),
+ "no_workflow_id": _make_observation(
+ scanner, session_id="s-no-wf", status=ObservationStatus.PENDING, workflow_id="", age=stale
+ ),
+ # A re-trigger reused the deterministic workflow id and reclaimed this old row — hands off.
+ "reclaimed_by_live_run": _make_observation(
+ scanner, session_id="s-live", status=ObservationStatus.PENDING, workflow_id="wf-open", age=stale
+ ),
+ # Temporal couldn't answer — skip rather than reap on uncertainty.
+ "describe_error": _make_observation(
+ scanner, session_id="s-err", status=ObservationStatus.RUNNING, workflow_id="wf-err", age=stale
+ ),
+ "too_fresh": _make_observation(
+ scanner,
+ session_id="s-fresh",
+ status=ObservationStatus.RUNNING,
+ workflow_id="wf-gone-2",
+ age=dt.timedelta(minutes=30),
+ ),
+ }
+
+ rows = await sync_to_async(_setup)()
+ temporal = _StubReapTemporal(
+ {"wf-gone-1": "not_found", "wf-timed-out": "closed", "wf-open": "open", "wf-err": "rpc_error"}
+ )
+
+ with patch(
+ "products.replay_vision.backend.temporal.activities.reap_orphaned_observations.async_connect",
+ AsyncMock(return_value=temporal),
+ ):
+ reaped = await reap_orphaned_observations_activity()
+
+ assert reaped == 3
+ statuses = {
+ key: await sync_to_async(lambda o=obs: ReplayObservation.objects.get(pk=o.pk))() for key, obs in rows.items()
+ }
+ for key in ("pending_gone", "running_timed_out", "no_workflow_id"):
+ assert statuses[key].status == ObservationStatus.FAILED, key
+ assert statuses[key].error_reason.startswith("orphaned:"), key
+ assert statuses[key].completed_at is not None, key
+ for key in ("reclaimed_by_live_run", "describe_error", "too_fresh"):
+ assert statuses[key].status == rows[key].status, key
+ assert statuses[key].completed_at is None, key
+ # The fresh row never reaches Temporal; the empty-workflow-id row is reaped without a describe.
+ assert set(temporal.described) == {"wf-gone-1", "wf-timed-out", "wf-open", "wf-err"}
diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
index f8548f1c0c0a..0181cb812ae8 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -15,11 +15,13 @@ from posthog.test.persons import create_person
from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
- SAMPLE_RATE_PRECISION,
SETTLE_INTERVAL,
ScannerCandidateQuery,
)
-from products.replay_vision.backend.queries.scanner_volume_estimate import estimate_scanner_session_volume
+from products.replay_vision.backend.queries.scanner_volume_estimate import (
+ ESTIMATE_WINDOW_DAYS,
+ estimate_scanner_session_volume,
+)
_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -34,6 +36,7 @@ def _make_query(**kwargs) -> ScannerCandidateQuery:
query=kwargs.pop("query", RecordingsQuery()),
last_swept_at=kwargs.pop("last_swept_at", _NOW - dt.timedelta(hours=1)),
sampling_rate=kwargs.pop("sampling_rate", 1.0),
+ sampling_salt=kwargs.pop("sampling_salt", "scanner-1"),
**kwargs,
)
@@ -109,23 +112,37 @@ def test_sampling_predicate_passthrough_at_full_rate():
assert q._sampling_predicate() is None
-def test_sampling_predicate_emits_false_at_zero():
- q = _make_query(sampling_rate=0.0)
[email protected]("rate", [0.0, 0.00004])
+def test_sampling_predicate_emits_false_below_one_bucket(rate):
+ q = _make_query(sampling_rate=rate)
expr = q._sampling_predicate()
assert isinstance(expr, ast.Constant) and expr.value is False
-def test_sampling_predicate_emits_modulo_compare_at_partial_rate():
- q = _make_query(sampling_rate=0.25)
+ "rate, expected_threshold",
+ [
+ (0.25, 2500),
+ # 0.29 * 10_000 is 2899.999… in floats; truncation used to shave a bucket.
+ (0.29, 2900),
+ (0.0001, 1),
+ ],
+)
+def test_sampling_predicate_emits_modulo_compare_at_partial_rate(rate, expected_threshold):
+ q = _make_query(sampling_rate=rate)
expr = q._sampling_predicate()
assert isinstance(expr, ast.CompareOperation)
assert expr.op == ast.CompareOperationOp.Lt
assert isinstance(expr.right, ast.Constant)
- assert expr.right.value == int(0.25 * SAMPLE_RATE_PRECISION)
+ assert expr.right.value == expected_threshold
modulo = expr.left
assert isinstance(modulo, ast.Call) and modulo.name == "modulo"
city = modulo.args[0]
assert isinstance(city, ast.Call) and city.name == "cityHash64"
+ concat = city.args[0]
+ assert isinstance(concat, ast.Call) and concat.name == "concat"
+ # The per-scanner salt makes scanners draw independent samples instead of the identical session subset.
+ assert isinstance(concat.args[1], ast.Constant) and concat.args[1].value == "scanner-1"
# Integration: actual ClickHouse query.
@@ -380,6 +397,40 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
assert estimate.matched_sessions == 1
+ @pytest.mark.django_db
+ def test_volume_estimate_window_is_exactly_30_days(self, team) -> None:
+ # A relative "-30d" date_from truncates to start-of-day, counting up to 31 days against the /30 divisor.
+ bound = _NOW - dt.timedelta(days=ESTIMATE_WINDOW_DAYS)
+ self._produce(
+ team.id,
+ "same-day-but-outside",
+ bound - dt.timedelta(hours=6, seconds=60),
+ bound - dt.timedelta(hours=6),
+ active_milliseconds=30_000,
+ )
+ self._produce(
+ team.id,
+ "inside",
+ _NOW - dt.timedelta(days=2),
+ _NOW - dt.timedelta(days=2) + dt.timedelta(seconds=60),
+ active_milliseconds=30_000,
+ )
+
+ estimate = estimate_scanner_session_volume(team=team, query=RecordingsQuery())
+
+ assert estimate.matched_sessions == 1
+
+ @pytest.mark.django_db
+ def test_volume_estimate_divisor_stays_full_for_old_but_quiet_teams(self, team) -> None:
+ # The bounded earliest-recording probe must not shrink the divisor for teams older than the window.
+ old = _NOW - dt.timedelta(days=40)
+ self._produce(team.id, "old-session", old, old + dt.timedelta(seconds=60), active_milliseconds=30_000)
+
+ estimate = estimate_scanner_session_volume(team=team, query=RecordingsQuery())
+
+ assert estimate.matched_sessions == 0
+ assert estimate.effective_window_days == ESTIMATE_WINDOW_DAYS
+
@pytest.mark.django_db
def test_filter_test_accounts_excludes_internal_users(self, team) -> None:
# test_account_filters are exclusion-style — the operator picks the accounts to drop.
@@ -554,6 +605,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
last_swept_at: dt.datetime,
query: RecordingsQuery | None = None,
sampling_rate: float = 1.0,
+ sampling_salt: str = "scanner-1",
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
last_seen_session_id: str | None = None,
):
@@ -562,6 +614,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
query=query if query is not None else RecordingsQuery(),
last_swept_at=last_swept_at,
sampling_rate=sampling_rate,
+ sampling_salt=sampling_salt,
candidate_limit=candidate_limit,
last_seen_session_id=last_seen_session_id,
).run()
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 4dc96ab6a3bd..ab71549a5b03 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -15,7 +15,12 @@ from google.genai.errors import APIError
from parameterized import parameterized
from prometheus_client import REGISTRY
from structlog.testing import capture_logs
-from temporalio.exceptions import ActivityError, ApplicationError
+from temporalio.exceptions import (
+ ActivityError,
+ ApplicationError,
+ TimeoutError as TemporalTimeoutError,
+ TimeoutType,
+)
from posthog.schema import ReplayVisionScannerFindingSignalInput
@@ -42,10 +47,7 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider im
)
from products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activity
from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity
-from products.replay_vision.backend.temporal.activities.embed_observation import (
- embed_observation_activity,
- embed_summarizer_observation_activity,
-)
+from products.replay_vision.backend.temporal.activities.embed_observation import embed_observation_activity
from products.replay_vision.backend.temporal.activities.emit_classifier_tags import emit_classifier_tags_activity
from products.replay_vision.backend.temporal.activities.emit_observation_event import emit_observation_event_activity
from products.replay_vision.backend.temporal.activities.emit_observation_signal import (
@@ -90,7 +92,6 @@ from products.replay_vision.backend.temporal.types import (
CreateObservationInputs,
CreateObservationOutput,
EmbedObservationInputs,
- EmbedSummarizerObservationInputs,
EmitClassifierTagsInputs,
EmitObservationSignalInputs,
EnsureSessionAssetInputs,
@@ -104,14 +105,36 @@ from products.replay_vision.backend.temporal.types import (
ScannerCallOutput,
ScannerLlmInputs,
ScannerResult,
+ ScannerSnapshot,
SessionMetadata,
UploadedVideo,
)
-from products.replay_vision.backend.temporal.workflow import _extract_kind_for_type, _root_cause_message
+from products.replay_vision.backend.temporal.workflow import (
+ _activity_timeout_kind,
+ _extract_kind_for_type,
+ _root_cause_message,
+)
from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
from products.signals.backend.models import SignalSourceConfig
+def test_scanner_snapshot_loads_rows_with_retired_model_and_provider_ids() -> None:
+ snapshot = ScannerSnapshot.load_for(
+ uuid.uuid4(),
+ {
+ "name": "old-scanner",
+ "scanner_type": "monitor",
+ "scanner_version": 1,
+ "model": "gemini-1.0-flash-retired-preview",
+ "provider": "hooli",
+ "emits_signals": False,
+ "scanner_config": {"prompt": "p"},
+ },
+ )
+ assert snapshot.model == "gemini-1.0-flash-retired-preview"
+ assert snapshot.provider == "hooli"
+
+
def _make_scanner(**overrides) -> ReplayScanner:
org = Organization.objects.create(name="vision-test-org")
team = Team.objects.create(organization=org, name="vision-test-team")
@@ -213,6 +236,36 @@ class TestCreateObservationActivity:
existing.refresh_from_db()
assert existing.workflow_id != "wf-second"
+ @pytest.mark.parametrize(
+ "status, completed_at, expect_reclaimed",
+ [
+ pytest.param(ObservationStatus.PENDING, None, True, id="own_pending_insert_is_reclaimed"),
+ pytest.param(ObservationStatus.FAILED, timezone.now(), False, id="own_terminal_row_is_not_reclaimed"),
+ ],
+ )
+ def test_unique_conflict_with_own_workflow_id(
+ self, status: str, completed_at: dt.datetime | None, expect_reclaimed: bool
+ ) -> None:
+ # A lost-result retry hits the UNIQUE constraint on its own insert; disowning it strands the row in `pending`.
+ scanner = _make_scanner()
+ existing = _make_observation(
+ scanner, session_id="sess-retry", workflow_id="wf-retry", status=status, completed_at=completed_at
+ )
+
+ result = create_observation_activity(
+ CreateObservationInputs(
+ scanner_id=scanner.id,
+ team_id=scanner.team_id,
+ session_id="sess-retry",
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ triggered_by_user_id=None,
+ workflow_id="wf-retry",
+ )
+ )
+
+ assert result.observation_id == existing.id
+ assert result.was_created is expect_reclaimed
+
def test_propagates_non_unique_integrity_errors(self) -> None:
# FK/CHECK violations must surface as activity failures, not silently fall into the dedup path.
scanner = _make_scanner()
@@ -1385,12 +1438,13 @@ async def test_apply_scanner_workflow_drives_full_success_pipeline() -> None:
assert activity_order[:2] == [create_observation_activity, mark_observation_running_activity]
# fetch + ensure_asset run in parallel — order between them is non-deterministic.
assert set(activity_order[2:4]) == {fetch_session_events_activity, ensure_session_asset_activity}
+ # Success is persisted before any downstream emission so a late transient failure can't discard the result.
assert activity_order[4:] == [
upload_video_to_gemini_activity,
call_scanner_provider_activity,
- embed_observation_activity,
- emit_observation_event_activity,
mark_observation_succeeded_activity,
+ emit_observation_event_activity,
+ embed_observation_activity,
cleanup_gemini_file_activity,
]
assert len(mocks.child_calls) == 1
@@ -1490,6 +1544,58 @@ async def test_apply_scanner_workflow_succeeds_even_when_cleanup_fails() -> None
assert cleanup_gemini_file_activity in called
+async def test_apply_scanner_workflow_stays_succeeded_when_post_success_emissions_fail() -> None:
+ # Once the result is persisted, event/embedding outages must not demote the observation to FAILED.
+ new_observation_id = uuid.uuid4()
+ 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),
+ upload_video_to_gemini_activity: UploadedVideo(
+ file_uri="gemini://files/x", mime_type="video/mp4", gemini_file_name="files/x"
+ ),
+ call_scanner_provider_activity: ScannerCallOutput(
+ model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9),
+ ),
+ },
+ activity_errors={
+ emit_observation_event_activity: RuntimeError("kafka down"),
+ embed_observation_activity: RuntimeError("embedding service down"),
+ },
+ )
+
+ await _run_workflow(_build_inputs(session_id="sess-flaky"), mocks)
+
+ called = {fn for fn, _ in mocks.activity_calls}
+ assert mark_observation_succeeded_activity in called
+ assert emit_observation_event_activity in called
+ assert embed_observation_activity in called
+ assert mark_observation_failed_activity not in called
+
+
+async def test_apply_scanner_workflow_marks_failed_when_mark_running_fails() -> None:
+ # An exhausted mark_running must land the row in FAILED, not strand it in PENDING.
+ new_observation_id = uuid.uuid4()
+ mocks = _WorkflowMocks(
+ activity_results={
+ create_observation_activity: CreateObservationOutput(
+ observation_id=new_observation_id, was_created=True, scanner_type=ScannerType.MONITOR
+ ),
+ },
+ activity_errors={mark_observation_running_activity: ApplicationError("db down", non_retryable=True)},
+ )
+
+ with pytest.raises(ApplicationError, match="db down"):
+ await _run_workflow(_build_inputs(session_id="sess-db-down"), mocks)
+
+ failed_input = next(arg for fn, arg in mocks.activity_calls if fn is mark_observation_failed_activity)
+ assert failed_input.observation_id == new_observation_id
+
+
@pytest.mark.asyncio
async def test_apply_scanner_workflow_exits_when_create_returns_was_created_false() -> None:
mocks = _WorkflowMocks(
@@ -1661,32 +1767,6 @@ async def test_embed_observation_emits_reasoning_for_non_summarizer(_name, model
assert metadata[key] == value
-async def test_embed_summarizer_observation_alias_still_emits_facets() -> None:
- # Back-compat: the renamed activity keeps the old name registered so summarizer workflows already in flight
- # at deploy time resolve. It takes the old input shape and emits facets with the old (scanner-less) metadata.
- out = SummarizerOutput(
- title="Investigation",
- summary="User browsed dashboards.",
- intent="Investigate slow query response",
- outcome="No issue reproduced.",
- keywords=["dashboard"],
- confidence=0.8,
- )
- inputs = EmbedSummarizerObservationInputs(
- team_id=99, session_id="sess-legacy", observation_id=uuid.uuid4(), summarizer_output=out
- )
- with patch(
- "products.replay_vision.backend.temporal.activities.embed_observation.emit_embedding_request"
- ) as mock_emit:
- await embed_summarizer_observation_activity(inputs)
-
- assert [call.kwargs["rendering"] for call in mock_emit.call_args_list] == ["intent", "outcome", "keywords"]
- metadata = mock_emit.call_args_list[0].kwargs["metadata"]
- assert metadata["session_id"] == "sess-legacy"
- assert "scanner_id" not in metadata # old metadata shape, pre-rename
-
-
@pytest.mark.asyncio
async def test_embed_observation_raises_propagates_failure() -> None:
inputs = EmbedObservationInputs(
@@ -1818,9 +1898,9 @@ async def test_apply_scanner_workflow_dispatches_summarizer_embedding_when_facet
activity_order = [fn for fn, _ in mocks.activity_calls]
call_idx = activity_order.index(call_scanner_provider_activity)
- assert activity_order[call_idx + 1] == embed_observation_activity
+ assert activity_order[call_idx + 1] == mark_observation_succeeded_activity
assert activity_order[call_idx + 2] == emit_observation_event_activity
- assert activity_order[call_idx + 3] == mark_observation_succeeded_activity
+ assert activity_order[call_idx + 3] == embed_observation_activity
assert emit_classifier_tags_activity not in activity_order
embed_input = next(arg for fn, arg in mocks.activity_calls if fn is embed_observation_activity)
@@ -1872,13 +1952,13 @@ async def test_apply_scanner_workflow_dispatches_classifier_side_effect() -> Non
await _run_workflow(_build_inputs(session_id="sess-cls", team_id=99), mocks, workflow_id="wf-cls")
- # Classifiers embed their reasoning AND fan out tags; embedding runs first.
+ # Classifiers embed their reasoning AND fan out tags; both run after success is persisted, embedding first.
activity_order = [fn for fn, _ in mocks.activity_calls]
call_idx = activity_order.index(call_scanner_provider_activity)
- assert activity_order[call_idx + 1] == embed_observation_activity
- assert activity_order[call_idx + 2] == emit_classifier_tags_activity
- assert activity_order[call_idx + 3] == emit_observation_event_activity
- assert activity_order[call_idx + 4] == mark_observation_succeeded_activity
+ assert activity_order[call_idx + 1] == mark_observation_succeeded_activity
+ assert activity_order[call_idx + 2] == emit_observation_event_activity
+ assert activity_order[call_idx + 3] == embed_observation_activity
+ assert activity_order[call_idx + 4] == emit_classifier_tags_activity
embed_input = next(arg for fn, arg in mocks.activity_calls if fn is embed_observation_activity)
assert embed_input.model_output == model_output
@@ -1914,36 +1994,6 @@ async def test_apply_scanner_workflow_embeds_monitor_reasoning_without_classifie
assert embed_input.model_output == model_output
-async def test_apply_scanner_workflow_marks_failed_when_side_effect_raises() -> None:
- new_observation_id = uuid.uuid4()
- side_effect_error = ApplicationError("embedding kafka down", non_retryable=True)
- mocks = _WorkflowMocks(
- activity_results={
- create_observation_activity: CreateObservationOutput(
- observation_id=new_observation_id,
- was_created=True,
- scanner_type=ScannerType.SUMMARIZER,
- ),
- ensure_session_asset_activity: EnsureSessionAssetOutput(asset_id=42),
- upload_video_to_gemini_activity: UploadedVideo(
- file_uri="gemini://files/x", mime_type="video/mp4", gemini_file_name="files/x"
- ),
- call_scanner_provider_activity: ScannerCallOutput(model_output=_summarizer_output_with_facets()),
- },
- activity_errors={embed_observation_activity: side_effect_error},
- )
-
- with pytest.raises(ApplicationError, match="embedding kafka down"):
- await _run_workflow(_build_inputs(session_id="sess-sum-fail"), mocks)
-
- called = [fn for fn, _ in mocks.activity_calls]
- assert emit_observation_event_activity not in called
- 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)
@@ -1988,6 +2038,34 @@ 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"
+ @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),
+ ("provider_call_non_timeout", "call_scanner_provider_activity", False, None),
+ ]
+ )
+ def test_activity_timeout_kind_maps_provider_activity_timeouts(
+ self, _label: str, activity_type: str, timed_out: bool, expected: str | None
+ ) -> None:
+ err = ActivityError(
+ "activity failed",
+ scheduled_event_id=1,
+ started_event_id=2,
+ identity="worker",
+ activity_type=activity_type,
+ activity_id="a1",
+ retry_state=None,
+ )
+ if timed_out:
+ err.__cause__ = TemporalTimeoutError(
+ "timed out", type=TimeoutType.START_TO_CLOSE, last_heartbeat_details=[]
+ )
+ else:
+ err.__cause__ = ApplicationError("boom", type="RuntimeError")
+ assert _activity_timeout_kind(err) == expected
+
_DURATION_MS = 600_000 # 10-minute recording for the citation tests
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 03241fd38d10..f27c9625a77b 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -399,26 +399,6 @@ export const ScannerTypeEnumApi = {
Summarizer: 'summarizer',
} as const
-/**
- * * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
- */
-export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]
-
-export const ScannerModelEnumApi = {
- Gemini3FlashPreview: 'gemini-3-flash-preview',
- Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
-} as const
-
-/**
- * * `google` - Google
- */
-export type ScannerProviderEnumApi = (typeof ScannerProviderEnumApi)[keyof typeof ScannerProviderEnumApi]
-
-export const ScannerProviderEnumApi = {
- Google: 'google',
-} as const
-
/**
* Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
*/
@@ -434,15 +414,10 @@ export interface ScannerSnapshotApi {
scanner_type: ScannerTypeEnumApi
/** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
scanner_version: number
- /** Concrete model that ran the observation.
- *
- * * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
- model: ScannerModelEnumApi
- /** Concrete provider that ran the observation.
- *
- * * `google` - Google */
- provider: ScannerProviderEnumApi
+ /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
+ model: string
+ /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
+ provider: string
/** Whether the observation was run with Signal emission enabled. */
emits_signals: boolean
/** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
@@ -487,7 +462,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. */
+ /** 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. */
readonly error_reason: string
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string
@@ -555,6 +530,26 @@ export interface VisionQuotaApi {
readonly projected_monthly_observations: number
}
+/**
+ * * `google` - Google
+ */
+export type ScannerProviderEnumApi = (typeof ScannerProviderEnumApi)[keyof typeof ScannerProviderEnumApi]
+
+export const ScannerProviderEnumApi = {
+ Google: 'google',
+} as const
+
+/**
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
+ */
+export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]
+
+export const ScannerModelEnumApi = {
+ Gemini3FlashPreview: 'gemini-3-flash-preview',
+ Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
+} as const
+
export interface ReplayScannerApi {
readonly id: string
/**
@@ -562,7 +557,10 @@ export interface ReplayScannerApi {
* @maxLength 255
*/
name: string
- /** Free-form description shown in the scanner management UI. */
+ /**
+ * Free-form description shown in the scanner management UI.
+ * @maxLength 1000
+ */
description?: string
/** What the scanner does: monitor, classifier, scorer, or summarizer.
*
@@ -576,7 +574,7 @@ export interface ReplayScannerApi {
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown
/**
- * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
* @minimum 0
* @maximum 1
*/
@@ -625,7 +623,10 @@ export interface PatchedReplayScannerApi {
* @maxLength 255
*/
name?: string
- /** Free-form description shown in the scanner management UI. */
+ /**
+ * Free-form description shown in the scanner management UI.
+ * @maxLength 1000
+ */
description?: string
/** What the scanner does: monitor, classifier, scorer, or summarizer.
*
@@ -639,7 +640,7 @@ export interface PatchedReplayScannerApi {
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown
/**
- * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
* @minimum 0
* @maximum 1
*/
@@ -963,7 +964,7 @@ export type VisionObservationsListParams = {
*/
offset?: number
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string
/**
@@ -1017,7 +1018,7 @@ export type VisionScannersObservationsListParams = {
*/
offset?: number
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string
/**
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index 81c3b8c81d80..8b9fdca614c6 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -224,6 +224,8 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({
*/
export const visionScannersCreateBodyNameMax = 255
+export const visionScannersCreateBodyDescriptionMax = 1000
+
export const visionScannersCreateBodySamplingRateMin = 0
export const visionScannersCreateBodySamplingRateMax = 1
@@ -232,7 +234,11 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.string()
.max(visionScannersCreateBodyNameMax)
.describe('Human-readable scanner name. Unique within the team.'),
- description: zod.string().optional().describe('Free-form description shown in the scanner management UI.'),
+ description: zod
+ .string()
+ .max(visionScannersCreateBodyDescriptionMax)
+ .optional()
+ .describe('Free-form description shown in the scanner management UI.'),
scanner_type: zod
.enum(['monitor', 'classifier', 'scorer', 'summarizer'])
.describe(
@@ -257,7 +263,9 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.min(visionScannersCreateBodySamplingRateMin)
.max(visionScannersCreateBodySamplingRateMax)
.optional()
- .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ .describe(
+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
@@ -288,6 +296,8 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
*/
export const visionScannersPartialUpdateBodyNameMax = 255
+export const visionScannersPartialUpdateBodyDescriptionMax = 1000
+
export const visionScannersPartialUpdateBodySamplingRateMin = 0
export const visionScannersPartialUpdateBodySamplingRateMax = 1
@@ -297,7 +307,11 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(visionScannersPartialUpdateBodyNameMax)
.optional()
.describe('Human-readable scanner name. Unique within the team.'),
- description: zod.string().optional().describe('Free-form description shown in the scanner management UI.'),
+ description: zod
+ .string()
+ .max(visionScannersPartialUpdateBodyDescriptionMax)
+ .optional()
+ .describe('Free-form description shown in the scanner management UI.'),
scanner_type: zod
.enum(['monitor', 'classifier', 'scorer', 'summarizer'])
.describe(
@@ -324,7 +338,9 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(visionScannersPartialUpdateBodySamplingRateMin)
.max(visionScannersPartialUpdateBodySamplingRateMax)
.optional()
- .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ .describe(
+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'
+ ),
provider: zod
.enum(['google'])
.describe('\* `google` - Google')
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index 461af47308c7..ab936af4ede4 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -37,6 +37,7 @@ export type FailureKind =
| 'rasterization_failed'
| 'validation_failed'
| 'internal_error'
+ | 'orphaned'
const FAILURE_KINDS: Record<FailureKind, { label: string; description: string }> = {
provider_transient: {
@@ -62,6 +63,11 @@ const FAILURE_KINDS: Record<FailureKind, { label: string; description: string }>
label: 'Internal error',
description: 'An unexpected PostHog error occurred. Please contact support.',
},
+ orphaned: {
+ label: 'Interrupted',
+ description:
+ 'The analysis was interrupted before finishing and has been cleaned up. Run the scanner on this recording again if needed.',
+ },
}
export type ParsedReason<K extends string> = { kind: K; label: string; message: string }
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9c81eac4bdd5..032f1baeb8f5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32689,28 +32689,6 @@ export namespace Schemas {
Summarizer: 'summarizer',
} as const;
- /**
- * * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
- */
- export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];
-
-
- export const ScannerModelEnum = {
- Gemini3FlashPreview: 'gemini-3-flash-preview',
- Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
- } as const;
-
- /**
- * * `google` - Google
- */
- export type ScannerProviderEnum = typeof ScannerProviderEnum[keyof typeof ScannerProviderEnum];
-
-
- export const ScannerProviderEnum = {
- Google: 'google',
- } as const;
-
/**
* Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
*/
@@ -32726,15 +32704,10 @@ export namespace Schemas {
scanner_type: ScannerTypeEnum;
/** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
scanner_version: number;
- /** Concrete model that ran the observation.
- *
- * * `gemini-3-flash-preview` - Gemini 3 Flash
- * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite */
- model: ScannerModelEnum;
- /** Concrete provider that ran the observation.
- *
- * * `google` - Google */
- provider: ScannerProviderEnum;
+ /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
+ model: string;
+ /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
+ provider: string;
/** Whether the observation was run with Signal emission enabled. */
emits_signals: boolean;
/** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
@@ -32768,7 +32741,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. */
+ /** 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. */
readonly error_reason: string;
/** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
readonly workflow_id: string;
@@ -32819,6 +32792,28 @@ export namespace Schemas {
results: ReplayObservation[];
}
+ /**
+ * * `google` - Google
+ */
+ export type ScannerProviderEnum = typeof ScannerProviderEnum[keyof typeof ScannerProviderEnum];
+
+
+ export const ScannerProviderEnum = {
+ Google: 'google',
+ } as const;
+
+ /**
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.1-flash-lite-preview` - Gemini 3 Flash Lite
+ */
+ export type ScannerModelEnum = typeof ScannerModelEnum[keyof typeof ScannerModelEnum];
+
+
+ export const ScannerModelEnum = {
+ Gemini3FlashPreview: 'gemini-3-flash-preview',
+ Gemini31FlashLitePreview: 'gemini-3.1-flash-lite-preview',
+ } as const;
+
export interface ReplayScanner {
readonly id: string;
/**
@@ -32826,7 +32821,10 @@ export namespace Schemas {
* @maxLength 255
*/
name: string;
- /** Free-form description shown in the scanner management UI. */
+ /**
+ * Free-form description shown in the scanner management UI.
+ * @maxLength 1000
+ */
description?: string;
/** What the scanner does: monitor, classifier, scorer, or summarizer.
*
@@ -32840,7 +32838,7 @@ export namespace Schemas {
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown;
/**
- * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
* @minimum 0
* @maximum 1
*/
@@ -40463,7 +40461,10 @@ export namespace Schemas {
* @maxLength 255
*/
name?: string;
- /** Free-form description shown in the scanner management UI. */
+ /**
+ * Free-form description shown in the scanner management UI.
+ * @maxLength 1000
+ */
description?: string;
/** What the scanner does: monitor, classifier, scorer, or summarizer.
*
@@ -40477,7 +40478,7 @@ export namespace Schemas {
/** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
query?: unknown;
/**
- * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).
+ * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
* @minimum 0
* @maximum 1
*/
@@ -59845,7 +59846,7 @@ export namespace Schemas {
*/
offset?: number;
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string;
/**
@@ -59899,7 +59900,7 @@ export namespace Schemas {
*/
offset?: number;
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string;
/**
@@ -67543,7 +67544,7 @@ export namespace Schemas {
*/
offset?: number;
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string;
/**
@@ -67597,7 +67598,7 @@ export namespace Schemas {
*/
offset?: number;
/**
- * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.
+ * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
*/
order_by?: string;
/**
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 559dfb87720c..84910492b679 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -26,7 +26,7 @@ export const VisionObservationsListQueryParams = /* @__PURE__ */ zod.object({
.string()
.optional()
.describe(
- 'Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.'
+ 'Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.'
),
session_id: zod.string().describe('Session recording id to return observations for.'),
})
@@ -100,6 +100,8 @@ export const VisionScannersCreateParams = /* @__PURE__ */ zod.object({
export const visionScannersCreateBodyNameMax = 255
+export const visionScannersCreateBodyDescriptionMax = 1000
+
export const visionScannersCreateBodySamplingRateMin = 0
export const visionScannersCreateBodySamplingRateMax = 1
@@ -108,7 +110,11 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.string()
.max(visionScannersCreateBodyNameMax)
.describe('Human-readable scanner name. Unique within the team.'),
- description: zod.string().optional().describe('Free-form description shown in the scanner management UI.'),
+ description: zod
+ .string()
+ .max(visionScannersCreateBodyDescriptionMax)
+ .optional()
+ .describe('Free-form description shown in the scanner management UI.'),
scanner_type: zod
.enum(['monitor', 'classifier', 'scorer', 'summarizer'])
.describe(
@@ -133,7 +139,9 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.object({
.min(visionScannersCreateBodySamplingRateMin)
.max(visionScannersCreateBodySamplingRateMax)
.optional()
- .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ .describe(
+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'
+ ),
provider: zod
.enum(['google'])
.describe('* `google` - Google')
@@ -185,6 +193,8 @@ export const VisionScannersPartialUpdateParams = /* @__PURE__ */ zod.object({
export const visionScannersPartialUpdateBodyNameMax = 255
+export const visionScannersPartialUpdateBodyDescriptionMax = 1000
+
export const visionScannersPartialUpdateBodySamplingRateMin = 0
export const visionScannersPartialUpdateBodySamplingRateMax = 1
@@ -194,7 +204,11 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(visionScannersPartialUpdateBodyNameMax)
.optional()
.describe('Human-readable scanner name. Unique within the team.'),
- description: zod.string().optional().describe('Free-form description shown in the scanner management UI.'),
+ description: zod
+ .string()
+ .max(visionScannersPartialUpdateBodyDescriptionMax)
+ .optional()
+ .describe('Free-form description shown in the scanner management UI.'),
scanner_type: zod
.enum(['monitor', 'classifier', 'scorer', 'summarizer'])
.describe(
@@ -221,7 +235,9 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(visionScannersPartialUpdateBodySamplingRateMin)
.max(visionScannersPartialUpdateBodySamplingRateMax)
.optional()
- .describe('0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling).'),
+ .describe(
+ '0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.'
+ ),
provider: zod
.enum(['google'])
.describe('* `google` - Google')
@@ -302,7 +318,7 @@ export const VisionScannersObservationsListQueryParams = /* @__PURE__ */ zod.obj
.string()
.optional()
.describe(
- 'Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending.'
+ 'Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.'
),
recording_subject: zod
.string()