: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): give observations with no poster a backfill sweep (#103698)
Tue Haulundf5f4ac21032b
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex b777950bd123..96ba6bdbbfa1 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -122,6 +122,7 @@ 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@@ -974,6 +975,7 @@ 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/products/replay_vision/backend/migrations/0097_replayobservation_media_render_attempted_at_and_more.py b/products/replay_vision/backend/migrations/0097_replayobservation_media_render_attempted_at_and_more.pynew file mode 100644index 000000000000..d5378ce5dcd8--- /dev/null+++ b/products/replay_vision/backend/migrations/0097_replayobservation_media_render_attempted_at_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.17 on 2026-09-21 11:56++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0096_replayobservationmedia"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayobservation",+ name="media_render_attempted_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="replayobservation",+ name="media_render_attempts",+ field=models.PositiveSmallIntegerField(db_default=0, default=0),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0098_replayobservation_rlo_succeeded_created_idx.py b/products/replay_vision/backend/migrations/0098_replayobservation_rlo_succeeded_created_idx.pynew file mode 100644index 000000000000..c72ccf9f5564--- /dev/null+++ b/products/replay_vision/backend/migrations/0098_replayobservation_rlo_succeeded_created_idx.py@@ -0,0 +1,23 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY cannot run inside a transaction; replay_observation is large in production.+ atomic = False++ dependencies = [+ ("replay_vision", "0097_replayobservation_media_render_attempted_at_and_more"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="replayobservation",+ index=models.Index(+ condition=models.Q(("status", "succeeded")),+ fields=["-created_at"],+ name="rlo_succeeded_created_idx",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 62d8050d1874..8e10ed324e0d 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0096_replayobservationmedia+0098_replayobservation_rlo_succeeded_created_idxdiff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex b1b20944124f..b387086c9966 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -118,6 +118,10 @@ 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.+ media_render_attempts = models.PositiveSmallIntegerField(default=0, db_default=0)+ media_render_attempted_at = models.DateTimeField(null=True, blank=True)+class Meta:constraints = [# Succeeded rows are sticky; admin deletes to re-trigger. A backfill may retake a failed row.@@ -144,6 +148,12 @@ 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.+ models.Index(+ fields=["-created_at"],+ name="rlo_succeeded_created_idx",+ condition=models.Q(status="succeeded"),+ ),models.Index(fields=["workflow_id"],name="rlo_workflow_id_idx",diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 3bf01ade1ad7..017907324f8f 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -56,6 +56,10 @@ 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@@ -80,6 +84,7 @@ WORKFLOWS = [RefreshScannerEstimatesWorkflow,RefreshSearchSuggestionsWorkflow,ReplayVisionGeminiCleanupSweepWorkflow,+ ReplayVisionMediaBackfillWorkflow,SweepScannerWorkflow,VisionAlertCheckWorkflow,]@@ -131,6 +136,7 @@ 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,]@@ -147,6 +153,7 @@ __all__ = ["RefreshScannerEstimatesWorkflow","RefreshSearchSuggestionsWorkflow","ReplayVisionGeminiCleanupSweepWorkflow",+ "ReplayVisionMediaBackfillWorkflow","SweepScannerWorkflow","advance_scanner_watermark_activity","refresh_prompt_suggestion_activity",diff --git a/products/replay_vision/backend/temporal/activities/ensure_session_asset.py b/products/replay_vision/backend/temporal/activities/ensure_session_asset.pyindex 6d60dd665b3c..9a87fefaa655 100644--- a/products/replay_vision/backend/temporal/activities/ensure_session_asset.py+++ b/products/replay_vision/backend/temporal/activities/ensure_session_asset.py@@ -1,3 +1,4 @@+from django.db.models import QuerySetfrom django.utils.timezone import nowfrom temporalio import activity@@ -14,24 +15,37 @@ _SHOW_METADATA_FOOTER = True_MOUSE_TAIL = False+def analysis_export_context(session_id: str) -> dict[str, object]:+ """The render settings the scan reads back off its analysis video."""+ return {+ "session_recording_id": session_id,+ "playback_speed": _PLAYBACK_SPEED,+ "recording_fps": _RECORDING_FPS,+ "show_metadata_footer": _SHOW_METADATA_FOOTER,+ "mouse_tail": _MOUSE_TAIL,+ }+++def analysis_assets(team_id: int, session_id: str) -> "QuerySet[ExportedAsset]":+ """Every MP4 rendered for this session with the settings the scan reads back off it.++ Shared so a caller that only needs to find one cannot drift from the render parameters.+ """+ context = analysis_export_context(session_id)+ return ExportedAsset.objects.filter(+ team_id=team_id,+ export_format=_EXPORT_FORMAT,+ is_system=True,+ **{f"export_context__{key}": value for key, value in context.items()},+ )++@activity.defn@track_activity()async def ensure_session_asset_activity(inputs: EnsureSessionAssetInputs) -> EnsureSessionAssetOutput:"""Get-or-create the `is_system=True` MP4 ExportedAsset for `(team, session)`; concurrent runs may produce orphaned duplicates that the asset expiry cleans up."""existing_id = (- await ExportedAsset.objects.filter(- team_id=inputs.team_id,- export_format=_EXPORT_FORMAT,- export_context__session_recording_id=inputs.session_id,- export_context__playback_speed=_PLAYBACK_SPEED,- export_context__recording_fps=_RECORDING_FPS,- export_context__show_metadata_footer=_SHOW_METADATA_FOOTER,- export_context__mouse_tail=_MOUSE_TAIL,- is_system=True,- )- .order_by("id")- .values_list("id", flat=True)- .afirst()+ await analysis_assets(inputs.team_id, inputs.session_id).order_by("id").values_list("id", flat=True).afirst())if existing_id is not None:return EnsureSessionAssetOutput(asset_id=existing_id)@@ -40,13 +54,7 @@ async def ensure_session_asset_activity(inputs: EnsureSessionAssetInputs) -> Ensasset = await ExportedAsset.objects.acreate(team_id=inputs.team_id,export_format=_EXPORT_FORMAT,- export_context={- "session_recording_id": inputs.session_id,- "playback_speed": _PLAYBACK_SPEED,- "recording_fps": _RECORDING_FPS,- "show_metadata_footer": _SHOW_METADATA_FOOTER,- "mouse_tail": _MOUSE_TAIL,- },+ export_context=analysis_export_context(inputs.session_id),created_at=created_at,is_system=True,)diff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.pyindex 89fb46cc3d28..cdc3174a417a 100644--- a/products/replay_vision/backend/temporal/activities/observation_media.py+++ b/products/replay_vision/backend/temporal/activities/observation_media.py@@ -4,6 +4,7 @@ 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@@ -89,6 +90,12 @@ 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__.pynew file mode 100644index 000000000000..dca82344730e--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/__init__.py@@ -0,0 +1,9 @@+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.pynew file mode 100644index 000000000000..1c4e8c7c0cbf--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/activities.py@@ -0,0 +1,133 @@+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.pynew file mode 100644index 000000000000..e926d3d32f70--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/constants.py@@ -0,0 +1,29 @@+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.pynew file mode 100644index 000000000000..0b5057399673--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/schedule.py@@ -0,0 +1,30 @@+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.pynew file mode 100644index 000000000000..13bac098c33b--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/types.py@@ -0,0 +1,27 @@+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.pynew file mode 100644index 000000000000..bfd07276562d--- /dev/null+++ b/products/replay_vision/backend/temporal/media_backfill/workflow.py@@ -0,0 +1,88 @@+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 6d71085b6d6d..81dc21947635 100644--- a/products/replay_vision/backend/temporal/media_types.py+++ b/products/replay_vision/backend/temporal/media_types.py@@ -13,6 +13,14 @@ THUMBNAIL_WIDTH_PX = 1280FALLBACK_THUMBNAIL_FRACTION = 0.25+MEDIA_WORKFLOW_NAME = "replay-vision-media"+++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."""+ return f"{MEDIA_WORKFLOW_NAME}-{observation_id}"++class ObservationMediaInputs(BaseModel, frozen=True):"""Input to ObservationMediaWorkflow, started fail-soft once an observation has succeeded."""diff --git a/products/replay_vision/backend/temporal/media_workflow.py b/products/replay_vision/backend/temporal/media_workflow.pyindex 091cb1c91b0e..2685aa26b64b 100644--- a/products/replay_vision/backend/temporal/media_workflow.py+++ b/products/replay_vision/backend/temporal/media_workflow.py@@ -13,6 +13,7 @@ with wf.unsafe.imports_passed_through():prepare_observation_thumbnail_activity,)from products.replay_vision.backend.temporal.media_types import (+ MEDIA_WORKFLOW_NAME,ExtractThumbnailActivityOutput,FinalizeObservationThumbnailInputs,ObservationMediaInputs,@@ -21,9 +22,18 @@ 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.+_THUMBNAIL_RETRY = common.RetryPolicy(+ maximum_attempts=5,+ initial_interval=dt.timedelta(seconds=20),+ backoff_coefficient=3.0,+ maximum_interval=dt.timedelta(minutes=5),+)+# Bounds the retry chain, so a broken render releases the child before the execution timeout.+_THUMBNAIL_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=15)[email protected](name="replay-vision-media")[email protected](name=MEDIA_WORKFLOW_NAME)class ObservationMediaWorkflow(PostHogWorkflow):"""Render the media that illustrates one succeeded observation. Today that is a single thumbnail."""@@ -43,7 +53,8 @@ class ObservationMediaWorkflow(PostHogWorkflow):prepared.activity_input.model_dump(exclude_none=True),task_queue=settings.RASTERIZATION_MEDIA_TASK_QUEUE,start_to_close_timeout=_THUMBNAIL_TIMEOUT,- retry_policy=common.RetryPolicy(maximum_attempts=2),+ schedule_to_close_timeout=_THUMBNAIL_SCHEDULE_TO_CLOSE,+ retry_policy=_THUMBNAIL_RETRY,)await wf.execute_activity(diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 21ea777fd85b..e170a6f5ee95 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -206,6 +206,12 @@ 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}@@ -357,3 +363,14 @@ 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/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 6d6d7aa442a9..7e997a0ef833 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -56,7 +56,11 @@ from products.replay_vision.backend.temporal.errors import (IneligibleSessionKind,ScannerFailureError,)-from products.replay_vision.backend.temporal.media_types import ObservationMediaInputs+from products.replay_vision.backend.temporal.media_types import (+ MEDIA_WORKFLOW_NAME,+ ObservationMediaInputs,+ build_media_workflow_id,+)from products.replay_vision.backend.temporal.scanners.base import BaseScannerOutputfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutputfrom products.replay_vision.backend.temporal.types import (@@ -570,7 +574,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):# Started, not awaited: the poster is delivery, and the scan has no reason to hold a workflow# slot open while one frame is cut. ABANDON keeps the child alive past the parent's close.await wf.start_child_workflow(- "replay-vision-media",+ MEDIA_WORKFLOW_NAME,ObservationMediaInputs(team_id=inputs.team_id,observation_id=observation_id,@@ -579,7 +583,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):signal_video_times=call_output.signal_video_spans,thumbnail_video_s=call_output.thumbnail_video_s,),- id=f"replay-vision-media-{observation_id}",+ 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.id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,diff --git a/products/replay_vision/backend/tests/test_media_backfill.py b/products/replay_vision/backend/tests/test_media_backfill.pynew file mode 100644index 000000000000..5d9abd5b738e--- /dev/null+++ b/products/replay_vision/backend/tests/test_media_backfill.py@@ -0,0 +1,188 @@+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 cc0fa856d507..cd15635b8789 100644--- a/products/replay_vision/backend/tests/test_observation_media.py+++ b/products/replay_vision/backend/tests/test_observation_media.py@@ -1,3 +1,4 @@+import dataclassesfrom datetime import datetime, timedeltafrom typing import Any@@ -8,6 +9,7 @@ from django.utils import timezonefrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from temporalio.testing import ActivityEnvironmentfrom posthog.models.utils import uuid7@@ -65,7 +67,7 @@ class TestObservationMedia(BaseTest):is_system=True,)- def _prepare(self, **overrides: Any) -> Any:+ def _inputs(self, **overrides: Any) -> ObservationMediaInputs:fields: dict[str, Any] = {"team_id": self.team.id,"observation_id": self.observation.id,@@ -73,7 +75,10 @@ class TestObservationMedia(BaseTest):"analysis_asset_id": self.analysis_asset.id,}fields.update(overrides)- return async_to_sync(prepare_observation_thumbnail_activity)(ObservationMediaInputs(**fields))+ return ObservationMediaInputs(**fields)++ def _prepare(self, **overrides: Any) -> Any:+ return async_to_sync(prepare_observation_thumbnail_activity)(self._inputs(**overrides))def test_media_object_is_written_outside_the_exports_prefix(self) -> None:prepared = self._prepare()@@ -138,6 +143,23 @@ 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.id