: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
refactor(replay-vision): extract scan orchestration into a service (#78744)
Tue Haulund5b1e0c04465d
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 6cf8ea3a07fb..4fdea43b3406 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -5,7 +5,7 @@ from typing import Any, cast, get_argsfrom zoneinfo import ZoneInfofrom django.conf import settings-from django.db import IntegrityError, transaction+from django.db import transactionfrom django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, Whenfrom django.db.models.fields.json import KeyTextTransform, KeyTransformfrom django.db.models.functions import Cast@@ -41,16 +41,7 @@ from products.replay_vision.backend.api.errors import ReplayVisionErrorSerializefrom products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enumfrom products.replay_vision.backend.api.observation_progress import stream_observation_progressfrom products.replay_vision.backend.api.observation_stats import compute_observation_stats-from products.replay_vision.backend.api.trigger import (- WorkflowStartOutcome,- check_observation_quota,- check_team_in_flight_capacity,- claim_apply_scanner_slot,- start_apply_scanner_workflow,-)-from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.consent import is_ai_data_processing_approved-from products.replay_vision.backend.enqueue_claims import release_enqueue_claimfrom products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXTfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_observation import (@@ -65,6 +56,7 @@ from products.replay_vision.backend.scanner_access import (scanner_for_reading_observations,scanners_for_reading_observations,)+from products.replay_vision.backend.scanning import RetryOutcome, retry_observationfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictfrom products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshotfrom products.tasks.backend.facade import api as tasks_facade@@ -915,85 +907,32 @@ class ReplayObservationViewSet(scanner = getattr(self, "_scanner_for_url_cache", None) or observation.scanner# Retry writes to the scanner; the session route's get_object only object-checks the observation row.self.check_object_permissions(self.request, scanner)- session_id = observation.session_id- original_pk = observation.pk- original_created_at = observation.created_at- # Ineligible is retryable because some gates are timing artifacts: the recording or its snapshots can- # finish ingesting after the scan ran (see IneligibleSessionKind.NO_SNAPSHOTS). Without this, the- # UNIQUE(scanner, session_id) row would lock the session out of that scanner forever.+ # Status first, matching the order before this moved: it needs no query, and a succeeded+ # observation should hear that it isn't retryable rather than about consent.if observation.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):raise ValidationError("Only failed or ineligible observations can be retried.")- # Gate consent before deleting the row: the replacement workflow fails closed at create time when- # consent is off, and the sweep never revisits past sessions, so the delete would leave nothing behind.+ # Consent is gated before the row is touched: the replacement workflow fails closed at create+ # time when consent is off, and the sweep never revisits past sessions, so a delete would leave+ # nothing behind.if not is_ai_data_processing_approved(self.team.id):raise ValidationError("AI data processing is turned off for this organization, so the scan can't run. ""An organization admin can turn it on in organization settings.")- # Advisory, and deliberately outside the lock below: the atomic claim is the authoritative gate,- # and these two read enough to be worth keeping off a held row lock.- check_observation_quota(self.team.organization_id, observation_credits_for_model(scanner.model))- check_team_in_flight_capacity(self.team.id)- # Locked so two concurrent retries can't both pass the status check and both delete the row.- with transaction.atomic():- locked = ReplayObservation.objects.select_for_update().get(pk=original_pk, team_id=self.team_id)- if locked.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):- raise ValidationError("Only failed or ineligible observations can be retried.")- # Captured before the delete cascades it away: a run that never starts has to put the team's- # rating back with the row, not just the row.- original_label = ReplayObservationLabel.objects.filter(- observation_id=original_pk, team_id=locked.team_id- ).first()- label_created_at = original_label.created_at if original_label else None- label_updated_at = original_label.updated_at if original_label else None- # Claimed before the delete so a capped retry never touches the row, and so never cascades- # away the observation's shared label for a request that changes nothing.- workflow_id, claimed = claim_apply_scanner_slot(scanner, session_id)- if not claimed:- raise Throttled(detail="This team is at its in-flight observation limit. Try again in a few minutes.")- try:- # Free the UNIQUE(scanner, session_id) slot; the ledger is immutable, so the failed attempt- # stays counted.- locked.delete()- except Exception:- release_enqueue_claim(- team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id, immediately=True- )- raise- workflow_id, outcome = start_apply_scanner_workflow(- scanner,- session_id,- triggered_by_user_id=cast(User, request.user).id,- trigger=ObservationTrigger.RETRY,- slot_already_claimed=True,- )- if outcome is not WorkflowStartOutcome.STARTED:- # The replacement run never started, so restore the original row and its rating instead of leaving- # the recording looking unscanned and the team's feedback gone.- try:- with transaction.atomic():- observation.pk = original_pk- observation.save(force_insert=True)- ReplayObservation.objects.filter(pk=original_pk, team_id=observation.team_id).update(- created_at=original_created_at- )- if original_label is not None:- original_label.save(force_insert=True)- # auto_now_add/auto_now stamp the insert with now; the rating happened earlier.- ReplayObservationLabel.objects.filter(pk=original_label.pk, team_id=observation.team_id).update(- created_at=label_created_at, updated_at=label_updated_at- )- except IntegrityError:- # A run we couldn't start is already persisting its own row for this (scanner, session);- # the recording isn't stranded, so report it as still finishing rather than 500ing.- outcome = WorkflowStartOutcome.ALREADY_RUNNING- if outcome is WorkflowStartOutcome.ALREADY_RUNNING:- # The prior run is still closing, so its deterministic id blocks the restart and no new row will appear.+ outcome, workflow_id = retry_observation(observation=observation, user=cast(User, request.user))+ if outcome is RetryOutcome.NOT_RETRYABLE:+ # Re-read under the row lock disagreed with the check above; a racing retry won.+ raise ValidationError("Only failed or ineligible observations can be retried.")+ if outcome is RetryOutcome.CAPPED:+ raise Throttled(detail="This team is at its in-flight observation limit. Try again in a few minutes.")+ if outcome is RetryOutcome.ALREADY_RUNNING:+ # The prior run is still closing, so its deterministic id blocks the restart and no new row+ # will appear.return Response({"detail": "The previous run is still finishing. Retry again in a moment."},status=status.HTTP_409_CONFLICT,)- if outcome is WorkflowStartOutcome.FAILED:+ if outcome is RetryOutcome.FAILED:# `detail` (not `error`) so ApiError carries the message into the frontend toast.return Response({"detail": "Failed to start the retry. The failed observation was kept; retry again in a moment."},diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.pyindex f05f4983153a..e1d3d74a8875 100644--- a/products/replay_vision/backend/api/prompt_suggestions.py+++ b/products/replay_vision/backend/api/prompt_suggestions.py@@ -25,7 +25,6 @@ from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottlefrom posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.search_attributes import POSTHOG_TEAM_ID_KEY-from products.replay_vision.backend.api.scanners import _scanner_config_error_messagefrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermissionfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation@@ -48,6 +47,7 @@ from products.replay_vision.backend.prompt_suggestions import (labels_fingerprint,)from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.scanner_config import scanner_config_errorfrom products.replay_vision.backend.temporal.constants import (EVALUATE_PROMPT_SUGGESTION_WORKFLOW_NAME,build_evaluate_prompt_suggestion_workflow_id,@@ -366,7 +366,7 @@ class ReplayScannerPromptSuggestionViewSet(config = {**(scanner.scanner_config or {}), "prompt": suggestion.suggested_prompt}# Same validation as the scanner edit endpoint: an oversized or malformed LLM rewrite# must not land in the config that every future observation snapshots.- message = _scanner_config_error_message(ScannerType(scanner.scanner_type), config)+ message = scanner_config_error(ScannerType(scanner.scanner_type), config)if message:raise ValidationError(f"This recommendation can't be applied: {message}")scanner.scanner_config = config@@ -406,7 +406,7 @@ class ReplayScannerPromptSuggestionViewSet(# A malformed edited config must be rejected before it charges credits on runs that can't succeed,# matching the validation apply runs before it writes the config.if edited_config is not None:- message = _scanner_config_error_message(ScannerType(scanner.scanner_type), edited_config)+ message = scanner_config_error(ScannerType(scanner.scanner_type), edited_config)if message:raise ValidationError(f"This config can't be tested: {message}")rated_count = self._rated_count(scanner)diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 27d2fb54d661..5d3dcc7c0c4a 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,4 +1,3 @@-from dataclasses import dataclassfrom typing import Any, NoReturn, castfrom django.db import IntegrityError@@ -49,10 +48,6 @@ from products.replay_vision.backend.api.trigger import ()from products.replay_vision.backend.billing import observation_credits_case, observation_credits_for_modelfrom products.replay_vision.backend.digest import provision_scanner_digest-from products.replay_vision.backend.enqueue_claims import (- pending_enqueue_claims_for_scanner,- pending_enqueue_claims_for_team,-)from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission, is_replay_vision_actions_enabledfrom products.replay_vision.backend.feedback_themes import cached_feedback_themesfrom products.replay_vision.backend.impact import (@@ -60,9 +55,7 @@ from products.replay_vision.backend.impact import (compute_scanner_impact,create_affected_cohort,)-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,ObservationStatus,ObservationTrigger,ReplayObservation,@@ -84,19 +77,14 @@ from products.replay_vision.backend.queries import ()from products.replay_vision.backend.quota import (ScannerSpend,- compute_quota_snapshot,credits_used_by_scanner,current_period_bounds,sum_enabled_scanner_estimated_credits,)+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_scannerfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags-from products.replay_vision.backend.tags import slugify_tag-from products.replay_vision.backend.temporal.constants import (- MAX_IN_FLIGHT_APPLIES_PER_SCANNER,- MAX_IN_FLIGHT_APPLIES_PER_TEAM,- MAX_SESSION_ID_LENGTH,-)-from products.replay_vision.backend.temporal.scanners import validate_scanner_config+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")@@ -153,53 +141,6 @@ def _refresh_estimate_fail_soft(scanner: ReplayScanner) -> None:logger.exception("replay_vision.estimate_refresh_failed", scanner_id=str(scanner.id))-def _scanner_config_error_message(scanner_type: ScannerType, scanner_config: Any) -> str | None:- if not isinstance(scanner_config, dict):- return "Scanner configuration must be a JSON object."- prompt = scanner_config.get("prompt")- if not isinstance(prompt, str) or not prompt.strip():- return "Prompt is required."- if len(prompt) > _MAX_PROMPT_LENGTH:- return f"Prompt can be at most {_MAX_PROMPT_LENGTH:,} characters."- if scanner_type == ScannerType.CLASSIFIER:- tags = scanner_config.get("tags") or []- if len(tags) == 0:- return "Tag vocabulary must have at least one tag."- if len(tags) > _MAX_TAGS:- return f"Tag vocabulary can have at most {_MAX_TAGS} tags."- if any(not isinstance(t, str) or not t.strip() for t in tags):- return "Tags can't be blank."- if any(len(t) > _MAX_TAG_LENGTH for t in tags):- return f"Tags can be at most {_MAX_TAG_LENGTH} characters."- # Uniqueness on the slug, since filtering/stripping/search all compare slugified tags downstream.- slugged: dict[str, str] = {}- for t in tags:- slug = slugify_tag(t)- if not slug:- return "Tags must contain letters or numbers."- if slug in slugged:- return f"Tags must be unique: '{slugged[slug]}' and '{t}' are the same tag."- slugged[slug] = t- if scanner_type == ScannerType.SCORER:- scale = scanner_config.get("scale")- if not isinstance(scale, dict):- return "Scale is required."- min_v, max_v = scale.get("min"), scale.get("max")- if not isinstance(min_v, (int, float)) or not isinstance(max_v, (int, float)):- return "Scale min and max must be numbers."- if min_v >= max_v:- return "Scale max must be greater than min."- try:- scanner = validate_scanner_config(scanner_config=scanner_config, scanner_type=scanner_type)- except (ValueError, PydanticValidationError):- return "Scanner configuration is invalid."- # The pydantic models ignore extra keys — reject here so typos and junk don't snapshot onto every observation.- unknown = set(scanner_config) - set(type(scanner).model_fields)- if unknown:- return f"Unknown scanner configuration keys: {', '.join(sorted(unknown))}."- return None--class FeedbackThemeSessionSerializer(serializers.Serializer):observation_id = serializers.CharField(help_text="Observation whose feedback comment backs this theme.")session_id = serializers.CharField(help_text="Session recording the feedback comment was about.")@@ -457,7 +398,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modescanner_config = attrs.get("scanner_config", getattr(self.instance, "scanner_config", None))if scanner_type is None:return # Upstream `scanner_type` ChoiceField rejects this on create; PATCH with no instance is unreachable.- message = _scanner_config_error_message(ScannerType(scanner_type), scanner_config)+ message = scanner_config_error(ScannerType(scanner_type), scanner_config)if message is not None:raise serializers.ValidationError({"scanner_config": message})@@ -694,21 +635,7 @@ class ObserveResponseSerializer(serializers.Serializer):# One request can start at most this many scans. Bounds the fan-out of a single bulk trigger well# under the in-flight caps; the frontend selects from one loaded page, so this is rarely the binding# limit — the concurrency headroom usually is.-BULK_OBSERVE_MAX_SESSIONS = 200---@dataclass(frozen=True, kw_only=True)-class _Headroom:- """What `_scan_headroom` worked out, kept together so a request computes it once.-- Keyword-only because `team_rows` and `scanner_rows` are both counts of in-flight observations, and- swapping them would silently loosen one of the two caps.- """-- max_starts: int- skip_reason: str- team_rows: int- scanner_rows: int+BULK_OBSERVE_MAX_SESSIONS = MAX_SESSIONS_PER_SCANclass BulkObserveRequestSerializer(serializers.Serializer):@@ -821,7 +748,7 @@ class InlineScanRequestSerializer(serializers.Serializer):raise serializers.ValidationError({"scanner_config": "Set the prompt in `prompt`, not here."})# One config from here on, validated exactly like a saved scanner's. The key covers it whole.merged = {**config, "prompt": attrs["prompt"]}- message = _scanner_config_error_message(ScannerType(attrs["scanner_type"]), merged)+ message = scanner_config_error(ScannerType(attrs["scanner_type"]), merged)if message is not None:raise serializers.ValidationError({"scanner_config": message})attrs["scanner_config"] = merged@@ -1342,13 +1269,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, visession_ids = list(dict.fromkeys(body.validated_data["session_ids"]))user = cast(User, request.user)- started, results = self._start_observations(- scanner,- session_ids,- user,- headroom=self._scan_headroom(model=scanner.model, scanner=scanner),- finished=self._finished_sessions(scanner, session_ids),- )+ started, results = scan_existing_scanner(scanner=scanner, session_ids=session_ids, user=user)report_user_action(user,@@ -1410,38 +1331,24 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viscanner_config = body.validated_data["scanner_config"]model = body.validated_data["model"]- key = inline_scan_key(scanner_type=scanner_type, scanner_config=scanner_config, model=model)- scanner = find_inline_scanner(team=self.team, key=key)- headroom = self._scan_headroom(model=model, scanner=scanner)- if scanner is None:- # Mint only once something can actually start, so an org with no headroom doesn't leave a- # scanner behind for every question it was unable to answer.- if headroom.max_starts <= 0:- if headroom.skip_reason == "skipped_quota":- self._report_quota_exhausted(None, "inline")- return Response(- InlineScanResponseSerializer(- {- "scan_id": None,- "started": 0,- "results": [{"session_id": s, "scan_outcome": headroom.skip_reason} for s in session_ids],- }- ).data,- status=status.HTTP_202_ACCEPTED,- )- scanner = create_inline_scanner(- team=self.team,- key=key,- scanner_type=scanner_type,- scanner_config=scanner_config,- model=model,+ scan = run_inline_scan(+ team=self.team,+ user=user,+ session_ids=session_ids,+ scanner_type=scanner_type,+ scanner_config=scanner_config,+ model=model,+ )+ if scan.scanner is None:+ # Nothing started and nothing already existed, so there is no id to read results through.+ # Key off the outcomes: the in-flight cap can bind here too, and that is not exhaustion.+ if any(result["scan_outcome"] == "skipped_quota" for result in scan.results):+ self._report_quota_exhausted(None, "inline")+ return Response(+ InlineScanResponseSerializer({"scan_id": None, "started": 0, "results": scan.results}).data,+ status=status.HTTP_202_ACCEPTED,)- # A scanner that did not exist a statement ago has no observations to have settled.- finished: frozenset[str] = frozenset()- else:- finished = self._finished_sessions(scanner, session_ids)-- started, results = self._start_observations(scanner, session_ids, user, headroom=headroom, finished=finished)+ scanner, started, results = scan.scanner, scan.started, scan.resultsreport_user_action(user,@@ -1463,79 +1370,6 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vistatus=status.HTTP_202_ACCEPTED,)- def _finished_sessions(self, scanner: ReplayScanner, session_ids: list[str]) -> frozenset[str]:- """Sessions this scanner already settled on.-- A terminal observation makes (scanner, session) permanently taken, so starting a workflow for one- would burn a run only to lose the INSERT and hand back the row we can already see.- """- return frozenset(- ReplayObservation.objects.filter(- scanner_id=scanner.id,- session_id__in=session_ids,- status__in=TERMINAL_STATUSES,- ).values_list("session_id", flat=True)- )-- def _start_observations(- self,- scanner: ReplayScanner,- session_ids: list[str],- user: User,- *,- headroom: _Headroom,- finished: frozenset[str],- ) -> tuple[int, list[dict[str, str]]]:- """Start a scan per session, as many as fit. Returns (started, per-session outcomes).-- "Scan what fits": the caller works out how many NEW scans can start once, up front, and passes it- in so one request takes the quota snapshot once. The tighter of the in-flight caps and the- remaining monthly quota bounds it; the loser names the skip reason so the user knows which limit- they hit. Decrementing a local counter as we start models each new in-flight row without- re-querying (a started scan consumes exactly one slot).- """- max_starts, skip_reason = headroom.max_starts, headroom.skip_reason- results: list[dict[str, str]] = []- started = 0- for session_id in session_ids:- # Checked before the cap so a settled session reports what it is rather than being- # reported as skipped, and consumes no headroom. `start_apply_scanner_workflow` enforces the- # same rule for callers that don't prefetch.- if session_id in finished:- results.append({"session_id": session_id, "scan_outcome": "already_scanned"})- continue- if started >= max_starts:- results.append({"session_id": session_id, "scan_outcome": skip_reason})- continue- _, outcome = start_apply_scanner_workflow(- scanner,- session_id,- triggered_by_user_id=user.id,- trigger=ObservationTrigger.ON_DEMAND,- # Row counts are this request's snapshot; the atomic claim inside makes racing- # requests visible to each other, which the snapshot alone cannot.- team_in_flight_rows=headroom.team_rows,- scanner_in_flight_rows=headroom.scanner_rows,- finished_sessions=finished,- )- if outcome is WorkflowStartOutcome.STARTED:- started += 1- results.append({"session_id": session_id, "scan_outcome": "started"})- elif outcome is WorkflowStartOutcome.ALREADY_SCANNED:- # The prefetched set was taken before the loop, so a session can settle mid-batch.- results.append({"session_id": session_id, "scan_outcome": "already_scanned"})- elif outcome is WorkflowStartOutcome.ALREADY_RUNNING:- # Already in flight — counted in the caps already, so it consumes no new headroom.- results.append({"session_id": session_id, "scan_outcome": "already_running"})- elif outcome is WorkflowStartOutcome.CAPPED:- # A racing request consumed the remaining slots, so the in-flight cap binds the rest.- results.append({"session_id": session_id, "scan_outcome": "skipped_limit"})- max_starts = started- skip_reason = "skipped_limit"- else:- results.append({"session_id": session_id, "scan_outcome": "failed"})- return started, results-def _report_quota_exhausted(self, scanner: ReplayScanner | None, trigger: str) -> None:"""A scan was blocked or capped by the org's monthly Replay vision credit limit.@@ -1553,48 +1387,6 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, virequest=self.request,)- def _scan_headroom(self, *, model: str, scanner: ReplayScanner | None) -> _Headroom:- """How many new scans can start, the reason once that's used up, and the row counts the- per-start slot claims reuse.-- `scanner=None` asks the same question for a config that has no scanner yet, so an inline scan can- decide whether minting one is worth it. The per-scanner terms are zero by definition there, which- is also why the caller can pass the answer straight into `_start_observations`.- """- team_in_flight = ReplayObservation.in_flight_for_team(self.team_id).count()- scanner_in_flight = 0- scanner_claims = 0- if scanner is not None:- scanner_in_flight = ReplayObservation.in_flight_for_team(self.team_id).filter(scanner_id=scanner.id).count()- scanner_claims = pending_enqueue_claims_for_scanner(scanner.id)- # Enqueued-but-not-yet-persisted scans hold claims instead of rows.- in_flight_limit = max(- 0,- min(- MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight - scanner_claims,- MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight - pending_enqueue_claims_for_team(self.team_id),- ),- )- snapshot = compute_quota_snapshot(self.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- # Report quota as the reason only when it's the strictly tighter limit.- if quota_limit < in_flight_limit:- return _Headroom(- max_starts=quota_limit,- skip_reason="skipped_quota",- team_rows=team_in_flight,- scanner_rows=scanner_in_flight,- )- return _Headroom(- max_starts=in_flight_limit,- skip_reason="skipped_limit",- team_rows=team_in_flight,- scanner_rows=scanner_in_flight,- )-@extend_schema(parameters=[ScannerImpactQuerySerializer], responses={200: ScannerImpactSerializer})@action(detail=True,diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.pynew file mode 100644index 000000000000..c0321b278dd4--- /dev/null+++ b/products/replay_vision/backend/scanner_config.py@@ -0,0 +1,63 @@+"""What a valid `scanner_config` looks like for each scanner type.++Its own module because both the API serializers and Max validate a config before saving or scanning+with it, and neither should import the other."""++from typing import Any++from pydantic import ValidationError as PydanticValidationError++from products.replay_vision.backend.models.replay_scanner import ScannerType+from products.replay_vision.backend.tags import slugify_tag+from products.replay_vision.backend.temporal.scanners import validate_scanner_config++_MAX_PROMPT_LENGTH = 20_000+_MAX_TAGS = 100+_MAX_TAG_LENGTH = 100+++def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str | None:+ if not isinstance(scanner_config, dict):+ return "Scanner configuration must be a JSON object."+ prompt = scanner_config.get("prompt")+ if not isinstance(prompt, str) or not prompt.strip():+ return "Prompt is required."+ if len(prompt) > _MAX_PROMPT_LENGTH:+ return f"Prompt can be at most {_MAX_PROMPT_LENGTH:,} characters."+ if scanner_type == ScannerType.CLASSIFIER:+ tags = scanner_config.get("tags") or []+ if len(tags) == 0:+ return "Tag vocabulary must have at least one tag."+ if len(tags) > _MAX_TAGS:+ return f"Tag vocabulary can have at most {_MAX_TAGS} tags."+ if any(not isinstance(t, str) or not t.strip() for t in tags):+ return "Tags can't be blank."+ if any(len(t) > _MAX_TAG_LENGTH for t in tags):+ return f"Tags can be at most {_MAX_TAG_LENGTH} characters."+ # Uniqueness on the slug, since filtering/stripping/search all compare slugified tags downstream.+ slugged: dict[str, str] = {}+ for t in tags:+ slug = slugify_tag(t)+ if not slug:+ return "Tags must contain letters or numbers."+ if slug in slugged:+ return f"Tags must be unique: '{slugged[slug]}' and '{t}' are the same tag."+ slugged[slug] = t+ if scanner_type == ScannerType.SCORER:+ scale = scanner_config.get("scale")+ if not isinstance(scale, dict):+ return "Scale is required."+ min_v, max_v = scale.get("min"), scale.get("max")+ if not isinstance(min_v, (int, float)) or not isinstance(max_v, (int, float)):+ return "Scale min and max must be numbers."+ if min_v >= max_v:+ return "Scale max must be greater than min."+ try:+ scanner = validate_scanner_config(scanner_config=scanner_config, scanner_type=scanner_type)+ except (ValueError, PydanticValidationError):+ return "Scanner configuration is invalid."+ # The pydantic models ignore extra keys — reject here so typos and junk don't snapshot onto every observation.+ unknown = set(scanner_config) - set(type(scanner).model_fields)+ if unknown:+ return f"Unknown scanner configuration keys: {', '.join(sorted(unknown))}."+ return Nonediff --git a/products/replay_vision/backend/scanning.py b/products/replay_vision/backend/scanning.pynew file mode 100644index 000000000000..dc87c33d7ab3--- /dev/null+++ b/products/replay_vision/backend/scanning.py@@ -0,0 +1,359 @@+"""Starting scans, independent of who asked.++The API and Max both need to answer the same questions before a scan runs: how many new scans fit under+the in-flight caps and the monthly credit budget, which sessions are already settled, and which scanner+an inline config resolves to. That logic lives here so there is one copy of it, and callers are left to+translate the outcome into their own shape (a DRF response, a sentence for a chat).++Nothing here checks consent or access. Callers do that, because the answer differs: the API raises, Max+explains.+"""++from dataclasses import dataclass+from enum import Enum+from typing import Any++from django.db import IntegrityError, transaction++from posthog.models.team import Team+from posthog.models.user import User++from products.replay_vision.backend.billing import observation_credits_for_model+from products.replay_vision.backend.enqueue_claims import (+ pending_enqueue_claims_for_scanner,+ pending_enqueue_claims_for_team,+ release_enqueue_claim,+)+from products.replay_vision.backend.inline_scan import create_inline_scanner, find_inline_scanner, inline_scan_key+from products.replay_vision.backend.models.replay_observation import TERMINAL_STATUSES, ReplayObservation+from 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.scanner_config import scanner_config_error+from products.replay_vision.backend.temporal.constants import (+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,+ build_apply_scanner_workflow_id,+)++# One page of recordings. Above this the in-flight caps bind long before the batch does.+MAX_SESSIONS_PER_SCAN = 200+++@dataclass(frozen=True, kw_only=True)+class ScanHeadroom:+ """What `scan_headroom` worked out, kept together so a request computes it once.++ Keyword-only because `team_rows` and `scanner_rows` are both counts of in-flight observations, and+ swapping them would silently loosen one of the two caps.+ """++ max_starts: int+ skip_reason: str+ team_rows: int+ scanner_rows: int+++@dataclass(frozen=True, kw_only=True)+class InlineScanResult:+ """`scanner` is None when nothing could start and none existed, so there is nothing to read back."""++ scanner: ReplayScanner | None+ started: int+ results: list[dict[str, str]]+++def scan_headroom(*, team: Team, model: str, scanner: ReplayScanner | None) -> ScanHeadroom:+ """How many new scans can start, the reason once that's used up, and the row counts the per-start+ slot claims reuse.++ `scanner=None` asks the same question for a config that has no scanner yet, so an inline scan can+ decide whether minting one is worth it. The per-scanner terms are zero by definition there, which is+ also why the caller can pass the answer straight into `start_observations`.+ """+ team_in_flight = ReplayObservation.in_flight_for_team(team.id).count()+ scanner_in_flight = 0+ scanner_claims = 0+ if scanner is not None:+ scanner_in_flight = ReplayObservation.in_flight_for_team(team.id).filter(scanner_id=scanner.id).count()+ scanner_claims = pending_enqueue_claims_for_scanner(scanner.id)+ # Enqueued-but-not-yet-persisted scans hold claims instead of rows.+ in_flight_limit = max(+ 0,+ min(+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight - scanner_claims,+ MAX_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+ # Report quota as the reason only when it's the strictly tighter limit.+ if quota_limit < in_flight_limit:+ return ScanHeadroom(+ max_starts=quota_limit,+ skip_reason="skipped_quota",+ team_rows=team_in_flight,+ scanner_rows=scanner_in_flight,+ )+ return ScanHeadroom(+ max_starts=in_flight_limit,+ skip_reason="skipped_limit",+ team_rows=team_in_flight,+ scanner_rows=scanner_in_flight,+ )+++def finished_sessions(scanner: ReplayScanner, session_ids: list[str]) -> frozenset[str]:+ """Sessions this scanner already settled on.++ A terminal observation makes (scanner, session) permanently taken, so starting a workflow for one+ would burn a run only to lose the INSERT and hand back the row we can already see.+ """+ return frozenset(+ ReplayObservation.objects.filter(+ scanner_id=scanner.id,+ session_id__in=session_ids,+ status__in=TERMINAL_STATUSES,+ ).values_list("session_id", flat=True)+ )+++def start_observations(+ *,+ scanner: ReplayScanner,+ session_ids: list[str],+ user: User,+ headroom: ScanHeadroom,+ finished: frozenset[str],+) -> tuple[int, list[dict[str, str]]]:+ """Start a scan per session, as many as fit. Returns (started, per-session outcomes).++ "Scan what fits": the caller works out how many NEW scans can start once, up front, and passes it in+ so a request takes the quota snapshot only once. The tighter of the in-flight caps and the remaining+ monthly quota bounds it; the loser names the skip reason so the user knows which limit they hit.+ Decrementing a local counter as we start models each new in-flight row without re-querying (a+ started scan consumes exactly one slot).+ """+ # Imported here to break the cycle: trigger imports quota, which imports prompt_evaluation, which+ # reaches temporal, whose activities import this module.+ from products.replay_vision.backend.api.trigger import ( # noqa: PLC0415+ WorkflowStartOutcome,+ start_apply_scanner_workflow,+ )+ from products.replay_vision.backend.models.replay_observation import ObservationTrigger # noqa: PLC0415++ max_starts, skip_reason = headroom.max_starts, headroom.skip_reason+ results: list[dict[str, str]] = []+ started = 0+ for session_id in session_ids:+ # Checked before the cap so a settled session reports what it is rather than being reported as+ # skipped, and consumes no headroom. `start_apply_scanner_workflow` enforces the same rule for+ # callers that don't prefetch.+ if session_id in finished:+ results.append({"session_id": session_id, "scan_outcome": "already_scanned"})+ continue+ if started >= max_starts:+ results.append({"session_id": session_id, "scan_outcome": skip_reason})+ continue+ _, outcome = start_apply_scanner_workflow(+ scanner,+ session_id,+ triggered_by_user_id=user.id,+ trigger=ObservationTrigger.ON_DEMAND,+ # Row counts are this request's snapshot; the atomic claim inside makes racing requests+ # visible to each other, which the snapshot alone cannot.+ team_in_flight_rows=headroom.team_rows,+ scanner_in_flight_rows=headroom.scanner_rows,+ finished_sessions=finished,+ )+ if outcome is WorkflowStartOutcome.STARTED:+ started += 1+ results.append({"session_id": session_id, "scan_outcome": "started"})+ elif outcome is WorkflowStartOutcome.ALREADY_SCANNED:+ # The prefetched set was taken before the loop, so a session can settle mid-batch.+ results.append({"session_id": session_id, "scan_outcome": "already_scanned"})+ elif outcome is WorkflowStartOutcome.ALREADY_RUNNING:+ # Already in flight — counted in the caps already, so it consumes no new headroom.+ results.append({"session_id": session_id, "scan_outcome": "already_running"})+ elif outcome is WorkflowStartOutcome.CAPPED:+ # A racing request consumed the remaining slots, so the in-flight cap binds the rest.+ results.append({"session_id": session_id, "scan_outcome": "skipped_limit"})+ max_starts = started+ skip_reason = "skipped_limit"+ else:+ results.append({"session_id": session_id, "scan_outcome": "failed"})+ return started, results+++def scan_existing_scanner(+ *, scanner: ReplayScanner, session_ids: list[str], user: User+) -> tuple[int, list[dict[str, str]]]:+ """Point a saved scanner at named sessions."""+ return start_observations(+ scanner=scanner,+ session_ids=session_ids,+ user=user,+ headroom=scan_headroom(team=scanner.team, model=scanner.model, scanner=scanner),+ finished=finished_sessions(scanner, session_ids),+ )+++def run_inline_scan(+ *,+ team: Team,+ user: User,+ session_ids: list[str],+ scanner_type: ScannerType,+ scanner_config: dict[str, Any],+ model: str,+) -> InlineScanResult:+ """Scan named sessions against a config nobody saved (see `inline_scan.py` for why a scanner exists).++ Raises ValueError on a config or batch the API layer would have rejected. Enforced here rather than+ only in the serializer because the config is persisted on the scanner and copied into every+ observation snapshot, so a caller that skips DRF must not be able to write one.+ """+ if len(session_ids) > MAX_SESSIONS_PER_SCAN:+ raise ValueError(f"At most {MAX_SESSIONS_PER_SCAN} sessions can be scanned at once.")+ config_error = scanner_config_error(scanner_type, scanner_config)+ if config_error is not None:+ raise ValueError(config_error)+ key = inline_scan_key(scanner_type=scanner_type, scanner_config=scanner_config, model=model)+ scanner = find_inline_scanner(team=team, key=key)+ headroom = scan_headroom(team=team, model=model, scanner=scanner)+ if scanner is None:+ # Mint only once something can actually start, so an org with no headroom doesn't leave a+ # scanner behind for every question it was unable to answer.+ if headroom.max_starts <= 0:+ return InlineScanResult(+ scanner=None,+ started=0,+ results=[{"session_id": s, "scan_outcome": headroom.skip_reason} for s in session_ids],+ )+ scanner = create_inline_scanner(+ team=team,+ key=key,+ scanner_type=scanner_type,+ scanner_config=scanner_config,+ model=model,+ )+ # A scanner that did not exist a statement ago has no observations to have settled.+ finished: frozenset[str] = frozenset()+ else:+ finished = finished_sessions(scanner, session_ids)++ started, results = start_observations(+ scanner=scanner, session_ids=session_ids, user=user, headroom=headroom, finished=finished+ )+ return InlineScanResult(scanner=scanner, started=started, results=results)+++class RetryOutcome(Enum):+ STARTED = "started"+ # Succeeded observations already have their answer; only failed and ineligible ones are retryable.+ NOT_RETRYABLE = "not_retryable"+ # The prior run is still closing, so its deterministic workflow id blocks the restart.+ ALREADY_RUNNING = "already_running"+ CAPPED = "capped"+ FAILED = "failed"+++def retry_observation(*, observation: ReplayObservation, user: User) -> tuple[RetryOutcome, str]:+ """Delete a failed or ineligible observation and scan the same recording again.++ The row has to go because UNIQUE(scanner, session_id) would otherwise lock the session out of that+ scanner forever, and the delete cascades the team's rating with it. So the rating is captured first+ and put back, timestamps and all, whenever the replacement run doesn't start: a retry that changes+ nothing must leave the recording exactly as it found it.+ """+ from products.replay_vision.backend.api.trigger import ( # noqa: PLC0415+ WorkflowStartOutcome,+ check_observation_quota,+ check_team_in_flight_capacity,+ claim_apply_scanner_slot,+ start_apply_scanner_workflow,+ )+ from products.replay_vision.backend.models.replay_observation import ( # noqa: PLC0415+ ObservationStatus,+ ObservationTrigger,+ )+ from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel # noqa: PLC0415++ scanner = observation.scanner+ session_id = observation.session_id+ original_pk = observation.pk+ original_created_at = observation.created_at+ # Ineligible is retryable because some gates are timing artifacts: the recording or its snapshots can+ # finish ingesting after the scan ran (see IneligibleSessionKind.NO_SNAPSHOTS).+ workflow_id = build_apply_scanner_workflow_id(scanner.id, session_id)+ if observation.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):+ return RetryOutcome.NOT_RETRYABLE, workflow_id+ # Advisory, and deliberately outside the lock below: the atomic claim is the authoritative gate, and+ # these two read enough to be worth keeping off a held row lock.+ # Raises QuotaLimitExceeded / Throttled, which callers already know how to render. Kept as+ # exceptions rather than outcomes so the API's existing 402 and 429 messages are unchanged.+ check_observation_quota(scanner.team.organization_id, observation_credits_for_model(scanner.model))+ check_team_in_flight_capacity(scanner.team_id)++ # Locked so two concurrent retries can't both pass the status check and both delete the row.+ with transaction.atomic():+ locked = ReplayObservation.objects.select_for_update().get(pk=original_pk, team_id=scanner.team_id)+ if locked.status not in (ObservationStatus.FAILED, ObservationStatus.INELIGIBLE):+ return RetryOutcome.NOT_RETRYABLE, workflow_id+ # Captured before the delete cascades it away: a run that never starts has to put the team's+ # rating back with the row, not just the row.+ original_label = ReplayObservationLabel.objects.filter(+ observation_id=original_pk, team_id=locked.team_id+ ).first()+ label_created_at = original_label.created_at if original_label else None+ label_updated_at = original_label.updated_at if original_label else None+ # Claimed before the delete so a capped retry never touches the row, and so never cascades away+ # the observation's shared label for a request that changes nothing.+ _, claimed = claim_apply_scanner_slot(scanner, session_id)+ if not claimed:+ return RetryOutcome.CAPPED, workflow_id+ try:+ # Free the UNIQUE(scanner, session_id) slot; the ledger is immutable, so the failed attempt+ # stays counted.+ locked.delete()+ except Exception:+ release_enqueue_claim(+ team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id, immediately=True+ )+ raise++ _, outcome = start_apply_scanner_workflow(+ scanner,+ session_id,+ triggered_by_user_id=user.id,+ trigger=ObservationTrigger.RETRY,+ slot_already_claimed=True,+ )+ if outcome is not WorkflowStartOutcome.STARTED:+ # The replacement run never started, so restore the original row and its rating instead of+ # leaving the recording looking unscanned and the team's feedback gone.+ try:+ with transaction.atomic():+ observation.pk = original_pk+ observation.save(force_insert=True)+ ReplayObservation.objects.filter(pk=original_pk, team_id=observation.team_id).update(+ created_at=original_created_at+ )+ if original_label is not None:+ original_label.save(force_insert=True)+ # auto_now_add/auto_now stamp the insert with now; the rating happened earlier.+ ReplayObservationLabel.objects.filter(pk=original_label.pk, team_id=observation.team_id).update(+ created_at=label_created_at, updated_at=label_updated_at+ )+ except IntegrityError:+ # A run we couldn't start is already persisting its own row for this (scanner, session); the+ # recording isn't stranded, so report it as still finishing rather than failing hard.+ outcome = WorkflowStartOutcome.ALREADY_RUNNING++ if outcome is WorkflowStartOutcome.ALREADY_RUNNING:+ return RetryOutcome.ALREADY_RUNNING, workflow_id+ if outcome is WorkflowStartOutcome.STARTED:+ return RetryOutcome.STARTED, workflow_id+ return RetryOutcome.FAILED, workflow_iddiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex e09f6730c6e2..12cfeed720f0 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1921,7 +1921,7 @@ class TestBulkObserveAction(_VisionAPITestCase):self._in_flight("running-1")self._in_flight("running-2")- with patch("products.replay_vision.backend.api.scanners.MAX_IN_FLIGHT_APPLIES_PER_SCANNER", 3):+ with patch("products.replay_vision.backend.scanning.MAX_IN_FLIGHT_APPLIES_PER_SCANNER", 3):resp = self.client.post(self.bulk_url(str(self.scanner.id)), data={"session_ids": ["x", "y", "z"]}, format="json")@@ -2135,6 +2135,23 @@ class TestRetryActions(_VisionAPITestCase):self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())start_workflow.assert_not_called()+ def test_retry_reports_status_before_consent(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Both paths 400, so only the message distinguishes them. A succeeded observation should hear+ # that it isn't retryable, not that the org needs to turn on AI.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ observation = self._create_failed("sess-order")+ ReplayObservation.objects.filter(id=observation.id).update(status=ObservationStatus.SUCCEEDED)+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()++ resp = self.client.post(self.retry_url(str(observation.id)))++ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertIn("retried", resp.json()["detail"])+def test_retry_rejects_non_terminal_statuses(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:diff --git a/products/replay_vision/backend/tests/test_scanning.py b/products/replay_vision/backend/tests/test_scanning.pynew file mode 100644index 000000000000..15f5a1012ba2--- /dev/null+++ b/products/replay_vision/backend/tests/test_scanning.py@@ -0,0 +1,45 @@+from typing import Any++import pytest+from posthog.test.base import BaseTest++from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN, run_inline_scan+++class TestInlineScanServiceBounds(BaseTest):+ """The service is reachable without DRF, so its own edge has to hold the bounds."""++ def _config(self, **overrides: Any) -> dict[str, Any]:+ config: dict[str, Any] = {"prompt": "did the user check out?"}+ config.update(overrides)+ return config++ @pytest.mark.django_db+ def test_rejects_a_config_the_api_would_reject(self):+ # The config is persisted on the scanner and copied into every observation snapshot, so a+ # caller that skips the serializer must not be able to write one the workflow can't run.+ with pytest.raises(ValueError):+ run_inline_scan(+ team=self.team,+ user=self.user,+ session_ids=["s1"],+ scanner_type=ScannerType.CLASSIFIER,+ scanner_config=self._config(),+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ assert not ReplayScanner.all_origins.filter(team=self.team).exists()++ @pytest.mark.django_db+ def test_rejects_a_batch_over_the_cap(self):+ # Otherwise a non-API caller starts an unbounded number of workflows.+ with pytest.raises(ValueError):+ run_inline_scan(+ team=self.team,+ user=self.user,+ session_ids=[f"s{i}" for i in range(MAX_SESSIONS_PER_SCAN + 1)],+ scanner_type=ScannerType.MONITOR,+ scanner_config=self._config(),+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ assert not ReplayScanner.all_origins.filter(team=self.team).exists()