: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): enforce per-scanner credit limits (#75133)
Arno Hillen9807e7e52fac
diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.pyindex f99229ebc43d..1941b99d528b 100644--- a/products/replay_vision/backend/api/prompt_suggestions.py+++ b/products/replay_vision/backend/api/prompt_suggestions.py@@ -45,13 +45,14 @@ from products.replay_vision.backend.prompt_suggestions import (generate_prompt_suggestion,labels_fingerprint,)-from products.replay_vision.backend.quota import quota_state+from products.replay_vision.backend.quota import compute_scanner_budget, quota_statefrom 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,)from products.replay_vision.backend.temporal.evaluation_types import EvaluatePromptSuggestionInputs+from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reachedlogger = structlog.get_logger(__name__)@@ -384,10 +385,10 @@ class ReplayScannerPromptSuggestionViewSet("Results land on the suggestion's `evaluation` field. Poll `current` while status is running. ""`session_limit` controls how many rated sessions are re-run (thumbs-down prioritized, up to ""`evaluation_session_cap`). Each successful re-run charges credits like a normal observation of "- "the same model. The request is refused with 402 when the planned credits exceed what is left of "- "the monthly limit. Monitor and classifier scanners get a kept/fixed/regressed classification, "- "while scorer and summarizer scanners show the raw before and after output. Requires session "- "recording edit access."+ "the same model. The request is refused with 402 when the planned credits exceed what is left "+ "for the current billing period, either the org's limit or this scanner's own. Monitor and classifier scanners get a "+ "kept/fixed/regressed classification, while scorer and summarizer scanners show the raw before "+ "and after output. Requires session recording edit access."),)@action(detail=True, methods=["post"], required_scopes=["replay_scanner:write", "session_recording:read"])@@ -414,6 +415,12 @@ class ReplayScannerPromptSuggestionViewSet(# both see "not in flight", and the second stub save moves `started_at`, which re-keys the usage# receipts of the first run's still-settling sessions and charges them twice.with transaction.atomic():+ # Serialize capped budget reads with the admission gate's row lock; scanner before+ # suggestion, matching apply's lock order. `credit_limit` comes from the earlier unlocked+ # fetch, so a limit set concurrently with this request fails open once (create_observation+ # re-reads under the lock; the next request here sees the limit).+ if scanner.credit_limit is not None:+ ReplayScanner.objects.select_for_update().filter(team_id=self.team_id, pk=scanner.id).only("pk").first()suggestion = ReplayScannerPromptSuggestion.objects.select_for_update().get(team_id=self.team_id, id=suggestion.id)@@ -436,6 +443,19 @@ class ReplayScannerPromptSuggestionViewSet(f"{quota.period_end.strftime('%b')} {quota.period_end.day}."))+ # A test re-runs the scanner, so it draws from the scanner's own limit too, on top of the org's.+ if scanner.credit_limit is not None:+ scanner_budget = compute_scanner_budget(scanner)+ if scanner_budget.would_exceed(planned_credits):+ record_scanner_limit_reached("evaluation")+ raise QuotaLimitExceeded(+ detail=(+ f"This test would use {planned_credits:,} credits but this scanner has "+ f"{scanner_budget.remaining or 0:,} left of its {scanner_budget.credit_limit or 0:,} credit "+ f"limit for this period. Lower the test session count or raise the scanner's limit."+ ),+ code="scanner_credit_limit_exceeded",+ )# Stamp running first so the UI never sees a gap and the planned spend counts against quota# right away. The select activity replaces this stub with the real total and fingerprint.previous_evaluation = suggestion.evaluation@@ -449,7 +469,9 @@ class ReplayScannerPromptSuggestionViewSet(EvaluatePromptSuggestionInputs( # type: ignore[arg-type]suggestion_id=suggestion.id,team_id=scanner.team_id,- session_limit=session_limit,+ # The admitted count, not the raw request limit: sessions rated between this+ # admission and the select activity must not widen the run past what was budgeted.+ session_limit=planned,config_override=edited_config,started_at=started_at,),diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 5b1a6cc5241c..29ba26aa87b4 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -45,6 +45,7 @@ from products.replay_vision.backend.api.filters import (from products.replay_vision.backend.api.trigger import (WorkflowStartOutcome,check_observation_quota,+ check_scanner_quota,check_team_in_flight_capacity,start_apply_scanner_workflow,)@@ -92,6 +93,7 @@ from products.replay_vision.backend.scanner_config import (from products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN, run_inline_scan, scan_existing_scannerfrom 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.metrics import record_scanner_limit_reached# Date is set by the schedule at trigger time, not by the user — strip on save._QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")@@ -769,8 +771,9 @@ class BulkObserveResultSerializer(serializers.Serializer):("started", "Started"),("already_running", "Already running"),("already_scanned", "Already scanned"),- ("skipped_limit", "Skipped - in-flight limit reached"),- ("skipped_quota", "Skipped - monthly credit quota reached"),+ ("skipped_limit", "Skipped, in-flight limit reached"),+ ("skipped_quota", "Skipped, the org's credit quota for this period was reached"),+ ("skipped_scanner_limit", "Skipped, scanner's own credit limit reached"),("failed", "Failed to start"),],help_text=(@@ -778,7 +781,8 @@ class BulkObserveResultSerializer(serializers.Serializer):"already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a ""finished observation for this session, so nothing was started and nothing was charged (read ""it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was "- "reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; "+ "reached before this session; 'skipped_quota' - the org's credit quota for this period would "+ "be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; ""'failed' - the workflow failed to start."),)@@ -1316,6 +1320,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viexcept QuotaLimitExceeded:self._report_quota_exhausted(scanner, "on_demand")raise+ # Deliberately outside the analytics wrapper above: that event means "the org ran out of+ # credits", and firing it for a self-imposed per-scanner cap would corrupt that metric.+ check_scanner_quota(scanner)check_team_in_flight_capacity(self.team.id)body = ObserveRequestSerializer(data=request.data)@@ -1394,6 +1401,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viuser = cast(User, request.user)started, results = scan_existing_scanner(scanner=scanner, session_ids=session_ids, user=user)+ if any(r["scan_outcome"] == "skipped_scanner_limit" for r in results):+ record_scanner_limit_reached("bulk")report_user_action(user,diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.pyindex 22554475018d..07b7a3eaed16 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 quota_state+from products.replay_vision.backend.quota import compute_scanner_budget, quota_statefrom products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_EXECUTION_TIMEOUT,APPLY_SCANNER_WORKFLOW_NAME,@@ -43,6 +43,7 @@ from products.replay_vision.backend.temporal.constants import (build_apply_scanner_workflow_id,build_process_vision_action_workflow_id,)+from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reachedfrom products.replay_vision.backend.temporal.types import ApplyScannerInputslogger = structlog.get_logger(__name__)@@ -81,6 +82,24 @@ def check_observation_quota(organization_id: UUID, observation_credits: int) ->)+def check_scanner_quota(scanner: ReplayScanner) -> None:+ """Raise 402 when this scanner's own credit limit leaves no room for another observation."""+ if scanner.credit_limit is None:+ return+ budget = compute_scanner_budget(scanner)+ # blocked is only true when a limit is set; the direct check narrows without an assert.+ if budget.credit_limit is not None and budget.blocked:+ record_scanner_limit_reached("on_demand")+ raise QuotaLimitExceeded(+ detail=(+ f"This scanner has {budget.remaining:,} of its {budget.credit_limit:,} credit limit left "+ f"for this period, not enough for another observation. Raise the scanner's limit to keep "+ f"scanning."+ ),+ code="scanner_credit_limit_exceeded",+ )++def _admission_still_within_caps(scanner: ReplayScanner) -> bool:"""Validate a fresh claim against fresh counts. The claim is already registered, so this readsees every competitor, and rows younger than the decay grace are still covered by their claims;diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex 5d336e18f7b0..640d2716204d 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -64,6 +64,7 @@ from products.replay_vision.backend.scanning import ()from products.replay_vision.backend.tag_suggestions import suggest_classifier_tagsfrom products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag+from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reachedfrom ee.hogai.tool import MaxToolfrom ee.hogai.utils.untrusted import as_untrusted_data, neutralize_markup@@ -766,6 +767,11 @@ def _scan_summary(started: int, results: list[dict[str, str]]) -> str:parts.append(f"{counts['already_running']} were already being scanned.")if counts.get("skipped_quota"):parts.append(f"{counts['skipped_quota']} were skipped: the monthly credit budget is used up.")+ if counts.get("skipped_scanner_limit"):+ parts.append(+ f"{counts['skipped_scanner_limit']} were skipped: this scanner reached its own credit limit. "+ "Scanning resumes when its billing period resets."+ )if counts.get("skipped_limit"):parts.append(f"{counts['skipped_limit']} were skipped: too many scans already running.")if counts.get("failed"):@@ -881,6 +887,8 @@ class ScanReplayVisionSessionsTool(ReplayVisionGatesMixin, MaxTool):if scanner is None:return f"Scanner {scanner_id} not found.", {"error": "not_found"}started, results = scan_existing_scanner(scanner=scanner, session_ids=sessions, user=self._user)+ if any(result["scan_outcome"] == "skipped_scanner_limit" for result in results):+ record_scanner_limit_reached("max_tool")return _scan_summary(started, results), {"scan_id": str(scanner.id), "results": results}if not prompt or not prompt.strip():diff --git a/products/replay_vision/backend/scanning.py b/products/replay_vision/backend/scanning.pyindex 7c8603d07839..fff155260de4 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 quota_state+from products.replay_vision.backend.quota import compute_scanner_budget, 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,@@ -85,10 +85,20 @@ def scan_headroom(*, team: Team, model: str, scanner: ReplayScanner | None) -> S),)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))+ cost = observation_credits_for_model(model)+ # None means nothing binds: an uncapped org (or scanner), or a free model that spends nothing.+ affordable = snapshot.affordable_count(cost)quota_limit = in_flight_limit if affordable is None else affordable- # Report quota as the reason only when it's the strictly tighter limit.+ scanner_affordable = compute_scanner_budget(scanner).affordable_count(cost) if scanner is not None else None+ scanner_limit = in_flight_limit if scanner_affordable is None else scanner_affordable+ # Report whichever limit is strictly tighter, so the user knows which one to raise.+ if scanner_limit < in_flight_limit and scanner_limit <= quota_limit:+ return ScanHeadroom(+ max_starts=scanner_limit,+ skip_reason="skipped_scanner_limit",+ team_rows=team_in_flight,+ scanner_rows=scanner_in_flight,+ )if quota_limit < in_flight_limit:return ScanHeadroom(max_starts=quota_limit,@@ -270,6 +280,7 @@ def retry_observation(*, observation: ReplayObservation, user: User) -> tuple[Refrom products.replay_vision.backend.api.trigger import ( # noqa: PLC0415WorkflowStartOutcome,check_observation_quota,+ check_scanner_quota,check_team_in_flight_capacity,claim_apply_scanner_slot,start_apply_scanner_workflow,@@ -294,6 +305,7 @@ def retry_observation(*, observation: ReplayObservation, user: User) -> tuple[Re# 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_scanner_quota(scanner)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.diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex cae8ea86e12a..da51f3439016 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -5,6 +5,7 @@ from products.replay_vision.backend.temporal.activities import (advance_backfill_cursor_activity,advance_scanner_watermark_activity,call_scanner_provider_activity,+ check_scanner_budget_activity,cleanup_gemini_file_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,@@ -92,6 +93,7 @@ ACTIVITIES: list[Callable[..., Any]] = [find_scanner_candidates_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,+ check_scanner_budget_activity,advance_scanner_watermark_activity,refresh_prompt_suggestion_activity,prepare_backfill_tick_activity,@@ -145,6 +147,7 @@ __all__ = ["advance_scanner_watermark_activity","refresh_prompt_suggestion_activity","call_scanner_provider_activity",+ "check_scanner_budget_activity","cleanup_gemini_file_activity","count_in_flight_applies_activity","count_in_flight_by_team_activity",diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex 533b6cd747ff..8caa302ce7da 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -10,6 +10,7 @@ from products.replay_vision.backend.temporal.activities.backfill import (reap_backfill_schedules_activity,)from products.replay_vision.backend.temporal.activities.call_scanner_provider import call_scanner_provider_activity+from products.replay_vision.backend.temporal.activities.check_scanner_budget import check_scanner_budget_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 (count_in_flight_applies_activity,@@ -71,6 +72,7 @@ __all__ = ["reap_backfill_schedules_activity","refresh_prompt_suggestion_activity","call_scanner_provider_activity",+ "check_scanner_budget_activity","cleanup_gemini_file_activity","count_in_flight_applies_activity","count_in_flight_by_team_activity",diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.pyindex 693f28e88c61..c79b5e2c9a2b 100644--- a/products/replay_vision/backend/temporal/activities/backfill.py+++ b/products/replay_vision/backend/temporal/activities/backfill.py@@ -25,7 +25,7 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (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.quota import compute_scanner_budget, quota_statefrom products.replay_vision.backend.temporal.activities.count_in_flight_applies import (count_in_flight,count_in_flight_rows,@@ -98,6 +98,13 @@ def prepare_backfill_tick_activity(inputs: BackfillTickInputs) -> PrepareBackfilrecord_backfill_tick_outcome("paused_quota")return PrepareBackfillTickOutput(action=BackfillTickAction.PAUSE)+ scanner_budget = compute_scanner_budget(backfill.scanner) if backfill.scanner.credit_limit is not None else None+ if scanner_budget is not None and scanner_budget.would_exceed(backfill.credits_per_observation):+ # Children would decline at create while the cursor walks past their sessions; the hold lets+ # the backfill resume when the period resets or the limit rises.+ record_backfill_tick_outcome("skipped_scanner_limit")+ return PrepareBackfillTickOutput(action=BackfillTickAction.SKIP)+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@@ -106,6 +113,11 @@ def prepare_backfill_tick_activity(inputs: BackfillTickInputs) -> PrepareBackfilaffordable = quota.affordable_count(backfill.credits_per_observation)if affordable is not None:budget = min(budget, affordable)+ if scanner_budget is not None:+ # The scanner's own cap bounds the batch the same way the org quota does.+ scanner_affordable = scanner_budget.affordable_count(backfill.credits_per_observation)+ if scanner_affordable is not None:+ budget = min(budget, scanner_affordable)if budget <= 0:record_backfill_tick_outcome("throttled")return PrepareBackfillTickOutput(action=BackfillTickAction.SKIP)diff --git a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py b/products/replay_vision/backend/temporal/activities/check_scanner_budget.pynew file mode 100644index 000000000000..89e8c2a0d3a2--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py@@ -0,0 +1,68 @@+from temporalio import activity++from products.replay_vision.backend.models.replay_scanner import ReplayScanner, initial_watermark+from products.replay_vision.backend.quota import compute_scanner_budget+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.metrics import record_sweep_outcome+from products.replay_vision.backend.temporal.sweep_types import CheckScannerBudgetInputs, CheckScannerBudgetOutput+++@track_activity()+def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScannerBudgetOutput:+ """Whether this scanner has room for another observation under its own credit limit.++ On a cap, advances the watermark past the window the scanner is skipping. Freezing it instead would+ make the first uncapped tick fetch a candidate window stretching back to when the limit was hit and+ burn the fresh period's budget on stale recordings, so a spend limit would become a spend spike.+ Mirrors what re-enabling a disabled scanner already does. The reset lives here, not in the workflow,+ because it needs the real clock.++ The watermark only advances when settled credits alone exceed the limit. In-flight reservations are+ transient (a failed observation releases its reservation without ever writing a receipt), so a+ transient in-flight spike must not permanently skip a window the scanner could actually afford once+ those reservations clear.+ """+ scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()+ if scanner is None:+ # The reconciler removes schedules for deleted scanners. A racing tick just stops here.+ return CheckScannerBudgetOutput(capped=False)+ if scanner.credit_limit is None:+ return CheckScannerBudgetOutput(capped=False)+ budget = compute_scanner_budget(scanner)+ if not budget.blocked:+ return CheckScannerBudgetOutput(capped=False)+ if not budget.blocked_by_settled_spend:+ # Only the in-flight portion pushes this over: capped for now, but don't advance the+ # watermark, since those reservations may release without ever settling.+ record_sweep_outcome("scanner_capped_in_flight")+ activity.logger.info(+ "Sweep skipped: scanner credit limit reached by in-flight reservations only",+ extra={+ "scanner_id": str(inputs.scanner_id),+ "team_id": inputs.team_id,+ "credit_limit": budget.credit_limit,+ "credits_used": budget.credits_used,+ },+ )+ return CheckScannerBudgetOutput(capped=True)+ record_sweep_outcome("scanner_capped_settled")+ # `.update` bypasses the model's version-tracking save(), matching how the watermark is advanced.+ watermark = initial_watermark()+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ last_swept_at=watermark,+ last_seen_session_id="",+ # The deep pass walks from its own watermark up to the fast one, so leaving it behind would+ # hand the first uncapped deep sweep exactly the window this reset skips.+ last_deep_swept_at=watermark,+ )+ activity.logger.info(+ "Sweep skipped: scanner credit limit reached",+ extra={+ "scanner_id": str(inputs.scanner_id),+ "team_id": inputs.team_id,+ "credit_limit": budget.credit_limit,+ "credits_used": budget.credits_used,+ },+ )+ return CheckScannerBudgetOutput(capped=True)diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex 9c2c4bc2cc5b..ba50918fba8b 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -1,3 +1,4 @@+import timefrom typing import Anyfrom django.db import IntegrityError, transaction@@ -14,9 +15,14 @@ from 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 ReplayScannerfrom products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill-from products.replay_vision.backend.quota import quota_state+from products.replay_vision.backend.quota import compute_scanner_budget, current_period_bounds, quota_statefrom products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.metrics import record_consent_skip, record_quota_exhausted_skip+from products.replay_vision.backend.temporal.metrics import (+ record_consent_skip,+ record_quota_exhausted_skip,+ record_scanner_admission_lock_wait,+ record_scanner_limit_reached,+)from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot, ScannerSnapshotfrom products.replay_vision.backend.temporal.types import CreateObservationInputs, CreateObservationOutput@@ -41,6 +47,39 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv)+def _reclaim_own_pending_insert(inputs: CreateObservationInputs) -> CreateObservationOutput | None:+ """A still-PENDING row stamped with our own workflow id is our earlier lost-result insert."""+ existing = ReplayObservation.objects.filter(scanner_id=inputs.scanner_id, session_id=inputs.session_id).first()+ if existing is None or existing.workflow_id != inputs.workflow_id or existing.status != ObservationStatus.PENDING:+ return None+ # Route through the validator so a malformed legacy snapshot surfaces as a tagged non-retryable error.+ existing_snapshot = ScannerSnapshot.load_for(existing.id, existing.scanner_snapshot)+ return CreateObservationOutput(+ observation_id=existing.id,+ was_created=True,+ scanner_type=existing_snapshot.scanner_type,+ )+++def _retake_failed_row(inputs: CreateObservationInputs, row_fields: dict[str, Any]) -> CreateObservationOutput | None:+ """Retake the session's FAILED row for a backfill, so the failed scan re-runs.++ Filtered on FAILED so a concurrent success wins and this no-ops."""+ retaken = ReplayObservation.objects.filter(+ scanner_id=inputs.scanner_id, session_id=inputs.session_id, status=ObservationStatus.FAILED+ ).update(**row_fields)+ if not retaken:+ return None+ existing = ReplayObservation.objects.get(scanner_id=inputs.scanner_id, session_id=inputs.session_id)+ # Route through the validator so a malformed snapshot surfaces as a tagged non-retryable error.+ existing_snapshot = ScannerSnapshot.load_for(existing.id, existing.scanner_snapshot)+ return CreateObservationOutput(+ observation_id=existing.id,+ was_created=True,+ scanner_type=existing_snapshot.scanner_type,+ )++def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutput:# team__organization is prefetched for the AI-consent check below.scanner = (@@ -127,8 +166,56 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut"backfill": backfill,}+ # Resolved before the lock to shrink the in-lock window; the period is stable for the admission decision.+ period = current_period_bounds(scanner.team.organization_id) if scanner.credit_limit is not None else Nonetry:with transaction.atomic():+ # Capped scanners serialize admissions on the row lock so concurrent applies cannot overshoot+ # the cap; uncapped scanners keep the lock-free path. The limit is re-read under the lock.+ if scanner.credit_limit is not None:+ lock_started = time.monotonic()+ locked = (+ ReplayScanner.objects.select_for_update().filter(pk=scanner.pk).only("pk", "credit_limit").first()+ )+ # Admissions on a busy capped scanner serialize here; the wait is visible, not guessed at.+ record_scanner_admission_lock_wait(time.monotonic() - lock_started)+ if locked is not None and locked.credit_limit is not None:+ scanner_budget = compute_scanner_budget(scanner, period)+ # Priced from `priced_model` (the frozen snapshot model for backfills), matching+ # what the observation will actually charge, not the scanner's current model.+ if scanner_budget.would_exceed(observation_credits_for_model(priced_model)):+ # A retry's own first insert counts as in-flight spend, so reclaim it instead of+ # stranding it PENDING. Only the own-reclaim case returns here; any other existing+ # row (including a retakeable FAILED one, which would spend fresh budget) falls+ # through to the capped skip.+ reclaimed_output = _reclaim_own_pending_insert(inputs)+ if reclaimed_output is not None:+ return reclaimed_output+ record_scanner_limit_reached("admission")+ activity.logger.info(+ "Skipping observation: scanner credit limit reached",+ extra={+ "scanner_id": str(inputs.scanner_id),+ "team_id": inputs.team_id,+ "session_id": inputs.session_id,+ "credit_limit": scanner_budget.credit_limit,+ "credits_used": scanner_budget.credits_used,+ },+ )+ return CreateObservationOutput(+ observation_id=None,+ was_created=False,+ scanner_type=scanner.scanner_type,+ )+ # A retake spends fresh budget, so on a capped scanner it must commit under this+ # lock. It cannot wait for the IntegrityError handler: the conflict aborts the+ # transaction, so the handler's retake would run unlocked and a concurrent+ # sibling's budget read could miss its in-flight spend, overshooting the cap.+ if backfill is not None:+ retaken_output = _retake_failed_row(inputs, row_fields)+ if retaken_output is not None:+ return retaken_output+observation = ReplayObservation.objects.create(scanner=scanner,team=scanner.team,@@ -149,7 +236,8 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut# Route through the validator so a malformed legacy snapshot surfaces as a tagged non-retryable error.existing_snapshot = ScannerSnapshot.load_for(existing.id, existing.scanner_snapshot)# A backfill quotes sessions whose earlier scan failed, so retake that row rather than report progress- # for a scan that never re-runs. Filtered on FAILED so a concurrent success wins and this no-ops.+ # for a scan that never re-runs. Capped scanners retake under the admission lock before the insert;+ # this unlocked path serves uncapped scanners, which tolerate no lock on admission either.retaken = bool(backfill is not Noneand existing.status == ObservationStatus.FAILEDdiff --git a/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py b/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.pyindex b9df36f77139..08dca819c4d9 100644--- a/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py+++ b/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py@@ -77,12 +77,17 @@ def select_evaluation_sessions_activity(inputs: SelectEvaluationSessionsInputs)rerun_config = dict(suggestion.suggested_config)else:rerun_config = {**(scanner.scanner_config or {}), "prompt": suggestion.suggested_prompt}+ # The API stamped the admitted model into the running stub before starting the workflow; using the+ # scanner's then-current model instead would let a model switch mid-run overspend the admitted budget.+ admitted_model = (+ suggestion.evaluation.get("model") if isinstance(suggestion.evaluation, dict) else None+ ) or scanner.model# Signals stay off so a dry run can't pollute the team's feeds.snapshot = ScannerSnapshot(name=scanner.name,scanner_type=scanner.scanner_type,scanner_version=scanner.scanner_version,- model=scanner.model,+ model=admitted_model,provider=scanner.provider,emits_signals=False,scanner_config=rerun_config,@@ -90,7 +95,7 @@ def select_evaluation_sessions_activity(inputs: SelectEvaluationSessionsInputs)suggestion.evaluation = build_running_evaluation(total=len(sessions),labels_fingerprint=labels_fingerprint(scanner),- model=scanner.model,+ model=admitted_model,started_at=inputs.started_at,)suggestion.save(update_fields=["evaluation"])diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex e7fe1ff52ad8..7fbb0f79cb77 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -122,6 +122,8 @@ MAX_IN_FLIGHT_APPLIES_PER_SCANNER = 150MAX_IN_FLIGHT_APPLIES_PER_TEAM = 300COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)+CHECK_SCANNER_BUDGET_TIMEOUT = dt.timedelta(seconds=30)+def in_flight_headroom(scanner_in_flight: int, team_in_flight: int) -> int:"""Dispatch headroom for a sweep tick: the tighter of the per-scanner and per-team caps.diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 6865a0d404c3..818b5847126a 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -78,10 +78,24 @@ REPLAY_VISION_BACKFILL_TICK_OUTCOMES = Counter(REPLAY_VISION_SWEEP_OUTCOMES = Counter("replay_vision_sweep_outcomes_total",- "Sweep tick outcomes: throttled at an in-flight cap, no candidates, or candidates found",+ "Sweep tick outcomes: throttled at an in-flight cap, capped by the scanner's own credit limit "+ "(settled spend, which skips the window for good, or in-flight reservations, which preserve the "+ "watermark), no candidates, or candidates found",["outcome"],)+REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT = Histogram(+ "replay_vision_scanner_admission_lock_wait_seconds",+ "Time spent acquiring the scanner row lock that serializes capped admissions",+ buckets=(0.005, 0.025, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0),+)++REPLAY_VISION_SCANNER_LIMIT_REACHED = Counter(+ "replay_vision_scanner_limit_reached_total",+ "Requests refused because a per-scanner credit limit left no room, by the API surface that refused",+ ["surface"],+)+REPLAY_VISION_SWEEP_CANDIDATES = Counter("replay_vision_sweep_candidates_total","Candidate sessions returned to sweeps for dispatch",@@ -171,6 +185,17 @@ def record_quota_exhausted_skip(scanner_type: str) -> None:_otel.record_counter_twin(REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS, 1, {"scanner_type": scanner_type})+def record_scanner_admission_lock_wait(seconds: float) -> None:+ REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT.observe(seconds)+ _otel.record_histogram_twin(REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT, seconds, {})+++def record_scanner_limit_reached(surface: str) -> None:+ """`surface` is "on_demand", "bulk", "evaluation", "max_tool", or "admission": the path that refused the work."""+ REPLAY_VISION_SCANNER_LIMIT_REACHED.labels(surface=surface).inc()+ _otel.record_counter_twin(REPLAY_VISION_SCANNER_LIMIT_REACHED, 1, {"surface": surface})++def record_credits_consumed(scanner_type: str, model: str, credits: int) -> None:labels = {"scanner_type": scanner_type, "model": model}REPLAY_VISION_CREDITS_CONSUMED.labels(**labels).inc(credits)diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.pyindex 42af7d6ea340..93a27b018a06 100644--- a/products/replay_vision/backend/temporal/sweep_types.py+++ b/products/replay_vision/backend/temporal/sweep_types.py@@ -53,6 +53,16 @@ class RefreshPromptSuggestionInputs(BaseModel, frozen=True):team_id: int+class CheckScannerBudgetInputs(BaseModel, frozen=True):+ scanner_id: UUID+ team_id: int+++class CheckScannerBudgetOutput(BaseModel, frozen=True):+ # Defaults to not-capped so a replayed history missing this field decodes to "keep sweeping".+ capped: bool = False++class AdvanceScannerWatermarkInputs(BaseModel, frozen=True):scanner_id: UUIDnew_last_swept_at: dt.datetimediff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.pyindex 461d9ed44397..62835e4ce305 100644--- a/products/replay_vision/backend/temporal/sweep_workflow.py+++ b/products/replay_vision/backend/temporal/sweep_workflow.py@@ -19,11 +19,15 @@ from posthog.temporal.common.search_attributes import (with wf.unsafe.imports_passed_through():from django.conf import settings- from products.replay_vision.backend.temporal.metrics import record_vision_action_occurrence_dropped+ from products.replay_vision.backend.temporal.metrics import (+ record_sweep_outcome,+ record_vision_action_occurrence_dropped,+ )from products.replay_vision.backend.models.replay_observation import ObservationTriggerfrom products.replay_vision.backend.temporal.activities import (advance_scanner_watermark_activity,+ check_scanner_budget_activity,count_in_flight_applies_activity,count_in_flight_by_team_activity,find_scanner_candidates_activity,@@ -32,6 +36,7 @@ from products.replay_vision.backend.temporal.activities import (from products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_EXECUTION_TIMEOUT,APPLY_SCANNER_WORKFLOW_NAME,+ CHECK_SCANNER_BUDGET_TIMEOUT,COUNT_IN_FLIGHT_APPLIES_TIMEOUT,PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,PROCESS_VISION_ACTION_WORKFLOW_NAME,@@ -44,6 +49,7 @@ from products.replay_vision.backend.temporal.constants import (from products.replay_vision.backend.temporal.sweep_types import (AdvanceScannerWatermarkInputs,CandidateSessionPayload,+ CheckScannerBudgetInputs,CountInFlightAppliesInputs,FindScannerCandidatesInputs,RefreshPromptSuggestionInputs,@@ -89,6 +95,26 @@ class SweepScannerWorkflow(PostHogWorkflow):"replay_vision.prompt_suggestion_refresh_failed", extra={"scanner_id": str(inputs.scanner_id)})+ # A capped scanner scans no sessions this tick; the heartbeats above spend no scanner+ # credits, so they ran first. Fails open (admissions stay gated at the persistence+ # boundary); patched so in-flight sweeps replay unchanged across the deploy.+ if wf.patched("replay-vision-scanner-credit-limit"):+ try:+ budget = await wf.execute_activity(+ check_scanner_budget_activity,+ CheckScannerBudgetInputs(scanner_id=inputs.scanner_id, team_id=inputs.team_id),+ start_to_close_timeout=CHECK_SCANNER_BUDGET_TIMEOUT,+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ )+ if budget.capped:+ return+ except Exception:+ if not wf.unsafe.is_replaying():+ record_sweep_outcome("scanner_budget_check_failed")+ wf.logger.warning(+ "replay_vision.scanner_budget_check_failed", extra={"scanner_id": str(inputs.scanner_id)}+ )+# Hard concurrency caps: per scanner (one bad config) and per team (many scanners), enforced as the# min of the two headrooms. Skip entirely when saturated. Keeps any single tenant from flooding the# shared rasterizer + provider concurrency. A DB error fails the count (single attempt), so the sweepdiff --git a/products/replay_vision/backend/tests/helpers.py b/products/replay_vision/backend/tests/helpers.pyindex 81043a567943..17c666e5d2bf 100644--- a/products/replay_vision/backend/tests/helpers.py+++ b/products/replay_vision/backend/tests/helpers.py@@ -1,9 +1,18 @@from typing import Any+from django.utils import timezone+from posthog.models import Team+from posthog.models.utils import uuid7from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.temporal.activities.create_observation import _build_scanner_snapshot@@ -13,6 +22,38 @@ def snapshot_for(scanner: ReplayScanner) -> dict[str, Any]:return _build_scanner_snapshot(scanner)+def seed_scanner_spend(scanner: ReplayScanner, credits: int, *, observations: int = 1) -> None:+ """Settle spend for a scanner: `observations` succeeded rows, each with a `credits` receipt.+ The budget reads the receipt ledger, so receipt-less observations count nothing."""+ if credits <= 0 or observations <= 0:+ return+ snapshot = snapshot_for(scanner)+ rows = ReplayObservation.objects.bulk_create(+ ReplayObservation(+ scanner=scanner,+ team=scanner.team,+ session_id=f"seed-spend-{uuid7()}",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_snapshot=snapshot,+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ for _ in range(observations)+ )+ ReplayObservationUsage.objects.bulk_create(+ ReplayObservationUsage(+ observation_id=row.id,+ organization_id=scanner.team.organization_id,+ team_id=scanner.team_id,+ scanner_id=scanner.id,+ observation_created_at=row.created_at,+ model=scanner.model,+ credits=credits,+ )+ for row in rows+ )++def create_experiment(team: Team, flag_key: str) -> Experiment:"""A launched-enough experiment with a multivariate flag, for targeting tests."""flag = FeatureFlag.objects.create(diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex ca2c87cfe0e6..41a02490e3f0 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -45,6 +45,7 @@ from products.replay_vision.backend.temporal.constants import ()from products.replay_vision.backend.tests.helpers import (create_experiment,+ seed_scanner_spend,snapshot_for as _snapshot_for,)from products.signals.backend.models import SignalSourceConfig@@ -2032,6 +2033,42 @@ class TestObserveAction(_VisionAPITestCase):self.assertEqual(report.call_args.args[1], "replay_vision_quota_exhausted")self.assertEqual(report.call_args.args[2]["trigger"], "on_demand")+ def test_observe_is_refused_when_the_scanner_limit_is_reached(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=1)++ resp = self.client.post(self.observe_url(str(self.scanner.id)), data={"session_id": "sess-42"}, format="json")++ self.assertEqual(resp.status_code, 402, resp.json())+ self.assertIn("scanner", resp.json()["detail"].lower())+ mock_async_to_sync.assert_not_called()++ def test_observe_scanner_limit_does_not_report_org_quota_exhaustion(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # A self-imposed per-scanner cap must never fire the org-exhaustion event: that metric means+ # "the org ran out of credits", not "this scanner hit the limit its owner chose".+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=1)++ 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-42"}, format="json"+ )++ self.assertEqual(resp.status_code, 402, resp.json())+ report.assert_not_called()++ def test_observe_is_unaffected_when_no_scanner_limit_is_set(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ resp = self.client.post(self.observe_url(str(self.scanner.id)), data={"session_id": "sess-42"}, format="json")++ self.assertEqual(resp.status_code, 202, resp.json())+@patch("products.replay_vision.backend.api.trigger.async_to_sync")@patch("products.replay_vision.backend.api.trigger.sync_connect")@@ -2120,6 +2157,109 @@ class TestBulkObserveAction(_VisionAPITestCase):self.assertEqual(events, ["replay_vision_bulk_scan_started", "replay_vision_quota_exhausted"])self.assertEqual(report.call_args.args[2]["trigger"], "bulk")+ def test_bulk_observe_reports_the_scanner_limit_as_the_skip_reason(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # The scanner's own limit is tighter than the wide-open org and in-flight caps, so every+ # session must be skipped under the scanner-specific reason, not the generic quota one.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ cost = observation_credits_for_model(self.scanner.model)+ seed_scanner_spend(self.scanner, cost)+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=cost)++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["s-1", "s-2"]}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 0)+ self.assertEqual({r["scan_outcome"] for r in body["results"]}, {"skipped_scanner_limit"})++ @parameterized.expand(+ [+ # Tied limits: the scanner limit names itself, since it's the one the user can raise.+ ("tied", 1, 1, "skipped_scanner_limit"),+ # Org limit strictly tighter than the scanner's own: the org quota is the binding reason.+ ("org_strictly_tighter", 2, 1, "skipped_quota"),+ ]+ )+ def test_bulk_observe_scanner_limit_tie_with_org_limit_wins_the_label(+ self,+ mock_sync_connect: MagicMock,+ mock_async_to_sync: MagicMock,+ _name: str,+ scanner_limit_multiplier: int,+ org_quota_multiplier: int,+ expected_outcome: str,+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ cost = observation_credits_for_model(self.scanner.model)+ seed_scanner_spend(self.scanner, cost)+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=cost * scanner_limit_multiplier)++ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", cost * org_quota_multiplier):+ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["s-1", "s-2"]}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 0)+ self.assertEqual({r["scan_outcome"] for r in body["results"]}, {expected_outcome})++ def test_bulk_observe_scanner_limit_does_not_report_org_quota_exhaustion(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ cost = observation_credits_for_model(self.scanner.model)+ seed_scanner_spend(self.scanner, cost)+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=cost)++ with patch("products.replay_vision.backend.api.scanners.report_user_action") as report:+ resp = self.client.post(self.bulk_url(str(self.scanner.id)), data={"session_ids": ["s-1"]}, format="json")++ self.assertEqual(resp.status_code, 202, resp.json())+ events = [call.args[1] for call in report.call_args_list]+ self.assertEqual(events, ["replay_vision_bulk_scan_started"])++ def test_bulk_observe_partial_fit_starts_what_the_scanner_limit_affords(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Room for exactly two more observations and three sessions requested: the batch starts two+ # and labels the remainder with the scanner-specific reason.+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ cost = observation_credits_for_model(self.scanner.model)+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=2 * cost)++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["p-1", "p-2", "p-3"]}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 2)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "started", "skipped_scanner_limit"])++ def test_bulk_observe_is_unaffected_when_no_scanner_limit_is_set(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()++ resp = self.client.post(+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["a", "b", "c"]}, format="json"+ )++ self.assertEqual(resp.status_code, 202, resp.json())+ body = resp.json()+ self.assertEqual(body["started"], 3)+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "started", "started"])+def test_quota_bound_batch_that_fits_does_not_report_exhaustion(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:@@ -2340,6 +2480,24 @@ class TestRetryActions(_VisionAPITestCase):self.assertTrue(ReplayObservation.objects.filter(id=observation.id).exists())start_workflow.assert_not_called()+ def test_retry_keeps_row_when_the_scanners_own_limit_is_reached(+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock+ ) -> None:+ # Retry deletes the failed row before dispatching; without this gate the refused replacement+ # leaves the row gone while the caller is told the retry started.+ start_workflow = MagicMock()+ mock_async_to_sync.return_value = start_workflow+ observation = self._create_failed("sess-scanner-limit")+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(+ credit_limit=observation_credits_for_model(self.scanner.model) - 1+ )++ 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())+ start_workflow.assert_not_called()+def test_retry_dispatch_failure_returns_503_with_row_and_label_restored(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pyindex b82c377afc4a..12f3e56d1495 100644--- a/products/replay_vision/backend/tests/test_backfills.py+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -17,6 +17,7 @@ from products.replay_vision.backend.api.backfills import (BackfillEnumerationThrottle,ReplayScannerBackfillViewSet,)+from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,@@ -59,6 +60,7 @@ from products.replay_vision.backend.temporal.constants import (from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshotfrom products.replay_vision.backend.temporal.sweep_types import CandidateSessionPayloadfrom products.replay_vision.backend.temporal.types import CreateObservationInputs+from products.replay_vision.backend.tests.helpers import seed_scanner_spend_WINDOW_END = dt.datetime(2026, 5, 1, tzinfo=dt.UTC)_WINDOW_START = _WINDOW_END - dt.timedelta(days=30)@@ -162,6 +164,77 @@ class TestCreateObservationForBackfill:assert observation.scanner_snapshot["scanner_config"] == {"prompt": "frozen prompt"}assert observation.triggered_by == ObservationTrigger.BACKFILL+ def test_scanner_limit_prices_the_backfill_observation_from_its_frozen_model(self) -> None:+ # The frozen 15-credit model is what the observation charges; switching the scanner to a+ # 2-credit model must not let it slip under a limit with only 5 credits left.+ scanner = _make_scanner(credit_limit=20)+ backfill = _make_backfill(scanner, scanner_snapshot=_frozen_snapshot(scanner))+ seed_scanner_spend(scanner, 15)+ ReplayScanner.objects.filter(pk=scanner.pk).update(model=ScannerModel.GEMINI_3_5_FLASH_LITE)+ scanner.refresh_from_db()+ result = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-frozen-price",+ triggered_by=ObservationTrigger.BACKFILL,+ triggered_by_user_id=None,+ workflow_id="wf-frozen-price",+ backfill_id=backfill.id,+ )+ )+ assert result.observation_id is None+ assert not result.was_created+ assert not backfill.observations.exists()++ def test_capped_retake_counts_as_in_flight_spend_for_the_next_admission(self) -> None:+ # The retake reserves fresh budget under the admission lock, so the next admission's budget+ # read must see it and refuse; missing it would overshoot the cap by the retaken row.+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_6_FLASH.value)+ scanner = _make_scanner(credit_limit=credits)+ backfill = _make_backfill(scanner)+ failed = ReplayObservation.objects.create(+ scanner=scanner,+ team=scanner.team,+ session_id="sess-a",+ status=ObservationStatus.FAILED,+ workflow_id="wf-old",+ scanner_snapshot=_frozen_snapshot(scanner),+ triggered_by=ObservationTrigger.BACKFILL,+ completed_at=timezone.now(),+ )++ retake = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-a",+ triggered_by=ObservationTrigger.BACKFILL,+ triggered_by_user_id=None,+ workflow_id="wf-retake",+ backfill_id=backfill.id,+ )+ )+ assert retake.was_created is True+ assert retake.observation_id == failed.id+ failed.refresh_from_db()+ assert failed.status == ObservationStatus.PENDING+ assert failed.workflow_id == "wf-retake"++ admission = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-b",+ triggered_by=ObservationTrigger.BACKFILL,+ triggered_by_user_id=None,+ workflow_id="wf-next",+ backfill_id=backfill.id,+ )+ )+ assert admission.was_created is False+ assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-b").exists()+@pytest.mark.parametrize("seeded_status,expect_retaken",[@@ -298,6 +371,35 @@ class TestBackfillTickActivities:assert result.action == BackfillTickAction.DISPATCHassert result.dispatch_budget > 0+ def test_prepare_holds_the_tick_when_the_scanner_limit_is_reached(self) -> None:+ # Held like the disabled-scanner case: children would decline at create while the cursor walks+ # past their sessions, completing the backfill with zero observations. The hold keeps it+ # RUNNING so it resumes when the period resets or the limit rises.+ scanner = _make_scanner(credit_limit=10)+ backfill = _make_backfill(scanner, credits_per_observation=5)+ seed_scanner_spend(scanner, 10)+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.SKIP+ backfill.refresh_from_db()+ assert backfill.status == BackfillStatus.RUNNING++ def test_prepare_clamps_batch_to_the_scanner_limits_headroom(self) -> None:+ scanner = _make_scanner(credit_limit=22)+ backfill = _make_backfill(scanner, credits_per_observation=5)+ seed_scanner_spend(scanner, 10)+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.DISPATCH+ # 12 credits of headroom at 5 apiece fits two children.+ assert result.dispatch_budget == 2++ def test_prepare_ignores_spend_on_an_uncapped_scanner(self) -> None:+ scanner = _make_scanner()+ backfill = _make_backfill(scanner, credits_per_observation=5)+ seed_scanner_spend(scanner, 1000)+ result = prepare_backfill_tick_activity(self._tick_inputs(backfill))+ assert result.action == BackfillTickAction.DISPATCH+ assert result.dispatch_budget == MAX_IN_FLIGHT_APPLIES_PER_BACKFILL+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.diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.pyindex 34f93fa14dac..db53ab7e69ba 100644--- a/products/replay_vision/backend/tests/test_max_tools.py+++ b/products/replay_vision/backend/tests/test_max_tools.py@@ -15,6 +15,7 @@ from posthog.models.team import Teamfrom posthog.rbac.user_access_control import UserAccessControlimport products.replay_vision.backend.max_tools as max_tools_module+from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.max_tools import (AnalyzeReplayVisionImpactTool,CreateReplayVisionActionTool,@@ -49,6 +50,7 @@ from products.replay_vision.backend.models.vision_action import (from products.replay_vision.backend.scanner_config import MAX_PROMPT_LENGTHfrom products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCANfrom products.replay_vision.backend.tags import slugify_tag+from products.replay_vision.backend.tests.helpers import seed_scanner_spendfrom ee.hogai.tool import ApprovalResumePayload, MaxTool@@ -559,6 +561,64 @@ class TestReplayVisionChargeConfirmation(BaseTest):assert "AI analysis" in content+class TestScanReplayVisionSessionsScannerLimit(BaseTest):+ """A capped scanner's skips have to be explained to the user and counted, like bulk_observe does."""++ def _tool(self) -> ScanReplayVisionSessionsTool:+ config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}+ return ScanReplayVisionSessionsTool(team=self.team, user=self.user, config=config)++ def _capped_scanner(self) -> ReplayScanner:+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="capped",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ cost = observation_credits_for_model(scanner.model)+ seed_scanner_spend(scanner, cost)+ ReplayScanner.objects.filter(pk=scanner.pk).update(credit_limit=cost)+ scanner.refresh_from_db()+ return scanner++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_scanner_limit_skips_are_explained_and_counted(self):+ # Without the sentence and the metric, the user just sees fewer scans started and nothing+ # records that the scanner's own limit was the reason.+ scanner = await sync_to_async(self._capped_scanner)()+ with patch("products.replay_vision.backend.max_tools.record_scanner_limit_reached") as record:+ content, artifact = await self._tool()._arun_impl(session_ids=["s1", "s2"], scanner_id=str(scanner.id))++ assert {r["scan_outcome"] for r in artifact["results"]} == {"skipped_scanner_limit"}+ assert "2 were skipped: this scanner reached its own credit limit." in content+ assert "billing period resets" in content+ record.assert_called_once_with("max_tool")++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_uncapped_scanner_records_no_scanner_limit_block(self):+ scanner = await sync_to_async(ReplayScanner.objects.create)(+ team=self.team,+ name="uncapped",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ start = MagicMock(return_value=MagicMock())+ with (+ patch("products.replay_vision.backend.api.trigger.sync_connect", MagicMock()),+ patch("products.replay_vision.backend.api.trigger.async_to_sync", return_value=start),+ patch("products.replay_vision.backend.max_tools.record_scanner_limit_reached") as record,+ ):+ content, artifact = await self._tool()._arun_impl(session_ids=["s1"], scanner_id=str(scanner.id))++ assert [r["scan_outcome"] for r in artifact["results"]] == ["started"]+ assert "credit limit" not in content+ record.assert_not_called()++class TestCreateReplayVisionScannerTool(BaseTest):def _tool(self) -> CreateReplayVisionScannerTool:config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}diff --git a/products/replay_vision/backend/tests/test_prompt_evaluation.py b/products/replay_vision/backend/tests/test_prompt_evaluation.pyindex 90945d6495a2..8415d9f28fd9 100644--- a/products/replay_vision/backend/tests/test_prompt_evaluation.py+++ b/products/replay_vision/backend/tests/test_prompt_evaluation.py@@ -14,7 +14,7 @@ from products.replay_vision.backend.models.replay_observation import ()from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabelfrom products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsage-from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerType+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.models.replay_scanner_prompt_suggestion import (ReplayScannerPromptSuggestion,SuggestionStatus,@@ -22,7 +22,6 @@ from products.replay_vision.backend.models.replay_scanner_prompt_suggestion impofrom products.replay_vision.backend.prompt_evaluation import (EVALUATE_PROMPT_SUGGESTION_EXECUTION_TIMEOUT,EVALUATION_SESSION_CAP,- EVALUATION_SESSION_DEFAULT,build_running_evaluation,classify_outcome,evaluation_supported,@@ -45,6 +44,7 @@ from products.replay_vision.backend.temporal.evaluation_types import (RecordEvaluationResultInputs,SelectEvaluationSessionsInputs,)+from products.replay_vision.backend.tests.helpers import seed_scanner_spendfrom products.replay_vision.backend.tests.test_api import _VisionAPITestCase@@ -434,8 +434,9 @@ class TestPromptEvaluationApi(_VisionAPITestCase):self.assertEqual(resp.json()["evaluation"]["total"], 1)client.start_workflow.assert_awaited_once()self.assertIn(str(suggestion.id), client.start_workflow.await_args.kwargs["id"])- # Without an explicit session_limit the test runs the small default, not the full cap.- self.assertEqual(client.start_workflow.await_args.args[1].session_limit, EVALUATION_SESSION_DEFAULT)+ # The workflow gets the admitted count, not the raw default: ratings added after the+ # budget check must not widen the run past what was charged for.+ self.assertEqual(client.start_workflow.await_args.args[1].session_limit, 1)# No edited config posted, so the run tests the stored suggestion.self.assertIsNone(client.start_workflow.await_args.args[1].config_override)# Receipt ids are keyed on started_at, so the run must carry the stamp it was started with rather@@ -444,6 +445,19 @@ class TestPromptEvaluationApi(_VisionAPITestCase):assert suggestion.evaluation is not Noneself.assertEqual(client.start_workflow.await_args.args[1].started_at, suggestion.evaluation["started_at"])+ def test_evaluate_bounds_the_run_to_the_admitted_session_count(self) -> None:+ # An explicit limit above the rated count is admitted (and budget-checked) at the rated+ # count; the workflow must not select more if extra ratings land before it runs.+ self._create_rated()+ suggestion = self._create_pending_suggestion()+ connect_patch, client = self._mock_temporal()+ with connect_patch:+ resp = self.client.post(self._url(suggestion.id), {"session_limit": 5}, format="json")++ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(resp.json()["evaluation"]["total"], 1)+ self.assertEqual(client.start_workflow.await_args.args[1].session_limit, 1)+def test_evaluate_passes_edited_config_to_workflow(self) -> None:self._create_rated()suggestion = self._create_pending_suggestion()@@ -673,3 +687,48 @@ class TestPromptEvaluationApi(_VisionAPITestCase):self.assertEqual(resp.status_code, 200, resp.json())self.assertEqual(resp.json()["evaluation"]["status"], "running")client.start_workflow.assert_awaited_once()++ def test_evaluate_is_refused_when_the_scanner_limit_cannot_cover_the_test(self) -> None:+ for i in range(3):+ self._create_rated(f"sess-{i}")+ suggestion = self._create_pending_suggestion()+ session_credits = observation_credits_for_model(self.scanner.model)+ # Spend leaves exactly one re-run's worth of credits, but the default plans three.+ seed_scanner_spend(self.scanner, 2 * session_credits)+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=3 * session_credits)+ connect_patch, client = self._mock_temporal()+ with connect_patch:+ resp = self.client.post(self._url(suggestion.id))++ self.assertEqual(resp.status_code, 402, resp.json())+ client.start_workflow.assert_not_awaited()+ suggestion.refresh_from_db()+ self.assertIsNone(suggestion.evaluation)++ def test_evaluate_scanner_limit_leaves_org_message_precedence_when_org_is_also_exhausted(self) -> None:+ # The org check runs first, so an org that is also out of budget must still report the org+ # message even though the scanner limit would also refuse this test.+ self._create_rated()+ suggestion = self._create_pending_suggestion()+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=1)+ quota = MagicMock(remaining=0, credit_limit=100, period_end=timezone.now())+ connect_patch, client = self._mock_temporal()+ with (+ connect_patch,+ patch("products.replay_vision.backend.api.prompt_suggestions.quota_state", return_value=quota),+ ):+ resp = self.client.post(self._url(suggestion.id))++ self.assertEqual(resp.status_code, 402)+ self.assertIn("monthly Replay Vision credit limit", resp.json()["detail"])+ client.start_workflow.assert_not_awaited()++ def test_evaluate_is_unaffected_when_no_scanner_limit_is_set(self) -> None:+ self._create_rated()+ suggestion = self._create_pending_suggestion()+ connect_patch, client = self._mock_temporal()+ with connect_patch:+ resp = self.client.post(self._url(suggestion.id))++ self.assertEqual(resp.status_code, 200, resp.json())+ client.start_workflow.assert_awaited_once()diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.pyindex f5661b373cbc..6def9d0ecf84 100644--- a/products/replay_vision/backend/tests/test_sweep.py+++ b/products/replay_vision/backend/tests/test_sweep.py@@ -10,6 +10,7 @@ from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedErrorfrom posthog.models import Organization, Team+from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,@@ -25,6 +26,7 @@ from products.replay_vision.backend.temporal import SweepScannerWorkflowfrom products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (advance_scanner_watermark_activity,)+from products.replay_vision.backend.temporal.activities.check_scanner_budget import check_scanner_budget_activityfrom products.replay_vision.backend.temporal.activities.count_in_flight_applies import (count_in_flight_applies_activity,count_in_flight_by_team_activity,@@ -42,6 +44,8 @@ from products.replay_vision.backend.temporal.constants import (from products.replay_vision.backend.temporal.sweep_types import (AdvanceScannerWatermarkInputs,CandidateSessionPayload,+ CheckScannerBudgetInputs,+ CheckScannerBudgetOutput,FindScannerCandidatesInputs,FindScannerCandidatesOutput,InFlightApplyCounts,@@ -49,6 +53,10 @@ from products.replay_vision.backend.temporal.sweep_types import ()from products.replay_vision.backend.temporal.vision_actions.activities import evaluate_due_vision_actions_activityfrom products.replay_vision.backend.temporal.vision_actions.types import DueVisionAction+from products.replay_vision.backend.tests.helpers import seed_scanner_spend, snapshot_for++# Every scanner built below runs on this model, so its price sets what one observation draws.+_OBSERVATION_CREDITS = observation_credits_for_model(ScannerModel.GEMINI_3_6_FLASH)def _make_scanner(**overrides) -> ReplayScanner:@@ -65,6 +73,22 @@ def _make_scanner(**overrides) -> ReplayScanner:return ReplayScanner.objects.create(**defaults)+def _seed_in_flight_observations(scanner: ReplayScanner, *, count: int) -> None:+ # Pending rows reserve credits live from their snapshot model. They settle no receipt until success.+ snapshot = snapshot_for(scanner)+ ReplayObservation.objects.bulk_create(+ ReplayObservation(+ scanner=scanner,+ team=scanner.team,+ session_id=f"in-flight-{i}",+ status=ObservationStatus.PENDING,+ scanner_snapshot=snapshot,+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ for i in range(count)+ )++# find_scanner_candidates_activity@@ -513,6 +537,74 @@ class TestAdvanceScannerWatermarkActivity:assert scanner.scanner_version == original_version+# check_scanner_budget_activity+++ "limit, spent_observations, expect_capped",+ [+ (None, 0, False),+ # No limit set, and heavy spend: never capped, watermark never touched.+ (None, 100, False),+ (20 * _OBSERVATION_CREDITS, 0, False),+ (20 * _OBSERVATION_CREDITS, 10, False),+ # Exactly one observation's worth of room left.+ (20 * _OBSERVATION_CREDITS, 19, False),+ # Credits left, but not enough for one more observation.+ (20 * _OBSERVATION_CREDITS - 1, 19, True),+ (20 * _OBSERVATION_CREDITS, 20, True),+ ],+)[email protected]_db(transaction=True)+def test_check_scanner_budget_activity_caps_and_advances_the_watermark(+ limit: int | None, spent_observations: int, expect_capped: bool+) -> None:+ scanner = _make_scanner(credit_limit=limit)+ stale = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ last_swept_at=stale, last_seen_session_id="sess-old", last_deep_swept_at=stale+ )+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=spent_observations)++ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))++ scanner.refresh_from_db()+ assert output.capped is expect_capped+ if expect_capped:+ # Skip the capped window rather than backfilling (and billing) it when the limit frees up.+ assert scanner.last_swept_at > stale+ assert scanner.last_seen_session_id == ""+ # The deep pass walks [last_deep_swept_at, last_swept_at), so a stale value would hand the+ # first uncapped deep sweep exactly the window this reset skips.+ assert scanner.last_deep_swept_at == scanner.last_swept_at+ else:+ assert scanner.last_swept_at == stale+ assert scanner.last_seen_session_id == "sess-old"+ assert scanner.last_deep_swept_at == stale++[email protected]_db(transaction=True)+def test_check_scanner_budget_activity_capped_by_in_flight_alone_does_not_advance_the_watermark() -> None:+ # Only adding in-flight reservations pushes this over the limit: a transient spike must skip+ # the tick without burning the permanent watermark advance.+ limit = 20 * _OBSERVATION_CREDITS+ scanner = _make_scanner(credit_limit=limit)+ stale = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ last_swept_at=stale, last_seen_session_id="sess-old", last_deep_swept_at=stale+ )+ seed_scanner_spend(scanner, _OBSERVATION_CREDITS, observations=10)+ _seed_in_flight_observations(scanner, count=10)++ output = check_scanner_budget_activity(CheckScannerBudgetInputs(scanner_id=scanner.id, team_id=scanner.team_id))++ scanner.refresh_from_db()+ assert output.capped is True+ assert scanner.last_swept_at == stale+ assert scanner.last_seen_session_id == "sess-old"+ assert scanner.last_deep_swept_at == stale++# SweepScannerWorkflow (mocked-Temporal)@@ -536,7 +628,13 @@ class _SweepMocks:# Default to no due vision actions unless a test overrides it.if activity_fn is evaluate_due_vision_actions_activity and activity_fn not in self.activity_results:return []- return self.activity_results.get(activity_fn)+ # Default to not-capped so the budget gate leaves every other sweep test unaffected.+ if activity_fn is check_scanner_budget_activity and activity_fn not in self.activity_results:+ return CheckScannerBudgetOutput(capped=False)+ result = self.activity_results.get(activity_fn)+ if isinstance(result, Exception):+ raise result+ return resultasync def start_child_workflow(self, *args: Any, **kwargs: Any) -> Any:wid = kwargs.get("id")@@ -571,6 +669,7 @@ async def _run_sweep(mocks: _SweepMocks, inputs: SweepScannerInputs | None = Nonpatch("temporalio.workflow.logger", fake_logger),# `workflow.patched` also needs the runtime; new executions take the patched branch.patch("temporalio.workflow.patched", return_value=patched),+ patch("temporalio.workflow.unsafe.is_replaying", return_value=False),):await SweepScannerWorkflow().run(inputs or _sweep_inputs())@@ -588,6 +687,7 @@ async def test_empty_batch_skips_dispatch_and_advance() -> None:assert [fn for fn, _ in mocks.activity_calls] == [evaluate_due_vision_actions_activity,refresh_prompt_suggestion_activity,+ check_scanner_budget_activity,count_in_flight_by_team_activity,find_scanner_candidates_activity,]@@ -782,6 +882,7 @@ async def test_inflight_cap_gates_the_sweep(assert [fn for fn, _ in mocks.activity_calls] == [evaluate_due_vision_actions_activity,refresh_prompt_suggestion_activity,+ check_scanner_budget_activity,count_in_flight_by_team_activity,]assert mocks.child_calls == []@@ -789,6 +890,43 @@ async def test_inflight_cap_gates_the_sweep(assert find_calls[0].candidate_limit == expected_candidate_limit+async def test_capped_scanner_skips_the_sweep_entirely() -> None:+ mocks = _SweepMocks(+ activity_results={+ check_scanner_budget_activity: CheckScannerBudgetOutput(capped=True),+ find_scanner_candidates_activity: FindScannerCandidatesOutput(candidates=[], saturated=False),+ },+ )++ await _run_sweep(mocks)++ called = [fn for fn, _ in mocks.activity_calls]+ # Capped means no session scans; the heartbeats spend no scanner credits, so they still run.+ assert evaluate_due_vision_actions_activity in called+ assert refresh_prompt_suggestion_activity in called+ assert find_scanner_candidates_activity not in called+ assert count_in_flight_by_team_activity not in called+ assert mocks.child_calls == []+++async def test_budget_check_failure_does_not_fail_the_sweep() -> None:+ # A rolling deploy can land the activity on a worker without it registered; the gate fails+ # open rather than erroring the whole sweep.+ mocks = _SweepMocks(+ activity_results={+ check_scanner_budget_activity: RuntimeError("activity type not registered"),+ find_scanner_candidates_activity: FindScannerCandidatesOutput(candidates=[], saturated=False),+ },+ )++ await _run_sweep(mocks)++ called = [fn for fn, _ in mocks.activity_calls]+ assert find_scanner_candidates_activity in called++@pytest.mark.asyncioasync def test_unpatched_sweep_replays_legacy_scanner_counter() -> None:# A sweep that started before the team-cap patch must replay the legacy scanner-only counter (its@@ -806,6 +944,8 @@ async def test_unpatched_sweep_replays_legacy_scanner_counter() -> None:called = [fn for fn, _ in mocks.activity_calls]assert count_in_flight_applies_activity in calledassert count_in_flight_by_team_activity not in called+ # The budget gate is patched too, so a pre-deploy sweep replays its history without it.+ assert check_scanner_budget_activity not in calledfind_calls = [inp for fn, inp in mocks.activity_calls if fn == find_scanner_candidates_activity]assert find_calls[0].candidate_limit == MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 3@@ -827,7 +967,8 @@ async def test_sweep_dispatches_a_child_per_due_vision_action() -> None:started = {call["id"] for call in mocks.child_calls}assert started == {build_process_vision_action_workflow_id(d.vision_action_id) for d in due}- # Dispatch happens before the session scan, so the children start even with no candidates.+ # Dispatch happens first, before the budget gate and the session scan, so the children+ # start even with no candidates.assert evaluate_due_vision_actions_activity == mocks.activity_calls[0][0]diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 4f9cc2c99a77..07a43d6514d5 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1,13 +1,14 @@import timeimport uuidimport datetime as dt+import threadingfrom typing import Anyimport pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.conf import settings-from django.db import IntegrityError+from django.db import IntegrityError, connectionsfrom django.utils import timezoneimport httpx@@ -137,7 +138,10 @@ from products.replay_vision.backend.temporal.workflow import (_failure_type,_root_cause_message,)-from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for+from products.replay_vision.backend.tests.helpers import (+ seed_scanner_spend,+ snapshot_for as _snapshot_for,+)from products.signals.backend.contracts import ReplayVisionScannerFindingSignalInputfrom products.signals.backend.models import SignalSourceConfig@@ -496,6 +500,186 @@ class TestCreateObservationActivity:)assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-no-consent").exists()+ @parameterized.expand(+ [+ (None, 0, True),+ (None, 10_000, True),+ (100, 0, True),+ (100, 80, True),+ (100, 90, False),+ (100, 100, False),+ (15, 0, True),+ (14, 0, False),+ ]+ )+ def test_scanner_credit_limit_gates_observation_creation(+ self, limit: int | None, already_spent_credits: int, expect_created: bool+ ) -> None:+ scanner = _make_scanner(credit_limit=limit)+ seed_scanner_spend(scanner, already_spent_credits)++ # This test isolates the scanner gate; keep the unsynced-org fallback quota out of the way.+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):+ result = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-scanner-limit",+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id="wf-scanner-limit",+ )+ )++ assert result.was_created is expect_created+ exists = ReplayObservation.objects.filter(scanner=scanner, session_id="sess-scanner-limit").exists()+ assert exists is expect_created++ def test_concurrent_admissions_cannot_exceed_scanner_credit_limit(self) -> None:+ # Two applies for different sessions race with a cap that fits exactly one observation. Without the+ # per-scanner lock both read a used=0 budget, both pass, and both reserve a PENDING row (overshoot).+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_6_FLASH.value)+ scanner = _make_scanner(credit_limit=credits)+ barrier = threading.Barrier(2)+ created: dict[str, bool] = {}++ def admit(session_id: str) -> None:+ barrier.wait()+ try:+ created[session_id] = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id=session_id,+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id=f"wf-{session_id}",+ )+ ).was_created+ finally:+ # Dropping the worker's own connection avoids stranding its lock transaction past teardown.+ connections.close_all()++ threads = [threading.Thread(target=admit, args=(s,)) for s in ("race-a", "race-b")]+ for thread in threads:+ thread.start()+ for thread in threads:+ # A lock regression must fail the test, not hang the suite.+ thread.join(timeout=30)+ assert not any(thread.is_alive() for thread in threads)++ assert sorted(created.values()) == [False, True]+ assert ReplayObservation.objects.filter(scanner=scanner, status=ObservationStatus.PENDING).count() == 1++ def test_concurrent_admissions_for_an_uncapped_scanner_both_succeed(self) -> None:+ # The admission lock is capped-only: two uncapped applies must not serialize or skip.+ scanner = _make_scanner(credit_limit=None)+ barrier = threading.Barrier(2)+ created: dict[str, bool] = {}++ def admit(session_id: str) -> None:+ barrier.wait()+ try:+ created[session_id] = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id=session_id,+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id=f"wf-{session_id}",+ )+ ).was_created+ finally:+ connections.close_all()++ threads = [threading.Thread(target=admit, args=(s,)) for s in ("free-a", "free-b")]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=30)+ assert not any(thread.is_alive() for thread in threads)++ assert sorted(created.values()) == [True, True]+ assert ReplayObservation.objects.filter(scanner=scanner, status=ObservationStatus.PENDING).count() == 2++ def test_concurrent_admissions_for_two_capped_scanners_do_not_serialize_each_other(self) -> None:+ # The admission lock is per scanner row: two different capped scanners on one team must both+ # admit their own observation, with no cross-scanner budget bleed or lock coupling.+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_6_FLASH.value)+ scanner_a = _make_scanner(credit_limit=credits)+ scanner_b = ReplayScanner.objects.create(+ team=scanner_a.team,+ name="capped-sibling",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ credit_limit=credits,+ )+ barrier = threading.Barrier(2)+ created: dict[str, bool] = {}++ def admit(scanner: ReplayScanner, session_id: str) -> None:+ barrier.wait()+ try:+ created[session_id] = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id=session_id,+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id=f"wf-{session_id}",+ )+ ).was_created+ finally:+ connections.close_all()++ threads = [+ threading.Thread(target=admit, args=(scanner_a, "sibling-a")),+ threading.Thread(target=admit, args=(scanner_b, "sibling-b")),+ ]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=30)+ assert not any(thread.is_alive() for thread in threads)++ assert created == {"sibling-a": True, "sibling-b": True}++ def test_retry_near_the_cap_reclaims_its_own_pending_row(self) -> None:+ # A Temporal retry whose first attempt committed the insert but lost the result must get its+ # row back: that row's own reservation fills the budget, so a plain refusal would strand it+ # PENDING forever while the workflow gives up.+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_6_FLASH.value)+ scanner = _make_scanner(credit_limit=credits)+ first_attempt = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-retry",+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id="wf-retry",+ )+ )+ assert first_attempt.was_created is True++ second_attempt = create_observation_activity(+ CreateObservationInputs(+ scanner_id=scanner.id,+ team_id=scanner.team_id,+ session_id="sess-retry",+ triggered_by=ObservationTrigger.SCHEDULE,+ triggered_by_user_id=None,+ workflow_id="wf-retry",+ )+ )++ assert second_attempt.observation_id == first_attempt.observation_id+ assert second_attempt.was_created is True+ assert ReplayObservation.objects.filter(scanner=scanner).count() == 1+@pytest.mark.django_db(transaction=True)class TestEgressConsentRecheck:diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 31e945f940e9..1183061d9570 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1048,8 +1048,9 @@ export interface BulkObserveRequestApi {* * `started` - Started* * `already_running` - Already running* * `already_scanned` - Already scanned- * * `skipped_limit` - Skipped - in-flight limit reached- * * `skipped_quota` - Skipped - monthly credit quota reached+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached* * `failed` - Failed to start*/export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]@@ -1060,6 +1061,7 @@ export const ScanOutcomeEnumApi = {AlreadyScanned: 'already_scanned',SkippedLimit: 'skipped_limit',SkippedQuota: 'skipped_quota',+ SkippedScannerLimit: 'skipped_scanner_limit',Failed: 'failed',} as const@@ -1069,13 +1071,14 @@ export const ScanOutcomeEnumApi = {export interface BulkObserveResultApi {/** The session recording this outcome is for. */session_id: string- /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; 'failed' - the workflow failed to start.+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the org's credit quota for this period would be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; 'failed' - the workflow failed to start.** * `started` - Started* * `already_running` - Already running* * `already_scanned` - Already scanned- * * `skipped_limit` - Skipped - in-flight limit reached- * * `skipped_quota` - Skipped - monthly credit quota reached+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached* * `failed` - Failed to start */scan_outcome: ScanOutcomeEnumApi}diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 4ce319a3849d..e24228aaf9aa 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -1062,7 +1062,7 @@ export const getVisionScannersPromptSuggestionsEvaluateCreateUrl = (}/**- * Test this suggestion before applying it: re-run the scanner with the suggested prompt against already-rated sessions in the background and compare each fresh output with the stored one. Results land on the suggestion's `evaluation` field. Poll `current` while status is running. `session_limit` controls how many rated sessions are re-run (thumbs-down prioritized, up to `evaluation_session_cap`). Each successful re-run charges credits like a normal observation of the same model. The request is refused with 402 when the planned credits exceed what is left of the monthly limit. Monitor and classifier scanners get a kept/fixed/regressed classification, while scorer and summarizer scanners show the raw before and after output. Requires session recording edit access.+ * Test this suggestion before applying it: re-run the scanner with the suggested prompt against already-rated sessions in the background and compare each fresh output with the stored one. Results land on the suggestion's `evaluation` field. Poll `current` while status is running. `session_limit` controls how many rated sessions are re-run (thumbs-down prioritized, up to `evaluation_session_cap`). Each successful re-run charges credits like a normal observation of the same model. The request is refused with 402 when the planned credits exceed what is left for the current billing period, either the org's limit or this scanner's own. Monitor and classifier scanners get a kept/fixed/regressed classification, while scorer and summarizer scanners show the raw before and after output. Requires session recording edit access.*/export const visionScannersPromptSuggestionsEvaluateCreate = async (projectId: string,diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 7856fd318fed..6fb97f7db97f 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -769,7 +769,7 @@ export const VisionScannersPromptSuggestionsApplyCreateBody = /* @__PURE__ */ zo})/**- * Test this suggestion before applying it: re-run the scanner with the suggested prompt against already-rated sessions in the background and compare each fresh output with the stored one. Results land on the suggestion's `evaluation` field. Poll `current` while status is running. `session_limit` controls how many rated sessions are re-run (thumbs-down prioritized, up to `evaluation_session_cap`). Each successful re-run charges credits like a normal observation of the same model. The request is refused with 402 when the planned credits exceed what is left of the monthly limit. Monitor and classifier scanners get a kept/fixed/regressed classification, while scorer and summarizer scanners show the raw before and after output. Requires session recording edit access.+ * Test this suggestion before applying it: re-run the scanner with the suggested prompt against already-rated sessions in the background and compare each fresh output with the stored one. Results land on the suggestion's `evaluation` field. Poll `current` while status is running. `session_limit` controls how many rated sessions are re-run (thumbs-down prioritized, up to `evaluation_session_cap`). Each successful re-run charges credits like a normal observation of the same model. The request is refused with 402 when the planned credits exceed what is left for the current billing period, either the org's limit or this scanner's own. Monitor and classifier scanners get a kept/fixed/regressed classification, while scorer and summarizer scanners show the raw before and after output. Requires session recording edit access.*/export const visionScannersPromptSuggestionsEvaluateCreateBodySessionLimitDefault = 10export const visionScannersPromptSuggestionsEvaluateCreateBodySessionLimitMax = 100diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.tsindex d7274e23d4bc..93b65ed5a0da 100644--- a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts@@ -29,6 +29,15 @@ export interface RowObservation {export const IN_PROGRESS_STATUSES = new Set<string>(['pending', 'running'])+type BulkSkipOutcome = 'skipped_limit' | 'skipped_quota' | 'skipped_scanner_limit'++const BULK_SKIP_MESSAGES: Record<BulkSkipOutcome, string> = {+ skipped_limit: 'No scans started. Too many scans are already running. Wait for some to finish, then try again.',+ skipped_quota:+ "No scans started. Your organization's Replay vision credit limit for this billing period is used up.",+ skipped_scanner_limit: 'No scans started. This scanner reached its credit limit for this billing period.',+}+// Headroom per visible session for the observations a retry stacks on top of the original scan.const OBSERVATIONS_PER_SESSION_ALLOWANCE = 4@@ -223,9 +232,18 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([const started = response.started// The backend scans what fits and reports the rest — surface the split so the user// knows a partial run happened rather than assuming everything started.- const limited = results.filter(- (r) => r.scan_outcome === 'skipped_limit' || r.scan_outcome === 'skipped_quota'- ).length+ const skipCounts: Record<BulkSkipOutcome, number> = {+ skipped_limit: 0,+ skipped_quota: 0,+ skipped_scanner_limit: 0,+ }+ for (const r of results) {+ if (r.scan_outcome && r.scan_outcome in skipCounts) {+ skipCounts[r.scan_outcome as BulkSkipOutcome] += 1+ }+ }+ const limited =+ skipCounts.skipped_limit + skipCounts.skipped_quota + skipCounts.skipped_scanner_limitconst failed = results.filter((r) => r.scan_outcome === 'failed').lengthconst extras = [limited ? `${limited} skipped (limit reached)` : null,@@ -238,7 +256,11 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([`Started ${started} scan${started === 1 ? '' : 's'}${extras ? ` — ${extras}` : ''}`)} else if (limited > 0) {- lemonToast.warning("No scans started — you've hit the in-flight or monthly credit limit.")+ // Ties break toward the most specific reason, matching the backend's headroom tie-break.+ const dominant = (+ ['skipped_scanner_limit', 'skipped_quota', 'skipped_limit'] as BulkSkipOutcome[]+ ).reduce((a, b) => (skipCounts[b] > skipCounts[a] ? b : a))+ lemonToast.warning(BULK_SKIP_MESSAGES[dominant])} else {lemonToast.error('No scans started. Please try again.')}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ec277a02fdc8..92f308ef320c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13502,8 +13502,9 @@ export namespace Schemas {* * `started` - Started* * `already_running` - Already running* * `already_scanned` - Already scanned- * * `skipped_limit` - Skipped - in-flight limit reached- * * `skipped_quota` - Skipped - monthly credit quota reached+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached* * `failed` - Failed to start*/export type ScanOutcomeEnum = typeof ScanOutcomeEnum[keyof typeof ScanOutcomeEnum];@@ -13515,6 +13516,7 @@ export namespace Schemas {AlreadyScanned: 'already_scanned',SkippedLimit: 'skipped_limit',SkippedQuota: 'skipped_quota',+ SkippedScannerLimit: 'skipped_scanner_limit',Failed: 'failed',} as const;@@ -13524,13 +13526,14 @@ export namespace Schemas {export interface BulkObserveResult {/** The session recording this outcome is for. */session_id: string;- /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; 'failed' - the workflow failed to start.+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the org's credit quota for this period would be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; 'failed' - the workflow failed to start.** * `started` - Started* * `already_running` - Already running* * `already_scanned` - Already scanned- * * `skipped_limit` - Skipped - in-flight limit reached- * * `skipped_quota` - Skipped - monthly credit quota reached+ * * `skipped_limit` - Skipped, in-flight limit reached+ * * `skipped_quota` - Skipped, the org's credit quota for this period was reached+ * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached* * `failed` - Failed to start */scan_outcome: ScanOutcomeEnum;}