: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): historical backfills for scanners (#79085)
Tue Haulundabb96fd19575
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 5a8e6dec6521..24bfcb7b8f3c 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -264,6 +264,7 @@ rules:|ReplayObservationLabel|ReplayObservationUsage|ReplayScanner+ |ReplayScannerBackfill|ReplayScannerPromptSuggestion|Repo|RepoRoutingRule@@ -610,6 +611,7 @@ rules:|ReplayObservationLabel|ReplayObservationUsage|ReplayScanner+ |ReplayScannerBackfill|ReplayScannerPromptSuggestion|Repo|RepoRoutingRulediff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ea086905b5b2..9038f21135d2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7019,9 +7019,9 @@ snapshots:scenes-app-replay-vision--scanner-editor-configure-tier-names--light:hash: v1.k794b7964.ce4949dd405f5c3f649603d9ef8c456fdbdb54bba316315da99de61381ed2adb.JE7suDQnoBdS-7uamAnvAQ49DzNNiyKXg8gh2HkeSOwscenes-app-replay-vision--scanner-editor-triggers--dark:- hash: v1.k794b7964.f3ba8840b00d2ad1cadba6bcc7e3394d5327327e2659676525564444c3502b5c.Cbr24do3OGZCDLPDZvcP8QXJnytpytSi4I8WB8cdz5s+ hash: v1.k794b7964.d5d7349cee24b107e7cc4026a11b525ebd8eaf0d58fcca76f476e4d9abe4df54.yxuHswihy4WM4sunFIL7bUKgJglMPmRmRRwtuavRnE0scenes-app-replay-vision--scanner-editor-triggers--light:- hash: v1.k794b7964.6290a477de19d7988d1382b57a37856deb6dd7da4d84f4b9da7eb055fba9eb15.0GmcdgRPuECrbutxVWwXKFH7lH0FEgWBksR-kGwi8QE+ hash: v1.k794b7964.74abe036edeb6479f4f8015cdc003465003e089c1a6a8b862a791afa1f8e907c.gblC39OvMrIptBQV0S2EtSws7fnFcD0H-QN75vG5t3Uscenes-app-replay-vision--scanner-observations--dark:hash: v1.k794b7964.836bbeb03dc8a6a02c7489875920b0e0098cc696580490eb7163b36eb8e835f3.r_NXe4vOXdXkB7NxFQuoq9N4a3BlD6DMwP5HHCX4c70scenes-app-replay-vision--scanner-observations--light:@@ -7035,21 +7035,21 @@ snapshots:scenes-app-replay-vision--scanner-templates--light:hash: v1.k794b7964.6c5b4b711fb1af56d29b5788348313d5a963e8f90c672a11ebc1d1e059884cb0.5vN5Bjf0TpzXvT_4cvpisjrfxVaveVdzA0_OALSdeEQscenes-app-replay-vision--scanners-list--dark:- hash: v1.k794b7964.fe74e30886a706a374e6db2af3a0440431d905e3e136264764d7018a3e2d89dc.Hs3f7Da68hnp-yX2tsgGGvdUfUdlxQ42XkUvyNz2s90+ hash: v1.k794b7964.f9c477e7ddedd2ca3df057155f8f56dc809a14f0adab09703bd958601e1e1ff1.lbVZQ47_DW-autefB6q_TIgLo4p8LbYBnjZ3qDKlQUsscenes-app-replay-vision--scanners-list--light:- hash: v1.k794b7964.f81504d48648f19b21f7ddf2c9442c52455bce5c48588959e5acff070ef8b69b.5pAS22um-Wki-ODtTjOw0D7ovzkk5OnD4lRBF4SbHtU+ hash: v1.k794b7964.ac26fc8b85f1f707838130407da7076e12f9846b8d52e2484ebda388e7e110a3.6NW_AV9o8JxLcpcP3ZTEA5ZszMdE7irC6foNFd1nMNoscenes-app-replay-vision--startup-program-cap--dark:- hash: v1.k794b7964.8367876fddc832954af0b927548951f2711b7ee98214495d221f30fc989b5e13.2X1TO-5JaluuEgdt2Rc3Qob82PcAh43pY3TXGsgABrk+ hash: v1.k794b7964.effc94d34b3b062b11dd0af0fb2204517034a323abf124db8844b662152fe73e.xmLf-KT-SJN7hqokhDgae9VzRgoON1oTn6KERsnaw-Yscenes-app-replay-vision--startup-program-cap--light:- hash: v1.k794b7964.b2e710513a3149bccd40a22fbe4ffa39df894867fd3effe4f56e62ba5fe83191.dyUpi7RZ_RtETlr2s5fiamCtlRzY7fxcsrn9kGNdXwQ+ hash: v1.k794b7964.4868ecb48e5f5f773c8e77fabab4ebce3eb223dfcff416396779324c3b237a6a.L1z_rYTahwj_8ZnsBmr1lC_Fz-JbqCVCPDX6L17dPIgscenes-app-replay-vision--summarizer-overview--dark:hash: v1.k794b7964.d7d432ba8156274a262953e51f967f433862cce316dd802f0fe2f4b56a3fdd14.57_3AVlefjGVbLbZNYt2DnQihf_EGLgE7HR1rZzZpqgscenes-app-replay-vision--summarizer-overview--light:hash: v1.k794b7964.f4cd388175bf16358030e2ad02abff949e1dccb34b702bb9ce8c4ce65ff32dfe.gfKH-mJ2VVS664K3yW1pg4gqSkPEBoFSspoe-446uOcscenes-app-replay-vision--usage-tab--dark:- hash: v1.k794b7964.429ccd5a1e987dcb8a926235ec5fbc42aff44a7e31c4bd77350e1e9973c6a967.MsoyFWWe0o-nRFlSjOPCtN9RZJTumwrf-K2YtavaRUs+ hash: v1.k794b7964.01fa1f108e7f37c99de9e5c17066c118bb508bd573cd1426ac015be008e1f07f.miPVL8MQMM1-QWULtvRBonS28PqGrf0QbUsqk7fUhpEscenes-app-replay-vision--usage-tab--light:- hash: v1.k794b7964.85d659e73222f0bb92c219a62e3fd528944b726d0552ac8d4033db8a1f61f0f9.jA8LQgrGupRzw_50CApS1Ny8Pqy3-ZoFw7zU7a2oIq4+ hash: v1.k794b7964.5720941b9fbc04e674c36e253a001363174d88f7468f6ee05455d4805f584a81.asfHysRPORqJe0n6Ufuc8LZdpRtJmXiRcl20ER96i_cscenes-app-saved-insights--empty-state--dark:hash: v1.k794b7964.43545664c9133c8afd354be6a6ed8f808c35b381101325d9605114632fcdc0c9.l8w9uEOEmrH6Xl1kNd9ueRtg_51cJUSjWLdjWDM0Fkoscenes-app-saved-insights--empty-state--light:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 1f7e6ec3fc71..523a249966e8 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -646,6 +646,7 @@ SPECTACULAR_SETTINGS = {"ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider","ObservationStatusEnum": "products.replay_vision.backend.models.replay_observation.ObservationStatus","ObservationTriggerEnum": "products.replay_vision.backend.models.replay_observation.ObservationTrigger",+ "BackfillStatusEnum": "products.replay_vision.backend.models.replay_scanner_backfill.BackfillStatus","ExportedRecordingStatusEnum": "products.replay.backend.models.exported_recording.ExportedRecording.Status","VisionActionRunStatusEnum": "products.replay_vision.backend.models.vision_action.VisionActionRunStatus","VisionAlertMetricEnum": "products.replay_vision.backend.models.vision_action.AlertMetric",diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex dcd426268897..66aa09c16923 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -4,12 +4,14 @@ A sub-product of Session Replay. Users configure named **scanners** that PostHog## Concepts-**Scanner** — a configured probe scoped to a team. Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, and a sampling rate. Each enabled scanner has a Temporal schedule that fires every 5 minutes and sweeps for newly settled recordings past the scanner's watermark (`last_swept_at`); disabling a scanner removes its schedule, and re-enabling restarts the sweep from now rather than backfilling the gap. Summarizers always emit per-facet embeddings for downstream free-text search.+**Scanner** — a configured probe scoped to a team. Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, and a sampling rate. Each enabled scanner has a Temporal schedule that fires every 5 minutes and sweeps for newly settled recordings past the scanner's watermark (`last_swept_at`); disabling a scanner removes its schedule, and re-enabling restarts the sweep from now rather than backfilling the gap (see **Backfill** for the explicit way to cover history). Summarizers always emit per-facet embeddings for downstream free-text search.**Inline scan** — a prompt pointed at named sessions with nothing saved, for a one-off question (`POST /vision/scanners/inline_scan/`, and the path agents take instead of creating a throwaway scanner). An observation belongs to a scanner, so a scan mints one keyed by a fingerprint of its config: the same question reuses the observations it already has, a different question gets its own. Those rows carry `origin=inline`, are never listed or swept, and are reaped once they have nothing to show. See `backend/inline_scan.py` for why they exist and `backend/scanner_access.py` for how results are read back.**Observation** — one application of a scanner to a session, unique per (scanner, session). Created in `pending` when triggered (by the scanner's schedule or the `/observe/` action), transitions to `running` while `ApplyScannerWorkflow` executes (rasterize the recording to video → upload to Gemini → multi-turn scan), and lands in `succeeded` (result persisted, then a `$recording_observed` event plus embeddings/tags emitted fail-soft), `failed` (with a `kind:message` `error_reason`), or `ineligible` (the session doesn't qualify — too short, too idle, no recording). Each observation snapshots the full scanner state (`scanner_snapshot`) that produced it, so subsequent edits to the scanner don't retro-mutate history. Rows stranded in `pending`/`running` by a dead workflow are failed as `orphaned` by a reaper on the reconciler tick.+**Backfill** — one historical scan of a scanner over a closed, past time window, walked newest-first. The window is closed, so the candidate query enumerates the exact eligible set at creation: the quoted cost (`total_count` x the model's credit price) is a ceiling, and actual spend only falls below it as already-observed sessions dedup, expired recordings land `ineligible`, and failures write no receipt. The scanner's full config is frozen into `scanner_snapshot` at creation, so later edits change neither the enumerated set nor the price nor what the observations record. A per-backfill Temporal schedule ticks every minute, dispatching the same `ApplyScannerWorkflow` children within the shared in-flight caps plus a per-backfill sub-cap; its `window_end` is clamped to the scanner's sweep watermark so live and backfill never contest a session. Backfill and live observations have equal quota priority: an active backfill's remaining commitment counts toward the projected monthly spend, the per-observation creation check enforces the org limit for both, and exhausting the monthly quota moves the backfill to `paused_quota` until an explicit resume.+**Quota** — succeeded observations write an immutable usage receipt; usage (receipts + in-flight rows) is counted against a monthly per-organization quota, with per-scanner volume estimates summed into a projected-usage prognosis shown at configuration time.## Experiment-created scanners@@ -20,10 +22,10 @@ The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` a## Layout-- `backend/models/` — `ReplayScanner`, `ReplayObservation`, usage receipts, quota grants.-- `backend/api/` — DRF viewsets and serializers (scanners, observations, stats, live progress over SSE).-- `backend/queries/` — ClickHouse candidate selection (watermark + settle window + eligibility + sampling) and volume estimates.-- `backend/temporal/` — the apply workflow and its activities, per-scanner sweep, schedule reconciler (+ observation reaper), estimate refresher, and the Gemini file cleanup sweep.+- `backend/models/` — `ReplayScanner`, `ReplayObservation`, `ReplayScannerBackfill`, usage receipts, quota grants.+- `backend/api/` — DRF viewsets and serializers (scanners, observations, backfills, stats, live progress over SSE).+- `backend/queries/` — ClickHouse candidate selection (watermark + settle window + eligibility + sampling), the backfill's bounded descending walk and its exact count, and volume estimates.+- `backend/temporal/` — the apply workflow and its activities, per-scanner sweep, per-backfill tick, schedule reconciler (+ observation and backfill-schedule reapers), estimate refresher, and the Gemini file cleanup sweep.- `backend/quota.py` — monthly quota accounting.- `backend/embeddings.py` — the embedding identity shared by the write and search sides.- `backend/max_tools.py` — Max AI tools (draft a scanner prompt, digest summaries, semantic search over observations).diff --git a/products/replay_vision/backend/admin.py b/products/replay_vision/backend/admin.pyindex 9c35771d44e9..64ddf4547301 100644--- a/products/replay_vision/backend/admin.py+++ b/products/replay_vision/backend/admin.py@@ -28,6 +28,7 @@ class ReplayObservationAdmin(admin.ModelAdmin):"session_id","triggered_by","triggered_by_user",+ "backfill","scanner_snapshot","scanner_result","workflow_id",diff --git a/products/replay_vision/backend/api/__init__.py b/products/replay_vision/backend/api/__init__.pyindex 547df0a7dab2..88b5d0d5881d 100644--- a/products/replay_vision/backend/api/__init__.py+++ b/products/replay_vision/backend/api/__init__.py@@ -1,3 +1,4 @@+from products.replay_vision.backend.api.backfills import ReplayScannerBackfillViewSetfrom products.replay_vision.backend.api.observations import ReplayObservationViewSet, SessionReplayObservationViewSetfrom products.replay_vision.backend.api.prompt_suggestions import ReplayScannerPromptSuggestionViewSetfrom products.replay_vision.backend.api.quota import VisionQuotaViewSet@@ -6,6 +7,7 @@ from products.replay_vision.backend.api.vision_actions import VisionActionRunVie__all__ = ["ReplayObservationViewSet",+ "ReplayScannerBackfillViewSet","ReplayScannerPromptSuggestionViewSet","ReplayScannerViewSet","SessionReplayObservationViewSet",diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.pynew file mode 100644index 000000000000..3aa4311afe56--- /dev/null+++ b/products/replay_vision/backend/api/backfills.py@@ -0,0 +1,369 @@+"""API for historical backfills: estimate, create, monitor, cancel, resume."""++import uuid+import datetime as dt+from datetime import datetime+from typing import Any, cast++from django.db import IntegrityError+from django.db.models import Count, Q, QuerySet+from django.utils import timezone++import structlog+from asgiref.sync import async_to_sync+from drf_spectacular.utils import extend_schema+from rest_framework import mixins, serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.shared import UserBasicSerializer+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle++from products.replay_vision.backend.billing import observation_credits_for_model+from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission+from products.replay_vision.backend.models.replay_observation import IN_FLIGHT_STATUSES, ObservationStatus+from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner+from products.replay_vision.backend.models.replay_scanner_backfill import (+ ACTIVE_BACKFILL_STATUSES,+ BackfillStatus,+ ReplayScannerBackfill,+)+from products.replay_vision.backend.queries.scanner_candidate_query import BackfillCandidateQuery+from products.replay_vision.backend.quota import quota_state+from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot++logger = structlog.get_logger(__name__)++# The enumeration runs inside the request; a pathological filter must fail the request, not hang it.+ENUMERATION_MAX_EXECUTION_SECONDS = 30++# Beyond a year a backfill is asking for recordings almost every team has already aged out, while the+# enumeration pays for the whole partition range. Bounds the per-request ClickHouse cost.+MAX_BACKFILL_WINDOW_DAYS = 365+++class BackfillEnumerationThrottle(PersonalApiKeyOrUserRateThrottle):+ """Covers session-authenticated callers, which the global burst/sustained throttles skip.++ `estimate` and `create` each run a synchronous ClickHouse enumeration, so an ordinary UI session+ could otherwise saturate the Replay Vision query pool by resubmitting wide windows.+ """++ scope = "replay_vision_backfill_enumeration"+ rate = "20/minute"+++class BackfillWindowSerializer(serializers.Serializer):+ window_start = serializers.DateTimeField(help_text="Inclusive lower bound of the historical window to scan.")+ window_end = serializers.DateTimeField(help_text="Exclusive upper bound of the window; clamped server-side to now.")++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if attrs["window_start"] >= attrs["window_end"]:+ raise ValidationError("window_start must be before window_end.")+ if attrs["window_end"] - attrs["window_start"] > dt.timedelta(days=MAX_BACKFILL_WINDOW_DAYS):+ raise ValidationError(+ f"Backfill windows are limited to {MAX_BACKFILL_WINDOW_DAYS} days. Pick a shorter range."+ )+ return attrs+++class BackfillEstimateResponseSerializer(serializers.Serializer):+ total_sessions = serializers.IntegerField(+ help_text="Upper bound on the sessions the backfill would scan, after sampling and quality "+ "filters and excluding sessions this scanner already reported an observation for."+ )+ total_credits = serializers.IntegerField(+ help_text="Cost ceiling in credits (1 credit = $0.01): total_sessions x credits_per_observation. "+ "Actual spend lands under it: sessions already tried, expired recordings, and failures are not billed."+ )+ credits_per_observation = serializers.IntegerField(+ help_text="Per-observation credit price at the scanner's current model."+ )+ credits_remaining = serializers.IntegerField(+ allow_null=True, help_text="Credits left in the org's monthly quota; null when the org is uncapped."+ )+ window_start = serializers.DateTimeField(help_text="The window lower bound the estimate covered.")+ window_end = serializers.DateTimeField(help_text="The window upper bound after clamping to now.")+++class ReplayScannerBackfillSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True, allow_null=True)+ succeeded_count = serializers.IntegerField(+ read_only=True, help_text="Observations from this backfill that succeeded."+ )+ failed_count = serializers.IntegerField(read_only=True, help_text="Observations from this backfill that failed.")+ ineligible_count = serializers.IntegerField(+ read_only=True, help_text="Sessions that turned out ineligible (too short, expired recording, ...)."+ )+ in_flight_count = serializers.IntegerField(+ read_only=True, help_text="Observations from this backfill still pending or running."+ )++ class Meta:+ model = ReplayScannerBackfill+ fields = [+ "id",+ "status",+ "window_start",+ "window_end",+ "total_count",+ "dispatched_count",+ "skipped_count",+ "credits_per_observation",+ "succeeded_count",+ "failed_count",+ "ineligible_count",+ "in_flight_count",+ "created_by",+ "created_at",+ "finished_at",+ ]+ read_only_fields = fields+++class ReplayScannerBackfillViewSet(+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ viewsets.GenericViewSet,+):+ """Historical backfills of a scanner over a closed time window (nested under a scanner)."""++ scope_object = "replay_scanner"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["create", "estimate", "cancel", "resume"]+ permission_classes = [ReplayVisionEnabledPermission]+ serializer_class = ReplayScannerBackfillSerializer+ # `objects` is fail-closed; `safely_get_queryset` re-scopes to the request team and scanner.+ queryset = ReplayScannerBackfill.objects.unscoped()++ def get_throttles(self) -> list[Any]:+ # Append, never replace: returning only this throttle would drop the global burst and+ # sustained limits from the two actions that run the heaviest query.+ if self.action in ("estimate", "create"):+ return [*super().get_throttles(), BackfillEnumerationThrottle()]+ return super().get_throttles()++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ # Same authorization as /observe/: a backfill dispatches scans, which exposes recording contents.+ if self.action in self.scope_object_write_actions:+ return ["replay_scanner:write", "session_recording:read"]+ return ["replay_scanner:read", "session_recording:read"]++ def _scanner_for_url(self) -> ReplayScanner:+ cached = getattr(self, "_scanner_for_url_cache", None)+ if cached is not None:+ return cached+ try:+ scanner_id = uuid.UUID(self.kwargs["parent_lookup_scanner_id"])+ except (KeyError, ValueError):+ raise NotFound()+ # `objects` is configured-only: an inline scan is a throwaway keyed to one question, so it has+ # no schedule to backfill and must not be addressable here (unlike the observation read paths,+ # which opt into `all_origins` to show inline results).+ scanner = ReplayScanner.objects.filter(team_id=self.team_id, pk=scanner_id).first()+ if scanner is None:+ raise NotFound()+ # Backfills expose and dispatch recording-derived scans, so they inherit the scanner's RBAC+ # and also require session_recording read (mirrors ReplayObservationViewSet._scanner_for_url).+ self.check_object_permissions(self.request, scanner)+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Replay Vision backfills require session_recording read access.")+ self._scanner_for_url_cache = scanner+ return scanner++ def safely_get_queryset(self, queryset: QuerySet[ReplayScannerBackfill]) -> QuerySet[ReplayScannerBackfill]:+ return (+ queryset.filter(team_id=self.team_id, scanner=self._scanner_for_url())+ .select_related("created_by")+ .annotate(+ succeeded_count=Count("observations", filter=Q(observations__status=ObservationStatus.SUCCEEDED)),+ failed_count=Count("observations", filter=Q(observations__status=ObservationStatus.FAILED)),+ ineligible_count=Count("observations", filter=Q(observations__status=ObservationStatus.INELIGIBLE)),+ in_flight_count=Count("observations", filter=Q(observations__status__in=IN_FLIGHT_STATUSES)),+ )+ .order_by("-created_at")+ )++ def _clamped_window(self, data: dict[str, Any]) -> tuple[datetime, datetime]:+ """The requested window, bounded above by the settle horizon the live sweep also waits for.++ Not `now`: a session inside the settle window is still recording or still merging, so scanning it+ yields a truncated observation, and the unique (scanner, session) constraint makes that the only+ observation the session will ever get. The live sweep could never replace it once the recording+ finished. Clamping here rather than in the query keeps the quoted count and the walk in agreement,+ so nobody is quoted for sessions the walk will skip.++ Deliberately not clamped to the scanner's sweep watermark. Overlapping the live sweep is safe:+ both paths mint the same deterministic workflow id and the unique (scanner, session) constraint+ means a session can only ever produce one observation, so nothing is scanned or billed twice.+ Whether a backfill is worth running is decided by how many *unobserved* recordings it would+ find, which `_enumerate` answers directly.+ """+ window_end = min(data["window_end"], timezone.now() - SETTLE_INTERVAL)+ window_start = data["window_start"]+ if window_start >= window_end:+ raise ValidationError("The end of the range must be in the past. Pick an earlier range.")+ return window_start, window_end++ def _enumerate(+ self,+ scanner: ReplayScanner,+ window_start: datetime,+ window_end: datetime,+ exclude_observed: bool = False,+ ) -> int:+ snapshot = BackfillScannerSnapshot.from_scanner(scanner)+ return BackfillCandidateQuery(+ team=self.team,+ query=scanner.recordings_query(),+ window_start=window_start,+ window_end=window_end,+ sampling_rate=snapshot.sampling_rate,+ sampling_salt=str(scanner.id),+ sampling_mode=snapshot.sampling_mode,+ exclude_observed_by_scanner=str(scanner.id) if exclude_observed else None,+ max_execution_time_seconds=ENUMERATION_MAX_EXECUTION_SECONDS,+ ).count()++ def _unobserved_count(self, scanner: ReplayScanner, window_start: datetime, window_end: datetime) -> int:+ """Upper bound on what a backfill over this window would scan, rejecting when it is zero.++ An upper bound rather than exact: the exclusion reads `$recording_observed`, which only exists+ for observations that succeeded and managed to publish, so sessions already tried and found+ ineligible or failed still count here. They cannot produce a second observation, so the real+ spend lands under the quote.++ Distinguishes "nothing here matches the scanner" from "everything here is already done"; the+ second count only runs on the rejection path, so the happy path stays at one ClickHouse query.+ """+ unobserved = self._enumerate(scanner, window_start, window_end, exclude_observed=True)+ if unobserved > 0:+ return unobserved+ if self._enumerate(scanner, window_start, window_end) > 0:+ raise ValidationError("All recordings in this range have already been scanned. Pick a different range.")+ # Naming sampling matters: a heavily sampled scanner finds nothing in a short range even+ # though its filters match plenty, and "filters" alone sends people to edit the wrong setting.+ if scanner.sampling_rate < 1:+ raise ValidationError(+ f"No recordings in this range match this scanner. It samples {scanner.sampling_rate:.1%} of "+ "sessions, so try a wider range."+ )+ raise ValidationError("No recordings in this range match this scanner's filters. Try a wider range.")++ @extend_schema(request=BackfillWindowSerializer, responses={200: BackfillEstimateResponseSerializer})+ @action(detail=False, methods=["post"], pagination_class=None)+ def estimate(self, request: Request, **kwargs: Any) -> Response:+ """Exactly enumerate what a backfill over the given window would dispatch and cost."""+ scanner = self._scanner_for_url()+ window = BackfillWindowSerializer(data=request.data)+ window.is_valid(raise_exception=True)+ window_start, window_end = self._clamped_window(window.validated_data)+ total = self._unobserved_count(scanner, window_start, window_end)+ price = observation_credits_for_model(scanner.model)+ quota = quota_state(self.team.organization_id)+ response = BackfillEstimateResponseSerializer(+ {+ "total_sessions": total,+ "total_credits": total * price,+ "credits_per_observation": price,+ "credits_remaining": quota.remaining,+ "window_start": window_start,+ "window_end": window_end,+ }+ )+ return Response(response.data)++ @extend_schema(request=BackfillWindowSerializer, responses={201: ReplayScannerBackfillSerializer})+ def create(self, request: Request, **kwargs: Any) -> Response:+ """Create a backfill: freeze the scanner config, enumerate the exact candidate set, start the tick schedule.++ The enumeration reruns here rather than trusting the client-confirmed estimate: the count is+ billing-relevant, so the authoritative value is computed server-side at creation time. New+ settled sessions between estimate and confirm can nudge total_count slightly.+ """+ scanner = self._scanner_for_url()+ window = BackfillWindowSerializer(data=request.data)+ window.is_valid(raise_exception=True)+ window_start, window_end = self._clamped_window(window.validated_data)+ if ReplayScannerBackfill.objects.filter(scanner=scanner, status__in=ACTIVE_BACKFILL_STATUSES).exists():+ raise ValidationError("This scanner already has an active backfill.")++ snapshot = BackfillScannerSnapshot.from_scanner(scanner)+ total = self._unobserved_count(scanner, window_start, window_end)+ try:+ backfill = ReplayScannerBackfill.objects.create(+ scanner=scanner,+ team=self.team,+ window_start=window_start,+ window_end=window_end,+ scanner_snapshot=snapshot.model_dump(mode="json"),+ credits_per_observation=observation_credits_for_model(snapshot.model),+ total_count=total,+ created_by=cast(Any, request.user),+ )+ except IntegrityError:+ # Concurrent create lost the one-active-per-scanner race.+ raise ValidationError("This scanner already has an active backfill.")++ # noqa below: keeps the temporalio client stack off the API module-load path.+ from products.replay_vision.backend.temporal.schedule import a_upsert_backfill_schedule # noqa: PLC0415++ try:+ async_to_sync(a_upsert_backfill_schedule)(backfill.id, scanner.team_id, scanner.id)+ except Exception:+ # The reconciler recreates missing schedules for running backfills, so don't fail the request.+ logger.exception("replay_vision.backfill_schedule_create_failed", backfill_id=str(backfill.id))++ # A just-created backfill has no observations; skip the aggregate re-query.+ for count_attr in ("succeeded_count", "failed_count", "ineligible_count", "in_flight_count"):+ setattr(backfill, count_attr, 0)+ return Response(self.get_serializer(backfill).data, status=status.HTTP_201_CREATED)++ @extend_schema(responses={200: ReplayScannerBackfillSerializer})+ @action(detail=True, methods=["post"], pagination_class=None)+ def cancel(self, request: Request, **kwargs: Any) -> Response:+ """Stop an active backfill; already-dispatched observations finish, nothing new dispatches."""+ backfill = self.get_object()+ updated = ReplayScannerBackfill.objects.filter(pk=backfill.pk, status__in=ACTIVE_BACKFILL_STATUSES).update(+ status=BackfillStatus.CANCELLED, finished_at=timezone.now()+ )+ if updated:+ from products.replay_vision.backend.temporal.schedule import a_delete_backfill_schedule # noqa: PLC0415++ try:+ async_to_sync(a_delete_backfill_schedule)(backfill.pk)+ except Exception:+ # The tick workflow and the reconciler both delete schedules of terminal rows.+ logger.exception("replay_vision.backfill_schedule_delete_failed", backfill_id=str(backfill.pk))+ backfill.status = BackfillStatus.CANCELLED+ backfill.finished_at = timezone.now()+ return Response(self.get_serializer(backfill).data)++ @extend_schema(responses={200: ReplayScannerBackfillSerializer})+ @action(detail=True, methods=["post"], pagination_class=None)+ def resume(self, request: Request, **kwargs: Any) -> Response:+ """Restart a backfill that paused when the monthly quota ran out."""+ backfill = self.get_object()+ updated = ReplayScannerBackfill.objects.filter(pk=backfill.pk, status=BackfillStatus.PAUSED_QUOTA).update(+ status=BackfillStatus.RUNNING+ )+ if not updated:+ raise ValidationError("Only a backfill paused on quota can be resumed.")+ from products.replay_vision.backend.temporal.schedule import a_resume_backfill_schedule # noqa: PLC0415++ try:+ async_to_sync(a_resume_backfill_schedule)(backfill.pk, backfill.team_id, backfill.scanner_id)+ except Exception:+ # A RUNNING row with a paused schedule would never tick again and nothing repairs it,+ # so roll the status back and surface the failure for a retry.+ logger.exception("replay_vision.backfill_schedule_resume_failed", backfill_id=str(backfill.pk))+ ReplayScannerBackfill.objects.filter(pk=backfill.pk, status=BackfillStatus.RUNNING).update(+ status=BackfillStatus.PAUSED_QUOTA+ )+ raise APIException("Couldn't resume the backfill. Try again.")+ backfill.status = BackfillStatus.RUNNING+ return Response(self.get_serializer(backfill).data)diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 4fdea43b3406..1d447c43187e 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -171,7 +171,12 @@ class ReplayObservationSerializer(serializers.ModelSerializer):triggered_by = serializers.ChoiceField(choices=ObservationTrigger.choices,read_only=True,- help_text="Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.",+ help_text="Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.",+ )+ backfill_id = serializers.UUIDField(+ read_only=True,+ allow_null=True,+ help_text="Backfill that dispatched this observation; null for live, on-demand, and retry triggers.",)triggered_by_user = UserBasicSerializer(read_only=True,@@ -238,6 +243,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):"scanner_result","triggered_by","triggered_by_user",+ "backfill_id","distinct_id","recording_subject_email","previous_observation_id",@@ -513,7 +519,10 @@ class ReplayObservationFilter(django_filters.FilterSet):triggered_by = MultiChoiceFilter(field_name="triggered_by",valid_choices=frozenset(v for v, _ in ObservationTrigger.choices),- help_text="Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.",+ help_text="Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.",+ )+ backfill_id = django_filters.UUIDFilter(+ field_name="backfill_id", help_text="Only observations dispatched by this backfill.")verdict = MultiChoiceFilter(field_name="scanner_result__model_output__verdict",diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.pyindex e1d3d74a8875..2512b0e9b6d8 100644--- a/products/replay_vision/backend/api/prompt_suggestions.py+++ b/products/replay_vision/backend/api/prompt_suggestions.py@@ -46,7 +46,7 @@ from products.replay_vision.backend.prompt_suggestions import (generate_prompt_suggestion,labels_fingerprint,)-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.quota import quota_statefrom products.replay_vision.backend.scanner_config import scanner_config_errorfrom products.replay_vision.backend.temporal.constants import (EVALUATE_PROMPT_SUGGESTION_WORKFLOW_NAME,@@ -428,7 +428,7 @@ class ReplayScannerPromptSuggestionViewSet(# overspend the month. An uncapped org (no credit limit) never trips this.planned = min(session_limit, rated_count)planned_credits = planned * observation_credits_for_model(scanner.model)- quota = compute_quota_snapshot(organization_id=self.team.organization_id)+ quota = quota_state(organization_id=self.team.organization_id)if quota.would_exceed(planned_credits):raise QuotaLimitExceeded(detail=(diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.pyindex 1a8cced85fc5..28e48a9d4814 100644--- a/products/replay_vision/backend/api/quota.py+++ b/products/replay_vision/backend/api/quota.py@@ -42,12 +42,27 @@ class VisionQuotaSerializer(serializers.Serializer):help_text="First moment of the next quota period (UTC); the current period's exclusive upper bound.",)projected_monthly_credits = serializers.IntegerField(+ read_only=True,+ help_text=(+ "`scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; "+ "prefer the two components when pro-rating, since only the scanner half is a monthly rate."+ ),+ )+ scanners_monthly_credits = serializers.IntegerField(read_only=True,help_text=("Credit-weighted sum of enabled scanners' projected observations/month across the organization. "+ "A monthly rate: only the part falling in the days left of the period lands this period. ""Scanners without a computed estimate contribute 0."),)+ backfills_committed_credits = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than "+ "a rate, so it lands in full regardless of how much of the period is left."+ ),+ )free_monthly_credits = serializers.IntegerField(read_only=True,help_text=(diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 308bdab9414a..9a699fdbaa4b 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -80,7 +80,7 @@ from products.replay_vision.backend.quota import (ScannerSpend,credits_used_by_scanner,current_period_bounds,- sum_enabled_scanner_estimated_credits,+ spend_projection,)from products.replay_vision.backend.scanner_config import (MAX_PROMPT_LENGTH,@@ -89,8 +89,8 @@ from products.replay_vision.backend.scanner_config import (scanner_config_error,)from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN, run_inline_scan, scan_existing_scanner+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags-from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH# Date is set by the schedule at trigger time, not by the user — strip on save._QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")@@ -992,6 +992,13 @@ class EstimateResponseSerializer(serializers.Serializer):"double-count the edited scanner."),)+ active_backfill_credits = serializers.IntegerField(+ help_text=(+ "Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's "+ "projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own "+ "segment instead of adding it to a per-month total."+ ),+ )sampling_rate = serializers.FloatField(help_text="Sampling rate applied to the projection. Echoed from the request.",)@@ -1631,11 +1638,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viobservations_per_month = project_monthly_observations(estimate, sampling_rate)credits_per_observation = observation_credits_for_model(body.validated_data["model"])- # The OTHER enabled scanners' projected total (same source as the quota snapshot), so the editor adds this- # estimate on top of a consistent snapshot instead of subtracting a possibly-stale per-scanner field.- other_enabled_scanners_monthly_credits = sum_enabled_scanner_estimated_credits(- self.team.organization_id, exclude_scanner_id=scanner_id- )+ # One projection read, excluding the scanner being edited, so the editor adds this estimate on top of a+ # consistent snapshot instead of subtracting a possibly-stale per-scanner field.+ projection = spend_projection(self.team.organization_id, exclude_scanner_id=scanner_id)return Response(EstimateResponseSerializer(@@ -1645,7 +1650,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi"estimated_observations_per_month": observations_per_month,"credits_per_observation": credits_per_observation,"estimated_credits_per_month": observations_per_month * credits_per_observation,- "other_enabled_scanners_monthly_credits": other_enabled_scanners_monthly_credits,+ "other_enabled_scanners_monthly_credits": projection.scanners_monthly_credits,+ "active_backfill_credits": projection.backfills_committed_credits,"sampling_rate": sampling_rate,}).datadiff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.pyindex 285e8dab5454..22554475018d 100644--- a/products/replay_vision/backend/api/trigger.py+++ b/products/replay_vision/backend/api/trigger.py@@ -32,7 +32,7 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.quota import quota_statefrom products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_EXECUTION_TIMEOUT,APPLY_SCANNER_WORKFLOW_NAME,@@ -68,7 +68,7 @@ def check_team_in_flight_capacity(team_id: int) -> None:def check_observation_quota(organization_id: UUID, observation_credits: int) -> None:"""Raise 402 when starting an observation of this credit cost would exceed the org's monthly limit."""- snapshot = compute_quota_snapshot(organization_id=organization_id)+ snapshot = quota_state(organization_id=organization_id)if snapshot.would_exceed(observation_credits):# would_exceed is only ever true when a limit is set, so credit_limit is non-None here.assert snapshot.credit_limit is not Nonediff --git a/products/replay_vision/backend/enqueue_claims.py b/products/replay_vision/backend/enqueue_claims.pyindex 177d1ca011a7..b188c6acc8d3 100644--- a/products/replay_vision/backend/enqueue_claims.py+++ b/products/replay_vision/backend/enqueue_claims.py@@ -14,6 +14,7 @@ import structlogfrom posthog import redisfrom products.replay_vision.backend.temporal.constants import (+ MAX_IN_FLIGHT_APPLIES_PER_BACKFILL,MAX_IN_FLIGHT_APPLIES_PER_SCANNER,MAX_IN_FLIGHT_APPLIES_PER_TEAM,)@@ -29,34 +30,33 @@ _RELEASE_GRACE_SECONDS = 60_TEAM_KEY_PREFIX = "@posthog/replay-vision/enqueued-team"_SCANNER_KEY_PREFIX = "@posthog/replay-vision/enqueued-scanner"+_BACKFILL_KEY_PREFIX = "@posthog/replay-vision/enqueued-backfill"# Re-claiming an existing member (same deterministic workflow id) never consumes a second slot.+# Generalized over KEYS: each key is one cap the claim must fit, with its allowance in ARGV[3 + i].+# Callers pass team and scanner; a backfill adds its own sub-cap key as a third._CLAIM_LUA = """-local team_key = KEYS[1]-local scanner_key = KEYS[2]local now = tonumber(ARGV[1])local member = ARGV[2]-local team_allowance = tonumber(ARGV[3])-local scanner_allowance = tonumber(ARGV[4])-local ttl = tonumber(ARGV[5])+local ttl = tonumber(ARGV[3])-redis.call('ZREMRANGEBYSCORE', team_key, '-inf', now)-redis.call('ZREMRANGEBYSCORE', scanner_key, '-inf', now)+for i, key in ipairs(KEYS) do+ redis.call('ZREMRANGEBYSCORE', key, '-inf', now)+end-if not redis.call('ZSCORE', team_key, member) then- if redis.call('ZCARD', team_key) >= team_allowance then- return 0- end- if redis.call('ZCARD', scanner_key) >= scanner_allowance then- return 0+if not redis.call('ZSCORE', KEYS[1], member) then+ for i, key in ipairs(KEYS) do+ if redis.call('ZCARD', key) >= tonumber(ARGV[3 + i]) then+ return 0+ endendendlocal expiry = now + ttl-redis.call('ZADD', team_key, expiry, member)-redis.call('ZADD', scanner_key, expiry, member)-redis.call('EXPIRE', team_key, ttl)-redis.call('EXPIRE', scanner_key, ttl)+for i, key in ipairs(KEYS) do+ redis.call('ZADD', key, expiry, member)+ redis.call('EXPIRE', key, ttl)+endreturn 1"""@@ -69,6 +69,10 @@ def _scanner_key(scanner_id: UUID) -> str:return f"{_SCANNER_KEY_PREFIX}:{scanner_id}"+def _backfill_key(backfill_id: UUID) -> str:+ return f"{_BACKFILL_KEY_PREFIX}:{backfill_id}"++def try_claim_enqueue_slot(*,team_id: int,@@ -76,21 +80,31 @@ def try_claim_enqueue_slot(workflow_id: str,team_in_flight_rows: int,scanner_in_flight_rows: int,+ backfill_id: UUID | None = None,+ backfill_in_flight_rows: int = 0,) -> bool:- """Atomically claim one enqueue slot against both in-flight caps; True when the scan may start."""- team_allowance = MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight_rows- scanner_allowance = MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight_rows+ """Atomically claim one enqueue slot against every in-flight cap; True when the scan may start.++ Passing `backfill_id` also holds the claim against that backfill's sub-cap, so successive ticks+ see the slots an earlier tick took before its children persisted their rows.+ """+ keys = [_team_key(team_id), _scanner_key(scanner_id)]+ allowances = [+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight_rows,+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight_rows,+ ]+ if backfill_id is not None:+ keys.append(_backfill_key(backfill_id))+ allowances.append(MAX_IN_FLIGHT_APPLIES_PER_BACKFILL - backfill_in_flight_rows)try:allowed = redis.get_client().eval(_CLAIM_LUA,- 2,- _team_key(team_id),- _scanner_key(scanner_id),+ len(keys),+ *keys,time.time(),workflow_id,- team_allowance,- scanner_allowance,_CLAIM_TTL_SECONDS,+ *allowances,)return bool(allowed)except Exception:@@ -99,18 +113,61 @@ def try_claim_enqueue_slot(return True-def release_enqueue_claim(*, team_id: int, scanner_id: UUID, workflow_id: str, immediately: bool = False) -> None:+def claim_enqueue_slot_prefix(+ *,+ team_id: int,+ scanner_id: UUID,+ workflow_ids: list[str],+ team_in_flight_rows: int,+ scanner_in_flight_rows: int,+ backfill_id: UUID | None = None,+ backfill_in_flight_rows: int = 0,+) -> int:+ """Claim slots for an ordered batch, returning how many leading ids were admitted.++ The batch variant of `claim_apply_scanner_slot` (which is per-request and re-reads the caps after+ each claim, far too many queries for a 50-wide fan-out). One row-count read is shared across the+ batch, which is sound because the Lua script counts claims taken earlier in the same loop itself.++ Stops at the first refusal instead of skipping ahead, so the admitted set is always a prefix of+ the caller's ordering. A keyset walk can then advance its cursor to the last admitted item and+ retry the rest, rather than stepping over sessions that were never dispatched.+ """+ for admitted, workflow_id in enumerate(workflow_ids):+ if not try_claim_enqueue_slot(+ team_id=team_id,+ scanner_id=scanner_id,+ workflow_id=workflow_id,+ team_in_flight_rows=team_in_flight_rows,+ scanner_in_flight_rows=scanner_in_flight_rows,+ backfill_id=backfill_id,+ backfill_in_flight_rows=backfill_in_flight_rows,+ ):+ return admitted+ return len(workflow_ids)+++def release_enqueue_claim(+ *,+ team_id: int,+ scanner_id: UUID,+ workflow_id: str,+ immediately: bool = False,+ backfill_id: UUID | None = None,+) -> None:"""Decay a claim once its observation row exists (or the start failed); unreleased claimsself-expire. `immediately` removes it outright, for claims that never covered anything."""expiry = time.time() + _RELEASE_GRACE_SECONDStry:+ keys = [_team_key(team_id), _scanner_key(scanner_id)]+ if backfill_id is not None:+ keys.append(_backfill_key(backfill_id))pipeline = redis.get_client().pipeline()- if immediately:- pipeline.zrem(_team_key(team_id), workflow_id)- pipeline.zrem(_scanner_key(scanner_id), workflow_id)- else:- pipeline.zadd(_team_key(team_id), {workflow_id: expiry}, xx=True)- pipeline.zadd(_scanner_key(scanner_id), {workflow_id: expiry}, xx=True)+ for key in keys:+ if immediately:+ pipeline.zrem(key, workflow_id)+ else:+ pipeline.zadd(key, {workflow_id: expiry}, xx=True)pipeline.execute()except Exception:record_enqueue_claim_failure("release")@@ -122,10 +179,31 @@ def pending_enqueue_claims_for_team(team_id: int) -> int:return _pending(_team_key(team_id))+def pending_enqueue_claims_for_backfill(backfill_id: UUID) -> int:+ return _pending(_backfill_key(backfill_id))++def pending_enqueue_claims_for_scanner(scanner_id: UUID) -> int:return _pending(_scanner_key(scanner_id))+def pending_enqueue_claims(team_id: int, scanner_id: UUID, backfill_id: UUID | None = None) -> dict[str, int]:+ """The three claim counts a cap check needs, in one round-trip instead of three."""+ keys = {"team": _team_key(team_id), "scanner": _scanner_key(scanner_id)}+ if backfill_id is not None:+ keys["backfill"] = _backfill_key(backfill_id)+ try:+ pipeline = redis.get_client().pipeline()+ cutoff = f"({time.time()}"+ for key in keys.values():+ pipeline.zcount(key, cutoff, "+inf")+ return dict(zip(keys, (int(count) for count in pipeline.execute())))+ except Exception:+ record_enqueue_claim_failure("count")+ logger.warning("replay_vision.enqueue_claim.count_failed", keys=list(keys.values()), exc_info=True)+ return dict.fromkeys(keys, 0)++def _pending(key: str) -> int:try:return int(redis.get_client().zcount(key, f"({time.time()}", "+inf"))diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex 211452923463..5f780662867c 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -47,7 +47,7 @@ from products.replay_vision.backend.queries.scanner_volume_estimate import (estimate_scanner_session_volume,project_monthly_observations,)-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.quota import compute_quota_snapshot, quota_statefrom products.replay_vision.backend.scanner_access import (is_uuid,scanner_for_reading_observations,@@ -769,7 +769,7 @@ def _truncate(text: str, limit: int = 120) -> str:def _credit_sentence(team: Team, cost: int, lead: str = "about") -> str:"""Credits and dollars against what's left. One phrasing, so a conversation never prices the samenumber two different ways."""- return _price(cost, compute_quota_snapshot(team.organization_id).remaining, lead)+ return _price(cost, quota_state(team.organization_id).remaining, lead)def _price(cost: int, remaining: int | None, lead: str = "about") -> str:@@ -1765,7 +1765,7 @@ class EstimateReplayVisionScannerTool(ReplayVisionGatesMixin, MaxTool):return "Couldn't work out the volume for that scanner just now.", {"error": "estimate_failed"}observations = project_monthly_observations(estimate, rate)cost = observation_credits_for_model(scanner.model) * observations- remaining = compute_quota_snapshot(self._team.organization_id).remaining+ remaining = quota_state(self._team.organization_id).remainingreturn (f"About {observations} recordings a month at {rate:.0%} sampling, costing roughly "f"{_price(cost, remaining, lead='')}".strip(),diff --git a/products/replay_vision/backend/migrations/0063_alter_replayobservation_triggered_by_and_more.py b/products/replay_vision/backend/migrations/0063_alter_replayobservation_triggered_by_and_more.pynew file mode 100644index 000000000000..3155082b28e4--- /dev/null+++ b/products/replay_vision/backend/migrations/0063_alter_replayobservation_triggered_by_and_more.py@@ -0,0 +1,163 @@+# Generated by Django 5.2.14 on 2026-08-06 14:17++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1292_oauthaccesstoken_sandbox_task_id"),+ ("replay_vision", "0061_replayscanner_drop_legacy_name_constraint"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="replayobservation",+ name="triggered_by",+ field=models.CharField(+ choices=[+ ("schedule", "Schedule"),+ ("on_demand", "On demand"),+ ("retry", "Retry"),+ ("backfill", "Backfill"),+ ],+ help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, a retry of a failed or ineligible observation, or a historical backfill.",+ max_length=16,+ ),+ ),+ migrations.CreateModel(+ name="ReplayScannerBackfill",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "window_start",+ models.DateTimeField(help_text="Inclusive lower bound of the historical window to scan."),+ ),+ (+ "window_end",+ models.DateTimeField(+ help_text="Exclusive upper bound of the window; clamped to the scanner's sweep watermark at creation."+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("running", "Running"),+ ("paused_quota", "Paused (quota)"),+ ("completed", "Completed"),+ ("cancelled", "Cancelled"),+ ],+ default="running",+ max_length=16,+ ),+ ),+ (+ "scanner_snapshot",+ models.JSONField(+ help_text="Frozen scanner config at creation; see `temporal.types.BackfillScannerSnapshot`."+ ),+ ),+ (+ "credits_per_observation",+ models.PositiveIntegerField(+ help_text="Per-observation credit price frozen at creation from the snapshot model."+ ),+ ),+ ("cursor_end_time", models.DateTimeField(blank=True, null=True)),+ (+ "cursor_session_id",+ models.CharField(blank=True, default="", max_length=200),+ ),+ (+ "total_count",+ models.PositiveIntegerField(+ help_text="Exact candidate enumeration at creation; the cost ceiling is total_count x credits_per_observation."+ ),+ ),+ ("dispatched_count", models.PositiveIntegerField(default=0)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "finished_at",+ models.DateTimeField(+ blank=True,+ help_text="When the backfill reached a terminal status (completed or cancelled).",+ null=True,+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "scanner",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="backfills",+ to="replay_vision.replayscanner",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ ),+ migrations.AddField(+ model_name="replayobservation",+ name="backfill",+ field=models.ForeignKey(+ blank=True,+ db_index=False,+ help_text="Backfill run that dispatched this observation; null for live, on-demand, and retry triggers.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="observations",+ to="replay_vision.replayscannerbackfill",+ ),+ ),+ migrations.AddIndex(+ model_name="replayscannerbackfill",+ index=models.Index(fields=["team", "created_at"], name="rvb_team_created_idx"),+ ),+ migrations.AddConstraint(+ model_name="replayscannerbackfill",+ constraint=models.UniqueConstraint(+ condition=models.Q(("status__in", ["running", "paused_quota"])),+ fields=("scanner",),+ name="rvb_one_active_per_scanner",+ ),+ ),+ migrations.AddConstraint(+ model_name="replayscannerbackfill",+ constraint=models.CheckConstraint(+ condition=models.Q(("window_start__lt", models.F("window_end"))),+ name="rvb_window_start_before_end",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0064_replayobservation_backfill_index.py b/products/replay_vision/backend/migrations/0064_replayobservation_backfill_index.pynew file mode 100644index 000000000000..ce3e3e9d16ca--- /dev/null+++ b/products/replay_vision/backend/migrations/0064_replayobservation_backfill_index.py@@ -0,0 +1,22 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("replay_vision", "0063_alter_replayobservation_triggered_by_and_more"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="replayobservation",+ index=models.Index(+ fields=["backfill"],+ name="rlo_backfill_idx",+ condition=models.Q(backfill__isnull=False),+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0065_replayscannerbackfill_skipped_count_and_more.py b/products/replay_vision/backend/migrations/0065_replayscannerbackfill_skipped_count_and_more.pynew file mode 100644index 000000000000..4e9ec7117058--- /dev/null+++ b/products/replay_vision/backend/migrations/0065_replayscannerbackfill_skipped_count_and_more.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.17 on 2026-08-07 19:06++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0064_replayobservation_backfill_index"),+ ("replay_vision", "0062_replayscanner_experiment_targeting"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayscannerbackfill",+ name="skipped_count",+ field=models.PositiveIntegerField(+ default=0,+ help_text="Candidates the walk stepped over because this scanner had already tried them. Counted at creation but never dispatched, so progress and remaining spend both have to account for them.",+ ),+ ),+ migrations.AlterField(+ model_name="replayscannerbackfill",+ name="total_count",+ field=models.PositiveIntegerField(+ help_text="Unobserved candidates enumerated at creation; the ceiling is total_count x credits_per_observation."+ ),+ ),+ migrations.AlterField(+ model_name="replayscannerbackfill",+ name="window_end",+ field=models.DateTimeField(help_text="Exclusive upper bound of the window; clamped to now at creation."),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 1c4059ee2c86..6454fd658495 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0062_replayscanner_experiment_targeting+0065_replayscannerbackfill_skipped_count_and_morediff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.pyindex 1093a2814ea5..b006ccce8b63 100644--- a/products/replay_vision/backend/models/__init__.py+++ b/products/replay_vision/backend/models/__init__.py@@ -2,6 +2,7 @@ from products.replay_vision.backend.models.replay_observation import ReplayObserfrom products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabelfrom products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfillfrom products.replay_vision.backend.models.replay_scanner_prompt_suggestion import ReplayScannerPromptSuggestionfrom products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun@@ -10,6 +11,7 @@ __all__ = ["ReplayObservationLabel","ReplayObservationUsage","ReplayScanner",+ "ReplayScannerBackfill","ReplayScannerPromptSuggestion","VisionAction","VisionActionRun",diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.pyindex 0dc05c56bddc..874b58b85731 100644--- a/products/replay_vision/backend/models/replay_observation.py+++ b/products/replay_vision/backend/models/replay_observation.py@@ -28,6 +28,7 @@ class ObservationTrigger(models.TextChoices):SCHEDULE = "schedule", "Schedule"ON_DEMAND = "on_demand", "On demand"RETRY = "retry", "Retry"+ BACKFILL = "backfill", "Backfill"class ReplayObservation(UUIDModel):@@ -76,10 +77,20 @@ class ReplayObservation(UUIDModel):help_text="PostHog Task minted from this observation's finding. Repeat create_task calls return this id instead of creating a duplicate.",)+ backfill = models.ForeignKey(+ "replay_vision.ReplayScannerBackfill",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="observations",+ # Indexed via the partial rlo_backfill_idx instead of a full-column default index.+ db_index=False,+ help_text="Backfill run that dispatched this observation; null for live, on-demand, and retry triggers.",+ )triggered_by = models.CharField(max_length=16,choices=ObservationTrigger.choices,- help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, or a retry of a failed or ineligible observation.",+ help_text="What started this observation: a per-scanner schedule fire, an explicit /observe/ call, a retry of a failed or ineligible observation, or a historical backfill.",)triggered_by_user = models.ForeignKey("posthog.User",@@ -123,6 +134,12 @@ class ReplayObservation(UUIDModel):name="rlo_team_in_flight_idx",condition=models.Q(status__in=("pending", "running")),),+ # Serves the per-backfill observation filter and progress counts; partial since live rows never match.+ models.Index(+ fields=["backfill"],+ name="rlo_backfill_idx",+ condition=models.Q(backfill__isnull=False),+ ),]@classmethoddiff --git a/products/replay_vision/backend/models/replay_scanner_backfill.py b/products/replay_vision/backend/models/replay_scanner_backfill.pynew file mode 100644index 000000000000..efe2a1e3626f--- /dev/null+++ b/products/replay_vision/backend/models/replay_scanner_backfill.py@@ -0,0 +1,94 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class BackfillStatus(models.TextChoices):+ RUNNING = "running", "Running"+ # Dispatch stopped because the org's monthly credit quota ran out; an explicit user resume restarts it.+ PAUSED_QUOTA = "paused_quota", "Paused (quota)"+ COMPLETED = "completed", "Completed"+ CANCELLED = "cancelled", "Cancelled"+++ACTIVE_BACKFILL_STATUSES = (BackfillStatus.RUNNING, BackfillStatus.PAUSED_QUOTA)+++class ReplayScannerBackfill(TeamScopedRootMixin, UUIDModel):+ """One historical scan of a scanner over a closed time window (see README).++ The scanner's config is frozen into `scanner_snapshot` at creation, so the enumerated candidate+ set and the per-observation price never drift while the backfill runs — the cost quoted in the+ confirm dialog is an exact ceiling for the backfill's whole lifetime.+ """++ scanner = models.ForeignKey("replay_vision.ReplayScanner", on_delete=models.CASCADE, related_name="backfills")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)++ window_start = models.DateTimeField(help_text="Inclusive lower bound of the historical window to scan.")+ window_end = models.DateTimeField(help_text="Exclusive upper bound of the window; clamped to now at creation.")++ status = models.CharField(max_length=16, choices=BackfillStatus.choices, default=BackfillStatus.RUNNING)++ scanner_snapshot = models.JSONField(+ help_text="Frozen scanner config at creation; see `temporal.types.BackfillScannerSnapshot`."+ )+ credits_per_observation = models.PositiveIntegerField(+ help_text="Per-observation credit price frozen at creation from the snapshot model."+ )++ # Descending keyset cursor: the next batch selects (end_time, session_id) < (cursor_end_time, cursor_session_id).+ # Null until the first batch dispatches; the walk starts from window_end.+ cursor_end_time = models.DateTimeField(null=True, blank=True)+ cursor_session_id = models.CharField(max_length=200, blank=True, default="")++ total_count = models.PositiveIntegerField(+ help_text="Unobserved candidates enumerated at creation; the ceiling is total_count x credits_per_observation."+ )+ dispatched_count = models.PositiveIntegerField(default=0)+ skipped_count = models.PositiveIntegerField(+ default=0,+ help_text=(+ "Candidates the walk stepped over because this scanner had already tried them. Counted at creation "+ "but never dispatched, so progress and remaining spend both have to account for them."+ ),+ )++ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ finished_at = models.DateTimeField(+ null=True, blank=True, help_text="When the backfill reached a terminal status (completed or cancelled)."+ )++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["scanner"],+ condition=models.Q(status__in=["running", "paused_quota"]),+ name="rvb_one_active_per_scanner",+ ),+ models.CheckConstraint(+ condition=models.Q(window_start__lt=models.F("window_end")), name="rvb_window_start_before_end"+ ),+ ]+ indexes = [+ models.Index(fields=["team", "created_at"], name="rvb_team_created_idx"),+ ]++ def save(self, *args, **kwargs) -> None:+ # Tenant invariant: backfill.team_id must match scanner.team_id.+ if self._state.adding:+ scanner_team_id = self.scanner.team_id+ if self.team_id and self.team_id != scanner_team_id:+ raise ValueError(+ f"ReplayScannerBackfill.team_id ({self.team_id}) must match scanner.team_id ({scanner_team_id})"+ )+ self.team_id = scanner_team_id+ super().save(*args, **kwargs)++ def __str__(self) -> str:+ return f"{self.scanner_id}:{self.window_start:%Y-%m-%d}..{self.window_end:%Y-%m-%d} [{self.status}]"diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex 434f99a443ae..1e2a42f8f91d 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -22,7 +22,7 @@ from posthog.session_recordings.queries.session_recording_list_from_query import)from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, SamplingMode-from products.replay_vision.backend.temporal.constants import (+from products.replay_vision.backend.session_limits import (MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,MAX_SESSION_ID_LENGTH,MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,@@ -41,6 +41,9 @@ MIN_SAMPLING_RATE = 1 / SAMPLE_RATE_PRECISIONDEFAULT_CANDIDATE_LIMIT = 5_000DEFAULT_MAX_EXECUTION_SECONDS = 180+# Emitted by `emit_observation_event_activity` once an observation succeeds.+OBSERVATION_EVENT_NAME = "$recording_observed"+# Calibrated from the prod score distribution: focused keeps roughly the top 25% of sessions, balanced the top 65%.FOCUSED_SURFACING_THRESHOLD = 0.30BALANCED_SURFACING_THRESHOLD = 0.10@@ -96,6 +99,24 @@ def eligibility_predicates() -> list[ast.Expr]:]+def _execute_candidate_query(+ query: ast.SelectQuery, *, team: Team, query_type: str, max_execution_time_seconds: int+) -> list[list]:+ """One home for the candidate queries' ClickHouse execution policy.++ The dedicated user keeps sweep and backfill admission out of the contended shared `default` pool.+ """+ with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT):+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type=query_type,+ settings=HogQLGlobalSettings(max_execution_time=max_execution_time_seconds),+ ch_user=ClickHouseUser.REPLAY_VISION,+ )+ return response.results or []++@dataclass(frozen=True)class CandidateSession:session_id: str@@ -156,16 +177,13 @@ class ScannerCandidateQuery:@tracer.start_as_current_span("ScannerCandidateQuery.run")def run(self) -> list[CandidateSession]:- with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT):- response = execute_hogql_query(- query=self.get_query(),- team=self._team,- query_type="ReplayVisionScannerCandidateQuery",- settings=HogQLGlobalSettings(max_execution_time=self._max_execution_time_seconds),- # Dedicated user keeps sweep admission out of the contended shared `default` pool.- ch_user=ClickHouseUser.REPLAY_VISION,- )- return [CandidateSession(session_id=row[0], session_end=row[1]) for row in (response.results or [])]+ rows = _execute_candidate_query(+ self.get_query(),+ team=self._team,+ query_type="ReplayVisionScannerCandidateQuery",+ max_execution_time_seconds=self._max_execution_time_seconds,+ )+ return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]def get_query(self) -> ast.SelectQuery:# `_inner.get_query()` re-parses every call, so in-place mutation is safe.@@ -215,29 +233,222 @@ class ScannerCandidateQuery:)def _sampling_predicate(self) -> ast.Expr | None:- if self._sampling_rate >= 1.0:+ return sampling_predicate(self._sampling_rate, self._sampling_salt)+++def sampling_predicate(sampling_rate: float, sampling_salt: str) -> ast.Expr | None:+ """Deterministic salted-hash downsample on the inner query's session rows; None means keep everything."""+ if sampling_rate >= 1.0:+ return None+ # round(), not int(): float error puts e.g. 0.29 * 10_000 at 2899.999…, and truncation would shave a bucket.+ threshold = max(0, round(sampling_rate * SAMPLE_RATE_PRECISION))+ if threshold <= 0:+ return ast.Constant(value=False)+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Call(+ name="modulo",+ args=[+ # concat rather than a second cityHash64 arg — HogQL pins cityHash64 to a single argument.+ ast.Call(+ name="cityHash64",+ args=[+ ast.Call(+ name="concat",+ args=[ast.Field(chain=["s", "session_id"]), ast.Constant(value=sampling_salt)],+ )+ ],+ ),+ ast.Constant(value=SAMPLE_RATE_PRECISION),+ ],+ ),+ right=ast.Constant(value=threshold),+ )+++class BackfillCandidateQuery:+ """Enumerate a backfill's candidate sessions inside a closed historical window.++ Same eligibility, sampling, and surfacing predicates as `ScannerCandidateQuery`, but bounded on both+ sides and walked newest-first: batches descend from `window_end` via a `(end_time, session_id)` keyset+ cursor. `count()` runs the identical predicate set without cursor or limit, so the creation-time+ enumeration is exactly the set the ticks will walk (the window is closed, so it can only shrink as+ recordings expire from retention — never grow).+ """++ def __init__(+ self,+ *,+ team: Team,+ query: RecordingsQuery,+ window_start: dt.datetime,+ window_end: dt.datetime,+ sampling_rate: float,+ sampling_salt: str,+ sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,+ cursor_end_time: dt.datetime | None = None,+ cursor_session_id: str | None = None,+ exclude_observed_by_scanner: str | None = None,+ candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,+ max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,+ ) -> None:+ for name, value in (("window_start", window_start), ("window_end", window_end)):+ if not isinstance(value, dt.datetime):+ raise TypeError(f"{name} must be a datetime, got {type(value).__name__}")+ if value.tzinfo is None:+ raise ValueError(f"{name} must be timezone-aware")+ if window_start >= window_end:+ raise ValueError("window_start must be before window_end")+ if candidate_limit <= 0:+ raise ValueError(f"candidate_limit must be positive, got {candidate_limit}")++ self._team = team+ self._window_start = window_start+ self._window_end = window_end+ self._cursor_end_time = cursor_end_time+ self._cursor_session_id = cursor_session_id+ self._exclude_observed_by_scanner = exclude_observed_by_scanner+ self._candidate_limit = candidate_limit+ self._max_execution_time_seconds = max_execution_time_seconds++ # The backfill owns the time window; the frozen scanner query only contributes filters.+ inner_query = query.model_copy(deep=True)+ inner_query.date_from = (window_start - _PARTITION_LOOKBACK).isoformat()+ # Sessions end at or after their start, so no candidate in the window starts past window_end.+ inner_query.date_to = window_end.isoformat()+ inner_query.limit = None+ inner_query.offset = None+ inner_query.after = None++ extra_having: list[ast.Expr] = eligibility_predicates()+ if (sampling := sampling_predicate(sampling_rate, sampling_salt)) is not None:+ extra_having.append(sampling)+ if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:+ extra_having.append(surfacing)++ self._inner = SessionRecordingListFromQuery(team=team, query=inner_query, extra_having_predicates=extra_having)++ @tracer.start_as_current_span("BackfillCandidateQuery.run")+ def run(self) -> list[CandidateSession]:+ rows = _execute_candidate_query(+ self.get_query(),+ team=self._team,+ query_type="ReplayVisionBackfillCandidateQuery",+ max_execution_time_seconds=self._max_execution_time_seconds,+ )+ return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]++ @tracer.start_as_current_span("BackfillCandidateQuery.count")+ def count(self) -> int:+ counted = ast.SelectQuery(+ select=[ast.Call(name="count", args=[])],+ select_from=ast.JoinExpr(table=self._windowed_candidates(), alias="candidates"),+ )+ rows = _execute_candidate_query(+ counted,+ team=self._team,+ query_type="ReplayVisionBackfillCountQuery",+ max_execution_time_seconds=self._max_execution_time_seconds,+ )+ return int(rows[0][0]) if rows else 0++ def get_query(self) -> ast.SelectQuery:+ query = self._windowed_candidates()+ if (cursor := self._cursor_predicate()) is not None:+ assert isinstance(query.where, ast.And)+ query.where.exprs.append(cursor)+ query.order_by = [+ ast.OrderExpr(expr=ast.Field(chain=["session_end"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["sessions", "session_id"]), order="DESC"),+ ]+ query.limit = ast.Constant(value=self._candidate_limit)+ return query++ def _windowed_candidates(self) -> ast.SelectQuery:+ """Window and eligibility predicates shared by the batch walk and the exact count."""+ # `_inner.get_query()` re-parses every call, so in-place mutation is safe.+ inner = self._inner.get_query()+ inner.order_by = None++ end_time = ast.Field(chain=["sessions", "end_time"])+ where_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq, left=end_time, right=ast.Constant(value=self._window_start)+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt, left=end_time, right=ast.Constant(value=self._window_end)+ ),+ # Excludes attacker-supplied over-length session_ids that would later wedge wire-payload validation.+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Call(name="length", args=[ast.Field(chain=["sessions", "session_id"])]),+ right=ast.Constant(value=MAX_SESSION_ID_LENGTH),+ ),+ ]+ if self._exclude_observed_by_scanner is not None:+ where_exprs.append(self._not_already_observed_predicate(self._exclude_observed_by_scanner))+ return ast.SelectQuery(+ select=[+ ast.Field(chain=["sessions", "session_id"]),+ ast.Alias(alias="session_end", expr=ast.Field(chain=["sessions", "end_time"])),+ ],+ select_from=ast.JoinExpr(table=cast(ast.SelectQuery, inner), alias="sessions"),+ where=ast.And(exprs=where_exprs),+ )++ def _not_already_observed_predicate(self, scanner_id: str) -> ast.Expr:+ """Drop sessions this scanner already published a `$recording_observed` event for.++ Reads the event rather than shipping observation ids over from Postgres, so the exclusion is+ a plain ClickHouse join with no cross-database list and no size ceiling. The trade-off is that+ the event is only emitted on the success path, and fail-soft even there, so ineligible,+ failed, and in-flight observations stay in the count. Those cannot produce a second+ observation (the unique constraint blocks it), which is why the total is an upper bound.+ """+ observed = ast.SelectQuery(+ select=[ast.Field(chain=["properties", "session_id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),+ where=ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["event"]),+ right=ast.Constant(value=OBSERVATION_EVENT_NAME),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["properties", "scanner_id"]),+ right=ast.Constant(value=scanner_id),+ ),+ # An observation is always emitted after its session ended, so the window's own+ # lower bound prunes partitions without ever excluding a relevant event.+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=self._window_start),+ ),+ ]+ ),+ )+ return ast.CompareOperation(+ op=ast.CompareOperationOp.NotIn,+ left=ast.Field(chain=["sessions", "session_id"]),+ right=observed,+ )++ def _cursor_predicate(self) -> ast.Expr | None:+ if self._cursor_end_time is None:return None- # round(), not int(): float error puts e.g. 0.29 * 10_000 at 2899.999…, and truncation would shave a bucket.- threshold = max(0, round(self._sampling_rate * SAMPLE_RATE_PRECISION))- if threshold <= 0:- return ast.Constant(value=False)+ end_time = ast.Field(chain=["sessions", "end_time"])+ if not self._cursor_session_id:+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Lt, left=end_time, right=ast.Constant(value=self._cursor_end_time)+ )+ # Mirror of the sweep's ascending keyset: lexicographic tuple comparison, walked downward.return ast.CompareOperation(op=ast.CompareOperationOp.Lt,- left=ast.Call(- name="modulo",- args=[- # concat rather than a second cityHash64 arg — HogQL pins cityHash64 to a single argument.- ast.Call(- name="cityHash64",- args=[- ast.Call(- name="concat",- args=[ast.Field(chain=["s", "session_id"]), ast.Constant(value=self._sampling_salt)],- )- ],- ),- ast.Constant(value=SAMPLE_RATE_PRECISION),- ],+ left=ast.Tuple(exprs=[end_time, ast.Field(chain=["sessions", "session_id"])]),+ right=ast.Tuple(+ exprs=[ast.Constant(value=self._cursor_end_time), ast.Constant(value=self._cursor_session_id)]),- right=ast.Constant(value=threshold),)diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 9d7d1219acd1..0e2dd6c968b8 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -21,6 +21,10 @@ from products.replay_vision.backend.models.replay_observation import ()from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.models.replay_scanner_backfill import (+ ACTIVE_BACKFILL_STATUSES,+ ReplayScannerBackfill,+)logger = structlog.get_logger(__name__)@@ -34,16 +38,19 @@ USAGE_KEY = "replay_vision_credits"@dataclass(frozen=True)-class QuotaSnapshot:- """All amounts are credits (1 credit = $0.01)."""+class QuotaState:+ """What the caps are and what has been spent. All amounts are credits (1 credit = $0.01).++ Everything enforcement needs and nothing it doesn't: deciding whether an observation may start+ reads only the limit and the spend so far. Projections live in `SpendProjection`, which costs+ extra queries no enforcement path should pay for.+ """# None means billing synced the product with no spend limit set: uncapped.credit_limit: int | Nonecredits_used: intperiod_start: datetimeperiod_end: datetime- # Credit-weighted sum of enabled scanners' persisted estimates across the org; uncomputed estimates count 0.- projected_monthly_credits: int# Display-only: the slice of `credit_limit` that never bills; see FREE_TIER_MONTHLY_CREDITS.free_monthly_credits: int = FREE_TIER_MONTHLY_CREDITS@@ -61,6 +68,40 @@ class QuotaSnapshot:"""Whether starting an observation costing `credits` would push usage past the limit (uncapped never does)."""return self.credit_limit is not None and self.credits_used + credits > self.credit_limit+ def affordable_count(self, credits_each: int) -> int | None:+ """How many observations at `credits_each` the remaining quota covers; None when nothing binds.++ Free models cost nothing, so they are never quota-bound; callers dividing by the price themselves+ have to remember that, and one of them did not.+ """+ remaining = self.remaining+ if remaining is None or credits_each <= 0:+ return None+ return remaining // credits_each+++@dataclass(frozen=True)+class SpendProjection:+ """What the org has committed for the rest of the period. Display only; nothing enforces on this."""++ # Credit-weighted sum of enabled scanners' persisted estimates; uncomputed estimates count 0. A monthly rate.+ scanners_monthly_credits: int+ # Committed-but-unspent credits of active backfills. A one-off charge, not a rate.+ backfills_committed_credits: int++ @property+ def total(self) -> int:+ return self.scanners_monthly_credits + self.backfills_committed_credits+++@dataclass(frozen=True)+class QuotaSnapshot(QuotaState):+ """`QuotaState` plus the projection, for the surfaces that show spend rather than gate on it."""++ projected_monthly_credits: int = 0+ scanners_monthly_credits: int = 0+ backfills_committed_credits: int = 0+def next_month_start(now: datetime) -> datetime:"""First moment (UTC) of the calendar month following the month containing `now`."""@@ -135,7 +176,7 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dreturn totals-def sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:+def _sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:"""Projected monthly credit spend from the org's enabled scanners' cached estimates."""scanners = ReplayScanner.objects.filter(team__organization_id=organization_id, enabled=True)if exclude_scanner_id is not None:@@ -145,6 +186,23 @@ def sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scannerreturn sum(observation_credits_for_model(model) * (estimate or 0) for model, estimate in rows)+def _sum_active_backfill_remaining_credits(organization_id: UUID) -> int:+ """Committed-but-unspent credits of the org's active backfills, priced at each backfill's frozen rate.++ Projection only: enforcement stays the per-observation creation check, identical for live and+ backfill applies. A new backfill's confirm dialog therefore sees earlier backfills' commitments+ inside the projected spend.+ """+ rows = (+ ReplayScannerBackfill.objects.unscoped()+ .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.+ return sum(max(0, total - dispatched - skipped) * price for total, dispatched, skipped, price in rows)++def _billing_synced_limit(organization: Organization | None) -> tuple[bool, int | None]:"""(synced, limit): whether billing has synced this product, and the credit limit it synced (None = uncapped)."""if organization is None or not organization.usage:@@ -164,7 +222,19 @@ def _billing_synced_limit(organization: Organization | None) -> tuple[bool, intreturn False, None-def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:+def spend_projection(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> SpendProjection:+ """The org's rest-of-period commitments, priced.++ `exclude_scanner_id` drops one scanner's stored estimate, for the editor's "others plus this+ proposal" forecast. Callers never touch the underlying scanner or backfill rows.+ """+ return SpendProjection(+ scanners_monthly_credits=_sum_enabled_scanner_estimated_credits(organization_id, exclude_scanner_id),+ backfills_committed_credits=_sum_active_backfill_remaining_credits(organization_id),+ )+++def quota_state(organization_id: UUID) -> QuotaState:# noqa comment below: prompt_evaluation pulls in the temporal package, whose activities import# this module — deferring breaks the quota -> prompt_evaluation -> temporal -> quota cycle.from products.replay_vision.backend.prompt_evaluation import in_flight_evaluation_credits # noqa: PLC0415@@ -194,14 +264,31 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:in_flight = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())# Prompt tests have no observation rows. Their unsettled sessions are committed spend too.usage = consumed + in_flight + in_flight_evaluation_credits(organization_id)- projected = sum_enabled_scanner_estimated_credits(organization_id)synced, credit_limit = _billing_synced_limit(organization)if not synced:credit_limit = MONTHLY_CREDIT_QUOTA- return QuotaSnapshot(+ return QuotaState(credit_limit=credit_limit,credits_used=usage,period_start=period.start,period_end=period.end,- projected_monthly_credits=projected,+ )+++def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:+ """Enforcement state plus the projection.++ Prefer `quota_state` wherever only the caps matter: this pays for two aggregates no gate reads.+ """+ state = quota_state(organization_id)+ projection = spend_projection(organization_id)+ return QuotaSnapshot(+ credit_limit=state.credit_limit,+ credits_used=state.credits_used,+ period_start=state.period_start,+ period_end=state.period_end,+ free_monthly_credits=state.free_monthly_credits,+ projected_monthly_credits=projection.total,+ scanners_monthly_credits=projection.scanners_monthly_credits,+ backfills_committed_credits=projection.backfills_committed_credits,)diff --git a/products/replay_vision/backend/routes.py b/products/replay_vision/backend/routes.pyindex f0daf8b6be52..c88d674f52fa 100644--- a/products/replay_vision/backend/routes.py+++ b/products/replay_vision/backend/routes.py@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistryfrom products.replay_vision.backend.api import (ReplayObservationViewSet,+ ReplayScannerBackfillViewSet,ReplayScannerPromptSuggestionViewSet,ReplayScannerViewSet,SessionReplayObservationViewSet,@@ -18,6 +19,9 @@ def register_routes(routers: RouterRegistry) -> None:project_vision_scanners_router.register(r"observations", ReplayObservationViewSet, "project_vision_scanner_observations", ["team_id", "scanner_id"])+ project_vision_scanners_router.register(+ r"backfills", ReplayScannerBackfillViewSet, "project_vision_scanner_backfills", ["team_id", "scanner_id"]+ )project_vision_scanners_router.register(r"prompt_suggestions",ReplayScannerPromptSuggestionViewSet,diff --git a/products/replay_vision/backend/scanning.py b/products/replay_vision/backend/scanning.pyindex dc87c33d7ab3..7c8603d07839 100644--- a/products/replay_vision/backend/scanning.py+++ b/products/replay_vision/backend/scanning.py@@ -27,7 +27,7 @@ from products.replay_vision.backend.enqueue_claims import (from products.replay_vision.backend.inline_scan import create_inline_scanner, find_inline_scanner, inline_scan_keyfrom products.replay_vision.backend.models.replay_observation import TERMINAL_STATUSES, ReplayObservationfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.quota import quota_statefrom products.replay_vision.backend.scanner_config import scanner_config_errorfrom products.replay_vision.backend.temporal.constants import (MAX_IN_FLIGHT_APPLIES_PER_SCANNER,@@ -84,11 +84,10 @@ def scan_headroom(*, team: Team, model: str, scanner: ReplayScanner | None) -> SMAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight - pending_enqueue_claims_for_team(team.id),),)- snapshot = compute_quota_snapshot(team.organization_id)- cost = observation_credits_for_model(model)- # Uncapped org, or a free model that spends nothing: quota can't bind. Otherwise, how many of THIS- # model's cost fit.- quota_limit = in_flight_limit if snapshot.remaining is None or cost <= 0 else snapshot.remaining // cost+ snapshot = quota_state(team.organization_id)+ # None means nothing binds: uncapped org, or a free model that spends nothing.+ affordable = snapshot.affordable_count(observation_credits_for_model(model))+ quota_limit = in_flight_limit if affordable is None else affordable# Report quota as the reason only when it's the strictly tighter limit.if quota_limit < in_flight_limit:return ScanHeadroom(diff --git a/products/replay_vision/backend/session_limits.py b/products/replay_vision/backend/session_limits.pynew file mode 100644index 000000000000..d89ebf83c9cb--- /dev/null+++ b/products/replay_vision/backend/session_limits.py@@ -0,0 +1,17 @@+"""Session eligibility limits shared by the query layer and the temporal package.++A leaf module: the candidate queries need these, and importing them from `temporal.constants`+would pull the whole temporal package (workflows + activities) into the query layer's import chain.+"""++# Capped so `replay-vision-apply-scanner-{scanner_uuid:36}-{session_id}` fits the 255-char `ReplayObservation.workflow_id` column.+MAX_SESSION_ID_LENGTH = 128++# Sessions shorter than this don't carry enough signal for the LLM to analyze.+MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S = 15++# Sessions with less than this much actual interaction are skipped — they're mostly idle.+MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S = 10++# Sessions with more than 1 hour of active interaction take too long to analyze well.+MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S = 3600diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 0c00c34eae1b..b454511c1750 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -2,12 +2,14 @@ from collections.abc import Callablefrom typing import Anyfrom products.replay_vision.backend.temporal.activities import (+ advance_backfill_cursor_activity,advance_scanner_watermark_activity,call_scanner_provider_activity,cleanup_gemini_file_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,create_observation_activity,+ delete_backfill_schedule_activity,delete_scanner_schedule_activity,embed_observation_activity,emit_classifier_tags_activity,@@ -16,6 +18,7 @@ from products.replay_vision.backend.temporal.activities import (ensure_session_asset_activity,fetch_session_events_activity,finalize_evaluation_activity,+ find_backfill_candidates_activity,find_scanner_candidates_activity,list_enabled_scanners_activity,list_scanner_schedules_activity,@@ -24,6 +27,9 @@ from products.replay_vision.backend.temporal.activities import (mark_observation_ineligible_activity,mark_observation_running_activity,mark_observation_succeeded_activity,+ pause_backfill_schedule_activity,+ prepare_backfill_tick_activity,+ reap_backfill_schedules_activity,reap_childless_inline_scanners_activity,reap_orphaned_observations_activity,reap_stuck_vision_action_runs_activity,@@ -34,6 +40,7 @@ from products.replay_vision.backend.temporal.activities import (upload_video_to_gemini_activity,upsert_scanner_schedule_activity,)+from products.replay_vision.backend.temporal.backfill_workflow import BackfillScannerWorkflowfrom products.replay_vision.backend.temporal.estimates import RefreshScannerEstimatesWorkflowfrom products.replay_vision.backend.temporal.evaluation_workflow import EvaluatePromptSuggestionWorkflowfrom products.replay_vision.backend.temporal.gemini_cleanup_sweep import (@@ -56,6 +63,7 @@ from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkfloWORKFLOWS = [ApplyScannerWorkflow,+ BackfillScannerWorkflow,EvaluatePromptSuggestionWorkflow,ReconcileScannerSchedulesWorkflow,RefreshScannerEstimatesWorkflow,@@ -83,6 +91,12 @@ ACTIVITIES: list[Callable[..., Any]] = [count_in_flight_by_team_activity,advance_scanner_watermark_activity,refresh_prompt_suggestion_activity,+ prepare_backfill_tick_activity,+ find_backfill_candidates_activity,+ advance_backfill_cursor_activity,+ pause_backfill_schedule_activity,+ delete_backfill_schedule_activity,+ reap_backfill_schedules_activity,select_evaluation_sessions_activity,record_evaluation_result_activity,finalize_evaluation_activity,@@ -109,6 +123,7 @@ __all__ = ["ACTIVITIES","WORKFLOWS","ApplyScannerWorkflow",+ "BackfillScannerWorkflow","EvaluatePromptSuggestionWorkflow","ProcessVisionActionWorkflow","ReconcileScannerSchedulesWorkflow",diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex 2e9e7a8c2f27..620d131c237f 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -1,6 +1,14 @@from products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (advance_scanner_watermark_activity,)+from products.replay_vision.backend.temporal.activities.backfill import (+ advance_backfill_cursor_activity,+ delete_backfill_schedule_activity,+ find_backfill_candidates_activity,+ pause_backfill_schedule_activity,+ prepare_backfill_tick_activity,+ reap_backfill_schedules_activity,+)from products.replay_vision.backend.temporal.activities.call_scanner_provider import call_scanner_provider_activityfrom products.replay_vision.backend.temporal.activities.cleanup_gemini_file import cleanup_gemini_file_activityfrom products.replay_vision.backend.temporal.activities.count_in_flight_applies import (@@ -53,7 +61,13 @@ from products.replay_vision.backend.temporal.activities.refresh_scanner_estimatefrom products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity__all__ = [+ "advance_backfill_cursor_activity","advance_scanner_watermark_activity",+ "delete_backfill_schedule_activity",+ "find_backfill_candidates_activity",+ "pause_backfill_schedule_activity",+ "prepare_backfill_tick_activity",+ "reap_backfill_schedules_activity","refresh_prompt_suggestion_activity","call_scanner_provider_activity","cleanup_gemini_file_activity",diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.pynew file mode 100644index 000000000000..75e4760b88ea--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/backfill.py@@ -0,0 +1,309 @@+"""Activities for the per-backfill tick workflow: gatekeeping, candidate walk, cursor advance, schedule ops."""++import asyncio+from uuid import UUID++from django.db.models import F+from django.utils import timezone++import structlog+from pydantic import ValidationError+from temporalio import activity+from temporalio.client import Client+from temporalio.exceptions import ApplicationError++from posthog.schema import RecordingsQuery++from posthog.sync import database_sync_to_async+from posthog.temporal.common.client import async_connect++from 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_scanner_backfill import (+ ACTIVE_BACKFILL_STATUSES,+ BackfillStatus,+ ReplayScannerBackfill,+)+from products.replay_vision.backend.queries.scanner_candidate_query import BackfillCandidateQuery+from products.replay_vision.backend.quota import quota_state+from products.replay_vision.backend.temporal.activities.count_in_flight_applies import (+ count_in_flight,+ count_in_flight_rows,+)+from products.replay_vision.backend.temporal.backfill_types import (+ AdvanceBackfillCursorInputs,+ AdvanceBackfillCursorOutput,+ BackfillScheduleOpInputs,+ BackfillTickAction,+ BackfillTickInputs,+ FindBackfillCandidatesInputs,+ FindBackfillCandidatesOutput,+ PrepareBackfillTickOutput,+)+from products.replay_vision.backend.temporal.constants import (+ BACKFILL_SCHEDULE_ID_PREFIX,+ BACKFILL_SCHEDULE_TYPE,+ backfill_dispatch_budget,+ build_apply_scanner_workflow_id,+)+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.metrics import record_backfill_tick_outcome+from products.replay_vision.backend.temporal.schedule import (+ a_delete_backfill_schedule,+ a_pause_backfill_schedule,+ a_upsert_backfill_schedule,+)+from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot+from products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayload++logger = structlog.get_logger(__name__)+++def _load_backfill(backfill_id: UUID, team_id: int) -> ReplayScannerBackfill | None:+ return (+ ReplayScannerBackfill.objects.for_team(team_id)+ .select_related("scanner", "team__organization")+ .filter(pk=backfill_id)+ .first()+ )+++@track_activity()+def prepare_backfill_tick_activity(inputs: BackfillTickInputs) -> PrepareBackfillTickOutput:+ """Decide what this tick does: dispatch a bounded batch, skip, pause on quota, or finish."""+ backfill = _load_backfill(inputs.backfill_id, inputs.team_id)+ if backfill is None or backfill.status in (BackfillStatus.COMPLETED, BackfillStatus.CANCELLED):+ record_backfill_tick_outcome("finished")+ return PrepareBackfillTickOutput(action=BackfillTickAction.FINISHED)+ if backfill.status == BackfillStatus.PAUSED_QUOTA:+ # Re-pause rather than skip: a recreated or racing schedule would otherwise fire every minute forever.+ record_backfill_tick_outcome("skipped_paused")+ return PrepareBackfillTickOutput(action=BackfillTickAction.PAUSE)+ if not backfill.team.organization.is_ai_data_processing_approved:+ # Children would decline at create while the cursor walks past their sessions; hold instead.+ record_backfill_tick_outcome("skipped_no_consent")+ return PrepareBackfillTickOutput(action=BackfillTickAction.SKIP)+ if not backfill.scanner.enabled:+ # Disabling a scanner holds its backfill without a status change; re-enabling resumes on the next tick.+ record_backfill_tick_outcome("skipped_scanner_disabled")+ return PrepareBackfillTickOutput(action=BackfillTickAction.SKIP)++ quota = quota_state(backfill.team.organization_id)+ if quota.would_exceed(backfill.credits_per_observation):+ # Filtered so a concurrent cancel wins over the pause.+ ReplayScannerBackfill.objects.for_team(inputs.team_id).filter(+ pk=inputs.backfill_id, status=BackfillStatus.RUNNING+ ).update(status=BackfillStatus.PAUSED_QUOTA)+ record_backfill_tick_outcome("paused_quota")+ return PrepareBackfillTickOutput(action=BackfillTickAction.PAUSE)++ in_flight = count_in_flight(inputs.team_id, backfill.scanner_id, backfill_id=backfill.id)+ budget = backfill_dispatch_budget(in_flight["scanner"], in_flight["team"], in_flight["backfill"])+ # Never dispatch more children than the quota can pay for: a child declined at create still advances+ # the cursor past its session. Concurrent spenders can still shrink headroom between this check and+ # creation; that residual loss is bounded by one batch and accepted.+ affordable = quota.affordable_count(backfill.credits_per_observation)+ if affordable is not None:+ budget = min(budget, affordable)+ if budget <= 0:+ record_backfill_tick_outcome("throttled")+ return PrepareBackfillTickOutput(action=BackfillTickAction.SKIP)+ record_backfill_tick_outcome("dispatch")+ return PrepareBackfillTickOutput(action=BackfillTickAction.DISPATCH, dispatch_budget=budget)+++@track_activity()+def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> FindBackfillCandidatesOutput:+ backfill = (+ ReplayScannerBackfill.objects.for_team(inputs.team_id)+ .select_related("team")+ .filter(pk=inputs.backfill_id)+ .first()+ )+ if backfill is None:+ return FindBackfillCandidatesOutput(candidates=[], more_work_below_cursor=False)++ rows = count_in_flight_rows(inputs.team_id, backfill.scanner_id, backfill.id)+ capacity = count_in_flight(inputs.team_id, backfill.scanner_id, backfill.id, rows=rows)+ if backfill_dispatch_budget(capacity["scanner"], capacity["team"], capacity["backfill"]) <= 0:+ # Headroom vanished since the prepare gate; skip the enumeration rather than run the tick's+ # most expensive query only to have every candidate refused by the claim below. Checked+ # against the same caps the claim enforces, sub-cap included, so it can actually fire.+ record_backfill_tick_outcome("throttled")+ return FindBackfillCandidatesOutput(candidates=[], more_work_below_cursor=True)++ snapshot = BackfillScannerSnapshot.load_for_backfill(backfill.id, backfill.scanner_snapshot)+ try:+ query = RecordingsQuery.model_validate({**snapshot.query, "kind": "RecordingsQuery"})+ except ValidationError as exc:+ raise ApplicationError(+ f"ReplayScannerBackfill {inputs.backfill_id} has malformed frozen query: {exc}", non_retryable=True+ ) from exc++ candidates = BackfillCandidateQuery(+ team=backfill.team,+ query=query,+ window_start=backfill.window_start,+ window_end=backfill.window_end,+ sampling_rate=snapshot.sampling_rate,+ # Same salt as the live sweep, so a sampled scanner backfills the same deterministic bucket it scans live.+ sampling_salt=str(backfill.scanner_id),+ sampling_mode=snapshot.sampling_mode,+ cursor_end_time=backfill.cursor_end_time,+ cursor_session_id=backfill.cursor_session_id or None,+ candidate_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(+ ReplayObservation.objects.filter(+ team_id=inputs.team_id,+ scanner_id=backfill.scanner_id,+ session_id__in=[c.session_id for c in candidates],+ ).values_list("session_id", flat=True)+ )+ dispatchable = [c for c in candidates if c.session_id not in already_observed]++ # 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+ # ticks would otherwise all read the same headroom. `create_observation_activity` releases the+ # claim once the row exists, and an unreleased claim expires on its own TTL.+ admitted = claim_enqueue_slot_prefix(+ team_id=inputs.team_id,+ scanner_id=backfill.scanner_id,+ workflow_ids=[build_apply_scanner_workflow_id(backfill.scanner_id, c.session_id) for c in dispatchable],+ team_in_flight_rows=rows["team"],+ scanner_in_flight_rows=rows["scanner"],+ backfill_id=backfill.id,+ backfill_in_flight_rows=rows["backfill"],+ )++ # The cursor may step over an already-observed session, because nothing will ever need doing for+ # it, but never over one the caps held back. Claiming stops at the first refusal, so the admitted+ # set is a prefix of `dispatchable` and everything before it in `candidates` is accounted for.+ truncated_by_caps = admitted < len(dispatchable)+ if truncated_by_caps:+ walked_to = dispatchable[admitted - 1] if admitted else None+ else:+ # An empty batch means the walk drained the window: leave the cursor alone and let the+ # short batch below complete the backfill.+ walked_to = candidates[-1] if candidates else None++ # Everything the cursor passes is accounted for, dispatched or not. Without counting the skipped ones+ # `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++ return FindBackfillCandidatesOutput(+ started_from_cursor_end_time=backfill.cursor_end_time,+ started_from_cursor_session_id=backfill.cursor_session_id,+ candidates=[+ CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in dispatchable[:admitted]+ ],+ skipped_delta=skipped,+ next_cursor_end_time=walked_to.session_end if walked_to else None,+ next_cursor_session_id=walked_to.session_id if walked_to else "",+ # Held-back candidates are still work below the cursor, so a truncated batch must not look+ # like a drained window; that would complete the backfill with sessions left unscanned.+ more_work_below_cursor=len(candidates) == inputs.candidate_limit or truncated_by_caps,+ )+++@track_activity()+def advance_backfill_cursor_activity(inputs: AdvanceBackfillCursorInputs) -> AdvanceBackfillCursorOutput:+ """Advance the descending cursor and dispatch count; a short batch completes the backfill.++ Filtered to RUNNING rows so a concurrent cancel or pause wins over the advance.+ """+ updates: dict[str, object] = {+ "dispatched_count": F("dispatched_count") + inputs.dispatched_delta,+ "skipped_count": F("skipped_count") + inputs.skipped_delta,+ }+ if inputs.new_cursor_end_time is not None:+ updates["cursor_end_time"] = inputs.new_cursor_end_time+ updates["cursor_session_id"] = inputs.new_cursor_session_id+ if inputs.exhausted:+ updates["status"] = BackfillStatus.COMPLETED+ updates["finished_at"] = timezone.now()+ # Matching the starting cursor makes this idempotent: Temporal retries an activity whose result+ # was lost after it committed, and a second blind increment would inflate progress and understate+ # the backfill's remaining credit commitment.+ updated = (+ ReplayScannerBackfill.objects.for_team(inputs.team_id)+ .filter(+ pk=inputs.backfill_id,+ status=BackfillStatus.RUNNING,+ cursor_end_time=inputs.expected_cursor_end_time,+ cursor_session_id=inputs.expected_cursor_session_id,+ )+ .update(**updates)+ )+ finished = inputs.exhausted and updated > 0+ if finished:+ record_backfill_tick_outcome("completed")+ return AdvanceBackfillCursorOutput(finished=finished)+++@track_activity()+async def pause_backfill_schedule_activity(inputs: BackfillScheduleOpInputs) -> None:+ await a_pause_backfill_schedule(inputs.backfill_id, note="monthly quota exhausted")+++@track_activity()+async def delete_backfill_schedule_activity(inputs: BackfillScheduleOpInputs) -> None:+ await a_delete_backfill_schedule(inputs.backfill_id)+++def _active_backfills_by_id() -> dict[UUID, tuple[int, UUID, str]]:+ """`{backfill_id: (team_id, scanner_id, status)}` for every non-terminal backfill."""+ rows = ReplayScannerBackfill.objects.unscoped().filter(status__in=ACTIVE_BACKFILL_STATUSES)+ return {+ row_id: (team_id, scanner_id, row_status)+ for row_id, team_id, scanner_id, row_status in rows.values_list("id", "team_id", "scanner_id", "status")+ }+++async def _recreate_schedule(+ backfill_id: UUID, team_id: int, scanner_id: UUID, row_status: str, client: Client+) -> None:+ await a_upsert_backfill_schedule(backfill_id, team_id, scanner_id, client)+ # A quota-paused backfill's schedule comes back paused; only an explicit user resume unpauses it.+ if row_status == BackfillStatus.PAUSED_QUOTA:+ await a_pause_backfill_schedule(backfill_id, note="monthly quota exhausted", client=client)+++@track_activity()+async def reap_backfill_schedules_activity() -> None:+ """Converge per-backfill schedules with the table: delete schedules whose row is terminal or gone+ (crash between terminal-mark and schedule-delete), recreate schedules a running row lost."""+ client = await async_connect()+ active = await database_sync_to_async(_active_backfills_by_id)()+ prefix = f"{BACKFILL_SCHEDULE_ID_PREFIX}-"+ seen: set[UUID] = set()+ fixes = []+ async for listing in await client.list_schedules(query=f'PostHogScheduleType = "{BACKFILL_SCHEDULE_TYPE}"'):+ if not listing.id.startswith(prefix):+ continue+ try:+ backfill_id = UUID(listing.id[len(prefix) :])+ except ValueError:+ logger.warning("replay_vision.backfill_reaper.unparseable_schedule_id", schedule_id=listing.id)+ continue+ seen.add(backfill_id)+ if backfill_id not in active:+ logger.info("replay_vision.backfill_reaper.deleting_stale", backfill_id=str(backfill_id))+ fixes.append(a_delete_backfill_schedule(backfill_id, client))+ for backfill_id, (team_id, scanner_id, row_status) in active.items():+ if backfill_id not in seen:+ logger.info("replay_vision.backfill_reaper.recreating_missing", backfill_id=str(backfill_id))+ fixes.append(_recreate_schedule(backfill_id, team_id, scanner_id, row_status, client))+ if fixes:+ await asyncio.gather(*fixes)diff --git a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.pyindex dee483063c1f..0e4c42ff7fd0 100644--- a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py+++ b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py@@ -1,3 +1,5 @@+from uuid import UUID+from django.db.models import Count, Qimport structlog@@ -5,10 +7,7 @@ from temporalio import activityfrom posthog.temporal.common.client import async_connect-from products.replay_vision.backend.enqueue_claims import (- pending_enqueue_claims_for_scanner,- pending_enqueue_claims_for_team,-)+from products.replay_vision.backend.enqueue_claims import pending_enqueue_claimsfrom products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.temporal.constants import in_flight_headroomfrom products.replay_vision.backend.temporal.decorators import track_activity@@ -35,22 +34,44 @@ async def count_in_flight_applies_activity(inputs: CountInFlightAppliesInputs) -return 0+def count_in_flight_rows(team_id: int, scanner_id: UUID, backfill_id: UUID | None = None) -> dict[str, int]:+ """Persisted pending/running rows for a scanner, its whole team, and optionally one backfill.++ Rows rather than Temporal visibility, so concurrency shares the quota system's single notion of+ in-flight. Callers enforcing a cap want `count_in_flight` below; this raw form is for the claim+ protocol, which adds outstanding claims itself.+ """+ aggregates = {+ "team": Count("id"),+ "scanner": Count("id", filter=Q(scanner_id=scanner_id)),+ }+ if backfill_id is not None:+ aggregates["backfill"] = Count("id", filter=Q(backfill_id=backfill_id))+ return ReplayObservation.in_flight_for_team(team_id).aggregate(**aggregates)+++def count_in_flight(+ team_id: int, scanner_id: UUID, backfill_id: UUID | None = None, rows: dict[str, int] | None = None+) -> dict[str, int]:+ """Capacity as the caps see it: persisted rows plus slots claimed but not yet persisted.++ Pass `rows` when the caller already has the raw counts, so the aggregate runs once rather than twice.+ """+ counts = dict(rows) if rows is not None else count_in_flight_rows(team_id, scanner_id, backfill_id)+ # The backfill claims matter as much as the others: without them the sub-cap only ever sees persisted+ # rows, so the next tick re-spends the slots this one took while its children were still queued.+ claims = pending_enqueue_claims(team_id, scanner_id, backfill_id)+ for scope, pending in claims.items():+ counts[scope] += pending+ return counts++@activity.defn@track_activity()def count_in_flight_by_team_activity(inputs: CountInFlightAppliesInputs) -> InFlightApplyCounts:- """Count in-flight (pending/running) observations for this scanner and for its whole team.-- Counts DB rows rather than Temporal visibility so concurrency shares the quota system's- single notion of in-flight. Rows stranded by failed workflows keep counting until the orphan- reaper clears them, which throttles sweeps during an incident instead of piling on new work.- """- counts = ReplayObservation.in_flight_for_team(inputs.team_id).aggregate(- team=Count("id"),- scanner=Count("id", filter=Q(scanner_id=inputs.scanner_id)),- )- # On-demand scans hold enqueue claims until their rows persist.- team = counts["team"] + pending_enqueue_claims_for_team(inputs.team_id)- scanner = counts["scanner"] + pending_enqueue_claims_for_scanner(inputs.scanner_id)+ counts = count_in_flight(inputs.team_id, inputs.scanner_id)+ team = counts["team"]+ scanner = counts["scanner"]# The workflow makes the same call on these counts; recorded here because metrics# can't be emitted from deterministic workflow code.if in_flight_headroom(scanner, team) <= 0:diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex 630111ea2033..b07da8224851 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -12,26 +12,16 @@ from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.enqueue_claims import release_enqueue_claimfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill+from products.replay_vision.backend.quota import quota_statefrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.metrics import record_consent_skip, record_quota_exhausted_skip-from products.replay_vision.backend.temporal.types import (- CreateObservationInputs,- CreateObservationOutput,- ScannerSnapshot,-)+from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot, ScannerSnapshot+from products.replay_vision.backend.temporal.types import CreateObservationInputs, CreateObservationOutputdef _build_scanner_snapshot(scanner: ReplayScanner) -> dict[str, Any]:- return ScannerSnapshot(- name=scanner.name,- scanner_type=scanner.scanner_type,- scanner_version=scanner.scanner_version,- model=scanner.model,- provider=scanner.provider,- emits_signals=scanner.emits_signals,- scanner_config=scanner.scanner_config,- ).model_dump(mode="json")+ return ScannerSnapshot.from_scanner(scanner).model_dump(mode="json")@activity.defn@@ -42,7 +32,12 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservreturn _create_observation(inputs)finally:# Every exit resolves the row's existence, so the enqueue claim is done; TTL covers a crash.- release_enqueue_claim(team_id=inputs.team_id, scanner_id=inputs.scanner_id, workflow_id=inputs.workflow_id)+ release_enqueue_claim(+ team_id=inputs.team_id,+ scanner_id=inputs.scanner_id,+ workflow_id=inputs.workflow_id,+ backfill_id=inputs.backfill_id,+ )def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutput:@@ -56,6 +51,19 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutif scanner is None:raise ValueError(f"ReplayScanner {inputs.scanner_id} not found for team {inputs.team_id}")+ backfill = None+ if inputs.backfill_id is not None:+ backfill = ReplayScannerBackfill.objects.for_team(inputs.team_id).filter(pk=inputs.backfill_id).first()+ if backfill is None or backfill.scanner_id != scanner.id:+ raise ValueError(f"ReplayScannerBackfill {inputs.backfill_id} not found for scanner {inputs.scanner_id}")+ if backfill.status == BackfillStatus.CANCELLED:+ # Cancelled between dispatch and persistence — honor the cancel instead of creating a row.+ activity.logger.info(+ "Skipping observation: backfill cancelled",+ extra={"backfill_id": str(inputs.backfill_id), "session_id": inputs.session_id},+ )+ return CreateObservationOutput(observation_id=None, was_created=False, scanner_type=scanner.scanner_type)+# No AI processing of recordings without organization consent, even for scanners created earlier.if not scanner.team.organization.is_ai_data_processing_approved:record_consent_skip(scanner.scanner_type)@@ -80,9 +88,18 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutf"User {inputs.triggered_by_user_id} is not a member of scanner {inputs.scanner_id}'s organization")+ # Backfill applies run the frozen config, not the scanner's current one.+ if backfill is not None:+ frozen = BackfillScannerSnapshot.load_for_backfill(backfill.id, backfill.scanner_snapshot)+ snapshot_dict = frozen.to_observation_snapshot().model_dump(mode="json")+ priced_model = frozen.model+ else:+ snapshot_dict = _build_scanner_snapshot(scanner)+ priced_model = scanner.model+# Deliberately check-then-act: the snapshot doesn't count enqueue claims, so a concurrent burst can# overshoot by at most the in-flight caps allow, which is accepted.- if compute_quota_snapshot(scanner.team.organization_id).would_exceed(observation_credits_for_model(scanner.model)):+ if quota_state(scanner.team.organization_id).would_exceed(observation_credits_for_model(priced_model)):record_quota_exhausted_skip(scanner.scanner_type)activity.logger.info("Skipping observation: monthly quota exhausted",@@ -102,9 +119,10 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutsession_id=inputs.session_id,status=ObservationStatus.PENDING,workflow_id=inputs.workflow_id,- scanner_snapshot=_build_scanner_snapshot(scanner),+ scanner_snapshot=snapshot_dict,triggered_by=inputs.triggered_by,triggered_by_user_id=inputs.triggered_by_user_id,+ backfill=backfill,)except IntegrityError as e:# Only swallow the dedup case; FK / CHECK violations should fail the activity.diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.pyindex c07dac5ae664..a64cc6052a72 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py@@ -14,7 +14,7 @@ from posthog.models.person.util import get_person_by_distinct_idfrom posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom products.replay_vision.backend.models.replay_observation import ReplayObservation-from products.replay_vision.backend.temporal.constants import (+from products.replay_vision.backend.session_limits import (MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S,MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S,diff --git a/products/replay_vision/backend/temporal/backfill_types.py b/products/replay_vision/backend/temporal/backfill_types.pynew file mode 100644index 000000000000..05a1e474e1ce--- /dev/null+++ b/products/replay_vision/backend/temporal/backfill_types.py@@ -0,0 +1,81 @@+"""Backfill-only Temporal types — split from `types.py` for the same reason as `sweep_types.py`."""++import enum+import datetime as dt+from uuid import UUID++from pydantic import BaseModel, Field++from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayload+++class BackfillTickInputs(BaseModel, frozen=True):+ backfill_id: UUID+ team_id: int+ # Immutable for a backfill's lifetime, so safe to bake into the schedule action.+ scanner_id: UUID+++class BackfillTickAction(enum.StrEnum):+ # Dispatch a batch bounded by `dispatch_budget`.+ DISPATCH = "dispatch"+ # Nothing to do this tick (no headroom, or the scanner is disabled); try again next fire.+ SKIP = "skip"+ # Org quota exhausted: the row is now paused_quota; the workflow pauses the schedule and exits.+ PAUSE = "pause"+ # Terminal row (completed/cancelled/missing): the workflow deletes the schedule and exits.+ FINISHED = "finished"+++class PrepareBackfillTickOutput(BaseModel, frozen=True):+ action: BackfillTickAction+ dispatch_budget: int = 0+++class FindBackfillCandidatesInputs(BaseModel, frozen=True):+ backfill_id: UUID+ team_id: int+ candidate_limit: int+++class FindBackfillCandidatesOutput(BaseModel, frozen=True):+ candidates: list[CandidateSessionPayload]+ # Where the walk got to, which is not always the last dispatched session: sessions this scanner+ # already observed are stepped over without dispatching, while sessions held back by the caps+ # must stay above the cursor so a later tick retries them. None leaves the cursor untouched.+ next_cursor_end_time: dt.datetime | None = None+ next_cursor_session_id: str = Field(default="", max_length=MAX_SESSION_ID_LENGTH)+ # Cursor the walk started from, threaded into the advance so it can match on it.+ started_from_cursor_end_time: dt.datetime | None = None+ started_from_cursor_session_id: str = Field(default="", max_length=MAX_SESSION_ID_LENGTH)+ # Candidates the walk stepped over as already tried. Defaults to 0 so replays of pre-change+ # histories decode, and they simply do not credit the skips.+ skipped_delta: int = 0+ # False only when the walk genuinely reached the window start: a batch the caps truncated still+ # has work below the cursor. The tick completes the backfill exactly when this is False.+ more_work_below_cursor: bool+++class AdvanceBackfillCursorInputs(BaseModel, frozen=True):+ backfill_id: UUID+ team_id: int+ # Cursor this tick started from. The update matches on it, so a retry after a committed-but-lost+ # attempt matches nothing and cannot double-count `dispatched_count`.+ expected_cursor_end_time: dt.datetime | None = None+ expected_cursor_session_id: str = Field(default="", max_length=MAX_SESSION_ID_LENGTH)+ # None leaves the cursor untouched (the empty-batch completion path).+ new_cursor_end_time: dt.datetime | None = None+ new_cursor_session_id: str = Field(default="", max_length=MAX_SESSION_ID_LENGTH)+ dispatched_delta: int = 0+ skipped_delta: int = 0+ # True when the batch came back short: the window is fully walked and the backfill completes.+ exhausted: bool+++class AdvanceBackfillCursorOutput(BaseModel, frozen=True):+ finished: bool+++class BackfillScheduleOpInputs(BaseModel, frozen=True):+ backfill_id: UUIDdiff --git a/products/replay_vision/backend/temporal/backfill_workflow.py b/products/replay_vision/backend/temporal/backfill_workflow.pynew file mode 100644index 000000000000..65277c2389fe--- /dev/null+++ b/products/replay_vision/backend/temporal/backfill_workflow.py@@ -0,0 +1,154 @@+"""Per-backfill tick: gate on quota and in-flight caps, dispatch a newest-first batch, advance the cursor."""++import asyncio++from temporalio import (+ common,+ workflow as wf,+)+from temporalio.common import SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.search_attributes import (+ POSTHOG_SCANNER_ID_KEY,+ POSTHOG_SESSION_RECORDING_ID_KEY,+ POSTHOG_TEAM_ID_KEY,+)++with wf.unsafe.imports_passed_through():+ from django.conf import settings++ from products.replay_vision.backend.models.replay_observation import ObservationTrigger+ from products.replay_vision.backend.temporal.activities import (+ advance_backfill_cursor_activity,+ delete_backfill_schedule_activity,+ find_backfill_candidates_activity,+ pause_backfill_schedule_activity,+ prepare_backfill_tick_activity,+ )+ from products.replay_vision.backend.temporal.backfill_types import (+ AdvanceBackfillCursorInputs,+ BackfillScheduleOpInputs,+ BackfillTickAction,+ BackfillTickInputs,+ FindBackfillCandidatesInputs,+ )+ from products.replay_vision.backend.temporal.constants import (+ ADVANCE_BACKFILL_CURSOR_TIMEOUT,+ APPLY_SCANNER_EXECUTION_TIMEOUT,+ APPLY_SCANNER_WORKFLOW_NAME,+ BACKFILL_SCANNER_WORKFLOW_NAME,+ BACKFILL_SCHEDULE_OP_TIMEOUT,+ FIND_BACKFILL_CANDIDATES_TIMEOUT,+ PREPARE_BACKFILL_TICK_TIMEOUT,+ build_apply_scanner_workflow_id,+ )+ from products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayload+ from products.replay_vision.backend.temporal.types import ApplyScannerInputs++[email protected](name=BACKFILL_SCANNER_WORKFLOW_NAME)+class BackfillScannerWorkflow(PostHogWorkflow):+ inputs_cls = BackfillTickInputs++ @wf.run+ async def run(self, inputs: BackfillTickInputs) -> None:+ prep = await wf.execute_activity(+ prepare_backfill_tick_activity,+ inputs,+ start_to_close_timeout=PREPARE_BACKFILL_TICK_TIMEOUT,+ # A failed gate skips this tick; the next fire retries in a minute.+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ )+ if prep.action == BackfillTickAction.FINISHED:+ await self._delete_own_schedule(inputs)+ return+ if prep.action == BackfillTickAction.PAUSE:+ await wf.execute_activity(+ pause_backfill_schedule_activity,+ BackfillScheduleOpInputs(backfill_id=inputs.backfill_id),+ start_to_close_timeout=BACKFILL_SCHEDULE_OP_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ return+ if prep.action == BackfillTickAction.SKIP or prep.dispatch_budget <= 0:+ return++ find_result = await wf.execute_activity(+ find_backfill_candidates_activity,+ FindBackfillCandidatesInputs(+ backfill_id=inputs.backfill_id, team_id=inputs.team_id, candidate_limit=prep.dispatch_budget+ ),+ start_to_close_timeout=FIND_BACKFILL_CANDIDATES_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ )++ if find_result.candidates:+ # Deterministic child ids collide with live-sweep applies of the same (scanner, session), so+ # a session observed live is skipped here for free.+ await asyncio.gather(*(self._start_child(inputs, c) for c in find_result.candidates))++ # The activity decides how far the walk got, since it can step over sessions that were+ # already observed but must not step over ones the caps held back.+ advance = AdvanceBackfillCursorInputs(+ backfill_id=inputs.backfill_id,+ team_id=inputs.team_id,+ new_cursor_end_time=find_result.next_cursor_end_time,+ new_cursor_session_id=find_result.next_cursor_session_id,+ expected_cursor_end_time=find_result.started_from_cursor_end_time,+ expected_cursor_session_id=find_result.started_from_cursor_session_id,+ dispatched_delta=len(find_result.candidates),+ skipped_delta=find_result.skipped_delta,+ exhausted=not find_result.more_work_below_cursor,+ )++ result = await wf.execute_activity(+ advance_backfill_cursor_activity,+ advance,+ start_to_close_timeout=ADVANCE_BACKFILL_CURSOR_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ if result.finished:+ await self._delete_own_schedule(inputs)++ async def _delete_own_schedule(self, inputs: BackfillTickInputs) -> None:+ # Best-effort: the reconciler's backfill reaper deletes stragglers.+ try:+ await wf.execute_activity(+ delete_backfill_schedule_activity,+ BackfillScheduleOpInputs(backfill_id=inputs.backfill_id),+ start_to_close_timeout=BACKFILL_SCHEDULE_OP_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ except Exception:+ wf.logger.exception(+ "replay_vision.backfill_schedule_delete_failed", extra={"backfill_id": str(inputs.backfill_id)}+ )++ async def _start_child(self, inputs: BackfillTickInputs, candidate: CandidateSessionPayload) -> None:+ try:+ await wf.start_child_workflow(+ APPLY_SCANNER_WORKFLOW_NAME,+ ApplyScannerInputs(+ scanner_id=inputs.scanner_id,+ session_id=candidate.session_id,+ team_id=inputs.team_id,+ triggered_by=ObservationTrigger.BACKFILL,+ backfill_id=inputs.backfill_id,+ ),+ id=build_apply_scanner_workflow_id(inputs.scanner_id, candidate.session_id),+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ parent_close_policy=wf.ParentClosePolicy.ABANDON,+ execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,+ search_attributes=TypedSearchAttributes(+ search_attributes=[+ SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),+ SearchAttributePair(key=POSTHOG_SESSION_RECORDING_ID_KEY, value=candidate.session_id),+ SearchAttributePair(key=POSTHOG_SCANNER_ID_KEY, value=str(inputs.scanner_id)),+ ]+ ),+ )+ except WorkflowAlreadyStartedError:+ passdiff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex da286073b544..6c8fab4cdb3b 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -80,21 +80,9 @@ LIST_SCANNER_SCHEDULES_TIMEOUT = dt.timedelta(seconds=120)RECONCILE_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)-# Capped so `replay-vision-apply-scanner-{scanner_uuid:36}-{session_id}` fits the 255-char `ReplayObservation.workflow_id` column.-MAX_SESSION_ID_LENGTH = 128-# Bounded so broker errors surface as activity failures instead of getting lost in the producer buffer.KAFKA_DELIVERY_TIMEOUT_S = 10.0-# Sessions shorter than this don't carry enough signal for the LLM to analyze.-MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S = 15--# Sessions with less than this much actual interaction are skipped — they're mostly idle.-MIN_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S = 10--# Sessions with more than 1 hour of active interaction take too long to analyze well.-MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S = 3600-# Signals source identity — must match the registered (SourceProduct, SourceType) pair and schema variant.# Prefixed so it stays unambiguous when imported alongside other products' signal-source constants.@@ -124,6 +112,41 @@ def in_flight_headroom(scanner_in_flight: int, team_in_flight: int) -> int:)+BACKFILL_SCANNER_WORKFLOW_NAME = "replay-vision-backfill-scanner"+BACKFILL_SCHEDULE_ID_PREFIX = "replay-vision-backfill"+# Search-attribute value stamped on every per-backfill schedule so the reconciler can list and reap them.+BACKFILL_SCHEDULE_TYPE = "replay-vision-backfill-tick"++# Each tick dispatches at most the backfill sub-cap, so a short interval keeps throughput bounded by+# in-flight capacity rather than tick cadence; overlap SKIP means a slow tick absorbs the next fire.+BACKFILL_TICK_INTERVAL = dt.timedelta(minutes=1)+# Covers the candidate query's ClickHouse budget plus child dispatch fan-out.+BACKFILL_TICK_EXECUTION_TIMEOUT = dt.timedelta(minutes=10)++PREPARE_BACKFILL_TICK_TIMEOUT = dt.timedelta(seconds=30)+FIND_BACKFILL_CANDIDATES_TIMEOUT = dt.timedelta(seconds=200)+ADVANCE_BACKFILL_CURSOR_TIMEOUT = dt.timedelta(seconds=30)+BACKFILL_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)+REAP_BACKFILL_SCHEDULES_TIMEOUT = dt.timedelta(minutes=3)++# A backfill's dispatches count toward the shared per-scanner/per-team caps but never fill more than+# this many slots, so live sweeps always retain rasterizer + provider capacity.+MAX_IN_FLIGHT_APPLIES_PER_BACKFILL = 50+++def backfill_schedule_id(backfill_id: UUID) -> str:+ return f"{BACKFILL_SCHEDULE_ID_PREFIX}-{backfill_id}"+++def backfill_dispatch_budget(scanner_in_flight: int, team_in_flight: int, backfill_in_flight: int) -> int:+ """How many apply-scanner children one backfill tick may dispatch: the shared sweep headroom+ further bounded by the backfill sub-cap. Pure, so it is safe inside deterministic workflow code."""+ return min(+ in_flight_headroom(scanner_in_flight, team_in_flight),+ MAX_IN_FLIGHT_APPLIES_PER_BACKFILL - backfill_in_flight,+ )++ESTIMATES_WORKFLOW_NAME = "replay-vision-refresh-scanner-estimates"ESTIMATES_WORKFLOW_ID = "replay-vision-estimate-refresher"ESTIMATES_SCHEDULE_ID = "replay-vision-estimate-refresher-schedule"diff --git a/products/replay_vision/backend/temporal/evaluation_types.py b/products/replay_vision/backend/temporal/evaluation_types.pyindex 8273d4eb8586..f37e5636d8cc 100644--- a/products/replay_vision/backend/temporal/evaluation_types.py+++ b/products/replay_vision/backend/temporal/evaluation_types.py@@ -3,7 +3,7 @@ from uuid import UUIDfrom pydantic import BaseModel, Field-from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.temporal.types import ScannerSnapshotdiff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 308237b9604a..6865a0d404c3 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -70,6 +70,12 @@ REPLAY_VISION_CREDITS_CONSUMED = Counter(["scanner_type", "model"],)+REPLAY_VISION_BACKFILL_TICK_OUTCOMES = Counter(+ "replay_vision_backfill_tick_outcomes_total",+ "Backfill tick outcomes: dispatched, throttled, paused on quota, skipped, or completed",+ ["outcome"],+)+REPLAY_VISION_SWEEP_OUTCOMES = Counter("replay_vision_sweep_outcomes_total","Sweep tick outcomes: throttled at an in-flight cap, no candidates, or candidates found",@@ -179,6 +185,11 @@ def record_sweep_outcome(outcome: str, candidates: int = 0) -> None:_otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATES, candidates, {})+def record_backfill_tick_outcome(outcome: str) -> None:+ REPLAY_VISION_BACKFILL_TICK_OUTCOMES.labels(outcome=outcome).inc()+ _otel.record_counter_twin(REPLAY_VISION_BACKFILL_TICK_OUTCOMES, 1, {"outcome": outcome})++def record_observation_e2e(scanner_type: str, seconds: float) -> None:labels = {"scanner_type": scanner_type}REPLAY_VISION_OBSERVATION_E2E.labels(**labels).observe(seconds)diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.pyindex cb634cdcc4a8..1af84045c3cd 100644--- a/products/replay_vision/backend/temporal/reconciler.py+++ b/products/replay_vision/backend/temporal/reconciler.py@@ -15,6 +15,7 @@ from products.replay_vision.backend.temporal.constants import (INLINE_SCANNER_REAP_TIMEOUT,LIST_ENABLED_SCANNERS_TIMEOUT,LIST_SCANNER_SCHEDULES_TIMEOUT,+ REAP_BACKFILL_SCHEDULES_TIMEOUT,REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT,REAP_ORPHANED_OBSERVATIONS_TIMEOUT,REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT,@@ -41,6 +42,7 @@ with workflow.unsafe.imports_passed_through():delete_scanner_schedule_activity,list_enabled_scanners_activity,list_scanner_schedules_activity,+ reap_backfill_schedules_activity,reap_childless_inline_scanners_activity,reap_orphaned_observations_activity,reap_stuck_vision_action_runs_activity,@@ -88,6 +90,16 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):except Exception:workflow.logger.exception("replay_vision.reap_childless_inline_scanners_failed")+ if workflow.patched("reap-backfill-schedules-2026-08"):+ try:+ await workflow.execute_activity(+ reap_backfill_schedules_activity,+ start_to_close_timeout=REAP_BACKFILL_SCHEDULES_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except Exception:+ workflow.logger.exception("replay_vision.reap_backfill_schedules_failed")+# A scanner toggled between the two listings recovers on the next tick.enabled_entries, existing_entries = await asyncio.gather(workflow.execute_activity(diff --git a/products/replay_vision/backend/temporal/schedule.py b/products/replay_vision/backend/temporal/schedule.pyindex 87b1b4b79b8c..92f79218d0fa 100644--- a/products/replay_vision/backend/temporal/schedule.py+++ b/products/replay_vision/backend/temporal/schedule.py@@ -23,7 +23,15 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connect-from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_schedule_exists, a_update_schedule+from posthog.temporal.common.schedule import (+ a_create_schedule,+ a_delete_schedule,+ a_pause_schedule,+ a_schedule_exists,+ a_trigger_schedule,+ a_unpause_schedule,+ a_update_schedule,+)from posthog.temporal.common.search_attributes import (POSTHOG_SCHEDULE_FINGERPRINT_KEY,POSTHOG_SCHEDULE_TYPE_KEY,@@ -32,11 +40,17 @@ from posthog.temporal.common.search_attributes import (from products.replay_vision.backend.fingerprint import SCHEDULE_FINGERPRINT_LENGTH, config_fingerprintfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.temporal.backfill_types import BackfillTickInputsfrom products.replay_vision.backend.temporal.constants import (+ BACKFILL_SCANNER_WORKFLOW_NAME,+ BACKFILL_SCHEDULE_TYPE,+ BACKFILL_TICK_EXECUTION_TIMEOUT,+ BACKFILL_TICK_INTERVAL,SCANNER_SCHEDULE_INTERVAL,SCANNER_SCHEDULE_TYPE,SWEEP_SCANNER_WORKFLOW_NAME,SWEEP_WORKFLOW_EXECUTION_TIMEOUT,+ backfill_schedule_id,scanner_schedule_id,)from products.replay_vision.backend.temporal.sweep_types import SweepScannerInputs@@ -62,10 +76,15 @@ def compute_schedule_fingerprint(snapshot: dict[str, Any] | None) -> str:return config_fingerprint(snapshot, length=SCHEDULE_FINGERPRINT_LENGTH)-def _compute_offset(scanner_id: UUID) -> dt.timedelta:- # UUID.int is stable across processes; modulo distributes fires uniformly across the window.- interval_s = max(1, int(SCANNER_SCHEDULE_INTERVAL.total_seconds()))- return dt.timedelta(seconds=scanner_id.int % interval_s)+def compute_schedule_offset(entity_id: UUID, interval: dt.timedelta) -> dt.timedelta:+ """Stagger per-entity schedules across their interval so they don't all fire on the same boundary.++ UUID.int is stable across processes; modulo distributes fires uniformly across the window. Without+ this, sibling schedules tick together and each reads the same in-flight counts before any of them+ has persisted a row.+ """+ interval_s = max(1, int(interval.total_seconds()))+ return dt.timedelta(seconds=entity_id.int % interval_s)def _build_schedule(scanner_id: UUID, team_id: int) -> Schedule:@@ -79,7 +98,12 @@ def _build_schedule(scanner_id: UUID, team_id: int) -> Schedule:retry_policy=common.RetryPolicy(maximum_attempts=1),),spec=ScheduleSpec(- intervals=[ScheduleIntervalSpec(every=SCANNER_SCHEDULE_INTERVAL, offset=_compute_offset(scanner_id))]+ intervals=[+ ScheduleIntervalSpec(+ every=SCANNER_SCHEDULE_INTERVAL,+ offset=compute_schedule_offset(scanner_id, SCANNER_SCHEDULE_INTERVAL),+ )+ ]),policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=SCANNER_SCHEDULE_INTERVAL),)@@ -110,6 +134,7 @@ async def upsert_interval_schedule(interval: dt.timedelta,execution_timeout: dt.timedelta,search_attributes: TypedSearchAttributes | None = None,+ offset: dt.timedelta | None = None,) -> None:"""Create or update a singleton interval schedule with SKIP overlap; first creation triggers immediately."""schedule = Schedule(@@ -121,15 +146,21 @@ async def upsert_interval_schedule(execution_timeout=execution_timeout,retry_policy=common.RetryPolicy(maximum_attempts=1),),- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=interval)]),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=interval, offset=offset)]),policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=interval),)if await a_schedule_exists(client, schedule_id):await a_update_schedule(client, schedule_id, schedule, search_attributes=search_attributes)- else:+ return+ try:await a_create_schedule(client, schedule_id, schedule, trigger_immediately=True, search_attributes=search_attributes)+ except RPCError as e:+ if e.status != RPCStatusCode.ALREADY_EXISTS:+ raise+ # Concurrent upsert beat us to create; treat as update.+ await a_update_schedule(client, schedule_id, schedule, search_attributes=search_attributes)async def a_upsert_scanner_schedule(scanner_id: UUID, team_id: int) -> None:@@ -166,15 +197,73 @@ async def a_upsert_scanner_schedule(scanner_id: UUID, team_id: int) -> None:await a_update_schedule(client, schedule_id, schedule, search_attributes=search_attributes)-async def a_delete_scanner_schedule(scanner_id: UUID) -> None:- """Idempotent — only swallows NOT_FOUND races; other RPC failures propagate."""- client = await async_connect()- schedule_id = scanner_schedule_id(scanner_id)- if not await a_schedule_exists(client, schedule_id):- return+async def a_upsert_backfill_schedule(+ backfill_id: UUID, team_id: int, scanner_id: UUID, client: Client | None = None+) -> None:+ """Create (or repair) the per-backfill tick schedule; first creation triggers immediately."""+ client = client or await async_connect()+ await upsert_interval_schedule(+ client,+ schedule_id=backfill_schedule_id(backfill_id),+ workflow_name=BACKFILL_SCANNER_WORKFLOW_NAME,+ workflow_id=f"{BACKFILL_SCANNER_WORKFLOW_NAME}-{backfill_id}",+ inputs=BackfillTickInputs(backfill_id=backfill_id, team_id=team_id, scanner_id=scanner_id),+ interval=BACKFILL_TICK_INTERVAL,+ execution_timeout=BACKFILL_TICK_EXECUTION_TIMEOUT,+ # Without this every backfill in the fleet ticks on the same minute boundary.+ offset=compute_schedule_offset(backfill_id, BACKFILL_TICK_INTERVAL),+ search_attributes=TypedSearchAttributes(+ search_attributes=[+ SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=team_id),+ SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=BACKFILL_SCHEDULE_TYPE),+ ]+ ),+ )+++async def _a_delete_schedule_idempotent(schedule_id: str, log_event: str, client: Client | None = None) -> None:+ """Delete directly and swallow the NOT_FOUND race; other RPC failures propagate."""+ client = client or await async_connect()try:await a_delete_schedule(client, schedule_id)except RPCError as e:if e.status != RPCStatusCode.NOT_FOUND:raise- logger.info("replay_vision.delete_schedule.already_gone", scanner_id=str(scanner_id))+ logger.info(log_event, schedule_id=schedule_id)+++async def a_delete_backfill_schedule(backfill_id: UUID, client: Client | None = None) -> None:+ await _a_delete_schedule_idempotent(+ backfill_schedule_id(backfill_id), "replay_vision.delete_backfill_schedule.already_gone", client+ )+++async def a_pause_backfill_schedule(backfill_id: UUID, note: str, client: Client | None = None) -> None:+ """Idempotent — pausing a missing schedule is a no-op."""+ client = client or await async_connect()+ try:+ await a_pause_schedule(client, backfill_schedule_id(backfill_id), note=note)+ except RPCError as e:+ if e.status != RPCStatusCode.NOT_FOUND:+ raise+++async def a_resume_backfill_schedule(backfill_id: UUID, team_id: int, scanner_id: UUID) -> None:+ """Unpause the tick schedule and fire a tick right away so a resume feels immediate.++ A lost schedule is recreated instead of failing the resume (creation triggers immediately).+ """+ client = await async_connect()+ schedule_id = backfill_schedule_id(backfill_id)+ try:+ await a_unpause_schedule(client, schedule_id, note="user resume")+ except RPCError as e:+ if e.status != RPCStatusCode.NOT_FOUND:+ raise+ await a_upsert_backfill_schedule(backfill_id, team_id, scanner_id, client)+ return+ await a_trigger_schedule(client, schedule_id)+++async def a_delete_scanner_schedule(scanner_id: UUID) -> None:+ await _a_delete_schedule_idempotent(scanner_schedule_id(scanner_id), "replay_vision.delete_schedule.already_gone")diff --git a/products/replay_vision/backend/temporal/snapshots.py b/products/replay_vision/backend/temporal/snapshots.pynew file mode 100644index 000000000000..7216e0a5f41e--- /dev/null+++ b/products/replay_vision/backend/temporal/snapshots.py@@ -0,0 +1,85 @@+"""Frozen scanner-config snapshots.++A leaf module: `types.py` participates in an import cycle with the `scanners` package, so anything+importable without that baggage (activities loaded early in the package init, the API layer) gets+the snapshot classes from here. `types.py` re-exports them for its existing importers.+"""++from typing import TYPE_CHECKING, Any+from uuid import UUID++from pydantic import BaseModel, Field, ValidationError+from temporalio.exceptions import ApplicationError++from products.replay_vision.backend.models.replay_scanner import ScannerType++if TYPE_CHECKING:+ from products.replay_vision.backend.models.replay_scanner import ReplayScanner+++class ScannerSnapshot(BaseModel, frozen=True):+ """Frozen view of a `ReplayScanner` at observation-create time, persisted into `ReplayObservation.scanner_snapshot`."""++ name: str+ scanner_type: ScannerType+ scanner_version: int = Field(ge=1)+ # Plain strings, not live enums: retiring a ScannerModel/ScannerProvider member must not break old-row loads.+ model: str+ provider: str+ emits_signals: bool+ scanner_config: dict[str, Any]++ @classmethod+ def from_scanner(cls, scanner: "ReplayScanner") -> "ScannerSnapshot":+ """The single scanner→snapshot field mapping; every snapshot producer must build through here."""+ return cls(+ name=scanner.name,+ scanner_type=scanner.scanner_type,+ scanner_version=scanner.scanner_version,+ model=scanner.model,+ provider=scanner.provider,+ emits_signals=scanner.emits_signals,+ scanner_config=scanner.scanner_config,+ )++ @classmethod+ def load_for(cls, observation_id: UUID, raw: dict[str, Any] | None) -> "ScannerSnapshot":+ """Validate a persisted `scanner_snapshot` blob, raising a non-retryable error tagged with the observation id."""+ try:+ return cls.model_validate(raw or {})+ except ValidationError as exc:+ raise ApplicationError(+ f"ReplayObservation {observation_id} has malformed scanner_snapshot: {exc}", non_retryable=True+ ) from exc+++class BackfillScannerSnapshot(ScannerSnapshot, frozen=True):+ """Full frozen scanner config persisted into `ReplayScannerBackfill.scanner_snapshot` — the observation+ snapshot fields plus the query/sampling inputs the candidate walk needs. Freezing both keeps the+ creation-time enumeration and its cost ceiling exact for the backfill's whole lifetime."""++ query: dict[str, Any]+ sampling_rate: float = Field(ge=0.0, le=1.0)+ sampling_mode: str++ @classmethod+ def from_scanner(cls, scanner: "ReplayScanner") -> "BackfillScannerSnapshot":+ return cls(+ **ScannerSnapshot.from_scanner(scanner).model_dump(),+ query=scanner.query,+ sampling_rate=scanner.sampling_rate,+ sampling_mode=scanner.sampling_mode,+ )++ @classmethod+ def load_for_backfill(cls, backfill_id: UUID, raw: dict[str, Any] | None) -> "BackfillScannerSnapshot":+ """Validate a persisted backfill `scanner_snapshot` blob, raising a non-retryable error tagged with the backfill id."""+ try:+ return cls.model_validate(raw or {})+ except ValidationError as exc:+ raise ApplicationError(+ f"ReplayScannerBackfill {backfill_id} has malformed scanner_snapshot: {exc}", non_retryable=True+ ) from exc++ def to_observation_snapshot(self) -> ScannerSnapshot:+ return ScannerSnapshot.model_validate(self.model_dump(include=set(ScannerSnapshot.model_fields)))diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.pyindex 93e7dda67445..283c450a8775 100644--- a/products/replay_vision/backend/temporal/sweep_types.py+++ b/products/replay_vision/backend/temporal/sweep_types.py@@ -5,7 +5,7 @@ from uuid import UUIDfrom pydantic import BaseModel, Field-from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHclass SweepScannerInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex 3da48d24345f..27e4e8292df7 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -2,17 +2,20 @@ import datetime as dtfrom typing import Annotated, Any, TypedDictfrom uuid import UUID-from pydantic import BaseModel, Field, ValidationError, model_validator-from temporalio.exceptions import ApplicationError+from pydantic import BaseModel, Field, model_validatorfrom products.replay_vision.backend.models.replay_observation import ObservationTriggerfrom products.replay_vision.backend.models.replay_scanner import ScannerType-from products.replay_vision.backend.temporal.constants import MAX_SESSION_ID_LENGTH+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.temporal.scanners.base import SignalFindingfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutputfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorOutputfrom products.replay_vision.backend.temporal.scanners.scorer import ScorerOutputfrom products.replay_vision.backend.temporal.scanners.summarizer import SummarizerOutput+from products.replay_vision.backend.temporal.snapshots import (+ BackfillScannerSnapshot as BackfillScannerSnapshot,+ ScannerSnapshot as ScannerSnapshot,+)AnyScannerOutput = Annotated[ClassifierOutput | MonitorOutput | ScorerOutput | SummarizerOutput,@@ -20,29 +23,6 @@ AnyScannerOutput = Annotated[]-class ScannerSnapshot(BaseModel, frozen=True):- """Frozen view of a `ReplayScanner` at observation-create time, persisted into `ReplayObservation.scanner_snapshot`."""-- name: str- scanner_type: ScannerType- scanner_version: int = Field(ge=1)- # Plain strings, not live enums: retiring a ScannerModel/ScannerProvider member must not break old-row loads.- model: str- provider: str- emits_signals: bool- scanner_config: dict[str, Any]-- @classmethod- def load_for(cls, observation_id: UUID, raw: dict[str, Any] | None) -> "ScannerSnapshot":- """Validate a persisted `scanner_snapshot` blob, raising a non-retryable error tagged with the observation id."""- try:- return cls.model_validate(raw or {})- except ValidationError as exc:- raise ApplicationError(- f"ReplayObservation {observation_id} has malformed scanner_snapshot: {exc}", non_retryable=True- ) from exc--class ScannerResult(BaseModel, frozen=True):"""Result data of a completed observation, persisted into `ReplayObservation.scanner_result`."""@@ -58,6 +38,8 @@ class ApplyScannerInputs(BaseModel, frozen=True):team_id: inttriggered_by: ObservationTriggertriggered_by_user_id: int | None = None+ # Set only for backfill-triggered applies; routes observation creation to the backfill's frozen snapshot.+ backfill_id: UUID | None = Noneclass CreateObservationInputs(BaseModel, frozen=True):@@ -67,6 +49,7 @@ class CreateObservationInputs(BaseModel, frozen=True):triggered_by: ObservationTriggertriggered_by_user_id: int | Noneworkflow_id: str+ backfill_id: UUID | None = Noneclass CreateObservationOutput(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 56ee6006d05f..fe8a16f273cb 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -237,6 +237,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):triggered_by=inputs.triggered_by,triggered_by_user_id=inputs.triggered_by_user_id,workflow_id=workflow_id,+ backfill_id=inputs.backfill_id,),start_to_close_timeout=dt.timedelta(seconds=30),schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.pyindex 621a6578da1e..8b69f42359b0 100644--- a/products/replay_vision/backend/tests/test_access_control.py+++ b/products/replay_vision/backend/tests/test_access_control.py@@ -188,6 +188,16 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):self.assertEqual(resp.status_code, 400, resp.json())self.assertEqual(resp.json()["attr"], "scanner_id")+ def test_backfills_inherit_scanner_object_rbac(self) -> None:+ scanner = self._create_scanner()+ self._set_resource_default("replay_scanner", "none")+ self.client.force_login(self.other_user)+ url = f"{self.scanners_url}{scanner.id}/backfills/"+ self.assertEqual(self.client.get(url).status_code, 403)+ window = {"window_start": "2026-01-01T00:00:00Z", "window_end": "2026-02-01T00:00:00Z"}+ self.assertEqual(self.client.post(f"{url}estimate/", window, format="json").status_code, 403)+ self.assertEqual(self.client.post(url, window, format="json").status_code, 403)+def test_experiment_targeting_rejects_an_experiment_the_caller_cannot_view(self) -> None:# A scanner-editor without experiment access must not be able to confirm an experiment's# existence via the targeting validation response; a denied experiment reads as not-found.diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 54d57659fc75..5477768aaddf 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -32,6 +32,7 @@ from products.replay_vision.backend.models.replay_scanner import (ScannerProvider,ScannerType,)+from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfillfrom products.replay_vision.backend.models.vision_action import VisionActionfrom products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVALfrom products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds@@ -1977,7 +1978,7 @@ class TestObserveAction(_VisionAPITestCase):mock_async_to_sync.return_value = MagicMock()exhausted = MagicMock(credit_limit=500, period_end=timezone.now())- with patch("products.replay_vision.backend.api.trigger.compute_quota_snapshot", return_value=exhausted):+ with patch("products.replay_vision.backend.api.trigger.quota_state", return_value=exhausted):with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:resp = self.client.post(self.observe_url(str(self.scanner.id)), data={"session_id": "sess-quota"}, format="json"@@ -2313,7 +2314,7 @@ class TestRetryActions(_VisionAPITestCase):observation = self._create_failed("sess-quota")exhausted = MagicMock(exhausted=True, credit_limit=500, period_end=timezone.now())- with patch("products.replay_vision.backend.api.trigger.compute_quota_snapshot", return_value=exhausted):+ with patch("products.replay_vision.backend.api.trigger.quota_state", return_value=exhausted):resp = self.client.post(self.retry_url(str(observation.id)))self.assertEqual(resp.status_code, 402, resp.json())self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())@@ -2713,6 +2714,35 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):edit_body = self.client.post(self.estimate_url, data={"scanner_id": str(a.id)}, format="json").json()self.assertEqual(edit_body["other_enabled_scanners_monthly_credits"], 250 * 15)+ def test_estimate_reports_active_backfill_commitment(self) -> None:+ # The editor replaces the fleet total with `others + this scanner`, which drops the backfill credits the+ # quota snapshot carries. Without this field the forecast understates period-end spend while one runs.+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="backfilled",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ ReplayScannerBackfill.objects.for_team(self.team.id).create(+ scanner=scanner,+ team=self.team,+ window_start=timezone.now() - timedelta(days=5),+ window_end=timezone.now(),+ scanner_snapshot={},+ credits_per_observation=5,+ total_count=100,+ dispatched_count=40,+ )++ body = self.client.post(self.estimate_url, data={}, format="json").json()++ assert body["active_backfill_credits"] == 60 * 5++ def test_estimate_reports_no_backfill_commitment_when_none_are_active(self) -> None:+ body = self.client.post(self.estimate_url, data={}, format="json").json()+ assert body["active_backfill_credits"] == 0+def test_estimate_rejects_scanner_id_outside_the_request_team(self) -> None:# A scanner_id from another team (even same org) must be rejected, not silently excluded from the others-sum.other_team = Team.objects.create(organization=self.team.organization, name="sibling")diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pynew file mode 100644index 000000000000..830215714dac--- /dev/null+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -0,0 +1,730 @@+import uuid+import datetime as dt++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.utils import timezone++from rest_framework.status import HTTP_429_TOO_MANY_REQUESTS+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.models import Organization, Team++from products.replay_vision.backend.api.backfills import (+ MAX_BACKFILL_WINDOW_DAYS,+ BackfillEnumerationThrottle,+ ReplayScannerBackfillViewSet,+)+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ObservationTrigger+from products.replay_vision.backend.models.replay_scanner import (+ SETTLE_INTERVAL,+ ReplayScanner,+ ScannerModel,+ ScannerType,+)+from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill+from products.replay_vision.backend.quota import QuotaState, compute_quota_snapshot, spend_projection+from products.replay_vision.backend.temporal.activities.backfill import (+ advance_backfill_cursor_activity,+ delete_backfill_schedule_activity,+ find_backfill_candidates_activity,+ pause_backfill_schedule_activity,+ prepare_backfill_tick_activity,+)+from products.replay_vision.backend.temporal.activities.create_observation import create_observation_activity+from products.replay_vision.backend.temporal.backfill_types import (+ AdvanceBackfillCursorInputs,+ AdvanceBackfillCursorOutput,+ BackfillTickAction,+ BackfillTickInputs,+ FindBackfillCandidatesInputs,+ FindBackfillCandidatesOutput,+ PrepareBackfillTickOutput,+)+from products.replay_vision.backend.temporal.backfill_workflow import BackfillScannerWorkflow+from products.replay_vision.backend.temporal.constants import (+ APPLY_SCANNER_WORKFLOW_NAME,+ MAX_IN_FLIGHT_APPLIES_PER_BACKFILL,+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,+ backfill_dispatch_budget,+ build_apply_scanner_workflow_id,+)+from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot+from products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayload+from products.replay_vision.backend.temporal.types import CreateObservationInputs++_WINDOW_END = dt.datetime(2026, 5, 1, tzinfo=dt.UTC)+_WINDOW_START = _WINDOW_END - dt.timedelta(days=30)+++def _make_scanner(**overrides) -> ReplayScanner:+ org = Organization.objects.create(name="backfill-test-org")+ team = Team.objects.create(organization=org, name="backfill-test-team")+ defaults: dict = {+ "team": team,+ "name": "t",+ "scanner_type": ScannerType.MONITOR,+ "scanner_config": {"prompt": "p"},+ "model": ScannerModel.GEMINI_3_6_FLASH,+ }+ defaults.update(overrides)+ return ReplayScanner.objects.create(**defaults)+++def _frozen_snapshot(scanner: ReplayScanner, **overrides) -> dict:+ return {**BackfillScannerSnapshot.from_scanner(scanner).model_dump(mode="json"), **overrides}+++def _make_backfill(scanner: ReplayScanner, **overrides) -> ReplayScannerBackfill:+ defaults: dict = {+ "scanner": scanner,+ "team": scanner.team,+ "window_start": _WINDOW_START,+ "window_end": _WINDOW_END,+ "scanner_snapshot": _frozen_snapshot(scanner),+ "credits_per_observation": 5,+ "total_count": 100,+ }+ defaults.update(overrides)+ return ReplayScannerBackfill.objects.for_team(scanner.team_id).create(**defaults)+++ "scanner_in_flight,team_in_flight,backfill_in_flight,expected",+ [+ # One case per cap that can win, plus the fully-saturated floor.+ (0, 0, 0, MAX_IN_FLIGHT_APPLIES_PER_BACKFILL),+ (0, 0, MAX_IN_FLIGHT_APPLIES_PER_BACKFILL, 0),+ (MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 10, 0, 0, 10),+ (0, MAX_IN_FLIGHT_APPLIES_PER_TEAM - 5, 0, 5),+ ],+)+def test_backfill_dispatch_budget_takes_the_tightest_cap(+ scanner_in_flight: int, team_in_flight: int, backfill_in_flight: int, expected: int+) -> None:+ assert backfill_dispatch_budget(scanner_in_flight, team_in_flight, backfill_in_flight) == expected++[email protected]_db(transaction=True)+class TestBackfillQuotaCommitment:+ def test_only_active_backfills_contribute_their_remaining_commitment(self) -> None:+ scanner = _make_scanner()+ org_id = scanner.team.organization_id+ _make_backfill(scanner, total_count=100, dispatched_count=40, credits_per_observation=5)+ # Terminal rows and fully-dispatched rows must not inflate the prognosis.+ cancelled_scanner = ReplayScanner.objects.create(+ team=scanner.team,+ name="c",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ _make_backfill(cancelled_scanner, status=BackfillStatus.CANCELLED, total_count=100, credits_per_observation=5)++ assert spend_projection(org_id).backfills_committed_credits == 60 * 5+ assert compute_quota_snapshot(org_id).projected_monthly_credits == 60 * 5++ def test_paused_backfill_still_counts_as_committed(self) -> None:+ scanner = _make_scanner()+ _make_backfill(+ scanner, status=BackfillStatus.PAUSED_QUOTA, total_count=10, dispatched_count=4, credits_per_observation=2+ )+ assert spend_projection(scanner.team.organization_id).backfills_committed_credits == 12++[email protected]_db(transaction=True)+class TestCreateObservationForBackfill:+ def test_backfill_observation_uses_frozen_snapshot_not_live_scanner(self) -> None:+ scanner = _make_scanner(scanner_config={"prompt": "new prompt"})+ backfill = _make_backfill(+ scanner, scanner_snapshot=_frozen_snapshot(scanner, scanner_config={"prompt": "frozen prompt"})+ )+ 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-1",+ backfill_id=backfill.id,+ )+ )+ assert result.was_created+ observation = backfill.observations.get()+ assert observation.scanner_snapshot["scanner_config"] == {"prompt": "frozen prompt"}+ assert observation.triggered_by == ObservationTrigger.BACKFILL++ def test_cancelled_backfill_skips_creation(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner, status=BackfillStatus.CANCELLED, finished_at=timezone.now())+ 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-1",+ backfill_id=backfill.id,+ )+ )+ assert not result.was_created+ assert not backfill.observations.exists()++[email protected]_db(transaction=True)+class TestBackfillTickActivities:+ @staticmethod+ def _tick_inputs(backfill: ReplayScannerBackfill) -> BackfillTickInputs:+ return BackfillTickInputs(backfill_id=backfill.id, team_id=backfill.team_id, scanner_id=backfill.scanner_id)++ def test_prepare_finishes_on_terminal_row_and_skips_on_disabled_scanner(self) -> None:+ scanner = _make_scanner()+ cancelled = _make_backfill(scanner, status=BackfillStatus.CANCELLED, finished_at=timezone.now())+ assert prepare_backfill_tick_activity(self._tick_inputs(cancelled)).action == BackfillTickAction.FINISHED++ scanner.enabled = False+ scanner.save()+ running = _make_backfill(scanner)+ assert prepare_backfill_tick_activity(self._tick_inputs(running)).action == BackfillTickAction.SKIP++ def test_prepare_repauses_a_quota_paused_row(self) -> None:+ # The reaper can recreate a paused backfill's schedule unpaused; a SKIP here would tick forever.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner, status=BackfillStatus.PAUSED_QUOTA)+ assert prepare_backfill_tick_activity(self._tick_inputs(backfill)).action == BackfillTickAction.PAUSE++ def test_prepare_skips_without_org_ai_consent(self) -> None:+ # Children would decline at create while the cursor walks past their sessions.+ scanner = _make_scanner()+ org = scanner.team.organization+ org.is_ai_data_processing_approved = False+ org.save()+ backfill = _make_backfill(scanner)+ assert prepare_backfill_tick_activity(self._tick_inputs(backfill)).action == BackfillTickAction.SKIP++ def test_prepare_clamps_batch_to_remaining_quota(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner, credits_per_observation=5)+ # A real state, not a mock: the point of the test is the arithmetic that turns remaining+ # credits into a batch size, and a stubbed collaborator can't fail when that changes.+ headroom = QuotaState(+ credit_limit=7,+ credits_used=0,+ period_start=_WINDOW_START,+ period_end=_WINDOW_END,+ )+ with patch(+ "products.replay_vision.backend.temporal.activities.backfill.quota_state",+ return_value=headroom,+ ):+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.DISPATCH+ assert result.dispatch_budget == 1++ def test_prepare_pauses_when_org_quota_exhausted(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ exhausted = MagicMock()+ exhausted.would_exceed.return_value = True+ with patch(+ "products.replay_vision.backend.temporal.activities.backfill.quota_state",+ return_value=exhausted,+ ):+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.PAUSE+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.PAUSED_QUOTA++ def test_prepare_dispatches_with_budget_when_headroom_available(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.DISPATCH+ assert result.dispatch_budget > 0++ def test_advance_is_idempotent_under_retry(self) -> None:+ # Temporal retries an activity whose result was lost after it committed; a blind second+ # increment would inflate progress and understate the remaining credit commitment.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ advance = AdvanceBackfillCursorInputs(+ backfill_id=backfill.id,+ team_id=backfill.team_id,+ new_cursor_end_time=_WINDOW_END - dt.timedelta(days=1),+ new_cursor_session_id="sess-1",+ dispatched_delta=5,+ exhausted=False,+ )+ advance_backfill_cursor_activity(advance)+ advance_backfill_cursor_activity(advance)+ 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.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ ReplayScannerBackfill.objects.for_team(backfill.team_id).filter(pk=backfill.id).update(+ total_count=10, credits_per_observation=5+ )++ advance_backfill_cursor_activity(+ AdvanceBackfillCursorInputs(+ backfill_id=backfill.id,+ team_id=backfill.team_id,+ new_cursor_end_time=_WINDOW_END - dt.timedelta(days=1),+ new_cursor_session_id="sess-10",+ dispatched_delta=6,+ skipped_delta=4,+ exhausted=False,+ )+ )++ backfill.refresh_from_db()+ assert (backfill.dispatched_count, backfill.skipped_count) == (6, 4)+ assert backfill.dispatched_count + backfill.skipped_count == backfill.total_count+ assert spend_projection(scanner.team.organization_id).backfills_committed_credits == 0++ def test_advance_updates_cursor_and_short_batch_completes(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ cursor_time = _WINDOW_END - dt.timedelta(days=2)+ result = advance_backfill_cursor_activity(+ AdvanceBackfillCursorInputs(+ backfill_id=backfill.id,+ team_id=backfill.team_id,+ new_cursor_end_time=cursor_time,+ new_cursor_session_id="sess-9",+ dispatched_delta=2,+ exhausted=False,+ )+ )+ assert not result.finished+ backfill.refresh_from_db()+ assert (backfill.cursor_end_time, backfill.cursor_session_id) == (cursor_time, "sess-9")+ assert backfill.dispatched_count == 2+ assert backfill.status == BackfillStatus.RUNNING++ result = advance_backfill_cursor_activity(+ AdvanceBackfillCursorInputs(+ backfill_id=backfill.id,+ team_id=backfill.team_id,+ expected_cursor_end_time=cursor_time,+ expected_cursor_session_id="sess-9",+ exhausted=True,+ )+ )+ assert result.finished+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.COMPLETED+ assert backfill.finished_at is not None++ def test_drained_window_finishes_instead_of_crashing_the_tick(self) -> None:+ # An empty batch used to index candidates[-1]. The activity runs with maximum_attempts=1, so the+ # tick died, the minute schedule refired forever, and the backfill sat RUNNING until cancelled.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ with patch("products.replay_vision.backend.temporal.activities.backfill.BackfillCandidateQuery") as query_cls:+ query_cls.return_value.run.return_value = []+ result = find_backfill_candidates_activity(+ FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)+ )+ assert result.candidates == []+ # A short batch is what completes the backfill, and the cursor must not move on an empty one.+ assert not result.more_work_below_cursor+ assert result.next_cursor_end_time is None+ assert result.skipped_delta == 0++ def test_advance_loses_to_concurrent_cancel(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner, status=BackfillStatus.CANCELLED, finished_at=timezone.now())+ result = advance_backfill_cursor_activity(+ AdvanceBackfillCursorInputs(backfill_id=backfill.id, team_id=backfill.team_id, exhausted=True)+ )+ assert not result.finished+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.CANCELLED+++class TestBackfillsApi(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.flag_patcher = patch(+ "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.flag_patcher.start()+ self.scanner = ReplayScanner.objects.create(+ team=self.team,+ name="backfill-api-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ self.base_url = f"/api/projects/{self.team.id}/vision/scanners/{self.scanner.id}/backfills"++ def tearDown(self) -> None:+ self.flag_patcher.stop()+ super().tearDown()++ def _window_body(self) -> dict:+ now = timezone.now()+ return {+ "window_start": (now - dt.timedelta(days=30)).isoformat(),+ "window_end": (now + dt.timedelta(days=1)).isoformat(),+ }++ @patch("products.replay_vision.backend.temporal.schedule.a_upsert_backfill_schedule", new_callable=AsyncMock)+ @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ def test_create_freezes_config_clamps_window_to_settle_horizon_and_rejects_second_active(+ self, mock_query: MagicMock, mock_upsert: AsyncMock+ ) -> None:+ mock_query.return_value.count.return_value = 7+ # Well behind the settle horizon, so the watermark assertion below measures the intended thing+ # rather than the microseconds between scanner creation and this request.+ self.scanner.last_swept_at = timezone.now() - dt.timedelta(days=2)+ self.scanner.save(update_fields=["last_swept_at"])+ response = self.client.post(f"{self.base_url}/", self._window_body(), format="json")+ assert response.status_code == 201, response.json()+ body = response.json()+ assert body["total_count"] == 7+ assert body["status"] == "running"++ backfill = ReplayScannerBackfill.objects.for_team(self.team.id).get(pk=body["id"])+ # A window reaching into the future is clamped back to the settle horizon, but is no longer cut+ # at the scanner's sweep watermark: overlap with the live sweep is safe and often the whole point.+ assert backfill.window_end <= timezone.now() - SETTLE_INTERVAL+ assert backfill.window_end > self.scanner.last_swept_at+ assert backfill.scanner_snapshot["scanner_config"] == {"prompt": "p"}+ assert backfill.credits_per_observation > 0+ assert mock_upsert.await_count == 1++ response = self.client.post(f"{self.base_url}/", self._window_body(), format="json")+ assert response.status_code == 400+ assert "active backfill" in response.json()["detail"]++ @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ def test_estimate_returns_exact_ceiling_without_creating_rows(self, mock_query: MagicMock) -> None:+ mock_query.return_value.count.return_value = 40+ response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")+ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["total_sessions"] == 40+ assert body["total_credits"] == 40 * body["credits_per_observation"]+ assert not ReplayScannerBackfill.objects.for_team(self.team.id).filter(scanner=self.scanner).exists()++ @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ def test_window_stops_at_the_settle_horizon_the_sweep_waits_for(self, mock_query: MagicMock) -> None:+ # A session inside the settle window is still recording or still merging. Scanning it yields a+ # truncated observation, and the unique (scanner, session) constraint means that is the only+ # observation the session ever gets, so the live sweep can never replace it once it finishes.+ mock_query.return_value.count.return_value = 3+ body = {+ "window_start": (timezone.now() - dt.timedelta(days=2)).isoformat(),+ "window_end": (timezone.now() + dt.timedelta(days=1)).isoformat(),+ }++ response = self.client.post(f"{self.base_url}/estimate/", body, format="json")++ assert response.status_code == 200, response.json()+ window_end = dt.datetime.fromisoformat(response.json()["window_end"])+ assert window_end <= timezone.now() - SETTLE_INTERVAL+ # The quote has to describe the window actually walked, or it counts sessions the walk skips.+ assert mock_query.call_args.kwargs["window_end"] == window_end++ def test_window_entirely_inside_the_settle_horizon_is_rejected(self) -> None:+ body = {+ "window_start": (timezone.now() - dt.timedelta(minutes=5)).isoformat(),+ "window_end": timezone.now().isoformat(),+ }+ response = self.client.post(f"{self.base_url}/estimate/", body, format="json")+ assert response.status_code == 400++ def test_estimate_rejects_window_longer_than_the_cap(self) -> None:+ # An unbounded window makes the synchronous enumeration pay for the whole partition range.+ body = {+ "window_start": (timezone.now() - dt.timedelta(days=MAX_BACKFILL_WINDOW_DAYS + 1)).isoformat(),+ "window_end": timezone.now().isoformat(),+ }+ response = self.client.post(f"{self.base_url}/estimate/", body, format="json")+ assert response.status_code == 400+ assert "365 days" in str(response.json())++ @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ def test_estimate_rejects_when_every_candidate_is_already_observed(self, mock_query: MagicMock) -> None:+ # Excluded run returns 0 while the unfiltered run finds rows: nothing left for a backfill to do.+ mock_query.return_value.count.side_effect = [0, 5]+ self.scanner.observations.create(+ team=self.team,+ session_id="already-done",+ status=ObservationStatus.SUCCEEDED,+ triggered_by=ObservationTrigger.SCHEDULE,+ scanner_snapshot={},+ completed_at=timezone.now(),+ )+ response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")+ assert response.status_code == 400+ assert "already been scanned" in str(response.json())++ @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ def test_estimate_rejects_when_nothing_matches_the_scanner(self, mock_query: MagicMock) -> None:+ mock_query.return_value.count.return_value = 0+ response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")+ assert response.status_code == 400+ assert "match this scanner" in str(response.json())++ @patch("products.replay_vision.backend.temporal.schedule.a_delete_backfill_schedule", new_callable=AsyncMock)+ def test_cancel_marks_terminal(self, _mock_delete: AsyncMock) -> None:+ backfill = _make_backfill(self.scanner)+ response = self.client.post(f"{self.base_url}/{backfill.id}/cancel/")+ assert response.status_code == 200, response.json()+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.CANCELLED+ assert backfill.finished_at is not None++ @patch("products.replay_vision.backend.temporal.schedule.a_resume_backfill_schedule", new_callable=AsyncMock)+ def test_resume_only_applies_to_quota_paused_backfills(self, _mock_resume: AsyncMock) -> None:+ backfill = _make_backfill(self.scanner, status=BackfillStatus.PAUSED_QUOTA)+ response = self.client.post(f"{self.base_url}/{backfill.id}/resume/")+ assert response.status_code == 200, response.json()+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.RUNNING++ running = backfill+ response = self.client.post(f"{self.base_url}/{running.id}/resume/")+ assert response.status_code == 400++ def test_enumerating_actions_are_throttled_and_cheap_ones_are_not(self) -> None:+ # The global burst/sustained throttles extend PersonalApiKeyRateThrottle, which gates on+ # personal-API-key auth, so a UI session skips them and could resubmit wide windows until the+ # ClickHouse pool is saturated. Denying the throttle and asserting the status proves it is wired+ # into the request path; inspecting get_throttles() alone passes even if DRF never consults it.+ backfill = _make_backfill(self.scanner, status=BackfillStatus.PAUSED_QUOTA)+ with (+ patch.object(BackfillEnumerationThrottle, "allow_request", return_value=False),+ patch.object(BackfillEnumerationThrottle, "wait", return_value=None),+ ):+ estimate = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")+ create = self.client.post(f"{self.base_url}/", self._window_body(), format="json")+ # Cancel and resume don't enumerate, so throttling them would just block recovery.+ resume = self.client.post(f"{self.base_url}/{backfill.id}/resume/")++ assert estimate.status_code == HTTP_429_TOO_MANY_REQUESTS+ assert create.status_code == HTTP_429_TOO_MANY_REQUESTS+ assert resume.status_code != HTTP_429_TOO_MANY_REQUESTS++ def test_enumeration_throttle_keeps_the_global_limits(self) -> None:+ # Appended, not substituted: the personal-API-key limits must survive on the heaviest actions.+ viewset = ReplayScannerBackfillViewSet()+ viewset.action = "estimate"+ assert len(viewset.get_throttles()) > 1+ assert BackfillEnumerationThrottle.rate++ def test_list_includes_observation_progress_counts(self) -> None:+ backfill = _make_backfill(self.scanner, dispatched_count=3)+ for i, status in enumerate([ObservationStatus.SUCCEEDED, ObservationStatus.FAILED, ObservationStatus.PENDING]):+ backfill.observations.create(+ scanner=self.scanner,+ team=self.team,+ session_id=f"sess-{i}",+ status=status,+ triggered_by=ObservationTrigger.BACKFILL,+ scanner_snapshot=backfill.scanner_snapshot,+ completed_at=timezone.now() if status != ObservationStatus.PENDING else None,+ )+ response = self.client.get(f"{self.base_url}/")+ assert response.status_code == 200+ row = response.json()["results"][0]+ assert (row["succeeded_count"], row["failed_count"], row["in_flight_count"]) == (1, 1, 1)+++# BackfillScannerWorkflow (mocked-Temporal)+++class _BackfillMocks:+ def __init__(+ self,+ *,+ activity_results: dict | None = None,+ child_errors_for_ids: dict[str, Exception] | None = None,+ ) -> None:+ self.activity_results = activity_results or {}+ self.child_errors_for_ids = child_errors_for_ids or {}+ self.activity_calls: list[tuple] = []+ self.child_calls: list[dict] = []++ async def execute_activity(self, activity_fn, activity_input, **_) -> object:+ self.activity_calls.append((activity_fn, activity_input))+ if activity_fn is advance_backfill_cursor_activity and activity_fn not in self.activity_results:+ return AdvanceBackfillCursorOutput(finished=False)+ return self.activity_results.get(activity_fn)++ async def start_child_workflow(self, *args, **kwargs) -> object:+ wid = kwargs.get("id")+ self.child_calls.append({"id": wid, "inputs": args[1] if len(args) > 1 else None})+ if wid is not None and wid in self.child_errors_for_ids:+ raise self.child_errors_for_ids[wid]+ return MagicMock()+++def _backfill_tick_inputs() -> BackfillTickInputs:+ return BackfillTickInputs(backfill_id=uuid.uuid4(), team_id=42, scanner_id=uuid.uuid4())+++async def _run_backfill_tick(mocks: _BackfillMocks, inputs: BackfillTickInputs | None = None) -> None:+ # `workflow.logger` reaches into the workflow runtime, which isn't set up here.+ fake_logger = type(+ "Logger",+ (),+ {+ "info": staticmethod(lambda *_a, **_kw: None),+ "warning": staticmethod(lambda *_a, **_kw: None),+ "exception": staticmethod(lambda *_a, **_kw: None),+ },+ )()+ with (+ patch("temporalio.workflow.execute_activity", side_effect=mocks.execute_activity),+ patch("temporalio.workflow.start_child_workflow", side_effect=mocks.start_child_workflow),+ patch("temporalio.workflow.logger", fake_logger),+ ):+ await BackfillScannerWorkflow().run(inputs or _backfill_tick_inputs())+++def _called(mocks: _BackfillMocks) -> list:+ return [fn for fn, _ in mocks.activity_calls]+++ "action,follow_up",+ [+ # A terminal row tears its own schedule down; without this the minute schedule outlives the backfill.+ (BackfillTickAction.FINISHED, delete_backfill_schedule_activity),+ (BackfillTickAction.PAUSE, pause_backfill_schedule_activity),+ ],+)+async def test_gate_actions_run_their_schedule_op_and_nothing_else(action, follow_up) -> None:+ mocks = _BackfillMocks(activity_results={prepare_backfill_tick_activity: PrepareBackfillTickOutput(action=action)})++ await _run_backfill_tick(mocks)++ assert _called(mocks) == [prepare_backfill_tick_activity, follow_up]+++ "prep",+ [+ PrepareBackfillTickOutput(action=BackfillTickAction.SKIP),+ # A dispatch with no budget must not run the tick's most expensive query.+ PrepareBackfillTickOutput(action=BackfillTickAction.DISPATCH, dispatch_budget=0),+ ],+)+async def test_held_tick_never_enumerates(prep) -> None:+ mocks = _BackfillMocks(activity_results={prepare_backfill_tick_activity: prep})++ await _run_backfill_tick(mocks)++ assert _called(mocks) == [prepare_backfill_tick_activity]+ assert mocks.child_calls == []+++async def test_dispatch_starts_a_child_per_candidate_and_threads_the_walk_into_the_advance() -> None:+ cursor = dt.datetime(2026, 4, 30, tzinfo=dt.UTC)+ inputs = _backfill_tick_inputs()+ mocks = _BackfillMocks(+ activity_results={+ prepare_backfill_tick_activity: PrepareBackfillTickOutput(+ action=BackfillTickAction.DISPATCH, dispatch_budget=2+ ),+ find_backfill_candidates_activity: FindBackfillCandidatesOutput(+ candidates=[+ CandidateSessionPayload(session_id="sess-a", session_end=cursor),+ CandidateSessionPayload(session_id="sess-b", session_end=cursor),+ ],+ skipped_delta=3,+ next_cursor_end_time=cursor,+ next_cursor_session_id="sess-b",+ started_from_cursor_end_time=None,+ started_from_cursor_session_id="",+ more_work_below_cursor=True,+ ),+ }+ )++ await _run_backfill_tick(mocks, inputs)++ assert [c["id"] for c in mocks.child_calls] == [+ build_apply_scanner_workflow_id(inputs.scanner_id, "sess-a"),+ build_apply_scanner_workflow_id(inputs.scanner_id, "sess-b"),+ ]+ advance = next(call for fn, call in mocks.activity_calls if fn is advance_backfill_cursor_activity)+ # The activity owns how far the walk got; the workflow must not recompute it from the batch.+ assert (advance.new_cursor_end_time, advance.new_cursor_session_id) == (cursor, "sess-b")+ assert (advance.dispatched_delta, advance.skipped_delta) == (2, 3)+ # More work below the cursor must not read as a drained window.+ assert not advance.exhausted+++async def test_drained_window_advances_then_deletes_its_own_schedule() -> None:+ mocks = _BackfillMocks(+ activity_results={+ prepare_backfill_tick_activity: PrepareBackfillTickOutput(+ action=BackfillTickAction.DISPATCH, dispatch_budget=5+ ),+ find_backfill_candidates_activity: FindBackfillCandidatesOutput(+ candidates=[], more_work_below_cursor=False+ ),+ advance_backfill_cursor_activity: AdvanceBackfillCursorOutput(finished=True),+ }+ )++ await _run_backfill_tick(mocks)++ assert mocks.child_calls == []+ assert _called(mocks) == [+ prepare_backfill_tick_activity,+ find_backfill_candidates_activity,+ advance_backfill_cursor_activity,+ delete_backfill_schedule_activity,+ ]+ advance = next(call for fn, call in mocks.activity_calls if fn is advance_backfill_cursor_activity)+ assert advance.exhausted+++async def test_child_already_started_by_the_live_sweep_does_not_fail_the_tick() -> None:+ cursor = dt.datetime(2026, 4, 30, tzinfo=dt.UTC)+ inputs = _backfill_tick_inputs()+ collided = build_apply_scanner_workflow_id(inputs.scanner_id, "sess-a")+ mocks = _BackfillMocks(+ activity_results={+ prepare_backfill_tick_activity: PrepareBackfillTickOutput(+ action=BackfillTickAction.DISPATCH, dispatch_budget=2+ ),+ find_backfill_candidates_activity: FindBackfillCandidatesOutput(+ candidates=[+ CandidateSessionPayload(session_id="sess-a", session_end=cursor),+ CandidateSessionPayload(session_id="sess-b", session_end=cursor),+ ],+ next_cursor_end_time=cursor,+ next_cursor_session_id="sess-b",+ more_work_below_cursor=True,+ ),+ },+ # Deterministic ids mean a session the live sweep is already applying collides here by design.+ child_errors_for_ids={collided: WorkflowAlreadyStartedError(collided, APPLY_SCANNER_WORKFLOW_NAME)},+ )++ await _run_backfill_tick(mocks, inputs)++ assert advance_backfill_cursor_activity in _called(mocks)diff --git a/products/replay_vision/backend/tests/test_prompt_evaluation.py b/products/replay_vision/backend/tests/test_prompt_evaluation.pyindex 5a872f83ef35..09bd18704b02 100644--- a/products/replay_vision/backend/tests/test_prompt_evaluation.py+++ b/products/replay_vision/backend/tests/test_prompt_evaluation.py@@ -524,7 +524,7 @@ class TestPromptEvaluationApi(_VisionAPITestCase):connect_patch, client = self._mock_temporal()with (connect_patch,- patch("products.replay_vision.backend.api.prompt_suggestions.compute_quota_snapshot", return_value=quota),+ patch("products.replay_vision.backend.api.prompt_suggestions.quota_state", return_value=quota),):resp = self.client.post(self._url(suggestion.id))@@ -549,7 +549,7 @@ class TestPromptEvaluationApi(_VisionAPITestCase):connect_patch, client = self._mock_temporal()with (connect_patch,- patch("products.replay_vision.backend.api.prompt_suggestions.compute_quota_snapshot", return_value=quota),+ patch("products.replay_vision.backend.api.prompt_suggestions.quota_state", return_value=quota),):# The default limit plans 3 re-runs but only 2 observations remain this month.resp = self.client.post(self._url(suggestion.id))diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.pyindex b467994ec937..8dd8386840ec 100644--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py@@ -18,6 +18,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (DEFAULT_CANDIDATE_LIMIT,FOCUSED_SURFACING_THRESHOLD,SETTLE_INTERVAL,+ BackfillCandidateQuery,ScannerCandidateQuery,surfacing_score_predicate,)@@ -652,3 +653,77 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):candidate_limit=candidate_limit,last_seen_session_id=last_seen_session_id,).run()+++@freeze_time(_FROZEN_TIME)+class TestBackfillCandidateQueryAgainstClickHouse(ClickhouseTestMixin):+ def setup_method(self, _method) -> None:+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())++ @staticmethod+ def _produce(team_id: int, session_id: str, first: dt.datetime, last: dt.datetime, **kwargs) -> None:+ kwargs.setdefault("active_milliseconds", 30_000)+ produce_replay_summary(+ team_id=team_id,+ session_id=session_id,+ first_timestamp=first.isoformat(),+ last_timestamp=last.isoformat(),+ **kwargs,+ )++ @staticmethod+ def _query(*, team, window_start: dt.datetime, window_end: dt.datetime, **kwargs) -> BackfillCandidateQuery:+ return BackfillCandidateQuery(+ team=team,+ query=kwargs.pop("query", RecordingsQuery()),+ window_start=window_start,+ window_end=window_end,+ sampling_rate=kwargs.pop("sampling_rate", 1.0),+ sampling_salt=kwargs.pop("sampling_salt", "scanner-1"),+ **kwargs,+ )++ @pytest.mark.django_db+ def test_rejects_inverted_window(self, team) -> None:+ with pytest.raises(ValueError, match="window_start must be before window_end"):+ self._query(team=team, window_start=_NOW, window_end=_NOW - dt.timedelta(days=1))++ @pytest.mark.django_db+ def test_descending_keyset_walk_partitions_the_enumerated_window(self, team) -> None:+ window_end = _NOW - dt.timedelta(days=1)+ window_start = window_end - dt.timedelta(days=7)+ inside = [f"sess-{i}" for i in range(5)]+ for i, session_id in enumerate(inside):+ end = window_end - dt.timedelta(hours=6 * (i + 1))+ self._produce(team.id, session_id, end - dt.timedelta(minutes=10), end)+ # Same end time as sess-0: exercises the (end_time, session_id) tie-breaker.+ tied_end = window_end - dt.timedelta(hours=6)+ self._produce(team.id, "sess-tied", tied_end - dt.timedelta(minutes=10), tied_end)+ # Outside the window on both sides: never enumerated, never walked.+ self._produce(+ team.id, "before-window", window_start - dt.timedelta(hours=2), window_start - dt.timedelta(hours=1)+ )+ self._produce(+ team.id, "after-window", window_end + dt.timedelta(minutes=1), window_end + dt.timedelta(minutes=30)+ )++ assert self._query(team=team, window_start=window_start, window_end=window_end).count() == 6++ walked: list[str] = []+ cursor_end, cursor_sid = None, None+ for _ in range(10):+ batch = self._query(+ team=team,+ window_start=window_start,+ window_end=window_end,+ cursor_end_time=cursor_end,+ cursor_session_id=cursor_sid,+ candidate_limit=2,+ ).run()+ if not batch:+ break+ walked.extend(c.session_id for c in batch)+ cursor_end, cursor_sid = batch[-1].session_end, batch[-1].session_id++ # Newest-first, tie broken by descending session_id, every enumerated session exactly once.+ assert walked == ["sess-tied", "sess-0", "sess-1", "sess-2", "sess-3", "sess-4"]diff --git a/products/replay_vision/backend/tests/test_schedule.py b/products/replay_vision/backend/tests/test_schedule.pyindex a3a8ab9475c6..333ca013d35c 100644--- a/products/replay_vision/backend/tests/test_schedule.py+++ b/products/replay_vision/backend/tests/test_schedule.py@@ -22,11 +22,11 @@ from products.replay_vision.backend.temporal.constants import ()from products.replay_vision.backend.temporal.schedule import (_build_schedule,- _compute_offset,_load_fingerprint,a_delete_scanner_schedule,a_upsert_scanner_schedule,compute_schedule_fingerprint,+ compute_schedule_offset,)from products.replay_vision.backend.temporal.sweep_types import SweepScannerInputs@@ -87,18 +87,20 @@ def test_schedule_id_format() -> None:def test_offset_is_deterministic_per_scanner() -> None:sid = uuid.uuid4()- assert _compute_offset(sid) == _compute_offset(sid)+ assert compute_schedule_offset(sid, SCANNER_SCHEDULE_INTERVAL) == compute_schedule_offset(+ sid, SCANNER_SCHEDULE_INTERVAL+ )def test_offset_within_interval() -> None:interval_s = int(SCANNER_SCHEDULE_INTERVAL.total_seconds())for _ in range(50):- offset = _compute_offset(uuid.uuid4())+ offset = compute_schedule_offset(uuid.uuid4(), SCANNER_SCHEDULE_INTERVAL)assert dt.timedelta(0) <= offset < dt.timedelta(seconds=interval_s)def test_offset_distributes_across_window() -> None:- offsets = {_compute_offset(uuid.uuid4()).total_seconds() for _ in range(100)}+ offsets = {compute_schedule_offset(uuid.uuid4(), SCANNER_SCHEDULE_INTERVAL).total_seconds() for _ in range(100)}assert len(offsets) > 50@@ -131,7 +133,7 @@ def test_build_schedule_carries_scanner_inputs_and_offset() -> None:assert inputs.scanner_id == scanner_idassert inputs.team_id == 99assert schedule.spec.intervals[0].every == SCANNER_SCHEDULE_INTERVAL- assert schedule.spec.intervals[0].offset == _compute_offset(scanner_id)+ assert schedule.spec.intervals[0].offset == compute_schedule_offset(scanner_id, SCANNER_SCHEDULE_INTERVAL)@pytest.mark.django_db(transaction=True)@@ -221,7 +223,8 @@ async def test_upsert_stamps_fingerprint_attribute(org_team) -> None:@parameterized.expand([- ("noop_when_schedule_missing", False, None, False, None),+ # Delete is issued unconditionally (no exists pre-check RPC); a missing schedule surfaces as NOT_FOUND.+ ("noop_when_schedule_missing", False, RPCStatusCode.NOT_FOUND, True, None),("calls_delete_when_present", True, None, True, None),("swallows_not_found_race", True, RPCStatusCode.NOT_FOUND, True, None),("propagates_other_rpc_errors", True, RPCStatusCode.UNAVAILABLE, True, RPCError),diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 8c12f02164e9..1a00d101753b 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -447,7 +447,7 @@ class TestCreateObservationActivity:def test_skips_insert_when_monthly_quota_exhausted(self) -> None:scanner = _make_scanner()with patch(- "products.replay_vision.backend.temporal.activities.create_observation.compute_quota_snapshot"+ "products.replay_vision.backend.temporal.activities.create_observation.quota_state") as mock_snapshot:mock_snapshot.return_value = QuotaSnapshot(credit_limit=5,diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 1d3d73b3ec45..ff6f95adbef8 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -581,6 +581,7 @@ export interface ScannerResultApi {* * `schedule` - Schedule* * `on_demand` - On demand* * `retry` - Retry+ * * `backfill` - Backfill*/export type ObservationTriggerEnumApi = (typeof ObservationTriggerEnumApi)[keyof typeof ObservationTriggerEnumApi]@@ -588,6 +589,7 @@ export const ObservationTriggerEnumApi = {Schedule: 'schedule',OnDemand: 'on_demand',Retry: 'retry',+ Backfill: 'backfill',} as const/**@@ -625,14 +627,20 @@ export interface ReplayObservationApi {readonly scanner_snapshot: ScannerSnapshotApi | null/** Result data persisted on success; null until the observation succeeds. */readonly scanner_result: ScannerResultApi | null- /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.+ /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.** * `schedule` - Schedule* * `on_demand` - On demand- * * `retry` - Retry */+ * * `retry` - Retry+ * * `backfill` - Backfill */readonly triggered_by: ObservationTriggerEnumApi/** User who triggered an on-demand observation; null for scheduled observations. */readonly triggered_by_user: UserBasicApi | null+ /**+ * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.+ * @nullable+ */+ readonly backfill_id: string | null/*** Distinct id of the person in the recorded session (the subject being watched); null if unknown.* @nullable@@ -706,8 +714,12 @@ export interface VisionQuotaApi {readonly period_start: string/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */readonly period_end: string- /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */+ /** `scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; prefer the two components when pro-rating, since only the scanner half is a monthly rate. */readonly projected_monthly_credits: number+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */+ readonly scanners_monthly_credits: number+ /** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */+ readonly backfills_committed_credits: number/** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */readonly free_monthly_credits: number}@@ -1117,6 +1129,86 @@ export interface ObserveResponseApi {workflow_id: string}+/**+ * * `running` - Running+ * * `paused_quota` - Paused (quota)+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ */+export type BackfillStatusEnumApi = (typeof BackfillStatusEnumApi)[keyof typeof BackfillStatusEnumApi]++export const BackfillStatusEnumApi = {+ Running: 'running',+ PausedQuota: 'paused_quota',+ Completed: 'completed',+ Cancelled: 'cancelled',+} as const++export interface ReplayScannerBackfillApi {+ readonly id: string+ readonly status: BackfillStatusEnumApi+ /** Inclusive lower bound of the historical window to scan. */+ readonly window_start: string+ /** Exclusive upper bound of the window; clamped to now at creation. */+ readonly window_end: string+ /** Unobserved candidates enumerated at creation; the ceiling is total_count x credits_per_observation. */+ readonly total_count: number+ readonly dispatched_count: number+ /** Candidates the walk stepped over because this scanner had already tried them. Counted at creation but never dispatched, so progress and remaining spend both have to account for them. */+ readonly skipped_count: number+ /** Per-observation credit price frozen at creation from the snapshot model. */+ readonly credits_per_observation: number+ /** Observations from this backfill that succeeded. */+ readonly succeeded_count: number+ /** Observations from this backfill that failed. */+ readonly failed_count: number+ /** Sessions that turned out ineligible (too short, expired recording, ...). */+ readonly ineligible_count: number+ /** Observations from this backfill still pending or running. */+ readonly in_flight_count: number+ readonly created_by: UserBasicApi | null+ readonly created_at: string+ /**+ * When the backfill reached a terminal status (completed or cancelled).+ * @nullable+ */+ readonly finished_at: string | null+}++export interface PaginatedReplayScannerBackfillListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ReplayScannerBackfillApi[]+}++export interface BackfillWindowApi {+ /** Inclusive lower bound of the historical window to scan. */+ window_start: string+ /** Exclusive upper bound of the window; clamped server-side to now. */+ window_end: string+}++export interface BackfillEstimateResponseApi {+ /** Upper bound on the sessions the backfill would scan, after sampling and quality filters and excluding sessions this scanner already reported an observation for. */+ total_sessions: number+ /** Cost ceiling in credits (1 credit = $0.01): total_sessions x credits_per_observation. Actual spend lands under it: sessions already tried, expired recordings, and failures are not billed. */+ total_credits: number+ /** Per-observation credit price at the scanner's current model. */+ credits_per_observation: number+ /**+ * Credits left in the org's monthly quota; null when the org is uncapped.+ * @nullable+ */+ credits_remaining: number | null+ /** The window lower bound the estimate covered. */+ window_start: string+ /** The window upper bound after clamping to now. */+ window_end: string+}+export interface ObservationStatusCountsApi {/** Total observations in the filtered set. */total: number@@ -1483,6 +1575,8 @@ export interface EstimateResponseApi {estimated_credits_per_month: number/** Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */other_enabled_scanners_monthly_credits: number+ /** Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own segment instead of adding it to a per-month total. */+ active_backfill_credits: number/** Sampling rate applied to the projection. Echoed from the request. */sampling_rate: number}@@ -1675,6 +1769,10 @@ export type VisionObservationsListParams = {}export type VisionObservationsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -1708,7 +1806,7 @@ export type VisionObservationsRetrieveParams = {*/tags?: string/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string/**@@ -1781,7 +1879,22 @@ export type VisionScannersImpactRetrieveParams = {window_days?: number}+export type VisionScannersBackfillsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type VisionScannersObservationsListParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -1823,7 +1936,7 @@ export type VisionScannersObservationsListParams = {*/tags?: string/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string/**@@ -1833,6 +1946,10 @@ export type VisionScannersObservationsListParams = {}export type VisionScannersObservationsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -1866,7 +1983,7 @@ export type VisionScannersObservationsRetrieveParams = {*/tags?: string/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string/**@@ -1876,6 +1993,10 @@ export type VisionScannersObservationsRetrieveParams = {}export type VisionScannersObservationsStatsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -1909,7 +2030,7 @@ export type VisionScannersObservationsStatsRetrieveParams = {*/tags?: string/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string/**diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex e6c7e7da2c86..4ce319a3849d 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -12,6 +12,8 @@ import type {AffectedCohortRequestApi,AffectedCohortResponseApi,ApplyPromptSuggestionRequestApi,+ BackfillEstimateResponseApi,+ BackfillWindowApi,BulkObserveRequestApi,BulkObserveResponseApi,CreateTaskFromObservationResponseApi,@@ -26,6 +28,7 @@ import type {ObserveRequestApi,ObserveResponseApi,PaginatedReplayObservationListApi,+ PaginatedReplayScannerBackfillListApi,PaginatedReplayScannerListApi,PaginatedReplayScannerPromptSuggestionListApi,PaginatedVisionActionListApi,@@ -35,6 +38,7 @@ import type {ReplayObservationApi,ReplayObservationLabelApi,ReplayScannerApi,+ ReplayScannerBackfillApi,ReplayScannerPromptSuggestionApi,RetryResponseApi,RunActionResponseApi,@@ -50,6 +54,7 @@ import type {VisionObservationsListParams,VisionObservationsRetrieveParams,VisionQuotaApi,+ VisionScannersBackfillsListParams,VisionScannersImpactRetrieveParams,VisionScannersListParams,VisionScannersObservationsListParams,@@ -611,6 +616,153 @@ export const visionScannersObserveCreate = async (})}+export const getVisionScannersBackfillsListUrl = (+ projectId: string,+ scannerId: string,+ params?: VisionScannersBackfillsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/?${stringifiedParams}`+ : `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/`+}++/**+ * Historical backfills of a scanner over a closed time window (nested under a scanner).+ */+export const visionScannersBackfillsList = async (+ projectId: string,+ scannerId: string,+ params?: VisionScannersBackfillsListParams,+ options?: RequestInit+): Promise<PaginatedReplayScannerBackfillListApi> => {+ return apiMutator<PaginatedReplayScannerBackfillListApi>(+ getVisionScannersBackfillsListUrl(projectId, scannerId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getVisionScannersBackfillsCreateUrl = (projectId: string, scannerId: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/`+}++/**+ * Create a backfill: freeze the scanner config, enumerate the exact candidate set, start the tick schedule.+ *+ * The enumeration reruns here rather than trusting the client-confirmed estimate: the count is+ * billing-relevant, so the authoritative value is computed server-side at creation time. New+ * settled sessions between estimate and confirm can nudge total_count slightly.+ */+export const visionScannersBackfillsCreate = async (+ projectId: string,+ scannerId: string,+ backfillWindowApi: BackfillWindowApi,+ options?: RequestInit+): Promise<ReplayScannerBackfillApi> => {+ return apiMutator<ReplayScannerBackfillApi>(getVisionScannersBackfillsCreateUrl(projectId, scannerId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(backfillWindowApi),+ })+}++export const getVisionScannersBackfillsRetrieveUrl = (projectId: string, scannerId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/${id}/`+}++/**+ * Historical backfills of a scanner over a closed time window (nested under a scanner).+ */+export const visionScannersBackfillsRetrieve = async (+ projectId: string,+ scannerId: string,+ id: string,+ options?: RequestInit+): Promise<ReplayScannerBackfillApi> => {+ return apiMutator<ReplayScannerBackfillApi>(getVisionScannersBackfillsRetrieveUrl(projectId, scannerId, id), {+ ...options,+ method: 'GET',+ })+}++export const getVisionScannersBackfillsCancelCreateUrl = (projectId: string, scannerId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/${id}/cancel/`+}++/**+ * Stop an active backfill; already-dispatched observations finish, nothing new dispatches.+ */+export const visionScannersBackfillsCancelCreate = async (+ projectId: string,+ scannerId: string,+ id: string,+ replayScannerBackfillApi?: NonReadonly<ReplayScannerBackfillApi>,+ options?: RequestInit+): Promise<ReplayScannerBackfillApi> => {+ return apiMutator<ReplayScannerBackfillApi>(getVisionScannersBackfillsCancelCreateUrl(projectId, scannerId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(replayScannerBackfillApi),+ })+}++export const getVisionScannersBackfillsResumeCreateUrl = (projectId: string, scannerId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/${id}/resume/`+}++/**+ * Restart a backfill that paused when the monthly quota ran out.+ */+export const visionScannersBackfillsResumeCreate = async (+ projectId: string,+ scannerId: string,+ id: string,+ replayScannerBackfillApi?: NonReadonly<ReplayScannerBackfillApi>,+ options?: RequestInit+): Promise<ReplayScannerBackfillApi> => {+ return apiMutator<ReplayScannerBackfillApi>(getVisionScannersBackfillsResumeCreateUrl(projectId, scannerId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(replayScannerBackfillApi),+ })+}++export const getVisionScannersBackfillsEstimateCreateUrl = (projectId: string, scannerId: string) => {+ return `/api/projects/${projectId}/vision/scanners/${scannerId}/backfills/estimate/`+}++/**+ * Exactly enumerate what a backfill over the given window would dispatch and cost.+ */+export const visionScannersBackfillsEstimateCreate = async (+ projectId: string,+ scannerId: string,+ backfillWindowApi: BackfillWindowApi,+ options?: RequestInit+): Promise<BackfillEstimateResponseApi> => {+ return apiMutator<BackfillEstimateResponseApi>(getVisionScannersBackfillsEstimateCreateUrl(projectId, scannerId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(backfillWindowApi),+ })+}+export const getVisionScannersObservationsListUrl = (projectId: string,scannerId: string,diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 0fd6f4706029..f37db2620488 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -685,6 +685,44 @@ export const VisionScannersObserveCreateBody = /* @__PURE__ */ zod}).describe('Body of POST \/vision\/scanners\/{id}\/observe\/.')+/**+ * Create a backfill: freeze the scanner config, enumerate the exact candidate set, start the tick schedule.+ *+ * The enumeration reruns here rather than trusting the client-confirmed estimate: the count is+ * billing-relevant, so the authoritative value is computed server-side at creation time. New+ * settled sessions between estimate and confirm can nudge total_count slightly.+ */+export const VisionScannersBackfillsCreateBody = /* @__PURE__ */ zod.object({+ window_start: zod.iso+ .datetime({ offset: true })+ .describe('Inclusive lower bound of the historical window to scan.'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive upper bound of the window; clamped server-side to now.'),+})++/**+ * Stop an active backfill; already-dispatched observations finish, nothing new dispatches.+ */+export const VisionScannersBackfillsCancelCreateBody = /* @__PURE__ */ zod.looseObject({})++/**+ * Restart a backfill that paused when the monthly quota ran out.+ */+export const VisionScannersBackfillsResumeCreateBody = /* @__PURE__ */ zod.looseObject({})++/**+ * Exactly enumerate what a backfill over the given window would dispatch and cost.+ */+export const VisionScannersBackfillsEstimateCreateBody = /* @__PURE__ */ zod.object({+ window_start: zod.iso+ .datetime({ offset: true })+ .describe('Inclusive lower bound of the historical window to scan.'),+ window_end: zod.iso+ .datetime({ offset: true })+ .describe('Exclusive upper bound of the window; clamped server-side to now.'),+})+/*** Set or update the observation's shared label: whether the scanner scored the session correctly, plus optional feedback on what it got wrong. One label per observation, shared across the team; these labels feed prompt improvement. Requires editor access to the scanner.*/diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 28dcdad8f66f..ee3b86feac33 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -22,6 +22,7 @@ import { visionQuotaLogic } from '../logics/visionQuotaLogic'import { getReplayVisionEditDisabledReason } from '../utils/accessControl'import { formatCreditsRange } from '../utils/credits'import { quotaBannerState } from '../utils/quotaProjection'+import { ScannerBackfillsTab } from './components/ScannerBackfillsTab'import { ScannerCalibrationTab } from './components/ScannerCalibrationTab'import { ScannerConfigReadonly } from './components/ScannerConfigReadonly'import { ScannerDigestCard } from './components/ScannerDigestCard'@@ -131,6 +132,11 @@ export function ReplayScannerSceneComponent(): JSX.Element {label: 'On-demand',content: <ScannerRunTab scannerId={scannerId} />,},+ {+ key: ReplayScannerTab.Backfills,+ label: 'Backfills',+ content: <ScannerBackfillsTab scannerId={scannerId} />,+ },{key: ReplayScannerTab.Configuration,label: 'Configuration',diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 1c504fedb541..bc443d695e9e 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -127,6 +127,8 @@ const quota: VisionQuotaApi = {remaining: 7600,exhausted: false,projected_monthly_credits: 5200,+ scanners_monthly_credits: 5200,+ backfills_committed_credits: 0,free_monthly_credits: 2500,period_start: '2026-05-01T00:00:00Z',period_end: '2026-06-01T00:00:00Z',diff --git a/products/replay_vision/frontend/replay_scanners/backfillsLogic.ts b/products/replay_vision/frontend/replay_scanners/backfillsLogic.tsnew file mode 100644index 000000000000..246e68f332ed--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/backfillsLogic.ts@@ -0,0 +1,288 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'++import { ApiError } from 'lib/api-error'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import {+ visionScannersBackfillsCancelCreate,+ visionScannersBackfillsCreate,+ visionScannersBackfillsEstimateCreate,+ visionScannersBackfillsList,+ visionScannersBackfillsResumeCreate,+} from '../generated/api'+import type { BackfillEstimateResponseApi, ReplayScannerBackfillApi } from '../generated/api.schemas'++export interface BackfillsLogicProps {+ scannerId: string+}++// Keeps progress counts fresh while a backfill is dispatching, without hammering the API when idle.+const ACTIVE_POLL_INTERVAL_MS = 10_000++export function isBackfillActive(backfill: ReplayScannerBackfillApi): boolean {+ return backfill.status === 'running' || backfill.status === 'paused_quota'+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface backfillsLogicValues {+ backfills: ReplayScannerBackfillApi[]+ backfillsLoading: boolean+ creatingBackfill: boolean+ estimate: BackfillEstimateResponseApi | null+ estimateLoading: boolean+ transitioningIds: string[]+ windowDateFrom: string | null+ windowDateTo: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface backfillsLogicActions {+ cancelBackfill: (id: string) => {+ id: string+ }+ createBackfill: (+ windowStart: string,+ windowEnd: string+ ) => {+ windowEnd: string+ windowStart: string+ }+ createBackfillDone: () => {+ value: true+ }+ loadBackfills: (background?: any) => {+ background: any+ }+ loadBackfillsFailure: () => {+ value: true+ }+ loadBackfillsSuccess: (backfills: ReplayScannerBackfillApi[]) => {+ backfills: ReplayScannerBackfillApi[]+ }+ requestEstimate: (+ windowStart: string,+ windowEnd: string+ ) => {+ windowEnd: string+ windowStart: string+ }+ requestEstimateFailure: () => {+ value: true+ }+ requestEstimateSuccess: (estimate: BackfillEstimateResponseApi) => {+ estimate: BackfillEstimateResponseApi+ }+ resumeBackfill: (id: string) => {+ id: string+ }+ setWindowRange: (+ dateFrom: string | null,+ dateTo: string | null+ ) => {+ dateFrom: string | null+ dateTo: string | null+ }+ transitionBackfillDone: (id: string) => {+ id: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface backfillsLogicMeta {+ key: string+}++export type backfillsLogicType = MakeLogicType<+ backfillsLogicValues,+ backfillsLogicActions,+ BackfillsLogicProps,+ backfillsLogicMeta+>++export const backfillsLogic = kea<backfillsLogicType>([+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'backfillsLogic']),+ props({} as BackfillsLogicProps),+ key((props) => props.scannerId),++ actions({+ loadBackfills: (background = false) => ({ background }),+ loadBackfillsSuccess: (backfills: ReplayScannerBackfillApi[]) => ({ backfills }),+ loadBackfillsFailure: true,+ requestEstimate: (windowStart: string, windowEnd: string) => ({ windowStart, windowEnd }),+ requestEstimateSuccess: (estimate: BackfillEstimateResponseApi) => ({ estimate }),+ requestEstimateFailure: true,+ createBackfill: (windowStart: string, windowEnd: string) => ({ windowStart, windowEnd }),+ createBackfillDone: true,+ cancelBackfill: (id: string) => ({ id }),+ resumeBackfill: (id: string) => ({ id }),+ transitionBackfillDone: (id: string) => ({ id }),+ setWindowRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ }),++ reducers({+ backfills: [+ [] as ReplayScannerBackfillApi[],+ {+ loadBackfillsSuccess: (_, { backfills }) => backfills,+ },+ ],+ backfillsLoading: [+ false,+ {+ loadBackfills: (state, { background }) => (background ? state : true),+ loadBackfillsSuccess: () => false,+ loadBackfillsFailure: () => false,+ },+ ],+ estimate: [+ null as BackfillEstimateResponseApi | null,+ {+ requestEstimate: () => null,+ requestEstimateSuccess: (_, { estimate }) => estimate,+ createBackfillDone: () => null,+ },+ ],+ estimateLoading: [+ false,+ {+ requestEstimate: () => true,+ requestEstimateSuccess: () => false,+ requestEstimateFailure: () => false,+ },+ ],+ creatingBackfill: [+ false,+ {+ createBackfill: () => true,+ createBackfillDone: () => false,+ },+ ],+ windowDateFrom: [null as string | null, { setWindowRange: (_, { dateFrom }) => dateFrom }],+ windowDateTo: [null as string | null, { setWindowRange: (_, { dateTo }) => dateTo }],+ transitioningIds: [+ [] as string[],+ {+ cancelBackfill: (state, { id }) => [...state, id],+ resumeBackfill: (state, { id }) => [...state, id],+ transitionBackfillDone: (state, { id }) => state.filter((i) => i !== id),+ },+ ],+ }),++ listeners(({ actions, props, values, cache }) => {+ /** Cancel and resume differ only in which endpoint they call and what to say when it fails. */+ const transitionBackfill = async (+ id: string,+ request: (teamId: string, scannerId: string, backfillId: string) => Promise<unknown>,+ errorMessage: string+ ): Promise<void> => {+ const teamId = teamLogic.values.currentTeamId+ try {+ if (teamId) {+ await request(String(teamId), props.scannerId, id)+ actions.loadBackfills(true)+ }+ } catch (error) {+ lemonToast.error(apiErrorMessage(error, errorMessage))+ } finally {+ actions.transitionBackfillDone(id)+ }+ }+ return {+ loadBackfills: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ try {+ const response = await visionScannersBackfillsList(String(teamId), props.scannerId, { limit: 100 })+ actions.loadBackfillsSuccess(response.results ?? [])+ } catch {+ actions.loadBackfillsFailure()+ lemonToast.error('Couldn’t load backfills. Refresh the page to try again.')+ }+ },+ loadBackfillsSuccess: () => {+ if (values.backfills.some((b) => b.status === 'running')) {+ cache.disposables.add(() => {+ const timerId = window.setTimeout(() => actions.loadBackfills(true), ACTIVE_POLL_INTERVAL_MS)+ return () => window.clearTimeout(timerId)+ }, 'backfillPoll')+ } else {+ cache.disposables.dispose('backfillPoll')+ }+ },+ requestEstimate: async ({ windowStart, windowEnd }, breakpoint) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return+ }+ await breakpoint(250)+ try {+ const estimate = await visionScannersBackfillsEstimateCreate(String(teamId), props.scannerId, {+ window_start: windowStart,+ window_end: windowEnd,+ })+ breakpoint()+ actions.requestEstimateSuccess(estimate)+ } catch (error: any) {+ breakpoint()+ actions.requestEstimateFailure()+ lemonToast.error(apiErrorMessage(error))+ }+ },+ createBackfill: async ({ windowStart, windowEnd }) => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ actions.createBackfillDone()+ return+ }+ try {+ await visionScannersBackfillsCreate(String(teamId), props.scannerId, {+ window_start: windowStart,+ window_end: windowEnd,+ })+ lemonToast.success('Backfill started')+ actions.loadBackfills()+ } catch (error: any) {+ lemonToast.error(apiErrorMessage(error))+ } finally {+ actions.createBackfillDone()+ }+ },+ cancelBackfill: async ({ id }) => {+ await transitionBackfill(+ id,+ visionScannersBackfillsCancelCreate,+ 'Couldn’t cancel the backfill. Try again.'+ )+ },+ resumeBackfill: async ({ id }) => {+ await transitionBackfill(+ id,+ visionScannersBackfillsResumeCreate,+ 'Couldn’t resume the backfill. Try again.'+ )+ },+ }+ }),++ afterMount(({ actions }) => {+ actions.loadBackfills()+ }),+])++function apiErrorMessage(error: unknown, fallback = 'Something went wrong. Try again.'): string {+ if (error instanceof ApiError) {+ // The estimate endpoint is throttled, so 429s are a routine outcome worth naming.+ if (error.formattedRetryAfter) {+ return `Too many requests. Try again in ${error.formattedRetryAfter}.`+ }+ if (error.detail) {+ return error.detail+ }+ }+ const detail = (error as any)?.data?.detail ?? (Array.isArray((error as any)?.data) ? (error as any).data[0] : null)+ return typeof detail === 'string' && detail.length > 0 ? detail : fallback+}diff --git a/products/replay_vision/frontend/replay_scanners/components/BackfillCostEstimate.tsx b/products/replay_vision/frontend/replay_scanners/components/BackfillCostEstimate.tsxnew file mode 100644index 000000000000..9f8bf399204f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/BackfillCostEstimate.tsx@@ -0,0 +1,141 @@+import { useValues } from 'kea'++import { LemonBanner, LemonCard, Spinner, Tooltip } from '@posthog/lemon-ui'++import { LemonLabel } from 'lib/lemon-ui/LemonLabel'++import type { BackfillEstimateResponseApi } from '../../generated/api.schemas'+import { visionQuotaLogic } from '../../logics/visionQuotaLogic'+import { creditsToUsd, formatCreditCount } from '../../utils/credits'+import { QUOTA_BACKFILL_CLASS, buildQuotaMeter, fleetContributions } from '../../utils/quotaContributions'+import { QUOTA_STATUS_STYLES } from '../../utils/quotaProjection'+import { QuotaMeter } from './QuotaMeterBar'++interface Props {+ estimate: BackfillEstimateResponseApi | null+ loading: boolean+}++/**+ * The scanner editor's cost meter, re-pointed at a one-off backfill.+ *+ * `projectQuota` is reused for the recurring part only. Its delta argument is a *monthly rate* that it+ * pro-rates across the days left in the period, which would shrink a backfill's cost to a fraction of+ * itself. A backfill is charged once, so it is added at full value as its own segment on top.+ */+export function BackfillCostEstimate({ estimate, loading }: Props): JSX.Element {+ const { displayQuota: quota, showUsd, onFreePlan } = useValues(visionQuotaLogic)++ // Rendered even with no estimate yet, showing the period as it already stands. Picking a range+ // then adds a segment to the existing bar instead of making a whole card appear.+ const backfillCredits = estimate?.total_credits ?? 0+ const cap = quota?.credit_limit ?? 0+ const used = quota?.credits_used ?? 0++ // This backfill leads the org's own commitments: segments absorb overflow left to right, so the charge being+ // decided on keeps its width and the rest-of-period forecast is what gets truncated.+ const model = buildQuotaMeter(quota, [+ ...(estimate+ ? [+ {+ key: 'this-backfill',+ label: 'This backfill',+ credits: backfillCredits,+ kind: 'one-off' as const,+ barClass: QUOTA_BACKFILL_CLASS,+ // Striped marks the charge still being decided; the org's committed backfills are solid.+ striped: true,+ },+ ]+ : []),+ ...fleetContributions(quota),+ ])+ const styles = QUOTA_STATUS_STYLES[model.status]+ const { projection, periodEndPct, hasCap } = model++ const breakdown = (+ <div className="text-xs space-y-0.5">+ <div>+ Spent this period: <strong>{formatCreditCount(used)}</strong>+ </div>+ <div>+ Projected from scanners:{' '}+ <strong>~{formatCreditCount(quota?.projected_monthly_credits ?? 0)}/month</strong>+ </div>+ {estimate && (+ <div>+ This backfill: <strong>at most {formatCreditCount(backfillCredits)}</strong>+ </div>+ )}+ {hasCap && (+ <div>+ Monthly limit: <strong>{formatCreditCount(cap)}</strong>+ </div>+ )}+ {projection.resetsOn && <div className="text-muted">Resets {projection.resetsOn}</div>}+ </div>+ )++ const overQuota =+ estimate !== null && estimate.credits_remaining !== null && backfillCredits > estimate.credits_remaining++ return (+ <LemonCard hoverEffect={false} className="p-3 space-y-2">+ <div className="flex items-baseline justify-between gap-3">+ <LemonLabel>Estimated cost</LemonLabel>+ {hasCap && (+ <Tooltip title={breakdown}>+ <span className={`text-xs tabular-nums ${styles.text}`}>+ {periodEndPct}%{' '}+ <span className="text-muted font-normal">by {projection.resetsOn ?? 'period end'}</span>+ </span>+ </Tooltip>+ )}+ </div>++ <div className="text-base font-semibold tabular-nums flex items-center gap-2">+ {estimate ? (+ <span>+ at most {formatCreditCount(backfillCredits)}+ <span className="text-sm font-normal text-muted">+ {showUsd ? ` (≈ ${creditsToUsd(backfillCredits)})` : ''} ·{' '}+ {estimate.total_sessions.toLocaleString()}{' '}+ {estimate.total_sessions === 1 ? 'recording' : 'recordings'} at{' '}+ {formatCreditCount(estimate.credits_per_observation)} each+ </span>+ </span>+ ) : (+ <span className="text-sm font-normal text-muted">+ {loading ? 'Counting recordings…' : 'Pick a time range to see the cost'}+ </span>+ )}+ {loading && estimate && (+ <Tooltip title="Recounting for the range you picked.">+ <Spinner className="text-muted text-sm" />+ </Tooltip>+ )}+ </div>++ {hasCap && (+ <>+ <Tooltip title={breakdown}>+ <div>+ <QuotaMeter+ model={model}+ label={`This backfill would take the period to ${periodEndPct}% of the monthly spend limit`}+ />+ </div>+ </Tooltip>+ </>+ )}++ {overQuota && (+ <LemonBanner type="warning">+ This backfill costs more than your remaining credits{onFreePlan ? ' on the free plan' : ''}. It+ scans the most recent recordings first, pauses when the quota runs out, and you can resume it next+ period.+ </LemonBanner>+ )}+ </LemonCard>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.tsindex 109579d025a4..0318cdef93d6 100644--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts@@ -1,23 +1,33 @@-import { clampSegmentWidths, quotaMeterWidths } from './QuotaMeterBar'+import { fitSegmentWidths, meterScale, quotaMeterWidths } from './QuotaMeterBar'describe('QuotaMeterBar', () => {- describe('clampSegmentWidths', () => {- it('passes widths through when they fit', () => {- expect(clampSegmentWidths([40, 20, 10])).toEqual([40, 20, 10])+ describe('fitSegmentWidths', () => {+ it('passes widths through when they fit under the limit', () => {+ expect(fitSegmentWidths([40, 20, 10])).toEqual([40, 20, 10])})- it('truncates the overflowing segment and zeroes the rest', () => {- expect(clampSegmentWidths([60, 30, 50])).toEqual([60, 30, 10])- expect(clampSegmentWidths([80, 120, 50])).toEqual([80, 20, 0])+ it('rescales every segment proportionally once the total overshoots', () => {+ expect(fitSegmentWidths([100, 50, 50])).toEqual([50, 25, 25])})- it('zeroes later segments when the bar is already saturated', () => {- expect(clampSegmentWidths([100, 30, 10])).toEqual([100, 0, 0])- expect(clampSegmentWidths([150, 30])).toEqual([100, 0])+ it('keeps an overshooting segment visible when little headroom is left', () => {+ // The whole point of rescaling: 5% of headroom must not swallow a segment six times its size.+ const [used, backfill] = fitSegmentWidths([95, 30])+ expect(backfill).toBeGreaterThan(used / 4)})- it('floors negative widths at zero without consuming headroom', () => {- expect(clampSegmentWidths([-10, 50])).toEqual([0, 50])+ it('floors negative widths at zero without shrinking the rest', () => {+ expect(fitSegmentWidths([-10, 50])).toEqual([0, 50])+ })+ })++ describe('meterScale', () => {+ it.each([+ ['stays at the limit when segments fit', [40, 20], 100],+ ['grows to the total once segments overshoot', [80, 70], 150],+ ['ignores negative segments', [120, -20], 120],+ ])('%s', (_name, pcts, expected) => {+ expect(meterScale(pcts)).toEqual(expected)})})diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsxindex b54af9381416..0ba20c3dde68 100644--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx@@ -3,8 +3,10 @@ import './QuotaMeterBar.scss'import clsx from 'clsx'import type { ReactNode } from 'react'+import type { QuotaMeterModel } from '../../utils/quotaContributions'+export interface QuotaMeterSegment {- /** Width as a percentage of the cap; may exceed the bar — segments are clamped cumulatively. */+ /** Width as a percentage of the cap; may exceed it — the bar rescales to the total instead of truncating. */pct: number/** Background class, e.g. `bg-success` / `bg-warning` / `bg-danger` / `bg-accent`. */barClass: string@@ -25,27 +27,53 @@ interface QuotaMeterBarProps {valueNow: numberlabel: stringsize?: 'small' | 'medium'+ /** Caption under the limit marker. Always shown, so the limit reads the same whether or not it is exceeded. */+ limitLabel?: stringclassName?: string}-/** Segment widths fill left to right; later segments absorb overflow past 100%. */-export function clampSegmentWidths(pcts: number[]): number[] {- let headroom = 100- return pcts.map((pct) => {- const width = Math.max(Math.min(pct, headroom), 0)- headroom -= width- return width- })+/** What the bar's full width represents: the limit, or the whole total once the segments overshoot it. */+export function meterScale(pcts: number[]): number {+ return Math.max(+ pcts.reduce((total, pct) => total + Math.max(pct, 0), 0),+ 100+ )}-/** Widths for `[free, billed, ...projected]`, with the free slice clamped inside the used slice. The bar and its- * legends both derive widths from this, so a legend chip can never outlive its segment. */-export function quotaMeterWidths(usedPct: number, usedFreePct: number, projectedPcts: number[]): number[] {+/**+ * Segment widths as a percentage of the rendered bar.+ *+ * Past the limit the bar rescales to the total rather than truncating. Clamping made whichever segment came last+ * vanish exactly when it mattered most: a small amount of headroom left under the limit would swallow a large+ * segment whole, and the user could not see the size of what they were about to commit to.+ */+export function fitSegmentWidths(pcts: number[]): number[] {+ const scale = 100 / meterScale(pcts)+ return pcts.map((pct) => Math.max(pct, 0) * scale)+}++/**+ * Layout for `[free, billed, ...projected]`, with the free slice clamped inside the used slice.+ *+ * The bar, its legends and the limit marker all read one object, so the segment composition lives in a single+ * place: a legend chip can never outlive its segment, and the marker can never disagree with the widths.+ */+export function quotaMeterLayout(+ usedPct: number,+ usedFreePct: number,+ projectedPcts: number[]+): { widths: number[]; limitMarkerPct: number } {const freePct = Math.max(Math.min(usedFreePct, usedPct), 0)- return clampSegmentWidths([freePct, usedPct - freePct, ...projectedPcts])+ const pcts = [freePct, usedPct - freePct, ...projectedPcts]+ return { widths: fitSegmentWidths(pcts), limitMarkerPct: 10000 / meterScale(pcts) }}-/** Quota meter: solid used segment plus projection segments; later segments absorb overflow past 100%. */+/** Widths alone, for callers that only size legend chips. */+export function quotaMeterWidths(usedPct: number, usedFreePct: number, projectedPcts: number[]): number[] {+ return quotaMeterLayout(usedPct, usedFreePct, projectedPcts).widths+}++/** Quota meter: solid used segment plus projection segments, rescaled with a limit marker when they overshoot. */export function QuotaMeterBar({usedPct,usedFreePct = 0,@@ -53,42 +81,72 @@ export function QuotaMeterBar({valueNow,label,size = 'medium',+ limitLabel = 'Spend limit',className,}: QuotaMeterBarProps): JSX.Element {- const widths = quotaMeterWidths(+ const { widths, limitMarkerPct } = quotaMeterLayout(usedPct,usedFreePct,projected.map((segment) => segment.pct))+ const overshoots = limitMarkerPct < 100+ // Keep the caption inside the card when the marker sits near either end, instead of centering it off the edge.+ const captionAnchor = limitMarkerPct > 85 ? 'translateX(-100%)' : limitMarkerPct < 15 ? 'none' : 'translateX(-50%)'return (- <div- className={clsx(- 'flex overflow-hidden bg-fill-tertiary',- size === 'small' ? 'h-1.5 rounded-full' : 'h-3 rounded',- className- )}- role="meter"- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={Math.min(Math.round(valueNow), 100)}- aria-label={label}- >- <div- className={clsx('transition-[width] duration-500 ease-out', QUOTA_METER_FREE_CLASS)}- style={{ width: `${widths[0]}%` }}- />- <div className="bg-muted transition-[width] duration-500 ease-out" style={{ width: `${widths[1]}%` }} />- {projected.map(({ barClass, striped }, index) => (+ <div className={className}>+ <div className="relative">+ <div+ className={clsx(+ 'flex overflow-hidden bg-fill-tertiary',+ size === 'small' ? 'h-1.5 rounded-full' : 'h-3 rounded'+ )}+ role="meter"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.min(Math.round(valueNow), 100)}+ aria-label={label}+ >+ <div+ className={clsx('transition-[width] duration-500 ease-out', QUOTA_METER_FREE_CLASS)}+ style={{ width: `${widths[0]}%` }}+ />+ <div+ className="bg-muted transition-[width] duration-500 ease-out"+ style={{ width: `${widths[1]}%` }}+ />+ {projected.map(({ barClass, striped }, index) => (+ <div+ key={index}+ className={clsx(+ 'transition-[width,background-color] duration-500 ease-out',+ striped && 'QuotaMeterBar__stripes QuotaMeterBar__stripes--animated',+ barClass+ )}+ style={{ width: `${widths[index + 2]}%` }}+ />+ ))}+ </div><div- key={index}className={clsx(- 'transition-[width,background-color] duration-500 ease-out',- striped && 'QuotaMeterBar__stripes QuotaMeterBar__stripes--animated',- barClass+ 'absolute w-0.5 rounded-full bg-text-3000 transition-[left] duration-500 ease-out',+ size === 'small' ? '-top-1 h-3.5' : '-top-1 h-5')}- style={{ width: `${widths[index + 2]}%` }}+ // At the limit the marker sits on the bar's own end, so pull it back inside rather than+ // letting it hang half off the edge.+ style={{ left: `${limitMarkerPct}%`, transform: overshoots ? undefined : 'translateX(-100%)' }}/>- ))}+ </div>+ {limitLabel && (+ // Its own row in normal flow, so the caption can never land on whatever the parent renders next.+ <div className="relative mt-1 h-4">+ <span+ className="absolute whitespace-nowrap text-[11px] font-medium text-secondary transition-[left] duration-500 ease-out"+ style={{ left: `${limitMarkerPct}%`, transform: captionAnchor }}+ >+ {limitLabel}+ </span>+ </div>+ )}</div>)}@@ -102,7 +160,7 @@ export function QuotaMeterLegendItem({}: {barClass?: stringstriped?: boolean- /** Clamped width of the matching segment; omit for entries that are always shown. */+ /** Rendered width of the matching segment; omit for entries that are always shown. */width?: numberchildren: ReactNode}): JSX.Element | null {@@ -122,3 +180,57 @@ export function QuotaMeterLegendItem({</div>)}++/**+ * Bar and legend for a `QuotaMeterModel`, together.+ *+ * The pairing is the point: widths are computed once and drive both, so a legend chip cannot label a+ * segment the bar didn't draw. Assembling them per card meant three copies and two width computations.+ */+export function QuotaMeter({+ model,+ label,+ size,+ className,+}: {+ model: QuotaMeterModel+ label: string+ size?: 'small' | 'medium'+ className?: string+}): JSX.Element {+ const { projection, segments, periodEndPct } = model+ const [freeWidth, billedWidth, ...segmentWidths] = quotaMeterWidths(+ projection.usedPct,+ projection.usedFreePct,+ segments.map((segment) => segment.pct)+ )+ return (+ <>+ <QuotaMeterBar+ className={className}+ size={size}+ usedPct={projection.usedPct}+ usedFreePct={projection.usedFreePct}+ projected={segments}+ valueNow={periodEndPct}+ label={label}+ />+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted">+ <QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>+ Free+ </QuotaMeterLegendItem>+ <QuotaMeterLegendItem width={billedWidth}>{freeWidth > 0 ? 'Billed' : 'Spent'}</QuotaMeterLegendItem>+ {segments.map((segment, index) => (+ <QuotaMeterLegendItem+ key={segment.key}+ barClass={segment.barClass}+ striped={segment.striped}+ width={segmentWidths[index]}+ >+ {segment.label}+ </QuotaMeterLegendItem>+ ))}+ </div>+ </>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsxindex 4503b91f501f..15af2c591e8b 100644--- a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx@@ -9,7 +9,6 @@ const base: QuotaProjection = {status: 'safe',exhausted: false,capReachDate: null,- percentLabel: 0,resetsOn: null,usedPct: 0,usedFreePct: 0,diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsxnew file mode 100644index 000000000000..d3160344c578--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx@@ -0,0 +1,269 @@+import { useActions, useValues } from 'kea'+import { combineUrl } from 'kea-router'++import { LemonButton, LemonTable, LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { dateStringToDayJs } from 'lib/utils/dateFilters'+import { urls } from 'scenes/urls'++import { DateMappingOption } from '~/types'++import type { BackfillStatusEnumApi, ReplayScannerBackfillApi } from '../../generated/api.schemas'+import { formatCreditCount, formatCredits } from '../../utils/credits'+import { backfillsLogic, isBackfillActive } from '../backfillsLogic'+import { ReplayScannerTab } from '../replayScannerSceneLogic'+import type { ScannerCreatedBy } from '../types'+import { BackfillCostEstimate } from './BackfillCostEstimate'++// Hour-scale presets matter as much as day-scale ones: a common case is re-scanning the last couple+// of hours after fixing a prompt, not re-scanning a month.+const BACKFILL_DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ { key: 'Last 3 hours', values: ['-3h'] },+ { key: 'Last 6 hours', values: ['-6h'] },+ { key: 'Last 24 hours', values: ['-24h'] },+ { key: 'Last 7 days', values: ['-7d'] },+ { key: 'Last 30 days', values: ['-30d'] },+ { key: 'Last 90 days', values: ['-90d'] },+]++const BACKFILL_STATUS_TAG: Record<BackfillStatusEnumApi, { label: string; type: LemonTagType }> = {+ running: { label: 'Running', type: 'success' },+ paused_quota: { label: 'Paused (quota)', type: 'warning' },+ completed: { label: 'Completed', type: 'default' },+ cancelled: { label: 'Cancelled', type: 'muted' },+}++/** Raw instant, so two window bounds can be compared at a glance. */+const WINDOW_TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'HH:mm' }++/** A full UUID overflows the observations filter row; the leading block still identifies a backfill,+ * and the Backfills table shows the whole id to match against. */+export function shortBackfillId(id: string): string {+ return id.slice(0, 8)+}++/** Convert a DateFilter token (`-30d`, an ISO date, or null) into an ISO instant for the API. */+export function resolveWindowBound(value: string | null, fallback: dayjs.Dayjs): string {+ return ((value && dateStringToDayJs(value)) || fallback).toISOString()+}++export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.Element {+ const logic = backfillsLogic({ scannerId })+ const {+ backfills,+ backfillsLoading,+ estimate,+ estimateLoading,+ creatingBackfill,+ transitioningIds,+ windowDateFrom,+ windowDateTo,+ } = useValues(logic)+ const { requestEstimate, createBackfill, cancelBackfill, resumeBackfill, setWindowRange } = useActions(logic)++ const activeBackfill = backfills.find(isBackfillActive)++ const estimateWindow = (dateFrom: string | null, dateTo: string | null): void => {+ setWindowRange(dateFrom, dateTo)+ requestEstimate(resolveWindowBound(dateFrom, dayjs().subtract(30, 'day')), resolveWindowBound(dateTo, dayjs()))+ }++ const startDisabledReason = activeBackfill+ ? 'This scanner already has an active backfill'+ : !estimate+ ? 'Pick a time range to see the cost first'+ : estimate.total_sessions === 0+ ? 'No eligible sessions in this time range'+ : undefined++ const columns: LemonTableColumns<ReplayScannerBackfillApi> = [+ {+ title: 'ID',+ key: 'id',+ render: (_, backfill) => (+ <CopyToClipboardInline explicitValue={backfill.id} description="backfill ID" iconSize="xsmall">+ <span className="font-mono text-xs">{backfill.id}</span>+ </CopyToClipboardInline>+ ),+ },+ {+ title: 'Start',+ key: 'window_start',+ // `timestampStyle="absolute"` is what suppresses the Today/Yesterday substitution; the+ // format props alone leave it on. A window bound has to read as an exact instant so two+ // rows can be compared, and this keeps TZLabel's timezone-conversion popover.+ render: (_, backfill) => (+ <TZLabel time={backfill.window_start} timestampStyle="absolute" {...WINDOW_TIME_FORMAT} />+ ),+ },+ {+ title: 'End',+ key: 'window_end',+ render: (_, backfill) => (+ <TZLabel time={backfill.window_end} timestampStyle="absolute" {...WINDOW_TIME_FORMAT} />+ ),+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, backfill) => (+ <LemonTag type={BACKFILL_STATUS_TAG[backfill.status].type}>+ {BACKFILL_STATUS_TAG[backfill.status].label}+ </LemonTag>+ ),+ },+ {+ title: 'Progress',+ key: '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 handled = backfill.dispatched_count + backfill.skipped_count+ const skippedNote = backfill.skipped_count ? `, ${backfill.skipped_count} already scanned` : ''+ return (+ <Tooltip+ title={`${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>+ </Tooltip>+ )+ },+ },+ {+ title: 'Spend',+ key: 'spend',+ render: (_, backfill) => (+ <Tooltip title={`At most ${formatCredits(backfill.total_count * backfill.credits_per_observation)}`}>+ <span>{formatCreditCount(backfill.succeeded_count * backfill.credits_per_observation)}</span>+ </Tooltip>+ ),+ },+ {+ title: 'Created',+ key: 'created',+ // Relative here, unlike the window bounds: "how long ago was this started" is the useful+ // reading, and it matches how created timestamps show elsewhere in the app.+ render: (_, backfill) => <TZLabel time={backfill.created_at} />,+ },+ {+ title: 'Created by',+ key: 'created_by',+ render: (_, backfill) =>+ backfill.created_by ? (+ // Same adapter the scanner list uses: the generated hedgehog_config shape does not+ // match ProfilePicture's, and it is not needed to draw an avatar.+ <ProfilePicture user={backfill.created_by as ScannerCreatedBy} size="md" showName />+ ) : (+ <span className="text-secondary">—</span>+ ),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, backfill) => (+ <More+ data-attr="vision-backfill-actions"+ overlay={+ <>+ <LemonButton+ fullWidth+ to={+ combineUrl(urls.replayVision(scannerId), {+ tab: ReplayScannerTab.Observations,+ backfill_id: backfill.id,+ }).url+ }+ data-attr="vision-backfill-view-observations"+ >+ View observations+ </LemonButton>+ {backfill.status === 'paused_quota' && (+ <LemonButton+ fullWidth+ onClick={() => resumeBackfill(backfill.id)}+ disabledReason={transitioningIds.includes(backfill.id) ? 'Resuming…' : undefined}+ data-attr="vision-backfill-resume"+ >+ Resume+ </LemonButton>+ )}+ {isBackfillActive(backfill) && (+ <LemonButton+ fullWidth+ status="danger"+ onClick={() => cancelBackfill(backfill.id)}+ disabledReason={transitioningIds.includes(backfill.id) ? 'Cancelling…' : undefined}+ data-attr="vision-backfill-cancel"+ >+ Cancel+ </LemonButton>+ )}+ </>+ }+ />+ ),+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="rounded border p-4 flex flex-col gap-3">+ <div>+ <h3 className="mb-1">Scan historical recordings</h3>+ <p className="text-muted mb-0">+ Run this scanner over older recordings, including ones from before you created it. The backfill+ skips recordings it has already scanned, so you're not billed twice. It uses the scanner's+ settings as they are now, so editing the scanner later won't change a backfill that's already+ running.+ </p>+ </div>+ <div className="flex items-center gap-2 flex-wrap">+ <DateFilter+ size="small"+ dateFrom={windowDateFrom}+ dateTo={windowDateTo}+ dateOptions={BACKFILL_DATE_OPTIONS}+ onChange={(dateFrom, dateTo) => estimateWindow(dateFrom, dateTo)}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['hours', 'days', 'weeks', 'months']}+ data-attr="vision-backfill-date-filter"+ />+ <LemonButton+ type="primary"+ size="small"+ onClick={() => estimate && createBackfill(estimate.window_start, estimate.window_end)}+ loading={creatingBackfill}+ disabledReason={startDisabledReason}+ data-attr="vision-backfill-start"+ >+ Start backfill+ </LemonButton>+ </div>+ <BackfillCostEstimate estimate={estimate} loading={estimateLoading} />+ </div>++ <LemonTable+ dataSource={backfills}+ columns={columns}+ loading={backfillsLoading}+ rowKey="id"+ emptyState="No backfills yet. Pick a time range above to scan historical recordings."+ data-attr="vision-backfills-table"+ />+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex a2962e8c2e7e..c6cd80f3e27a 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconCopy, IconEye, IconPlay, IconRefresh } from '@posthog/icons'+import { IconCopy, IconEye, IconPlay, IconRefresh, IconX } from '@posthog/icons'import { LemonButton, LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -24,6 +24,7 @@ import {replayScannerLogic,} from '../replayScannerLogic'import { OBSERVATION_TRIGGER_TAG } from '../types'+import { shortBackfillId } from './ScannerBackfillsTab'const STATUS_OPTIONS: { value: ObservationStatusValue; label: string }[] = [{ value: 'succeeded', label: 'Succeeded' },@@ -92,6 +93,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):observationSubjectFilter,observationDateFrom,observationDateTo,+ observationBackfillFilter,hasActiveObservationFilters,observationDetailLinkParams,availableTags,@@ -112,6 +114,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):setObservationTagFilter,setObservationSubjectFilter,setObservationDateRange,+ setObservationBackfillFilter,clearObservationFilters,copyAllObservations,} = useActions(logic)@@ -289,6 +292,25 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):searchable/>)}+ {observationBackfillFilter && (+ // Same secondary/small button the FilterPills next to it render, so+ // the row stays visually uniform. It carries a clear action rather+ // than a dropdown, because this filter arrives from a link and has+ // nothing to choose between.+ <LemonButton+ type="secondary"+ size="small"+ tooltip={`Backfill ${observationBackfillFilter}`}+ sideAction={{+ icon: <IconX />,+ onClick: () => setObservationBackfillFilter(null),+ tooltip: 'Clear backfill filter',+ }}+ data-attr="vision-observations-backfill-filter"+ >+ Backfill {shortBackfillId(observationBackfillFilter)}+ </LemonButton>+ )}<LemonButtontype="tertiary"size="small"diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsxindex cb6a04aee19e..75f96e599d65 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx@@ -10,15 +10,14 @@ import { QuotaImminentBanner } from '../../components/QuotaImminentBanner'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'import { creditsToUsd, formatCreditCount } from '../../utils/credits'import {- QUOTA_STATUS_STYLES,- type QuotaStatus,- daysUntilCapReached,- hasCreditLimit,- projectQuota,- splitProjectedPct,-} from '../../utils/quotaProjection'+ QUOTA_BACKFILL_CLASS,+ QUOTA_OTHER_SCANNERS_CLASS,+ QUOTA_STATUS_CLASS,+ buildQuotaMeter,+} from '../../utils/quotaContributions'+import { QUOTA_STATUS_STYLES, type QuotaStatus, daysUntilCapReached } from '../../utils/quotaProjection'import { replayScannerLogic } from '../replayScannerLogic'-import { QUOTA_METER_FREE_CLASS, QuotaMeterBar, QuotaMeterLegendItem, quotaMeterWidths } from './QuotaMeterBar'+import { QuotaMeter } from './QuotaMeterBar'import { QuotaStatusLine } from './QuotaStatusLine'interface Props {@@ -45,32 +44,53 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {// The estimate already applies the quality filter and sampling rate backend-side.const projectedObservations = scannerEstimate?.estimated_observations_per_month ?? nullconst projectedCredits = scannerEstimate?.estimated_credits_per_month ?? null- const hasCap = hasCreditLimit(quota)const used = quota?.credits_used ?? 0const cap = quota?.credit_limit ?? 0// `other_enabled_scanners_monthly_credits` comes from the same estimate response as `projectedCredits`, so the// two are a consistent snapshot. Subtracting this scanner's stored estimate from the live fleet sum instead would// race the estimate-refresh cadence and double-count the scanner right after creating it.- const fleetMonthly = quota?.projected_monthly_credits ?? 0const othersMonthly = scannerEstimate?.other_enabled_scanners_monthly_credits ?? 0- // projectQuota wants a delta off the stored fleet total, so compute the new fleet total (others + this) and pass the difference.- const newFleetMonthly = projectedCredits !== null ? othersMonthly + projectedCredits : fleetMonthly- const projection = projectQuota(quota, newFleetMonthly - fleetMonthly)- const { status, percentLabel, resetsOn, usedPct, usedFreePct, projectedPct } = projection+ const backfillCredits = scannerEstimate?.active_backfill_credits ?? 0++ // The proposed scanner replaces its own stored estimate, so this lists the fleet explicitly rather than+ // adjusting the org total. Backfills stay a one-off; only the two scanner figures are rates.+ const model = buildQuotaMeter(quota, [+ {+ key: 'backfills',+ label: 'Backfills',+ credits: backfillCredits,+ kind: 'one-off',+ barClass: QUOTA_BACKFILL_CLASS,+ },+ {+ key: 'others',+ label: 'Projected (other scanners)',+ credits: othersMonthly,+ kind: 'monthly-rate',+ barClass: QUOTA_OTHER_SCANNERS_CLASS,+ },+ {+ key: 'this-scanner',+ label: 'Projected (this scanner)',+ credits: projectedCredits ?? 0,+ kind: 'monthly-rate',+ // The model resolves this to the card's status colour, which depends on the projection it is part of.+ barClass: QUOTA_STATUS_CLASS,+ striped: true,+ },+ ])+ const { projection, periodEndPct, hasCap } = model+ const { resetsOn } = projection+ const newFleetMonthly = othersMonthly + (projectedCredits ?? 0)- const effectiveStatus: QuotaStatus = projectedCredits === null ? 'safe' : status+ // Nothing proposed yet, so the forecast isn't a verdict on this scanner.+ const effectiveStatus: QuotaStatus = projectedCredits === null ? 'safe' : model.statusconst styles = QUOTA_STATUS_STYLES[effectiveStatus]// No estimate means the projection isn't about the scanner being edited.const imminentDays = projectedCredits !== null ? daysUntilCapReached(projection) : null- const { thisScannerPct, othersPct } = splitProjectedPct(projectedPct, projectedCredits ?? 0, othersMonthly)- const [freeWidth, billedWidth, othersWidth, thisWidth] = quotaMeterWidths(usedPct, usedFreePct, [- othersPct,- thisScannerPct,- ])-const breakdown = (<div className="text-xs space-y-0.5"><div>@@ -82,6 +102,11 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {<div>Projected from other scanners: <strong>~{formatCreditCount(othersMonthly)}/month</strong></div>+ {backfillCredits > 0 && (+ <div>+ Committed by active backfills: <strong>{formatCreditCount(backfillCredits)}</strong>+ </div>+ )}{hasCap && (<div>Monthly limit: <strong>{formatCreditCount(cap)}</strong>@@ -103,7 +128,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {{hasCap && projectedCredits !== null && (<Tooltip title={breakdown}><span className={`text-xs tabular-nums ${styles.text}`}>- {percentLabel}%{' '}+ {periodEndPct}%{' '}<span className="text-muted font-normal">by {resetsOn ?? 'period end'}</span></span></Tooltip>@@ -158,33 +183,15 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {{hasCap && projectedCredits !== null && (<><Tooltip title={breakdown}>- <QuotaMeterBar- usedPct={usedPct}- usedFreePct={usedFreePct}- projected={[- { pct: othersPct, barClass: 'bg-accent' },- { pct: thisScannerPct, barClass: styles.bar, striped: true },- ]}- valueNow={percentLabel}- label={`Projected ${percentLabel}% of the monthly spend limit by ${- resetsOn ?? 'period end'- }`}- />+ <div>+ <QuotaMeter+ model={model}+ label={`Projected ${periodEndPct}% of the monthly spend limit by ${+ resetsOn ?? 'period end'+ }`}+ />+ </div></Tooltip>- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted">- <QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>- Free- </QuotaMeterLegendItem>- <QuotaMeterLegendItem width={billedWidth}>- {freeWidth > 0 ? 'Billed' : 'Spent'}- </QuotaMeterLegendItem>- <QuotaMeterLegendItem barClass="bg-accent" width={othersWidth}>- Projected (other scanners)- </QuotaMeterLegendItem>- <QuotaMeterLegendItem barClass={styles.bar} striped width={thisWidth}>- Projected (this scanner)- </QuotaMeterLegendItem>- </div></>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsxindex dd7f37bbf62f..fae9988de262 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx@@ -14,11 +14,12 @@ import { QuotaExhaustedNote } from '../../components/QuotaExhaustedNote'import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'import { creditsToUsd, formatCreditCount } from '../../utils/credits'-import { QUOTA_STATUS_STYLES, hasCreditLimit, projectQuota } from '../../utils/quotaProjection'+import { buildQuotaMeter, fleetContributions } from '../../utils/quotaContributions'+import { QUOTA_STATUS_STYLES } from '../../utils/quotaProjection'import { STARTUP_CAP_EXPLANATION } from '../../utils/startupCap'import { replayScannersLogic } from '../replayScannersLogic'import { SCANNER_TYPE_OPTIONS } from '../types'-import { QUOTA_METER_FREE_CLASS, QuotaMeterBar, QuotaMeterLegendItem, quotaMeterWidths } from './QuotaMeterBar'+import { QuotaMeter } from './QuotaMeterBar'import { QuotaStatusLine } from './QuotaStatusLine'import { VisionInsightChart } from './VisionInsightChart'@@ -40,11 +41,11 @@ export function VisionMetrics(): JSX.Element {showStartupCapLine,} = useValues(visionQuotaLogic)- const projection = projectQuota(quota)- const { resetsOn, status, percentLabel, usedPct, usedFreePct, projectedPct } = projection- const hasCap = hasCreditLimit(quota)- const [freeWidth, billedWidth, projectedWidth] = quotaMeterWidths(usedPct, usedFreePct, [projectedPct])+ // Backfills are charged once, so they can't ride in the pro-rated projection; the model keeps them apart.+ const model = buildQuotaMeter(quota, fleetContributions(quota))+ const { projection, periodEndPct, hasCap, status } = modelconst styles = QUOTA_STATUS_STYLES[status]+ const { resetsOn } = projection// Memoized so a re-render (e.g. stats/quota arriving) can't churn the query and abort an in-flight load.// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.@@ -122,7 +123,7 @@ export function VisionMetrics(): JSX.Element {<div className="text-muted text-xs font-medium uppercase">Spend this period</div>{hasCap && (<span className={`text-xs tabular-nums ${styles.text}`}>- {percentLabel}%{' '}+ {periodEndPct}%{' '}<span className="text-muted font-normal">by period end{resetsOn ? ` (${resetsOn})` : ''}</span>@@ -177,32 +178,18 @@ export function VisionMetrics(): JSX.Element {</div>}>- <QuotaMeterBar+ <QuotaMeter+ model={model}className="mt-2"- usedPct={usedPct}- usedFreePct={usedFreePct}- projected={[{ pct: projectedPct, barClass: styles.bar, striped: true }]}- valueNow={percentLabel}- label={`Projected ${percentLabel}% of the monthly spend limit`}+ label={`Projected ${periodEndPct}% of the monthly spend limit`}/></Tooltip>- <div className="flex flex-wrap items-center gap-3 text-xs text-muted mt-1.5">- <QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>- Free- </QuotaMeterLegendItem>- <QuotaMeterLegendItem width={billedWidth}>- {freeWidth > 0 ? 'Billed' : 'Spent'}- </QuotaMeterLegendItem>- <QuotaMeterLegendItem barClass={styles.bar} striped width={projectedWidth}>- Projected- </QuotaMeterLegendItem>- {/* The exhausted note below carries this status, so don't say it twice. */}- {!projection.exhausted && (- <span className="ml-auto">- <QuotaStatusLine projection={projection} onFreePlan={onFreePlan} />- </span>- )}- </div>+ {/* The exhausted note below carries this status, so don't say it twice. */}+ {!projection.exhausted && (+ <div className="text-xs text-muted mt-1.5">+ <QuotaStatusLine projection={projection} onFreePlan={onFreePlan} />+ </div>+ )}{projection.exhausted && (<div className="mt-1.5"><QuotaExhaustedNote onFreePlan={onFreePlan} />diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 6a98fe818ec2..bd9e5af2de0f 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -515,6 +515,7 @@ describe('replayScannerLogic', () => {observationSubjectFilter: '',observationDateFrom: null as string | null,observationDateTo: null as string | null,+ observationBackfillFilter: null as string | null,observationsSort: null,scanner: null,}@@ -523,6 +524,12 @@ describe('replayScannerLogic', () => {expect(buildObservationListParams({ ...emptyValues })).toEqual({})})+ it('passes the backfill filter as backfill_id', () => {+ expect(buildObservationListParams({ ...emptyValues, observationBackfillFilter: 'bf-1' })).toEqual({+ backfill_id: 'bf-1',+ })+ })+it('passes limit and offset only when offset is positive', () => {expect(buildObservationListParams({ ...emptyValues }, 50, 0)).toEqual({ limit: 50 })expect(buildObservationListParams({ ...emptyValues }, 50, 100)).toEqual({ limit: 50, offset: 100 })diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex eeda42cea041..366cdc9e2912 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -123,6 +123,7 @@ interface ObservationListParams {offset?: numberstatus?: stringtriggered_by?: string+ backfill_id?: stringverdict?: stringtags?: stringrecording_subject?: string@@ -160,6 +161,7 @@ interface ObservationFilterValues {observationSubjectFilter: stringobservationDateFrom: string | nullobservationDateTo: string | null+ observationBackfillFilter: string | null}/** The filter (non-pagination, non-sort) params shared by the list/stats endpoints and the URL query string. */@@ -167,11 +169,11 @@ function observationFilterParams(values: ObservationFilterValues): Pick<ObservationListParams,- 'status' | 'triggered_by' | 'verdict' | 'tags' | 'recording_subject' | 'date_from' | 'date_to'+ 'status' | 'triggered_by' | 'verdict' | 'tags' | 'recording_subject' | 'date_from' | 'date_to' | 'backfill_id'> {const params: Pick<ObservationListParams,- 'status' | 'triggered_by' | 'verdict' | 'tags' | 'recording_subject' | 'date_from' | 'date_to'+ 'status' | 'triggered_by' | 'verdict' | 'tags' | 'recording_subject' | 'date_from' | 'date_to' | 'backfill_id'> = {}if (values.observationStatusFilter.length > 0) {params.status = values.observationStatusFilter.join(',')@@ -194,6 +196,9 @@ function observationFilterParams(if (values.observationDateTo) {params.date_to = values.observationDateTo}+ if (values.observationBackfillFilter) {+ params.backfill_id = values.observationBackfillFilter+ }return params}@@ -240,6 +245,7 @@ export interface replayScannerLogicValues {isNew: booleanisScannerSubmitting: booleanisScannerValid: boolean+ observationBackfillFilter: string | nullobservationDateFrom: string | nullobservationDateTo: string | nullobservationDetailLinkParams: Record<string, string>@@ -375,6 +381,7 @@ export interface replayScannerLogicActions {values?: ReplayScanner}restoreObservationsTableState: (state: {+ backfillId: string | nulldateFrom: string | nulldateTo: string | nullpage: number@@ -385,6 +392,7 @@ export interface replayScannerLogicActions {triggeredBy: ObservationTriggeredByValue[]verdict: ObservationVerdictValue[]}) => {+ backfillId: string | nulldateFrom: string | nulldateTo: string | nullpage: number@@ -439,6 +447,9 @@ export interface replayScannerLogicActions {dateFrom: string | nulldateTo: string | null}+ setObservationBackfillFilter: (value: string | null) => {+ value: string | null+ }setObservationDateRange: (dateFrom: string | null,dateTo: string | null@@ -550,7 +561,8 @@ export interface replayScannerLogicMeta {observationTagFilter: string[],observationSubjectFilter: string,observationDateFrom: string | null,- observationDateTo: string | null+ observationDateTo: string | null,+ observationBackfillFilter: string | null) => booleanobservationDetailLinkParams: (observationStatusFilter: ObservationStatusEnumApi[],@@ -560,6 +572,7 @@ export interface replayScannerLogicMeta {observationSubjectFilter: string,observationDateFrom: string | null,observationDateTo: string | null,+ observationBackfillFilter: string | null,observationsSort: ObservationsSorting | null,scanner: ReplayScanner) => Record<string, string>@@ -614,6 +627,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setObservationTagFilter: (values: string[]) => ({ values }),setObservationSubjectFilter: (value: string) => ({ value }),setObservationDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ setObservationBackfillFilter: (value: string | null) => ({ value }),clearObservationFilters: true,restoreObservationsTableState: (state: {page: number@@ -625,6 +639,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([subject: stringdateFrom: string | nulldateTo: string | null+ backfillId: string | null}) => state,setChartDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),requestScannerEstimate: true,@@ -1028,6 +1043,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([restoreObservationsTableState: (_, { dateTo }) => dateTo,},],+ observationBackfillFilter: [+ null as string | null,+ {+ setObservationBackfillFilter: (_, { value }) => value,+ clearObservationFilters: () => null,+ restoreObservationsTableState: (_, { backfillId }) => backfillId,+ },+ ],chartDateFrom: ['-14d' as string | null, { setChartDateRange: (_, { dateFrom }) => dateFrom }],chartDateTo: [null as string | null, { setChartDateRange: (_, { dateTo }) => dateTo }],}),@@ -1068,6 +1091,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([s.observationSubjectFilter,s.observationDateFrom,s.observationDateTo,+ s.observationBackfillFilter,],(statusFilter: ObservationStatusValue[],@@ -1076,7 +1100,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([tagFilter: string[],subjectFilter: string,dateFrom: string | null,- dateTo: string | null+ dateTo: string | null,+ backfillFilter: string | null): boolean =>statusFilter.length > 0 ||triggeredByFilter.length > 0 ||@@ -1084,7 +1109,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([tagFilter.length > 0 ||subjectFilter.trim().length > 0 ||dateFrom !== null ||- dateTo !== null,+ dateTo !== null ||+ backfillFilter !== null,],// Carried into observation detail links so server-computed prev/next neighbors honor the table's filters + sort.observationDetailLinkParams: [@@ -1096,6 +1122,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([s.observationSubjectFilter,s.observationDateFrom,s.observationDateTo,+ s.observationBackfillFilter,s.observationsSort,s.scanner,],@@ -1107,6 +1134,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([observationSubjectFilter: string,observationDateFrom: string | null,observationDateTo: string | null,+ observationBackfillFilter: string | null,observationsSort: ObservationsSorting | null,scanner: ReplayScanner | null): Record<string, string> =>@@ -1118,6 +1146,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([observationSubjectFilter,observationDateFrom,observationDateTo,+ observationBackfillFilter,observationsSort,scanner,}) as Record<string, string>,@@ -1506,6 +1535,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setObservationTriggeredByFilter: () => reloadObservationsAndStats(),setObservationVerdictFilter: () => reloadObservationsAndStats(),setObservationTagFilter: () => reloadObservationsAndStats(),+ setObservationBackfillFilter: () => reloadObservationsAndStats(),setObservationDateRange: () => reloadObservationsAndStats(),setObservationSubjectFilter: async (_, breakpoint) => {// Free-text search — debounce so typing doesn't fire a request per keystroke.@@ -1586,6 +1616,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setObservationVerdictFilter: writeUrl,setObservationTagFilter: writeUrl,setObservationDateRange: writeUrl,+ setObservationBackfillFilter: writeUrl,setObservationSubjectFilter: writeUrlReplace,clearObservationFilters: writeUrl,}@@ -1610,6 +1641,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([typeof subjectRaw === 'string' ? subjectRaw : typeof subjectRaw === 'number' ? String(subjectRaw) : ''const dateFrom = typeof searchParams.date_from === 'string' ? searchParams.date_from : nullconst dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : null+ const backfillId = typeof searchParams.backfill_id === 'string' ? searchParams.backfill_id : nullconst sameAsCurrent =page === values.observationsPage &&sort.columnKey === values.observationsSort?.columnKey &&@@ -1620,7 +1652,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([objectsEqual(tags, values.observationTagFilter) &&subject === values.observationSubjectFilter &&dateFrom === values.observationDateFrom &&- dateTo === values.observationDateTo+ dateTo === values.observationDateTo &&+ backfillId === values.observationBackfillFilterif (!sameAsCurrent) {actions.restoreObservationsTableState({page,@@ -1632,6 +1665,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([subject,dateFrom,dateTo,+ backfillId,})}},@@ -1687,6 +1721,7 @@ const TABLE_URL_PARAM_KEYS = ['recording_subject','date_from','date_to',+ 'backfill_id',] as const/** Observation-filter params the scanner page reads from the URL; links into the Observations tab build from these keys. */diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.tsindex 3d9dc658d5b2..af0a1b104891 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts@@ -10,6 +10,7 @@ export enum ReplayScannerTab {Observations = 'observations',Calibration = 'calibration',OnDemand = 'on-demand',+ Backfills = 'backfills',Configuration = 'configuration',Actions = 'actions',}diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 897f98ca3754..0ecdefeb5393 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -30,6 +30,7 @@ export const OBSERVATION_TRIGGER_TAG: Record<schedule: { label: 'Schedule', type: 'default' },on_demand: { label: 'On demand', type: 'highlight' },retry: { label: 'Retry', type: 'completion' },+ backfill: { label: 'Backfill', type: 'caution' },}// Typed against the generated retrieve params so a renamed or dropped backend filter fails the build.diff --git a/products/replay_vision/frontend/utils/quotaContributions.test.ts b/products/replay_vision/frontend/utils/quotaContributions.test.tsnew file mode 100644index 000000000000..b7a9ea743b5a--- /dev/null+++ b/products/replay_vision/frontend/utils/quotaContributions.test.ts@@ -0,0 +1,73 @@+import type { VisionQuotaApi } from '../generated/api.schemas'+import { type QuotaContribution, buildQuotaMeter } from './quotaContributions'++const HALF_PERIOD_QUOTA: VisionQuotaApi = {+ credit_limit: 1000,+ credits_used: 100,+ remaining: 900,+ exhausted: false,+ free_monthly_credits: 0,+ projected_monthly_credits: 400,+ scanners_monthly_credits: 400,+ backfills_committed_credits: 0,+ // Half the period is left, so a monthly rate lands at half value and a one-off lands whole.+ period_start: '2026-05-01T00:00:00Z',+ period_end: '2026-05-03T00:00:00Z',+} as VisionQuotaApi++const contribution = (overrides: Partial<QuotaContribution>): QuotaContribution => ({+ key: 'k',+ label: 'l',+ credits: 0,+ kind: 'monthly-rate',+ barClass: 'bg-accent',+ ...overrides,+})++describe('quotaContributions', () => {+ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(new Date('2026-05-02T00:00:00Z'))+ })+ afterEach(() => {+ jest.useRealTimers()+ })++ it('charges a one-off in full while pro-rating a rate over the days left', () => {+ // The bug this prevents: routing a backfill through the rate path shrank it to a fraction.+ const { segments } = buildQuotaMeter(HALF_PERIOD_QUOTA, [+ contribution({ key: 'backfill', credits: 200, kind: 'one-off' }),+ contribution({ key: 'scanners', credits: 200, kind: 'monthly-rate' }),+ ])+ const bySegment = Object.fromEntries(segments.map((s) => [s.key, s.pct]))+ expect(bySegment.backfill).toBeCloseTo(20)+ expect(bySegment.scanners).toBeCloseTo(10)+ })++ it('splits one projection across rate contributions instead of pro-rating each separately', () => {+ const { projection, segments } = buildQuotaMeter(HALF_PERIOD_QUOTA, [+ contribution({ key: 'others', credits: 300 }),+ contribution({ key: 'mine', credits: 100 }),+ ])+ const total = segments.reduce((sum, s) => sum + s.pct, 0)+ expect(total).toBeCloseTo(projection.projectedPct)+ expect(segments[0].pct).toBeCloseTo(segments[1].pct * 3)+ })++ it('keeps the headline percentage equal to what the bar draws', () => {+ // The other bug: a headline computed apart from the segments disagreed with them.+ const model = buildQuotaMeter(HALF_PERIOD_QUOTA, [+ contribution({ key: 'backfill', credits: 350, kind: 'one-off' }),+ contribution({ key: 'scanners', credits: 400 }),+ ])+ const drawn = model.projection.usedPct + model.segments.reduce((sum, s) => sum + s.pct, 0)+ expect(model.periodEndPct).toBe(Math.round(drawn))+ })++ it('reports no cap and zero-width segments for an uncapped org', () => {+ const model = buildQuotaMeter({ ...HALF_PERIOD_QUOTA, credit_limit: null } as VisionQuotaApi, [+ contribution({ key: 'backfill', credits: 500, kind: 'one-off' }),+ ])+ expect(model.hasCap).toBe(false)+ expect(model.segments[0].pct).toBe(0)+ })+})diff --git a/products/replay_vision/frontend/utils/quotaContributions.ts b/products/replay_vision/frontend/utils/quotaContributions.tsnew file mode 100644index 000000000000..e762860afbfb--- /dev/null+++ b/products/replay_vision/frontend/utils/quotaContributions.ts@@ -0,0 +1,127 @@+import type { VisionQuotaApi } from '../generated/api.schemas'+import {+ QUOTA_STATUS_STYLES,+ QUOTA_WARN_THRESHOLD,+ type QuotaProjection,+ type QuotaStatus,+ hasCreditLimit,+ projectQuota,+} from './quotaProjection'++/** Backfill commitments, wherever they appear: a hue no status can take, so the two never collide. */+export const QUOTA_BACKFILL_CLASS = 'bg-brand-blue'+/** The rest of the fleet's scanners, when a surface is singling one scanner out. */+export const QUOTA_OTHER_SCANNERS_CLASS = 'bg-accent'+/** Marks the contribution that should carry the card's status colour. */+export const QUOTA_STATUS_CLASS = 'status'++/**+ * Something a surface adds to the spend meter on top of what the period has already spent.+ *+ * `kind` is the point of this type. A scanner estimate is a monthly *rate*, so it lands in this+ * period only in proportion to the days left; a backfill is charged once, when it runs. Feeding a+ * one-off through the rate path shrinks it to a fraction of itself, which is the bug this prevents.+ */+export interface QuotaContribution {+ key: string+ label: string+ credits: number+ kind: 'monthly-rate' | 'one-off'+ barClass: string+ striped?: boolean+}++export interface QuotaMeterSegmentModel {+ key: string+ label: string+ pct: number+ barClass: string+ striped?: boolean+}++export interface QuotaMeterModel {+ projection: QuotaProjection+ /** One verdict for the whole card, counting every contribution the bar draws. */+ status: QuotaStatus+ /** Bar segments in render order, already as percentages of the limit. */+ segments: QuotaMeterSegmentModel[]+ /** Where the period lands counting every contribution; exceeds 100 on overshoot. */+ periodEndPct: number+ hasCap: boolean+}++/** The org's own commitments, correctly typed: scanners are a rate, backfills are not. */+export function fleetContributions(quota: VisionQuotaApi | null): QuotaContribution[] {+ return [+ {+ key: 'backfills',+ label: 'Backfills',+ credits: quota?.backfills_committed_credits ?? 0,+ kind: 'one-off',+ barClass: QUOTA_BACKFILL_CLASS,+ },+ {+ key: 'scanners',+ label: 'Projected (scanners)',+ credits: quota?.scanners_monthly_credits ?? 0,+ kind: 'monthly-rate',+ barClass: QUOTA_STATUS_CLASS,+ striped: true,+ },+ ]+}++/**+ * Turn contributions into meter segments, in one place.+ *+ * Surfaces say what they are adding and how it is charged. They never convert credits to+ * percentages, order segments, or compute the headline number, because doing that per card is what+ * produced a one-off pro-rated into invisibility and a headline that disagreed with its own bar.+ */+export function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: QuotaContribution[]): QuotaMeterModel {+ const hasCap = hasCreditLimit(quota)+ const cap = hasCap ? quota.credit_limit : 0+ const rates = contributions.filter((c) => c.kind === 'monthly-rate')+ const rateTotal = rates.reduce((sum, c) => sum + c.credits, 0)+ // The contributions are the whole projection, so move `projectQuota` off the stored fleet rate onto them.+ const projection = projectQuota(quota, rateTotal - (quota?.projected_monthly_credits ?? 0))++ const asPct = (credits: number): number => (hasCap && cap > 0 ? (credits / cap) * 100 : 0)+ const segments = contributions.map((c) => ({+ key: c.key,+ label: c.label,+ barClass: c.barClass,+ striped: c.striped,+ // Rate contributions share the already pro-rated projection, split by weight, so the parts sum to+ // exactly what the projection says rather than drifting from it.+ pct:+ c.kind === 'one-off'+ ? asPct(c.credits)+ : rateTotal > 0+ ? (projection.projectedPct * c.credits) / rateTotal+ : 0,+ }))++ const periodEndPct = Math.round(projection.usedPct + segments.reduce((sum, s) => sum + s.pct, 0))+ // One verdict, from the same total the bar draws. Deriving it per card produced a headline that+ // could read green beside a bar sitting past the limit marker.+ const status: QuotaStatus =+ projection.status === 'danger' || periodEndPct >= 100+ ? 'danger'+ : periodEndPct >= QUOTA_WARN_THRESHOLD * 100+ ? 'warning'+ : 'safe'++ return {+ projection,+ status,+ // The status colour is resolved here so no caller patches a segment after the fact.+ segments: segments.map((segment) =>+ segment.barClass === QUOTA_STATUS_CLASS+ ? { ...segment, barClass: QUOTA_STATUS_STYLES[status].bar }+ : segment+ ),+ periodEndPct,+ hasCap,+ }+}diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.tsindex ce30a9f35b1b..5fe0f98a59be 100644--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts@@ -1,11 +1,4 @@-import {- daysUntilCapReached,- exhaustionForecast,- hasBillableSpend,- projectQuota,- quotaUx,- splitProjectedPct,-} from './quotaProjection'+import { daysUntilCapReached, exhaustionForecast, hasBillableSpend, projectQuota, quotaUx } from './quotaProjection'import { makeQuota } from './quotaTestUtils'describe('hasBillableSpend', () => {@@ -29,14 +22,12 @@ describe('projectQuota', () => {expect(projectQuota(null)).toMatchObject({ status: 'safe', usedPct: 0, projectedPct: 0 })expect(projectQuota(makeQuota({ credit_limit: null, remaining: null }))).toMatchObject({status: 'safe',- percentLabel: 0,})})it('treats a zero limit as fully blocking, not uncapped', () => {const proj = projectQuota(makeQuota({ credit_limit: 0, remaining: 0, exhausted: true }))expect(proj.status).toBe('danger')- expect(proj.percentLabel).toBe(100)expect(proj.exhausted).toBe(true)})@@ -44,13 +35,11 @@ describe('projectQuota', () => {// 3,000/month fleet → 100/day → ends at 3,000 of 10,000.const proj = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))expect(proj.status).toBe('safe')- expect(proj.percentLabel).toBe(30)})it('zero fleet rate projects flat usage to period end', () => {const proj = projectQuota(makeQuota({ credits_used: 4_000 }))expect(proj.projectedPct).toBe(0)- expect(proj.percentLabel).toBe(40)expect(proj.capReachDate).toBeNull()})@@ -58,7 +47,6 @@ describe('projectQuota', () => {// 3,000 used + 9,000/month fleet → 300/day × 20 days → ends at 9,000 (90% of cap).const proj = projectQuota(makeQuota({ credits_used: 3_000, projected_monthly_credits: 9_000 }))expect(proj.status).toBe('warning')- expect(proj.percentLabel).toBe(90)})it('danger when projected to exhaust before period end', () => {@@ -87,7 +75,6 @@ describe('projectQuota', () => {const base = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))const withDelta = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }), 6_000)expect(withDelta.projectedPct).toBeGreaterThan(base.projectedPct)- expect(withDelta.percentLabel).toBeGreaterThan(base.percentLabel)})it('a negative scanner delta lowers the projection and clamps at zero', () => {@@ -112,7 +99,6 @@ describe('projectQuota', () => {it('reports unclamped percentages on overshoot', () => {// 8,000 used + 30,000/month × 20 days = 20,000 more → 280% of the 10,000 cap.const proj = projectQuota(makeQuota({ credits_used: 8_000, projected_monthly_credits: 30_000 }))- expect(proj.percentLabel).toBe(280)expect(proj.projectedPct).toBeCloseTo(200, 0)})})@@ -131,20 +117,6 @@ describe('daysUntilCapReached', () => {})})-describe('splitProjectedPct', () => {- it('apportions by monthly volume', () => {- expect(splitProjectedPct(30, 100, 200)).toEqual({ thisScannerPct: 10, othersPct: 20 })- })-- it('gives everything to this scanner when the fleet is empty', () => {- expect(splitProjectedPct(30, 100, 0)).toEqual({ thisScannerPct: 30, othersPct: 0 })- })-- it('defaults the share to zero (no division by zero) when both volumes are zero', () => {- expect(splitProjectedPct(30, 0, 0)).toEqual({ thisScannerPct: 0, othersPct: 30 })- })-})-describe('quotaUx', () => {it('returns nothing when no limit is configured', () => {expect(quotaUx(null)).toEqual({})diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.tsindex c98f2865f15a..09e62acc2b85 100644--- a/products/replay_vision/frontend/utils/quotaProjection.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.ts@@ -19,10 +19,8 @@ export interface QuotaProjection {status: QuotaStatusexhausted: booleancapReachDate: dayjs.Dayjs | null- /** Projected period-end spend as a rounded percentage of the limit; exceeds 100 on overshoot. */- percentLabel: numberresetsOn: string | null- /** Actual spend as a percentage of the limit; `QuotaMeterBar` clamps for display. */+ /** Actual spend as a percentage of the limit; `QuotaMeterBar` rescales past 100 for display. */usedPct: number/** The slice of `usedPct` covered by non-billable credits, so the meter can shade it separately. */usedFreePct: number@@ -34,7 +32,6 @@ const EMPTY: QuotaProjection = {status: 'safe',exhausted: false,capReachDate: null,- percentLabel: 0,resetsOn: null,usedPct: 0,usedFreePct: 0,@@ -92,7 +89,6 @@ export function projectQuota(...EMPTY,status: 'danger',exhausted: quota.exhausted,- percentLabel: 100,usedPct: 100,resetsOn: quota.period_end ? dayjs(quota.period_end).format('MMMM D') : null,}@@ -124,7 +120,6 @@ export function projectQuota(status,exhausted: quota.exhausted,capReachDate,- percentLabel: Math.round(projectedPeriodEndRatio * 100),resetsOn,usedPct: (used / cap) * 100,usedFreePct: (Math.min(used, quota.free_monthly_credits) / cap) * 100,@@ -141,18 +136,6 @@ export function daysUntilCapReached(projection: QuotaProjection): number | nullreturn days <= IMMINENT_CAP_DAYS ? days : null}-/** Apportion a projected percentage between this scanner and the rest of the fleet by monthly credit volume. */-export function splitProjectedPct(- projectedPct: number,- thisScannerMonthly: number,- othersMonthly: number-): { thisScannerPct: number; othersPct: number } {- const combined = thisScannerMonthly + othersMonthly- const thisScannerPct = combined > 0 ? (projectedPct * thisScannerMonthly) / combined : 0- // Exact complement so the two segments always sum to the full projection.- return { thisScannerPct, othersPct: projectedPct - thisScannerPct }-}-/*** Disabled-reason / tooltip for scan triggers based on the monthly credit limit.* Assumes block-only overage policy; revisit when `usage_based` lands so we don't disable on metered orgs.diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.tsindex d5583fea5d41..453dcdfed557 100644--- a/products/replay_vision/frontend/utils/quotaTestUtils.ts+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts@@ -10,6 +10,8 @@ export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaAremaining: 10_000,exhausted: false,projected_monthly_credits: 0,+ scanners_monthly_credits: 0,+ backfills_committed_credits: 0,free_monthly_credits: 2500,period_start: daysFromNow(-10),period_end: daysFromNow(20),diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 2a25ca689198..998c6a089a0b 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -293,6 +293,24 @@ tools:creates a new cohort. Use it anywhere cohorts work: funnel breakdowns, retention, survey targeting,experiment exclusion. Fails when the window has no users or none resolve to a person profile.feature_flag: replay-vision+ vision-scanners-backfills-cancel-create:+ operation: vision_scanners_backfills_cancel_create+ enabled: false+ vision-scanners-backfills-create:+ operation: vision_scanners_backfills_create+ enabled: false+ vision-scanners-backfills-estimate-create:+ operation: vision_scanners_backfills_estimate_create+ enabled: false+ vision-scanners-backfills-list:+ operation: vision_scanners_backfills_list+ enabled: false+ vision-scanners-backfills-resume-create:+ operation: vision_scanners_backfills_resume_create+ enabled: false+ vision-scanners-backfills-retrieve:+ operation: vision_scanners_backfills_retrieve+ enabled: falsevision-scanners-bulk-observe-create:operation: vision_scanners_bulk_observe_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0f4f6ee4fa58..a960b4f8c71c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -10318,6 +10318,47 @@ export namespace Schemas {AzureBlob: 'AzureBlob',} as const;+ export interface BackfillEstimateResponse {+ /** Upper bound on the sessions the backfill would scan, after sampling and quality filters and excluding sessions this scanner already reported an observation for. */+ total_sessions: number;+ /** Cost ceiling in credits (1 credit = $0.01): total_sessions x credits_per_observation. Actual spend lands under it: sessions already tried, expired recordings, and failures are not billed. */+ total_credits: number;+ /** Per-observation credit price at the scanner's current model. */+ credits_per_observation: number;+ /**+ * Credits left in the org's monthly quota; null when the org is uncapped.+ * @nullable+ */+ credits_remaining: number | null;+ /** The window lower bound the estimate covered. */+ window_start: string;+ /** The window upper bound after clamping to now. */+ window_end: string;+ }++ /**+ * * `running` - Running+ * * `paused_quota` - Paused (quota)+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ */+ export type BackfillStatusEnum = typeof BackfillStatusEnum[keyof typeof BackfillStatusEnum];+++ export const BackfillStatusEnum = {+ Running: 'running',+ PausedQuota: 'paused_quota',+ Completed: 'completed',+ Cancelled: 'cancelled',+ } as const;++ export interface BackfillWindow {+ /** Inclusive lower bound of the historical window to scan. */+ window_start: string;+ /** Exclusive upper bound of the window; clamped server-side to now. */+ window_end: string;+ }+/*** * `AED` - AED* * `AFN` - AFN@@ -27672,6 +27713,8 @@ export namespace Schemas {estimated_credits_per_month: number;/** Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */other_enabled_scanners_monthly_credits: number;+ /** Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own segment instead of adding it to a per-month total. */+ active_backfill_credits: number;/** Sampling rate applied to the projection. Echoed from the request. */sampling_rate: number;}@@ -45194,6 +45237,7 @@ export namespace Schemas {* * `schedule` - Schedule* * `on_demand` - On demand* * `retry` - Retry+ * * `backfill` - Backfill*/export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];@@ -45202,6 +45246,7 @@ export namespace Schemas {Schedule: 'schedule',OnDemand: 'on_demand',Retry: 'retry',+ Backfill: 'backfill',} as const;/**@@ -47897,14 +47942,20 @@ export namespace Schemas {readonly scanner_snapshot: ScannerSnapshot | null;/** Result data persisted on success; null until the observation succeeds. */readonly scanner_result: ScannerResult | null;- /** Whether this observation came from the schedule, an on-demand request, or a retry of a failed or ineligible observation.+ /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.** * `schedule` - Schedule* * `on_demand` - On demand- * * `retry` - Retry */+ * * `retry` - Retry+ * * `backfill` - Backfill */readonly triggered_by: ObservationTriggerEnum;/** User who triggered an on-demand observation; null for scheduled observations. */readonly triggered_by_user: UserBasic | null;+ /**+ * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.+ * @nullable+ */+ readonly backfill_id: string | null;/*** Distinct id of the person in the recorded session (the subject being watched); null if unknown.* @nullable@@ -47943,6 +47994,46 @@ export namespace Schemas {results: ReplayObservation[];}+ export interface ReplayScannerBackfill {+ readonly id: string;+ readonly status: BackfillStatusEnum;+ /** Inclusive lower bound of the historical window to scan. */+ readonly window_start: string;+ /** Exclusive upper bound of the window; clamped to now at creation. */+ readonly window_end: string;+ /** Unobserved candidates enumerated at creation; the ceiling is total_count x credits_per_observation. */+ readonly total_count: number;+ readonly dispatched_count: number;+ /** Candidates the walk stepped over because this scanner had already tried them. Counted at creation but never dispatched, so progress and remaining spend both have to account for them. */+ readonly skipped_count: number;+ /** Per-observation credit price frozen at creation from the snapshot model. */+ readonly credits_per_observation: number;+ /** Observations from this backfill that succeeded. */+ readonly succeeded_count: number;+ /** Observations from this backfill that failed. */+ readonly failed_count: number;+ /** Sessions that turned out ineligible (too short, expired recording, ...). */+ readonly ineligible_count: number;+ /** Observations from this backfill still pending or running. */+ readonly in_flight_count: number;+ readonly created_by: UserBasic | null;+ readonly created_at: string;+ /**+ * When the backfill reached a terminal status (completed or cancelled).+ * @nullable+ */+ readonly finished_at: string | null;+ }++ export interface PaginatedReplayScannerBackfillList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: ReplayScannerBackfill[];+ }+/*** * `google` - Google*/@@ -76585,8 +76676,12 @@ export namespace Schemas {readonly period_start: string;/** First moment of the next quota period (UTC); the current period's exclusive upper bound. */readonly period_end: string;- /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */+ /** `scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; prefer the two components when pro-rating, since only the scanner half is a monthly rate. */readonly projected_monthly_credits: number;+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */+ readonly scanners_monthly_credits: number;+ /** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */+ readonly backfills_committed_credits: number;/** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */readonly free_monthly_credits: number;}@@ -87977,6 +88072,10 @@ export namespace Schemas {};export type VisionObservationsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string;/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -88010,7 +88109,7 @@ export namespace Schemas {*/tags?: string;/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string;/**@@ -88083,7 +88182,22 @@ export namespace Schemas {window_days?: number;};+ export type VisionScannersBackfillsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type VisionScannersObservationsListParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string;/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -88125,7 +88239,7 @@ export namespace Schemas {*/tags?: string;/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string;/**@@ -88135,6 +88249,10 @@ export namespace Schemas {};export type VisionScannersObservationsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string;/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -88168,7 +88286,7 @@ export namespace Schemas {*/tags?: string;/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string;/**@@ -88178,6 +88296,10 @@ export namespace Schemas {};export type VisionScannersObservationsStatsRetrieveParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string;/*** Only observations created at or after this time. Accepts ISO 8601 or a relative date like `-7d`; values without an explicit offset are interpreted in the project's timezone.*/@@ -88211,7 +88333,7 @@ export namespace Schemas {*/tags?: string;/**- * Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.*/triggered_by?: string;/**diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 90c489019558..5860f0e29244 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -492,6 +492,7 @@ export const VisionObservationsRetrieveParams = /* @__PURE__ */ zod.object({})export const VisionObservationsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ backfill_id: zod.string().optional().describe('Only observations dispatched by this backfill.'),date_from: zod.string().optional()@@ -534,7 +535,9 @@ export const VisionObservationsRetrieveQueryParams = /* @__PURE__ */ zod.object(triggered_by: zod.string().optional()- .describe('Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.'),+ .describe(+ 'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'+ ),verdict: zod.string().optional()@@ -1016,6 +1019,7 @@ export const VisionScannersObservationsListParams = /* @__PURE__ */ zod.object({})export const VisionScannersObservationsListQueryParams = /* @__PURE__ */ zod.object({+ backfill_id: zod.string().optional().describe('Only observations dispatched by this backfill.'),date_from: zod.string().optional()@@ -1060,7 +1064,9 @@ export const VisionScannersObservationsListQueryParams = /* @__PURE__ */ zod.objtriggered_by: zod.string().optional()- .describe('Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.'),+ .describe(+ 'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'+ ),verdict: zod.string().optional()@@ -1081,6 +1087,7 @@ export const VisionScannersObservationsRetrieveParams = /* @__PURE__ */ zod.obje})export const VisionScannersObservationsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ backfill_id: zod.string().optional().describe('Only observations dispatched by this backfill.'),date_from: zod.string().optional()@@ -1123,7 +1130,9 @@ export const VisionScannersObservationsRetrieveQueryParams = /* @__PURE__ */ zodtriggered_by: zod.string().optional()- .describe('Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.'),+ .describe(+ 'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'+ ),verdict: zod.string().optional()@@ -1143,6 +1152,7 @@ export const VisionScannersObservationsStatsRetrieveParams = /* @__PURE__ */ zod})export const VisionScannersObservationsStatsRetrieveQueryParams = /* @__PURE__ */ zod.object({+ backfill_id: zod.string().optional().describe('Only observations dispatched by this backfill.'),date_from: zod.string().optional()@@ -1185,7 +1195,9 @@ export const VisionScannersObservationsStatsRetrieveQueryParams = /* @__PURE__ *triggered_by: zod.string().optional()- .describe('Filter by trigger source (schedule, on_demand, or retry). Accepts a comma-separated list.'),+ .describe(+ 'Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.'+ ),verdict: zod.string().optional()diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex 149ba118f7e5..f9a719062b96 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -338,6 +338,7 @@ const visionObservationsRetrieve = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/observations/${encodeURIComponent(String(params.id))}/`,query: {+ backfill_id: params.backfill_id,date_from: params.date_from,date_to: params.date_to,labeled: params.labeled,@@ -628,6 +629,7 @@ const visionScannersObservationsGet = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/observations/${encodeURIComponent(String(params.id))}/`,query: {+ backfill_id: params.backfill_id,date_from: params.date_from,date_to: params.date_to,labeled: params.labeled,@@ -663,6 +665,7 @@ const visionScannersObservationsList = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/observations/`,query: {+ backfill_id: params.backfill_id,date_from: params.date_from,date_to: params.date_to,labeled: params.labeled,@@ -711,6 +714,7 @@ const visionScannersObservationsStats = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/observations/stats/`,query: {+ backfill_id: params.backfill_id,date_from: params.date_from,date_to: params.date_to,labeled: params.labeled,