: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
fix(replay-vision): align the backfill quote with the candidate walk (#80780)
Tue Haulund4853c6c89e71
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex 874b58b85731..9a348dc1c0d4 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -107,7 +107,7 @@ class ReplayObservation(UUIDModel):class Meta:constraints = [- # Failed/succeeded rows are sticky; admin deletes to re-trigger.+ # Succeeded rows are sticky; admin deletes to re-trigger. A backfill may retake a failed row.models.UniqueConstraint(fields=["scanner", "session_id"], name="replay_observation_unique_scanner_session"),models.CheckConstraint(condition=(diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 0e2dd6c968b8..601e3ab76237 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -198,8 +198,8 @@ def _sum_active_backfill_remaining_credits(organization_id: UUID) -> int:.filter(team__organization_id=organization_id, status__in=ACTIVE_BACKFILL_STATUSES).values_list("total_count", "dispatched_count", "skipped_count", "credits_per_observation"))- # Skipped candidates were counted at creation but will never be dispatched, so they are not a- # commitment; leaving them in strands phantom credits in the projection for the whole run.+ # Skipped candidates were quoted and then scanned by the live sweep first, so the backfill no longer+ # owes their credits. Leaving them in strands phantom commitment for the rest of the run.return sum(max(0, total - dispatched - skipped) * price for total, dispatched, skipped, price in rows)diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.pyindex 75e4760b88ea..5d6dfc573e10 100644--- a/products/replay_vision/backend/temporal/activities/backfill.py+++ b/products/replay_vision/backend/temporal/activities/backfill.py@@ -18,7 +18,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connectfrom products.replay_vision.backend.enqueue_claims import claim_enqueue_slot_prefix-from products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.replay_scanner_backfill import (ACTIVE_BACKFILL_STATUSES,BackfillStatus,@@ -156,16 +156,25 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> Fcandidate_limit=inputs.candidate_limit,).run()- # Dedup at creation only collides with a *running* apply, so without this a re-run over an- # already-scanned window pays for a child workflow per session just to no-op.- already_observed = set(+ # Succeeded only, matching the `$recording_observed` event the creation-time count excludes on.+ # Postgres rather than that count's fail-soft ClickHouse read, whose hiccup would report every session+ # unobserved and turn the retake path below into real re-scans and real charges.+ succeeded_at = dict(ReplayObservation.objects.filter(team_id=inputs.team_id,scanner_id=backfill.scanner_id,+ status=ObservationStatus.SUCCEEDED,session_id__in=[c.session_id for c in candidates],- ).values_list("session_id", flat=True)+ ).values_list("session_id", "completed_at"))- dispatchable = [c for c in candidates if c.session_id not in already_observed]+ dispatchable = [c for c in candidates if c.session_id not in succeeded_at]+ # Only sessions the live sweep reached after this backfill was quoted were in its total, so only those+ # count as work done; earlier successes were already excluded at creation.+ overtaken = {+ session_id+ for session_id, completed in succeeded_at.items()+ if completed is not None and completed > backfill.created_at+ }# Claim a slot per dispatchable candidate before the workflow starts its children: a started# child is invisible to the row-count caps until it persists its observation, so successive@@ -196,7 +205,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F# `dispatched_count` could never reach `total_count` on a window this scanner has already partly tried,# which strands progress short of complete and leaves phantom credits in the org's projected spend.walked_through = candidates.index(walked_to) + 1 if walked_to is not None else 0- skipped = walked_through - admitted+ skipped = sum(1 for c in candidates[:walked_through] if c.session_id in overtaken)return FindBackfillCandidatesOutput(started_from_cursor_end_time=backfill.cursor_end_time,diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex b07da8224851..9c2c4bc2cc5b 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -1,6 +1,7 @@from typing import Anyfrom django.db import IntegrityError, transaction+from django.utils import timezoneimport psycopg.errorsfrom temporalio import activity@@ -111,18 +112,28 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutscanner_type=scanner.scanner_type,)+ # Shared by the insert and the retake below, so a column added here can't be set on one path only.+ row_fields: dict[str, Any] = {+ "status": ObservationStatus.PENDING,+ # `replay_observation_completed_at_matches_status` requires a pending row to carry no completion time.+ "completed_at": None,+ # The reservation and the usage receipt both window off this, so a retake that kept the failed+ # attempt's stamp would bill into a period that may already be closed.+ "created_at": timezone.now(),+ "workflow_id": inputs.workflow_id,+ "scanner_snapshot": snapshot_dict,+ "triggered_by": inputs.triggered_by,+ "triggered_by_user_id": inputs.triggered_by_user_id,+ "backfill": backfill,+ }+try:with transaction.atomic():observation = ReplayObservation.objects.create(scanner=scanner,team=scanner.team,session_id=inputs.session_id,- status=ObservationStatus.PENDING,- workflow_id=inputs.workflow_id,- scanner_snapshot=snapshot_dict,- triggered_by=inputs.triggered_by,- triggered_by_user_id=inputs.triggered_by_user_id,- backfill=backfill,+ **row_fields,)except IntegrityError as e:# Only swallow the dedup case; FK / CHECK violations should fail the activity.@@ -137,11 +148,18 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut)# Route through the validator so a malformed legacy snapshot surfaces as a tagged non-retryable error.existing_snapshot = ScannerSnapshot.load_for(existing.id, existing.scanner_snapshot)+ # A backfill quotes sessions whose earlier scan failed, so retake that row rather than report progress+ # for a scan that never re-runs. Filtered on FAILED so a concurrent success wins and this no-ops.+ retaken = bool(+ backfill is not None+ and existing.status == ObservationStatus.FAILED+ and ReplayObservation.objects.filter(pk=existing.pk, status=ObservationStatus.FAILED).update(**row_fields)+ )# A still-PENDING row stamped with our own workflow id is our earlier lost-result insert — reclaim it.reclaimed = existing.workflow_id == inputs.workflow_id and existing.status == ObservationStatus.PENDINGreturn CreateObservationOutput(observation_id=existing.id,- was_created=reclaimed,+ was_created=retaken or reclaimed,scanner_type=existing_snapshot.scanner_type,)diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pyindex 830215714dac..5da1cab8f78a 100644--- a/products/replay_vision/backend/tests/test_backfills.py+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -17,7 +17,11 @@ from products.replay_vision.backend.api.backfills import (BackfillEnumerationThrottle,ReplayScannerBackfillViewSet,)-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ObservationTrigger+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)from products.replay_vision.backend.models.replay_scanner import (SETTLE_INTERVAL,ReplayScanner,@@ -158,6 +162,53 @@ class TestCreateObservationForBackfill:assert observation.scanner_snapshot["scanner_config"] == {"prompt": "frozen prompt"}assert observation.triggered_by == ObservationTrigger.BACKFILL+ @pytest.mark.parametrize(+ "seeded_status,expect_retaken",+ [+ # A failed scan emits no $recording_observed event, so the creation-time count quotes that session+ # as work. Leaving the row alone would report progress for a scan that never re-ran.+ (ObservationStatus.FAILED, True),+ # A succeeded session is already billed; retaking it would scan and charge twice.+ (ObservationStatus.SUCCEEDED, False),+ ],+ )+ def test_backfill_retakes_only_a_failed_observation(self, seeded_status: str, expect_retaken: bool) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ existing = ReplayObservation.objects.create(+ scanner=scanner,+ team=scanner.team,+ session_id="sess-1",+ status=seeded_status,+ workflow_id="wf-old",+ scanner_snapshot=_frozen_snapshot(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ completed_at=timezone.now(),+ )+ seeded_at = existing.created_at++ result = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-1",+ triggered_by=ObservationTrigger.BACKFILL,+ triggered_by_user_id=None,+ workflow_id="wf-new",+ backfill_id=backfill.id,+ )+ )++ assert result.was_created is expect_retaken+ existing.refresh_from_db()+ assert existing.status == (ObservationStatus.PENDING if expect_retaken else seeded_status)+ assert existing.workflow_id == ("wf-new" if expect_retaken else "wf-old")+ if expect_retaken:+ # A pending row must carry no completion time, and the period windows key off created_at,+ # so a retaken row billing into the period its first attempt ran in would escape the cap.+ assert existing.completed_at is None+ assert existing.created_at > seeded_at+def test_cancelled_backfill_skips_creation(self) -> None:scanner = _make_scanner()backfill = _make_backfill(scanner, status=BackfillStatus.CANCELLED, finished_at=timezone.now())@@ -265,10 +316,9 @@ class TestBackfillTickActivities:backfill.refresh_from_db()assert backfill.dispatched_count == 5- def test_skipped_candidates_count_toward_progress_and_release_their_commitment(self) -> None:- # Sessions the scanner already tried are counted at creation but never dispatched, so without- # crediting them progress can never reach total_count and the untouched remainder keeps- # inflating the org's projected spend for the whole run.+ def test_skipped_candidates_count_as_done_and_clear_their_commitment(self) -> None:+ # A skipped candidate was quoted and then scanned by the live sweep first, so it is done and the+ # backfill no longer owes its credits.scanner = _make_scanner()backfill = _make_backfill(scanner)ReplayScannerBackfill.objects.for_team(backfill.team_id).filter(pk=backfill.id).update(@@ -289,7 +339,7 @@ class TestBackfillTickActivities:backfill.refresh_from_db()assert (backfill.dispatched_count, backfill.skipped_count) == (6, 4)- assert backfill.dispatched_count + backfill.skipped_count == backfill.total_count+ # All ten accounted for, so nothing is still committed.assert spend_projection(scanner.team.organization_id).backfills_committed_credits == 0def test_advance_updates_cursor_and_short_batch_completes(self) -> None:diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsxindex d3160344c578..dd1b67c16900 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx@@ -126,18 +126,22 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.Ekey: 'progress',render: (_, backfill) => {const settled = backfill.succeeded_count + backfill.failed_count + backfill.ineligible_count- // Skipped recordings are done with, so they count toward progress; leaving them out- // strands the bar short of its total on any window the scanner had already partly tried.+ const skippedNote = backfill.skipped_count+ ? `, ${backfill.skipped_count} scanned by the live sweep first`+ : ''+ // Both count as done: dispatched by this backfill, or taken over by the sweep while it ran.const handled = backfill.dispatched_count + backfill.skipped_count- const skippedNote = backfill.skipped_count ? `, ${backfill.skipped_count} already scanned` : ''+ const nothingToDo = backfill.status === 'completed' && handled === 0+ const progress = nothingToDo+ ? 'Nothing left to scan'+ : `${handled.toLocaleString('en-US')} of ${backfill.total_count.toLocaleString(+ 'en-US'+ )} scanned${settled > 0 ? ` (${settled.toLocaleString('en-US')} settled)` : ''}`return (<Tooltiptitle={`${backfill.succeeded_count} succeeded, ${backfill.failed_count} failed, ${backfill.ineligible_count} ineligible, ${backfill.in_flight_count} in flight${skippedNote}`}>- <span>- {handled.toLocaleString('en-US')} of {backfill.total_count.toLocaleString('en-US')} handled- {settled > 0 ? ` (${settled.toLocaleString('en-US')} settled)` : ''}- </span>+ <span className={nothingToDo ? 'text-muted' : undefined}>{progress}</span></Tooltip>)},