:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): render thumbnails on the main rasterizer (#105099)
Tue Haulund582f782d694a
diff --git a/nodejs/src/session-replay/recording-rasterizer/storage.ts b/nodejs/src/session-replay/recording-rasterizer/storage.tsindex 4ef548ab7234..7cd84aa54953 100644--- a/nodejs/src/session-replay/recording-rasterizer/storage.ts+++ b/nodejs/src/session-replay/recording-rasterizer/storage.ts@@ -131,7 +131,7 @@ export async function downloadFromS3(bucket: string, key: string, localPath: strif (!res.Body) {throw new RasterizationError(`S3 object is empty: s3://${bucket}/${key}`, false, 'S3_DOWNLOAD_EMPTY')}- // Streamed, not buffered: the media worker reads several tens-of-megabytes MP4s at once.+ // Streamed, not buffered: thumbnail extraction reads several tens-of-megabytes MP4s at once.await pipeline(res.Body as Readable, fs.createWriteStream(localPath))} catch (err) {if (err instanceof RasterizationError) {diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 70e104b49ce2..444ddc2a6c96 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -1,7 +1,7 @@import osfrom posthog.settings.access import SECRET_KEY-from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TEST+from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUGfrom posthog.settings.utils import get_from_env, get_list, str_to_boolTEMPORAL_NAMESPACE: str = os.getenv("TEMPORAL_NAMESPACE", "default")@@ -304,12 +304,6 @@ LOGS_VOLUME_TICK_TASK_QUEUE = _set_temporal_task_queue(os.getenv("LOGS_VOLUME_TICK_TASK_QUEUE", "logs-volume-tick-task-queue"))RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process-# Replay Vision observation media (thumbnails, clips). Kept off the shared rasterization-# queue so media never competes with customer exports and session video summaries.-# Collapsed in dev, where a single rasterizer serves every queue: nothing polls the media-# queue locally, so the render would strand and the poster would never appear. Tests keep the-# split, because what they assert about routing is the production behaviour.-RASTERIZATION_MEDIA_TASK_QUEUE = RASTERIZATION_TASK_QUEUE if DEBUG and not TEST else "rasterization-media-task-queue"# Error tracking# Global on/off switch for auto-merging close fingerprints into their nearest issue.diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 96ba6bdbbfa1..d33f8c109515 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -122,7 +122,6 @@ from products.replay_vision.backend.temporal.estimates import create_replay_visifrom products.replay_vision.backend.temporal.gemini_cleanup_sweep import (create_replay_vision_gemini_cleanup_sweep_schedule,)-from products.replay_vision.backend.temporal.media_backfill import create_replay_vision_media_backfill_schedulefrom products.replay_vision.backend.temporal.read_meter import create_replay_vision_read_meter_schedulefrom products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedulefrom products.replay_vision.backend.temporal.search_suggestions import create_replay_vision_search_suggestions_schedule@@ -151,6 +150,12 @@ async def cleanup_sync_vectors_schedule(client: Client):await a_delete_schedule(client, "ai-sync-vectors-schedule")+async def cleanup_replay_vision_media_backfill_schedule(client: Client):+ """Retired: delete the Replay Vision poster backfill schedule, whose workflow no worker registers anymore."""+ if await a_schedule_exists(client, "replay-vision-media-backfill-schedule"):+ await a_delete_schedule(client, "replay-vision-media-backfill-schedule")++async def create_run_quota_limiting_schedule(client: Client):"""Create or update the schedule for the RunQuotaLimitingWorkflow.@@ -898,6 +903,7 @@ async def create_error_tracking_recommendations_refresh_schedule(client: Client)schedules = [cleanup_sync_vectors_schedule,+ cleanup_replay_vision_media_backfill_schedule,create_run_quota_limiting_schedule,create_schedule_due_billing_alert_checks_schedule,create_context_layer_dream_schedule,@@ -975,7 +981,6 @@ if settings.CLOUD_DEPLOYMENT:# Gemini uploads only happen in cloud; each sweep reaps only the files tracked in this# deployment's own Redis index, so per-deployment scoping is inherent.schedules.append(create_replay_vision_gemini_cleanup_sweep_schedule)- schedules.append(create_replay_vision_media_backfill_schedule)schedules.append(create_run_usage_reports_schedule)schedules.append(create_finalize_usage_reports_schedule)if should_register_checkpoint_compaction_schedule():diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.pyindex edc7f0cf6fa3..12ba1c06b493 100644--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py@@ -451,13 +451,13 @@ def _activity_error() -> ActivityError:@pytest.mark.asyncio[email protected]("route_to_media", [False, True])-async def test_render_runs_on_the_requested_queue(route_to_media: bool):[email protected]("route_elsewhere", [False, True])+async def test_render_runs_on_the_requested_queue(route_elsewhere: bool):from django.conf import settingsfrom posthog.temporal.session_replay.rasterize_recording.types import RasterizationActivityInput- requested_queue = settings.RASTERIZATION_MEDIA_TASK_QUEUE if route_to_media else None+ requested_queue = "other-rasterization-task-queue" if route_elsewhere else Noneexpected_queue = requested_queue or settings.RASTERIZATION_TASK_QUEUErendered_on: list[str] = []@@ -495,7 +495,7 @@ async def test_render_runs_on_the_requested_queue(route_to_media: bool):# Both queues carry a render worker, so a mis-routed render still completes and the# assertion below names the wrong queue instead of hanging forever.Worker(env.client, task_queue=settings.RASTERIZATION_TASK_QUEUE, activities=[render_mocked]),- Worker(env.client, task_queue=settings.RASTERIZATION_MEDIA_TASK_QUEUE, activities=[render_mocked]),+ Worker(env.client, task_queue="other-rasterization-task-queue", activities=[render_mocked]),):await env.client.execute_workflow(RasterizeRecordingWorkflow.run,diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex b387086c9966..03f972d129eb 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -118,7 +118,8 @@ class ReplayObservation(UUIDModel):completed_at = models.DateTimeField(null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)- # The backfill sweep backs off on these; `db_default` because recording-api inserts this raw.+ # Unused since the media backfill sweep was removed: nothing writes them and nothing reads them. Dropped+ # in a follow-up migration, so do not build on them.media_render_attempts = models.PositiveSmallIntegerField(default=0, db_default=0)media_render_attempted_at = models.DateTimeField(null=True, blank=True)@@ -148,7 +149,7 @@ class ReplayObservation(UUIDModel):),# Serves the per-scanner list ordering and the prev/next-neighbor lookups (both order by created_at).models.Index(fields=["scanner", "created_at"], name="rlo_scanner_created_idx"),- # Serves the media backfill's cross-team walk; every other created_at index is prefixed.+ # Served the media backfill's cross-team walk, which is gone. Dropped in a follow-up migration.models.Index(fields=["-created_at"],name="rlo_succeeded_created_idx",diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex d127a5fece50..1abe8ba2c764 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -57,10 +57,6 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (ReplayVisionGeminiCleanupSweepWorkflow,sweep_gemini_files_activity,)-from products.replay_vision.backend.temporal.media_backfill import (- ReplayVisionMediaBackfillWorkflow,- find_media_backfill_candidates_activity,-)from products.replay_vision.backend.temporal.media_workflow import ObservationMediaWorkflowfrom products.replay_vision.backend.temporal.read_meter import MeterScannerReadsWorkflowfrom products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflow@@ -85,7 +81,6 @@ WORKFLOWS = [RefreshScannerEstimatesWorkflow,RefreshSearchSuggestionsWorkflow,ReplayVisionGeminiCleanupSweepWorkflow,- ReplayVisionMediaBackfillWorkflow,SweepScannerWorkflow,VisionAlertCheckWorkflow,]@@ -138,7 +133,6 @@ ACTIVITIES: list[Callable[..., Any]] = [reap_childless_inline_scanners_activity,reap_orphaned_observations_activity,sweep_gemini_files_activity,- find_media_backfill_candidates_activity,list_stale_search_suggestions_activity,refresh_scanner_search_suggestions_activity,]@@ -155,7 +149,6 @@ __all__ = ["RefreshScannerEstimatesWorkflow","RefreshSearchSuggestionsWorkflow","ReplayVisionGeminiCleanupSweepWorkflow",- "ReplayVisionMediaBackfillWorkflow","SweepScannerWorkflow","advance_scanner_watermark_activity","refresh_prompt_suggestion_activity",diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 0c7fd2c1bf82..3d71fc800b4a 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -75,7 +75,7 @@ from products.replay_vision.backend.temporal.network_tool import (from products.replay_vision.backend.temporal.scanners import scanner_from_snapshotfrom products.replay_vision.backend.temporal.scanners.base import (STEP_CORE,- STEP_MEDIA,+ STEP_MAX_OUTPUT_TOKENS,STEP_SIGNALS,TIMESTAMP_CITATION_RE,BaseScanner,@@ -646,9 +646,11 @@ async def _run_mission(await _delete_video_cache(cache_client, cache.name)finalized, signals = scanner.assemble(step_outputs)- thumbnail_video_s = getattr(step_outputs.get(STEP_MEDIA), "thumbnail_t", None)return _MissionOutcome(- finalized=finalized, signals=signals, verification=verification, thumbnail_video_s=thumbnail_video_s+ finalized=finalized,+ signals=signals,+ verification=verification,+ thumbnail_video_s=getattr(step_outputs.get(STEP_CORE), "thumbnail_t", None),)@@ -1045,7 +1047,7 @@ def _step_config(# Return thought summaries so the model's reasoning is visible in LLM analytics. Answer parsing is# unaffected (`response.text` skips thought parts); models with thinking off just return none."thinking_config": types.ThinkingConfig(include_thoughts=True),- "max_output_tokens": step.max_output_tokens,+ "max_output_tokens": STEP_MAX_OUTPUT_TOKENS,}if not allow_tools:return types.GenerateContentConfig(**kwargs) # inline, no tool to call — the model must answer nowdiff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.pyindex cdc3174a417a..89fb46cc3d28 100644--- a/products/replay_vision/backend/temporal/activities/observation_media.py+++ b/products/replay_vision/backend/temporal/activities/observation_media.py@@ -4,7 +4,6 @@ from uuid import uuid4from django.conf import settingsfrom django.db import IntegrityError, transaction-from django.db.models import Ffrom django.utils.timezone import nowimport structlog@@ -90,12 +89,6 @@ async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs))if observation is None:raise ApplicationError(f"Observation {media_inputs.observation_id} is gone", non_retryable=True)- # Stamped once per render, live or backfilled, so the sweep can back off a failing one. A retry of- # this activity is the same render, and counting it would spend the sweep's budget of three on one.- if (activity.info().attempt if activity.in_activity() else 1) == 1:- await ReplayObservation.objects.filter(pk=media_inputs.observation_id, team_id=media_inputs.team_id).aupdate(- media_render_attempts=F("media_render_attempts") + 1, media_render_attempted_at=now()- )scanner_result = observation or {}clock = video_clock_from_export_context(context)video_time_s = _pick_video_time_s(media_inputs, scanner_result.get("model_output"), clock, duration_s)diff --git a/products/replay_vision/backend/temporal/media_backfill/__init__.py b/products/replay_vision/backend/temporal/media_backfill/__init__.pydeleted file mode 100644index dca82344730e..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-from products.replay_vision.backend.temporal.media_backfill.activities import find_media_backfill_candidates_activity-from products.replay_vision.backend.temporal.media_backfill.schedule import create_replay_vision_media_backfill_schedule-from products.replay_vision.backend.temporal.media_backfill.workflow import ReplayVisionMediaBackfillWorkflow--__all__ = [- "ReplayVisionMediaBackfillWorkflow",- "create_replay_vision_media_backfill_schedule",- "find_media_backfill_candidates_activity",-]diff --git a/products/replay_vision/backend/temporal/media_backfill/activities.py b/products/replay_vision/backend/temporal/media_backfill/activities.pydeleted file mode 100644index 1c4e8c7c0cbf..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/activities.py+++ /dev/null@@ -1,133 +0,0 @@-from uuid import UUID--from django.db.models import Exists, OuterRef-from django.db.models.fields.json import KeyTextTransform-from django.utils.timezone import now--import structlog-from asgiref.sync import sync_to_async-from temporalio import activity--from products.exports.backend.models.exported_asset import ExportedAsset-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation-from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia-from products.replay_vision.backend.temporal.activities.ensure_session_asset import analysis_export_context-from products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.media_backfill.constants import (- ATTEMPT_COOLDOWN,- CANDIDATE_SCAN_LIMIT,- MAX_OBSERVATION_AGE,- MAX_OBSERVATIONS_PER_TICK,- MAX_RENDER_ATTEMPTS,- MIN_OBSERVATION_AGE,-)-from products.replay_vision.backend.temporal.media_backfill.types import (- FindMediaBackfillCandidatesOutput,- MediaBackfillCandidate,- MediaBackfillInputs,-)-from products.replay_vision.backend.temporal.metrics import record_media_backfill_tick--logger = structlog.get_logger(__name__)---def _analysis_asset_ids(rows: list[tuple[UUID, int, str]]) -> dict[tuple[int, str], int]:- """The usable analysis video per (team, session), in one query for the whole page."""- if not rows:- return {}- # The render settings come from the activity that writes these assets, so a change there cannot- # leave the sweep matching videos the scan would not read back.- settings = analysis_export_context("")- discriminators = {- f"export_context__{key}": value for key, value in settings.items() if key != "session_recording_id"- }- found = (- ExportedAsset.objects.filter(- export_format=ExportedAsset.ExportFormat.MP4,- is_system=True,- team_id__in={team_id for _, team_id, _ in rows},- **discriminators,- )- .annotate(session=KeyTextTransform("session_recording_id", "export_context"))- .filter(session__in={session_id for _, _, session_id in rows})- .exclude(content_location=None)- .exclude(content_location="")- .order_by("id")- .values_list("team_id", "session", "id")- )- by_session: dict[tuple[int, str], int] = {}- for team_id, session_id, asset_id in found:- by_session.setdefault((team_id, session_id), asset_id)- return by_session---def _find(limit: int) -> FindMediaBackfillCandidatesOutput:- # A sweep is genuinely cross-team and has no request to take a team from, so the media model's- # fail-closed manager needs its escape hatch. ReplayObservation is not team-scoped.- has_media = ReplayObservationMedia.objects.unscoped().filter(observation_id=OuterRef("pk"))- rows = list(- ReplayObservation.objects.filter(- status=ObservationStatus.SUCCEEDED,- created_at__lt=now() - MIN_OBSERVATION_AGE,- created_at__gt=now() - MAX_OBSERVATION_AGE,- )- .annotate(has_media=Exists(has_media))- .filter(has_media=False)- .exclude(media_render_attempts__gte=MAX_RENDER_ATTEMPTS)- .exclude(media_render_attempted_at__gt=now() - ATTEMPT_COOLDOWN)- .order_by("-created_at")- .values_list("id", "team_id", "session_id")[:CANDIDATE_SCAN_LIMIT]- )- # Counted separately so a stalled sweep shows why it is finding nothing.- cooling_off = (- ReplayObservation.objects.filter(- status=ObservationStatus.SUCCEEDED,- media_render_attempted_at__gt=now() - ATTEMPT_COOLDOWN,- media_render_attempts__lt=MAX_RENDER_ATTEMPTS,- )- .annotate(has_media=Exists(has_media))- .filter(has_media=False)- .count()- )-- assets = _analysis_asset_ids(rows)-- candidates: list[MediaBackfillCandidate] = []- without_video = 0- for observation_id, team_id, session_id in rows:- asset_id = assets.get((team_id, session_id))- if asset_id is None:- # The video outlives the observation by about 30 days, so the oldest gaps stay unfillable.- without_video += 1- continue- candidates.append(- MediaBackfillCandidate(- team_id=team_id, observation_id=observation_id, session_id=session_id, analysis_asset_id=asset_id- )- )- if len(candidates) >= limit:- break-- return FindMediaBackfillCandidatesOutput(- candidates=candidates, without_video=without_video, cooling_off=cooling_off- )---@track_activity()-async def find_media_backfill_candidates_activity(- inputs: MediaBackfillInputs,-) -> FindMediaBackfillCandidatesOutput:- """Succeeded observations with no media whose analysis video is still stored, newest first."""- limit = max(1, inputs.limit or MAX_OBSERVATIONS_PER_TICK)- result = await sync_to_async(_find)(limit)- record_media_backfill_tick(- dispatched=len(result.candidates), without_video=result.without_video, cooling_off=result.cooling_off- )- logger.info(- "replay_vision.media_backfill.candidates",- found=len(result.candidates),- without_video=result.without_video,- cooling_off=result.cooling_off,- )- return resultdiff --git a/products/replay_vision/backend/temporal/media_backfill/constants.py b/products/replay_vision/backend/temporal/media_backfill/constants.pydeleted file mode 100644index e926d3d32f70..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/constants.py+++ /dev/null@@ -1,29 +0,0 @@-from datetime import timedelta--SCHEDULE_ID = "replay-vision-media-backfill-schedule"-WORKFLOW_ID = "replay-vision-media-backfill"-WORKFLOW_NAME = "replay-vision-media-backfill"-SCHEDULE_TYPE = "replay-vision-media-backfill"--SCHEDULE_INTERVAL = timedelta(minutes=5)--# 3000 an hour, which clears a day of missing posters in under a day. The media fleet renders about-# as fast again on one pod, and KEDA has 19 more, so this paces storage rather than compute: each-# poster is about 120KB.-MAX_OBSERVATIONS_PER_TICK = 250-CANDIDATE_SCAN_LIMIT = 1000-# A live scan is already rendering anything newer, and would win the race for the same id anyway.-MIN_OBSERVATION_AGE = timedelta(minutes=15)-# Inside the analysis video's own lifetime on purpose. Reaching past it finds observations whose-# video is gone, which can never be filled, record no attempt, and so sit at the head of a-# newest-first walk rescanning themselves on every tick.-MAX_OBSERVATION_AGE = timedelta(days=7)-ATTEMPT_COOLDOWN = timedelta(hours=6)-# Past this the recording is broken, and retrying forever would hold the head of the walk.-MAX_RENDER_ATTEMPTS = 3--FIND_CANDIDATES_TIMEOUT = timedelta(minutes=2)-WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=10)-# The bound the live path gives the same child. Abandoned children outlive this workflow, and one that-# never closes holds the deterministic id against every later tick.-MEDIA_CHILD_EXECUTION_TIMEOUT = timedelta(minutes=20)diff --git a/products/replay_vision/backend/temporal/media_backfill/schedule.py b/products/replay_vision/backend/temporal/media_backfill/schedule.pydeleted file mode 100644index 0b5057399673..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/schedule.py+++ /dev/null@@ -1,30 +0,0 @@-from temporalio.client import Client-from temporalio.common import SearchAttributePair, TypedSearchAttributes--from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY--from products.replay_vision.backend.temporal.media_backfill.constants import (- SCHEDULE_ID,- SCHEDULE_INTERVAL,- SCHEDULE_TYPE,- WORKFLOW_EXECUTION_TIMEOUT,- WORKFLOW_ID,- WORKFLOW_NAME,-)-from products.replay_vision.backend.temporal.media_backfill.types import MediaBackfillInputs-from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule---async def create_replay_vision_media_backfill_schedule(client: Client) -> None:- await upsert_interval_schedule(- client,- schedule_id=SCHEDULE_ID,- workflow_name=WORKFLOW_NAME,- workflow_id=WORKFLOW_ID,- inputs=MediaBackfillInputs(),- interval=SCHEDULE_INTERVAL,- execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,- search_attributes=TypedSearchAttributes(- search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]- ),- )diff --git a/products/replay_vision/backend/temporal/media_backfill/types.py b/products/replay_vision/backend/temporal/media_backfill/types.pydeleted file mode 100644index 13bac098c33b..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/types.py+++ /dev/null@@ -1,27 +0,0 @@-from uuid import UUID--from pydantic import BaseModel---class MediaBackfillInputs(BaseModel, frozen=True):- """Input to ReplayVisionMediaBackfillWorkflow. The schedule passes none of it."""-- # Overrides the per-tick cap, for a one-off manual run.- limit: int | None = None---class MediaBackfillCandidate(BaseModel, frozen=True):- """One observation that has no media and whose analysis video is still stored."""-- team_id: int- observation_id: UUID- session_id: str- analysis_asset_id: int---class FindMediaBackfillCandidatesOutput(BaseModel, frozen=True):- candidates: list[MediaBackfillCandidate] = []- # Observations that looked eligible until their analysis video turned out to be gone.- without_video: int = 0- # Observations whose render was tried recently and is waiting out its cooldown.- cooling_off: int = 0diff --git a/products/replay_vision/backend/temporal/media_backfill/workflow.py b/products/replay_vision/backend/temporal/media_backfill/workflow.pydeleted file mode 100644index bfd07276562d..000000000000--- a/products/replay_vision/backend/temporal/media_backfill/workflow.py+++ /dev/null@@ -1,88 +0,0 @@-import asyncio--import temporalio.workflow as wf-from temporalio import common-from temporalio.common import SearchAttributePair, TypedSearchAttributes-from temporalio.exceptions import WorkflowAlreadyStartedError-from temporalio.workflow import ParentClosePolicy--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY--from products.replay_vision.backend.temporal.media_backfill.constants import (- FIND_CANDIDATES_TIMEOUT,- MEDIA_CHILD_EXECUTION_TIMEOUT,- WORKFLOW_NAME,-)-from products.replay_vision.backend.temporal.media_backfill.types import MediaBackfillCandidate, MediaBackfillInputs--with wf.unsafe.imports_passed_through():- from django.conf import settings-- from products.replay_vision.backend.temporal.media_backfill.activities import (- find_media_backfill_candidates_activity,- )- from products.replay_vision.backend.temporal.media_types import (- MEDIA_WORKFLOW_NAME,- ObservationMediaInputs,- build_media_workflow_id,- )--[email protected](name=WORKFLOW_NAME)-class ReplayVisionMediaBackfillWorkflow(PostHogWorkflow):- """Give a poster to succeeded observations that have none.-- Catch-up for observations scanned before media existed, and repair for renders the fail-soft- media path dropped. The moment comes from the stored scanner result: the model's own pick is- long gone, so these fall back to a citation or a quarter of the way in.- """-- inputs_cls = MediaBackfillInputs- inputs_optional = True-- @wf.run- async def run(self, inputs: MediaBackfillInputs) -> int:- found = await wf.execute_activity(- find_media_backfill_candidates_activity,- inputs,- start_to_close_timeout=FIND_CANDIDATES_TIMEOUT,- # A failed tick is not worth retrying: the next one is five minutes away.- retry_policy=common.RetryPolicy(maximum_attempts=1),- )- if not found.candidates:- return 0-- started = await asyncio.gather(*(self._start(c) for c in found.candidates))- return sum(started)-- async def _start(self, candidate: MediaBackfillCandidate) -> bool:- try:- await wf.start_child_workflow(- MEDIA_WORKFLOW_NAME,- ObservationMediaInputs(- team_id=candidate.team_id,- observation_id=candidate.observation_id,- session_id=candidate.session_id,- analysis_asset_id=candidate.analysis_asset_id,- ),- # The id the live path uses, so a scan already rendering this wins and the sweep skips it.- id=build_media_workflow_id(candidate.observation_id),- task_queue=settings.REPLAY_VISION_TASK_QUEUE,- parent_close_policy=ParentClosePolicy.ABANDON,- execution_timeout=MEDIA_CHILD_EXECUTION_TIMEOUT,- # Without these a backfilled render is not findable by team in the Temporal UI.- search_attributes=TypedSearchAttributes(- search_attributes=[- SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=candidate.team_id),- SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=candidate.session_id),- ]- ),- )- return True- except WorkflowAlreadyStartedError:- return False- except Exception as error:- # One observation must never sink the tick.- wf.logger.warning("replay_vision.media_backfill.start_failed", extra={"error": str(error)})- return Falsediff --git a/products/replay_vision/backend/temporal/media_types.py b/products/replay_vision/backend/temporal/media_types.pyindex 81dc21947635..d01ba81d6f92 100644--- a/products/replay_vision/backend/temporal/media_types.py+++ b/products/replay_vision/backend/temporal/media_types.py@@ -1,5 +1,6 @@-"""Types for the observation media workflow: one thumbnail per succeeded observation today, clips later."""+"""Types for the observation media workflow: one thumbnail per succeeded observation."""+import datetime as dtfrom uuid import UUIDfrom pydantic import BaseModel, Field@@ -15,9 +16,14 @@ FALLBACK_THUMBNAIL_FRACTION = 0.25MEDIA_WORKFLOW_NAME = "replay-vision-media"+# Bounds the thumbnail's retry chain, queue wait included.+THUMBNAIL_SCHEDULE_TO_CLOSE = dt.timedelta(hours=6)+# Past the retry chain, so a stuck render fails its own activity rather than the whole child.+MEDIA_WORKFLOW_EXECUTION_TIMEOUT = THUMBNAIL_SCHEDULE_TO_CLOSE + dt.timedelta(minutes=30)+def build_media_workflow_id(observation_id: UUID) -> str:- """One id per observation, so a backfill cannot start a render a scan is already running."""+ """One id per observation, so a retried scan cannot start a second render beside one still running."""return f"{MEDIA_WORKFLOW_NAME}-{observation_id}"diff --git a/products/replay_vision/backend/temporal/media_workflow.py b/products/replay_vision/backend/temporal/media_workflow.pyindex 2685aa26b64b..f98b21590502 100644--- a/products/replay_vision/backend/temporal/media_workflow.py+++ b/products/replay_vision/backend/temporal/media_workflow.py@@ -14,6 +14,7 @@ with wf.unsafe.imports_passed_through():)from products.replay_vision.backend.temporal.media_types import (MEDIA_WORKFLOW_NAME,+ THUMBNAIL_SCHEDULE_TO_CLOSE,ExtractThumbnailActivityOutput,FinalizeObservationThumbnailInputs,ObservationMediaInputs,@@ -22,15 +23,12 @@ with wf.unsafe.imports_passed_through():_THUMBNAIL_TIMEOUT = dt.timedelta(minutes=5)_STATE_RETRY = common.RetryPolicy(maximum_attempts=3)-# Ridden out here rather than left for the backfill sweep to rediscover fifteen minutes later.+# Nothing retries a lost poster later, so this chain has to outlast a rasterizer backlog or outage._THUMBNAIL_RETRY = common.RetryPolicy(- maximum_attempts=5,initial_interval=dt.timedelta(seconds=20),backoff_coefficient=3.0,- maximum_interval=dt.timedelta(minutes=5),+ maximum_interval=dt.timedelta(minutes=15),)-# Bounds the retry chain, so a broken render releases the child before the execution timeout.-_THUMBNAIL_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=15)@wf.defn(name=MEDIA_WORKFLOW_NAME)@@ -51,9 +49,9 @@ class ObservationMediaWorkflow(PostHogWorkflow):raw_result = await wf.execute_activity("extract-thumbnail",prepared.activity_input.model_dump(exclude_none=True),- task_queue=settings.RASTERIZATION_MEDIA_TASK_QUEUE,+ task_queue=settings.RASTERIZATION_TASK_QUEUE,start_to_close_timeout=_THUMBNAIL_TIMEOUT,- schedule_to_close_timeout=_THUMBNAIL_SCHEDULE_TO_CLOSE,+ schedule_to_close_timeout=THUMBNAIL_SCHEDULE_TO_CLOSE,retry_policy=_THUMBNAIL_RETRY,)diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex e170a6f5ee95..21ea777fd85b 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -206,12 +206,6 @@ REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge("Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",)-REPLAY_VISION_MEDIA_BACKFILL_TICK = Counter(- "replay_vision_media_backfill_tick",- "Observations a media backfill tick dispatched, skipped as unfillable, or left cooling off",- labelnames=["outcome"],-)-def record_observation(status: str, scanner_type: str) -> None:labels = {"status": status, "scanner_type": scanner_type}@@ -363,14 +357,3 @@ def record_enqueue_claim_failure(operation: str) -> None:def record_gemini_cleanup_backlog(count: int) -> None:REPLAY_VISION_GEMINI_CLEANUP_BACKLOG.set(count)_otel.record_gauge_twin(REPLAY_VISION_GEMINI_CLEANUP_BACKLOG, count)---def record_media_backfill_tick(*, dispatched: int, without_video: int, cooling_off: int) -> None:- """A fail-soft path leaves no other trace, so the sweep's own numbers are the alert surface."""- for outcome, count in (- ("dispatched", dispatched),- ("without_video", without_video),- ("cooling_off", cooling_off),- ):- REPLAY_VISION_MEDIA_BACKFILL_TICK.labels(outcome=outcome).inc(count)- _otel.record_counter_twin(REPLAY_VISION_MEDIA_BACKFILL_TICK, count, {"outcome": outcome})diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 66737ab8a160..525cee8f29ac 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -43,7 +43,6 @@ SIGNAL_HEADLINE_MAX_LENGTH = 80# Stable step names the producer (`mission_steps`) and consumers (`assemble`) key on.STEP_CORE = "core"STEP_SIGNALS = "signals"-STEP_MEDIA = "media"# Ceiling on one step's response, thought tokens included, because Gemini counts thinking against the cap.# Every response schema is a few hundred tokens of JSON, so this only bounds the tail: a model that thinks@@ -52,10 +51,6 @@ STEP_MEDIA = "media"# a re-prompt that bills them again.STEP_MAX_OUTPUT_TOKENS = 16_384-# The media turn answers with one integer, so its whole cost is the thinking in front of it. Held well-# below the shared cap, because this turn rides every scan in the product.-MEDIA_STEP_MAX_OUTPUT_TOKENS = 2_048-class SignalFinding(BaseModel, frozen=True):"""Optional side-mission finding: a bug, crash, or design flaw the recording itself reveals. See the side-mission prompt block."""@@ -135,18 +130,6 @@ class SignalsResponse(BaseModel, frozen=True):return self-class MediaResponse(BaseModel, frozen=True):- """The media turn's structured output: which frame of the video illustrates the finding."""-- thumbnail_t: int = Field(- ge=0,- description=(- "The moment to cut the thumbnail from, in whole seconds of video time counted from the start of the "- "video file — the same scale you cite moments in, not the footer's `REC_T`."- ),- )--@dataclass(frozen=True)class MissionStep:"""One structured turn in a scanner's conversation: an instruction, the schema the model must answer with,@@ -162,7 +145,6 @@ class MissionStep:response_model: type[BaseModel]required: bool = Truevalidate: Callable[[BaseModel], str | None] | None = field(default=None)- max_output_tokens: int = STEP_MAX_OUTPUT_TOKENS_CONFIDENCE_DESCRIPTION = (@@ -196,6 +178,21 @@ def notability_reason_field() -> Any:return Field(default=None, description=_NOTABILITY_REASON_DESCRIPTION)+_THUMBNAIL_DESCRIPTION = (+ "The moment to cut the thumbnail from, in whole seconds of video time counted from the start of the video "+ "file, the same scale you cite moments in, not the footer's `REC_T`."+)+++def thumbnail_field() -> Any:+ """`thumbnail_t` field for LLM-response schemas, declared last so the pick never precedes the answer.++ Optional for the same reason as `notability`: a skipped pick must not fail a paid-for scan. Readers fall back+ to a cited or signal moment when absent.+ """+ return Field(default=None, ge=0, description=_THUMBNAIL_DESCRIPTION)++def notability_field() -> Any:"""`notability` field for LLM-response schemas.@@ -311,24 +308,12 @@ class BaseScanner(BaseModel, frozen=True):]def mission_steps(self) -> list[MissionStep]:- """The full ordered turn list: the core task, the signals side mission when enabled, then the media turn."""+ """The full ordered turn list: the core task, then the signals side mission when enabled."""steps = self.core_steps()if self.emits_signals:steps.append(self._signals_step())- steps.append(self._media_step())return steps- def _media_step(self) -> MissionStep:- instruction = render_prompt("media_step.jinja")- # Best-effort, and last, so the thumbnail can never move a calibrated answer or sink a paid-for scan.- return MissionStep(- name=STEP_MEDIA,- instruction=instruction,- response_model=MediaResponse,- required=False,- max_output_tokens=MEDIA_STEP_MAX_OUTPUT_TOKENS,- )-def _signals_step(self) -> MissionStep:instruction = render_prompt("signals_step.jinja", min_signal_confidence=MIN_SIGNAL_CONFIDENCE)# Best-effort: a side-mission failure must not sink the whole scan.diff --git a/products/replay_vision/backend/temporal/scanners/classifier.py b/products/replay_vision/backend/temporal/scanners/classifier.pyindex 4440e0a09034..ee08c6d24fb4 100644--- a/products/replay_vision/backend/temporal/scanners/classifier.py+++ b/products/replay_vision/backend/temporal/scanners/classifier.py@@ -15,6 +15,7 @@ from products.replay_vision.backend.temporal.scanners.base import (confidence_field,notability_field,notability_reason_field,+ thumbnail_field,)_MAX_FREEFORM_TAGS = 5@@ -92,6 +93,7 @@ class ClassifierScanner(BaseScanner, frozen=True):fields["notability_reason"] = (str | None, notability_reason_field())fields["notability"] = (float | None, notability_field())fields["confidence"] = (float, confidence_field())+ fields["thumbnail_t"] = (int | None, thumbnail_field())return create_model("ClassifierLlmResponse", **fields)@cached_propertydiff --git a/products/replay_vision/backend/temporal/scanners/monitor.py b/products/replay_vision/backend/temporal/scanners/monitor.pyindex 63757746c5f1..ad1284a073de 100644--- a/products/replay_vision/backend/temporal/scanners/monitor.py+++ b/products/replay_vision/backend/temporal/scanners/monitor.py@@ -12,6 +12,7 @@ from products.replay_vision.backend.temporal.scanners.base import (confidence_field,notability_field,notability_reason_field,+ thumbnail_field,)MonitorVerdict = Literal["yes", "no", "inconclusive"]@@ -32,6 +33,7 @@ class MonitorLlmResponse(BaseModel, frozen=True):notability_reason: str | None = notability_reason_field()notability: float | None = notability_field()confidence: float = confidence_field()+ thumbnail_t: int | None = thumbnail_field()class MonitorOutput(BaseScannerOutput, frozen=True):diff --git a/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja b/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinjaindex b71535134433..3a3cf790b9b5 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/_macros.jinja@@ -12,3 +12,8 @@ Cite key moments inside `{{ field_name }}` as `(t <seconds>)`, following the Cit{%- macro rate_notability() -%}Separately from your answer above, judge the session itself: in `notability_reason` name the single moment a product team would most want to see (or say plainly that nothing stands out), then set `notability` per the notability calibration rules. Judge what happened to the person, not whether it matches your answer above — a session can be worth watching even when your answer is a non-event, and a routine session stays low even when your answer is a hit. Weigh the area this scanner watches: the team chose it, so difficulty there matters more to them than the same difficulty elsewhere in the session, and repeated or severe trouble in that area is worth watching even when your answer already covers it.{%- endmacro -%}++{# The poster frame, asked in the core turn: a turn of its own costs a full conversation re-send per scan. Call as `{{ pick_media() }}`. #}+{%- macro pick_media() -%}+Last, pick the single frame that best illustrates what you found, so a person scanning a list of recordings can tell at a glance what this one is about, and give it in `thumbnail_t` in whole seconds of video time, the same scale you cite moments in, not the footer's `REC_T`. Pick a frame where the screen shows the thing itself: the error, the broken layout, the step the user was stuck on, the page your answer is about. Avoid a blank page, a full-page spinner, a modal backdrop mid-fade, and the first seconds of the recording, which are usually still loading. When nothing stands out, pick a moment where the user was clearly doing something rather than the start of the video.+{%- endmacro -%}diff --git a/products/replay_vision/backend/temporal/scanners/prompts/classifier_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/classifier_step.jinjaindex 652dd8e268f5..485d56e0426e 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/classifier_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/classifier_step.jinja@@ -1,4 +1,4 @@-{% from "_macros.jinja" import cite_in, rate_notability %}Categorize this session according to: {{ user_prompt }}+{% from "_macros.jinja" import cite_in, pick_media, rate_notability %}Categorize this session according to: {{ user_prompt }}In `reasoning`, work through what the session shows that bears on this; then choose tags from this fixed vocabulary: [{{ vocabulary }}]. {% if multi_label %}Pick every tag that applies.{% else %}Pick exactly one tag.{% endif %} A tag is required even when the session never shows what the criterion describes, so in that case pick the least wrong one and follow the relevance rules: lead the `reasoning` with the fact that the session doesn't show it, and keep `confidence` low.{% if allow_freeform_tags %}@@ -9,3 +9,5 @@ Freeform tags this scanner has already used on other sessions: [{{ known_freefor{{ cite_in('reasoning') }}{{ rate_notability() }}++{{ pick_media() }}diff --git a/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinjadeleted file mode 100644index 0fc49a574808..000000000000--- a/products/replay_vision/backend/temporal/scanners/prompts/media_step.jinja+++ /dev/null@@ -1,5 +0,0 @@-Last pass, and a small one. Pick the single frame that best illustrates what you found, so a person scanning a list of recordings can tell at a glance what this one is about.--Give the moment in `thumbnail_t`, in whole seconds of video time — the same scale you cite moments in, not the footer's `REC_T`.--Pick a frame where the screen shows the thing itself: the error, the broken layout, the step the user was stuck on, the page your answer is about. Avoid a blank page, a full-page spinner, a modal backdrop mid-fade, and the first seconds of the recording, which are usually still loading. When nothing stands out, pick a moment where the user was clearly doing something rather than the start of the video.diff --git a/products/replay_vision/backend/temporal/scanners/prompts/monitor_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/monitor_step.jinjaindex 2a4f1b3c0eaa..e3ae0add7574 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/monitor_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/monitor_step.jinja@@ -1,4 +1,4 @@-{% from "_macros.jinja" import cite_in, rate_notability %}Decide whether the following condition occurred during the session: {{ user_prompt }}+{% from "_macros.jinja" import cite_in, pick_media, rate_notability %}Decide whether the following condition occurred during the session: {{ user_prompt }}Before deciding, verify each moment that bears on this condition with `get_events_around`: the video alone is easy to misread, and what the events record at a moment outranks a visual impression of it.@@ -7,3 +7,5 @@ In `reasoning`, weigh the evidence for and against, noting what the events confi{{ cite_in('reasoning') }}{{ rate_notability() }}++{{ pick_media() }}diff --git a/products/replay_vision/backend/temporal/scanners/prompts/scorer_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/scorer_step.jinjaindex f0d86505cde6..e716b9fc97ba 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/scorer_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/scorer_step.jinja@@ -1,4 +1,4 @@-{% from "_macros.jinja" import cite_in, rate_notability %}Rate this session against the following criterion: {{ user_prompt }}+{% from "_macros.jinja" import cite_in, pick_media, rate_notability %}Rate this session against the following criterion: {{ user_prompt }}Before scoring, verify the moments that drive your score with `get_events_around`: what the events record at a moment outranks a visual impression of it, and a score toward either end of the scale needs event-checked moments behind it, not just how the session looks.@@ -7,3 +7,5 @@ In `reasoning`, work through what you observed in the session that bears on this{{ cite_in('reasoning') }}{{ rate_notability() }}++{{ pick_media() }}diff --git a/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinjaindex 4a47ca97377a..1c54df4e7145 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/summarizer_summary_step.jinja@@ -1,4 +1,4 @@-{% from "_macros.jinja" import cite_in, rate_notability %}Summarize this session.{% if user_prompt %}+{% from "_macros.jinja" import cite_in, pick_media, rate_notability %}Summarize this session.{% if user_prompt %}Additional context from the team operating the product being recorded:{{ user_prompt }}{% endif %}@@ -8,3 +8,5 @@ Additional context from the team operating the product being recorded:{{ cite_in('summary') }}{{ rate_notability() }}++{{ pick_media() }}diff --git a/products/replay_vision/backend/temporal/scanners/scorer.py b/products/replay_vision/backend/temporal/scanners/scorer.pyindex fa03d1321fe8..5523a93e5fd8 100644--- a/products/replay_vision/backend/temporal/scanners/scorer.py+++ b/products/replay_vision/backend/temporal/scanners/scorer.py@@ -12,6 +12,7 @@ from products.replay_vision.backend.temporal.scanners.base import (confidence_field,notability_field,notability_reason_field,+ thumbnail_field,)@@ -61,6 +62,7 @@ class ScorerScanner(BaseScanner, frozen=True):notability_reason=(str | None, notability_reason_field()),notability=(float | None, notability_field()),confidence=(float, confidence_field()),+ thumbnail_t=(int | None, thumbnail_field()),)def prompt_context(self) -> dict[str, Any]:diff --git a/products/replay_vision/backend/temporal/scanners/summarizer.py b/products/replay_vision/backend/temporal/scanners/summarizer.pyindex e7376c0d52d5..e6db5aad0579 100644--- a/products/replay_vision/backend/temporal/scanners/summarizer.py+++ b/products/replay_vision/backend/temporal/scanners/summarizer.py@@ -13,6 +13,7 @@ from products.replay_vision.backend.temporal.scanners.base import (confidence_field,notability_field,notability_reason_field,+ thumbnail_field,)SummaryLength = Literal["short", "medium", "long"]@@ -38,6 +39,7 @@ class SummarizerSummaryResponse(BaseModel, frozen=True):notability_reason: str | None = notability_reason_field()notability: float | None = notability_field()confidence: float = confidence_field()+ thumbnail_t: int | None = thumbnail_field()class SummarizerOutput(BaseScannerOutput, frozen=True):diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex ea1192e28eba..4da5693ab950 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -288,7 +288,7 @@ class ScannerCallOutput(BaseModel, frozen=True):# Extracted from the LLM response before `finalize` so per-type output mapping can't drop them.signals: list[SignalFinding] = Field(default_factory=list)verification: VerificationRecord | None = None- # Video seconds the model picked for the thumbnail; None when the best-effort media turn produced nothing.+ # Video seconds the model picked for the thumbnail; None when it skipped the optional pick.thumbnail_video_s: int | None = None# Signal spans on the video clock, which `signals` no longer carries once they move to session time.signal_video_spans: list[tuple[int, int]] = Field(default_factory=list)diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 9520c2e2748f..ce65c619353c 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -58,6 +58,7 @@ from products.replay_vision.backend.temporal.errors import (ScannerFailureError,)from products.replay_vision.backend.temporal.media_types import (+ MEDIA_WORKFLOW_EXECUTION_TIMEOUT,MEDIA_WORKFLOW_NAME,ObservationMediaInputs,build_media_workflow_id,@@ -600,11 +601,14 @@ class ApplyScannerWorkflow(PostHogWorkflow):),id=build_media_workflow_id(observation_id),task_queue=settings.REPLAY_VISION_TASK_QUEUE,- # A retried observation reuses its id, and the run it supersedes has long closed.+ # A retried observation reuses its id, so the render it supersedes must not block this one once+ # it has closed, whatever it closed as. A run still open keeps the id and this start fails, which+ # is what we want: that run is already rendering this observation.id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,parent_close_policy=ParentClosePolicy.ABANDON,- retry_policy=common.RetryPolicy(maximum_attempts=2),- execution_timeout=dt.timedelta(minutes=20),+ # The execution timeout spans every attempt and the thumbnail's own retries fill it, so a second run has no time left.+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ execution_timeout=MEDIA_WORKFLOW_EXECUTION_TIMEOUT,)except Exception:wf.logger.exception("Media rendering could not be started for observation %s", observation_id)diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex 8c6e93ade0c2..9131b0d82f6a 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -34,7 +34,6 @@ from products.replay_vision.backend.temporal.events_tool import events_toolfrom products.replay_vision.backend.temporal.metrics import REPLAY_VISION_VERIFICATION_OUTCOMESfrom products.replay_vision.backend.temporal.scanners.base import (STEP_MAX_OUTPUT_TOKENS,- MediaResponse,MissionStep,SignalFinding,SignalsResponse,@@ -87,8 +86,7 @@ class _Resp:class _FakeModels:def __init__(self, responses: list[_Resp]) -> None:- # Every full mission ends with the best-effort media turn, which no test is about.- self._it = iter([*responses, _Resp(text=MediaResponse(thumbnail_t=1).model_dump_json())])+ self._it = iter(responses)self.calls: list[dict[str, Any]] = []async def generate_content(self, **kwargs: Any) -> _Resp:@@ -408,7 +406,7 @@ async def test_signal_timestamps_use_recording_duration(description="A blank dialog covers the editor and prevents input.",confidence=0.9,)- core = MonitorLlmResponse(verdict="yes", reasoning="The dialog blocked input.", confidence=0.9)+ core = MonitorLlmResponse(verdict="yes", reasoning="The dialog blocked input.", confidence=0.9, thumbnail_t=7)client = _FakeClient([_Resp(text=core.model_dump_json())]+ [@@ -439,7 +437,9 @@ async def test_signal_timestamps_use_recording_duration()assert cast(MonitorOutput, outcome.finalized).verdict == "yes"assert outcome.signals == ([] if expected_end is None else [signal.model_copy(update={"end_time": expected_end})])- assert len(client.models.calls) == 2 + len(end_times)+ # The pick rides the core answer, so no turn of its own is spent on it.+ assert outcome.thumbnail_video_s == 7+ assert len(client.models.calls) == 1 + len(end_times)@pytest.mark.asyncio@@ -855,7 +855,7 @@ class TestVerifyPositives:async def test_verify_draws_are_blind_core_only_turns_over_the_live_cache(self) -> None:run = await self._scan(mode="enforce", answers=["yes", "no"], emits_signals=True)assert run.calls == [- {"steps": ["core", "signals", "media"], "cache_name": "caches/abc"},+ {"steps": ["core", "signals"], "cache_name": "caches/abc"},{"steps": ["core_verify_2"], "cache_name": "caches/abc"},"delete_cache",]diff --git a/products/replay_vision/backend/tests/test_media_backfill.py b/products/replay_vision/backend/tests/test_media_backfill.pydeleted file mode 100644index 5d9abd5b738e..000000000000--- a/products/replay_vision/backend/tests/test_media_backfill.py+++ /dev/null@@ -1,188 +0,0 @@-from datetime import timedelta--from posthog.test.base import BaseTest--from django.db import connection-from django.test.utils import CaptureQueriesContext-from django.utils import timezone--from asgiref.sync import async_to_sync-from parameterized import parameterized--from posthog.models.utils import uuid7--from products.exports.backend.models.exported_asset import ExportedAsset-from products.replay_vision.backend.models.replay_observation import (- ObservationStatus,- ObservationTrigger,- ReplayObservation,-)-from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType-from products.replay_vision.backend.temporal.activities.ensure_session_asset import analysis_export_context-from products.replay_vision.backend.temporal.media_backfill.activities import find_media_backfill_candidates_activity-from products.replay_vision.backend.temporal.media_backfill.constants import (- ATTEMPT_COOLDOWN,- MAX_OBSERVATION_AGE,- MAX_RENDER_ATTEMPTS,- MIN_OBSERVATION_AGE,-)-from products.replay_vision.backend.temporal.media_backfill.types import MediaBackfillInputs-from products.replay_vision.backend.tests.helpers import snapshot_for---class TestMediaBackfillCandidates(BaseTest):- def setUp(self) -> None:- super().setUp()- self.scanner = ReplayScanner.objects.create(- team=self.team,- name="Checkout monitor",- scanner_type=ScannerType.MONITOR,- scanner_config={"prompt": "did the user check out?"},- model=ScannerModel.GEMINI_3_8_FLASH,- )-- def _observation(- self, *, status: str = ObservationStatus.SUCCEEDED, age: timedelta | None = None- ) -> ReplayObservation:- observation = ReplayObservation.objects.create(- scanner=self.scanner,- team=self.team,- session_id=f"s-{uuid7()}",- status=status,- completed_at=timezone.now(),- scanner_snapshot=snapshot_for(self.scanner),- triggered_by=ObservationTrigger.SCHEDULE,- )- created = timezone.now() - (age if age is not None else MIN_OBSERVATION_AGE + timedelta(minutes=5))- ReplayObservation.objects.filter(pk=observation.pk).update(created_at=created)- observation.refresh_from_db()- return observation-- def _analysis_video(self, observation: ReplayObservation, *, rendered: bool = True) -> ExportedAsset:- return ExportedAsset.objects.create(- team=self.team,- export_format=ExportedAsset.ExportFormat.MP4,- export_context=analysis_export_context(observation.session_id),- content_location=f"exports/mp4/team-{self.team.id}/{observation.session_id}.mp4" if rendered else None,- is_system=True,- )-- def _record_attempt(self, observation: ReplayObservation, *, attempts: int, when) -> None:- ReplayObservation.objects.filter(pk=observation.pk).update(- media_render_attempts=attempts, media_render_attempted_at=when- )-- def _candidates(self, limit: int | None = None):- return async_to_sync(find_media_backfill_candidates_activity)(MediaBackfillInputs(limit=limit))-- def test_an_observation_without_media_is_a_candidate(self) -> None:- observation = self._observation()- asset = self._analysis_video(observation)-- result = self._candidates()-- assert [c.observation_id for c in result.candidates] == [observation.id]- assert result.candidates[0].analysis_asset_id == asset.id-- def test_an_observation_that_already_has_a_poster_is_skipped(self) -> None:- observation = self._observation()- asset = self._analysis_video(observation)- ReplayObservationMedia.objects.for_team(self.team.id).create(- team_id=self.team.id,- observation=observation,- asset=asset,- kind=ReplayObservationMedia.Kind.THUMBNAIL,- position=0,- video_start_ms=1000,- )-- assert self._candidates().candidates == []-- @parameterized.expand(["video expired", "video never rendered", "observation failed"])- def test_an_ineligible_observation_is_not_dispatched(self, case: str) -> None:- failed = case == "observation failed"- observation = self._observation(status=ObservationStatus.FAILED if failed else ObservationStatus.SUCCEEDED)- if case == "video never rendered":- self._analysis_video(observation, rendered=False)- elif failed:- self._analysis_video(observation)-- assert self._candidates().candidates == []-- def test_an_unfillable_observation_is_counted(self) -> None:- # Its analysis video has expired, so no tick will ever fix it.- self._observation()-- assert self._candidates().without_video == 1-- def test_a_fresh_observation_is_left_to_its_own_scan(self) -> None:- # The live path is already rendering it, and both would race the same workflow id.- fresh = self._observation(age=timedelta(minutes=1))- self._analysis_video(fresh)-- assert self._candidates().candidates == []-- def test_the_limit_caps_a_tick(self) -> None:- for _ in range(3):- self._analysis_video(self._observation())-- assert len(self._candidates(limit=2).candidates) == 2-- def test_the_newest_candidates_go_first(self) -> None:- older = self._observation(age=timedelta(days=3))- newer = self._observation(age=timedelta(hours=2))- self._analysis_video(older)- self._analysis_video(newer)-- result = self._candidates()-- assert [c.observation_id for c in result.candidates] == [newer.id, older.id]-- def test_the_walk_stops_at_the_video_retention_floor(self) -> None:- # Past this age the analysis video is gone, so rescanning those rows every tick buys nothing.- ancient = self._observation(age=MAX_OBSERVATION_AGE + timedelta(days=1))- self._analysis_video(ancient)-- assert self._candidates().candidates == []-- def test_a_recent_attempt_waits_out_its_cooldown(self) -> None:- observation = self._observation()- self._analysis_video(observation)- self._record_attempt(observation, attempts=1, when=timezone.now() - timedelta(minutes=5))-- result = self._candidates()-- assert result.candidates == []- assert result.cooling_off == 1-- def test_an_old_attempt_is_tried_again(self) -> None:- observation = self._observation()- self._analysis_video(observation)- self._record_attempt(observation, attempts=1, when=timezone.now() - ATTEMPT_COOLDOWN - timedelta(hours=1))-- assert [c.observation_id for c in self._candidates().candidates] == [observation.id]-- def test_an_observation_that_keeps_failing_is_given_up_on(self) -> None:- # Otherwise it holds the head of a newest-first walk and nothing older is ever reached.- observation = self._observation()- self._analysis_video(observation)- self._record_attempt(- observation, attempts=MAX_RENDER_ATTEMPTS, when=timezone.now() - ATTEMPT_COOLDOWN - timedelta(hours=1)- )-- result = self._candidates()-- assert result.candidates == []- assert result.cooling_off == 0-- def test_a_page_of_candidates_costs_a_fixed_number_of_queries(self) -> None:- # The tick dispatches up to 250, so a per-candidate lookup would be hundreds of round trips.- for _ in range(6):- self._analysis_video(self._observation())-- with CaptureQueriesContext(connection) as queries:- result = self._candidates()-- assert len(result.candidates) == 6- assert len(queries.captured_queries) <= 4diff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.pyindex cd15635b8789..ba0d58ce0682 100644--- a/products/replay_vision/backend/tests/test_observation_media.py+++ b/products/replay_vision/backend/tests/test_observation_media.py@@ -1,4 +1,3 @@-import dataclassesfrom datetime import datetime, timedeltafrom typing import Any@@ -9,7 +8,6 @@ from django.utils import timezonefrom asgiref.sync import async_to_syncfrom parameterized import parameterized-from temporalio.testing import ActivityEnvironmentfrom posthog.models.utils import uuid7@@ -143,23 +141,6 @@ class TestObservationMedia(BaseTest):assert media.asset_id == prepared.media_asset_idassert (media.asset.content_location or "").startswith("replay-vision/media/")- def test_a_retry_of_the_same_render_does_not_spend_another_attempt(self) -> None:- # The backfill sweep gives up after three attempts, so an activity retry must not count as one.- self._prepare()- self.observation.refresh_from_db()- assert self.observation.media_render_attempts == 1- assert self.observation.media_render_attempted_at is not None-- async def retry_the_same_activity() -> None:- environment = ActivityEnvironment()- environment.info = dataclasses.replace(environment.info, attempt=2)- await environment.run(prepare_observation_thumbnail_activity, self._inputs())-- async_to_sync(retry_the_same_activity)()-- self.observation.refresh_from_db()- assert self.observation.media_render_attempts == 1-def test_an_observation_deleted_mid_render_expires_the_asset_with_its_location(self) -> None:prepared = self._prepare()observation_id = self.observation.iddiff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.pyindex 32db2e67129b..70a4b003e059 100644--- a/products/replay_vision/backend/tests/test_scanners.py+++ b/products/replay_vision/backend/tests/test_scanners.py@@ -863,12 +863,12 @@ class TestSignalSideMission:def test_mission_excludes_signals_step_by_default(self) -> None:scanner = scanner_from_db(_build_replay_scanner())- assert [s.name for s in scanner.mission_steps()] == ["core", "media"]+ assert [s.name for s in scanner.mission_steps()] == ["core"]assert _signals_step(scanner) is Nonedef test_mission_appends_signals_step_when_emitting(self) -> None:scanner = scanner_from_db(_build_replay_scanner(emits_signals=True))- step = scanner.mission_steps()[-2]+ step = scanner.mission_steps()[-1]assert step.name == "signals"assert step.response_model is SignalsResponse# The side mission is best-effort: a failed signals turn must not sink the scan.@@ -879,7 +879,7 @@ class TestSignalSideMission:scanner = scanner_from_db(_build_replay_scanner(scanner_type=scanner_type, scanner_config=config, emits_signals=True))- assert scanner.mission_steps()[-2].name == "signals"+ assert scanner.mission_steps()[-1].name == "signals"@pytest.mark.parametrize("start_time, end_time", [(0, 0), (72, 72), (72, 78)])def test_signals_parse_and_assemble_alongside_output(self, start_time: int, end_time: int) -> None: