: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): per-scanner credit budget accounting (#75086)
Arno Hillen193943a4dcf5
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txtindex ffe7624d00f6..0b60f00165cc 100644--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt@@ -5,16 +5,14 @@# safe when the migration's operations are idempotent (a re-run is a no-op on already-applied# rows). The usual reason to want it is a long-running data migration that commits in batches# so it never holds locks or bloats WAL for one giant transaction.-## Before adding a line here, prefer keeping the migration atomic (the default) if the data# volume is small, or moving a genuinely large backfill to an async migration.-## Adding a line means: I understand this migration runs without transaction rollback safety,# and its operations are idempotent so a bin/migrate retry after a partial failure is safe.-## Format: one "<app_label>.<migration_name>" per line, e.g.# posthog.1234_backfill_something_in_batchesposthog.1264_delete_revenue_analytics_user_product_listproduct_analytics.0004_delete_revenue_analytics_insightstasks.0079_backfill_task_repositories+replay_vision.0070_backfill_usage_scanner_idtasks.0088_backfill_task_search_documentsdiff --git a/products/replay_vision/backend/migrations/0067_scanner_credit_limit.py b/products/replay_vision/backend/migrations/0067_scanner_credit_limit.pynew file mode 100644index 000000000000..38f2a5ae8c87--- /dev/null+++ b/products/replay_vision/backend/migrations/0067_scanner_credit_limit.py@@ -0,0 +1,50 @@+# Generated by Django 5.2.14 on 2026-07-30 14:19++import django.core.validators+from django.conf import settings+from django.db import migrations, models++from posthog.migration_helpers import AddConstraintNotValid+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1271_add_pardot_integration_kind"),+ ("replay_vision", "0066_replayscanner_last_deep_swept_at"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="replayobservationusage",+ name="scanner_id",+ field=models.UUIDField(+ help_text="The scanner that produced this observation. Per-scanner credit limits aggregate on this (plain id, no FK).",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="replayscanner",+ name="credit_limit",+ field=models.PositiveIntegerField(+ blank=True,+ help_text="Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap.",+ null=True,+ validators=[django.core.validators.MinValueValidator(1)],+ ),+ ),+ # NOT VALID adds the constraint with only a brief metadata lock, skipping the row scan.+ # VALIDATE runs in the follow-up migration so the ACCESS EXCLUSIVE lock is not held+ # across the scan and scanner reads/writes are never blocked during deploy.+ AddConstraintNotValid(+ model_name="replayscanner",+ constraint=models.CheckConstraint(+ condition=models.Q(+ ("credit_limit__isnull", True),+ ("credit_limit__gte", 1),+ _connector="OR",+ ),+ name="replay_scanner_credit_limit_positive",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0068_scanner_usage_scanner_id_index.py b/products/replay_vision/backend/migrations/0068_scanner_usage_scanner_id_index.pynew file mode 100644index 000000000000..e090582ed00b--- /dev/null+++ b/products/replay_vision/backend/migrations/0068_scanner_usage_scanner_id_index.py@@ -0,0 +1,24 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Isolated from the schema+ # changes in 0066 so those keep atomic rollback safety while the index build stays non-blocking.+ atomic = False++ dependencies = [+ ("replay_vision", "0067_scanner_credit_limit"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="replayobservationusage",+ index=models.Index(+ condition=models.Q(("scanner_id__isnull", False)),+ fields=["scanner_id", "observation_created_at"],+ name="rlou_scanner_created_idx",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0069_validate_replay_scanner_credit_limit_positive.py b/products/replay_vision/backend/migrations/0069_validate_replay_scanner_credit_limit_positive.pynew file mode 100644index 000000000000..b39ed57e22d5--- /dev/null+++ b/products/replay_vision/backend/migrations/0069_validate_replay_scanner_credit_limit_positive.py@@ -0,0 +1,19 @@+from django.db import migrations++from posthog.migration_helpers import ValidateConstraint+++class Migration(migrations.Migration):+ # VALIDATE runs under SHARE UPDATE EXCLUSIVE (does not block reads or writes). Kept in its+ # own migration so 0066's NOT VALID add commits and releases its ACCESS EXCLUSIVE lock first,+ # rather than holding it across the validation scan.+ dependencies = [+ ("replay_vision", "0068_scanner_usage_scanner_id_index"),+ ]++ operations = [+ ValidateConstraint(+ model_name="replayscanner",+ name="replay_scanner_credit_limit_positive",+ ),+ ]diff --git a/products/replay_vision/backend/migrations/0070_backfill_usage_scanner_id.py b/products/replay_vision/backend/migrations/0070_backfill_usage_scanner_id.pynew file mode 100644index 000000000000..2028830823f9--- /dev/null+++ b/products/replay_vision/backend/migrations/0070_backfill_usage_scanner_id.py@@ -0,0 +1,59 @@+import uuid++from django.db import migrations++BATCH_SIZE = 10_000+++def backfill_scanner_id(apps, schema_editor):+ """Attribute pre-existing receipts to their scanner, so a limit set mid-period counts the+ period's earlier spend instead of starting from zero. Receipts whose observation was already+ deleted have nothing to derive from and stay unattributed, as do pre-stack prompt-evaluation+ receipts, whose synthetic observation_id (uuid5 of suggestion/session/started_at, see+ prompt_evaluation.py) matches no observation row; that spend is bounded by the evaluation+ session cap and accepted. A follow-up migration in the notification PR repeats this pass to+ catch receipts written by old-code workers during the rolling deploy."""+ usage_table = apps.get_model("replay_vision", "ReplayObservationUsage")._meta.db_table+ observation_table = apps.get_model("replay_vision", "ReplayObservation")._meta.db_table+ # Keyset pagination on the pk: the null scanner_id rows have no index, so a plain LIMIT+ # loop would re-scan the table head on every batch.+ last_id = uuid.UUID("00000000-0000-0000-0000-000000000000")+ with schema_editor.connection.cursor() as cursor:+ while True:+ cursor.execute(+ f"""+ WITH batch AS (+ SELECT u.id AS usage_id, o.scanner_id AS scanner_id+ FROM {usage_table} u+ JOIN {observation_table} o ON o.id = u.observation_id+ WHERE u.scanner_id IS NULL AND u.id > %(last_id)s+ ORDER BY u.id+ LIMIT {BATCH_SIZE}+ )+ UPDATE {usage_table} AS tgt+ SET scanner_id = batch.scanner_id+ FROM batch+ WHERE tgt.id = batch.usage_id+ RETURNING batch.usage_id+ """,+ {"last_id": last_id},+ )+ updated_ids = [row[0] for row in cursor.fetchall()]+ if not updated_ids:+ break+ last_id = max(updated_ids)+ if len(updated_ids) < BATCH_SIZE:+ break+++class Migration(migrations.Migration):+ # Batches commit independently so the update never holds long locks on the receipt table.+ atomic = False++ dependencies = [+ ("replay_vision", "0069_validate_replay_scanner_credit_limit_positive"),+ ]++ operations = [+ migrations.RunPython(backfill_scanner_id, migrations.RunPython.noop, elidable=False),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex b8a062b24a6b..9c0537ff6a88 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0066_replayscanner_last_deep_swept_at+0070_backfill_usage_scanner_iddiff --git a/products/replay_vision/backend/models/replay_observation_usage.py b/products/replay_vision/backend/models/replay_observation_usage.pyindex c02c8f19bd5a..40f4297d65c0 100644--- a/products/replay_vision/backend/models/replay_observation_usage.py+++ b/products/replay_vision/backend/models/replay_observation_usage.py@@ -23,6 +23,10 @@ class ReplayObservationUsage(UUIDModel):null=True,help_text="The observation's team; the per-team billing usage report groups on this (plain id, no FK).",)+ scanner_id = models.UUIDField(+ null=True,+ help_text="The scanner that produced this observation. Per-scanner credit limits aggregate on this (plain id, no FK).",+ )observation_created_at = models.DateTimeField(help_text="The observation's created_at; the monthly quota window filters on this.",)@@ -42,6 +46,15 @@ class ReplayObservationUsage(UUIDModel):models.Index(fields=["organization", "observation_created_at"]),# Drives the daily per-team billing usage query, which buckets receipts by write time.models.Index(fields=["created_at", "team_id"], name="rlou_created_team_idx"),+ # Drives the per-scanner credit limit aggregate over the current billing period. Partial+ # because the aggregate only ever looks up concrete scanner ids; rows left null (their+ # observation was deleted before the 0070 backfill, or they are pre-stack evaluation+ # receipts with synthetic observation ids) are never queried.+ models.Index(+ fields=["scanner_id", "observation_created_at"],+ name="rlou_scanner_created_idx",+ condition=models.Q(scanner_id__isnull=False),+ ),]def __str__(self) -> str:diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex fafb3df0692b..be49af9f686a 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -185,6 +185,15 @@ class ReplayScanner(UUIDModel):help_text="When the estimate was last computed. Refreshed on config saves and by the sweep when stale.",)+ # Not "monthly": this resets with the org's billing period, which is only a calendar month+ # until billing syncs a real one. See quota.current_period_bounds.+ credit_limit = models.PositiveIntegerField(+ null=True,+ blank=True,+ validators=[MinValueValidator(1)],+ help_text="Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap.",+ )+created_at = models.DateTimeField(auto_now_add=True)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")updated_at = models.DateTimeField(auto_now=True)@@ -220,6 +229,12 @@ class ReplayScanner(UUIDModel):condition=models.Q(sampling_rate__gte=0.0) & models.Q(sampling_rate__lte=1.0),name="replay_scanner_sampling_rate_range",),+ # A stray 0 would read as "block every observation" to the quota check, and be+ # indistinguishable from an unset cap. NULL stays valid: it means no scanner-level cap.+ models.CheckConstraint(+ condition=models.Q(credit_limit__isnull=True) | models.Q(credit_limit__gte=1),+ name="replay_scanner_credit_limit_positive",+ ),]indexes = [models.Index(fields=["team", "enabled"], name="rl_team_enabled_idx"),diff --git a/products/replay_vision/backend/prompt_evaluation.py b/products/replay_vision/backend/prompt_evaluation.pyindex b4e942a7401f..961572b6cd61 100644--- a/products/replay_vision/backend/prompt_evaluation.py+++ b/products/replay_vision/backend/prompt_evaluation.py@@ -124,21 +124,41 @@ def evaluation_in_flight(evaluation: Any) -> bool:return timezone.now() - started_at < EVALUATE_PROMPT_SUGGESTION_EXECUTION_TIMEOUT + _EVALUATION_RUNNING_GRACE+def _unsettled_evaluation_credits(evaluation: Any, scanner_model: str | None) -> int:+ """Credits one running evaluation still plans to charge. Settled sessions hold a receipt or never charge."""+ if not isinstance(evaluation, dict) or not evaluation_in_flight(evaluation):+ return 0+ unsettled = max(0, int(evaluation.get("total") or 0) - len(evaluation.get("results") or []))+ # Receipts bill the model frozen at workflow start, so the reservation prices from the same frozen+ # value. Stubs written before the field existed fall back to the scanner's current model.+ model = evaluation.get("model") or scanner_model+ return unsettled * observation_credits_for_model(model or "")++def in_flight_evaluation_credits(organization_id: uuid.UUID) -> int:- """Credits that running evaluations still plan to charge. Settled sessions hold a receipt or never charge."""+ """Credits that the org's running evaluations still plan to charge."""rows = ReplayScannerPromptSuggestion.objects.filter(team__organization_id=organization_id, evaluation__status="running").values_list("evaluation", "scanner__model")- total = 0- for evaluation, scanner_model in rows:- if not isinstance(evaluation, dict) or not evaluation_in_flight(evaluation):- continue- unsettled = max(0, int(evaluation.get("total") or 0) - len(evaluation.get("results") or []))- # Receipts bill the model frozen at workflow start, so the reservation prices from the same frozen- # value. Stubs written before the field existed fall back to the scanner's current model.- model = evaluation.get("model") or scanner_model- total += unsettled * observation_credits_for_model(model or "")- return total+ return sum(_unsettled_evaluation_credits(evaluation, model) for evaluation, model in rows)+++def in_flight_evaluation_credits_by_scanner(+ organization_id: uuid.UUID, scanner_ids: list[uuid.UUID]+) -> dict[uuid.UUID, int]:+ """The same reservation split per scanner: an evaluation re-runs one scanner, so it spends that+ scanner's own cap as well as the org's. Scanners with nothing running are omitted."""+ if not scanner_ids:+ return {}+ rows = ReplayScannerPromptSuggestion.objects.filter(+ team__organization_id=organization_id, scanner_id__in=scanner_ids, evaluation__status="running"+ ).values_list("scanner_id", "evaluation", "scanner__model")+ totals: dict[uuid.UUID, int] = {}+ for scanner_id, evaluation, model in rows:+ credits = _unsettled_evaluation_credits(evaluation, model)+ if credits:+ totals[scanner_id] = totals.get(scanner_id, 0) + credits+ return totalsdef build_running_evaluation(diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 601e3ab76237..fde6cd5f8113 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -1,5 +1,5 @@from collections import Counter-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom datetime import UTC, datetimefrom uuid import UUID@@ -46,7 +46,7 @@ class QuotaState:extra queries no enforcement path should pay for."""- # None means billing synced the product with no spend limit set: uncapped.+ # None means no limit applies: an org billing synced with no spend limit, or a scanner with no cap set.credit_limit: int | Nonecredits_used: intperiod_start: datetime@@ -150,6 +150,11 @@ class ScannerSpend:def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dict[UUID, ScannerSpend]:"""Credits and observation counts for each scanner's succeeded observations in the current billing period.+ This is the displayed figure, deliberately read from observation rows rather than the receipt ledger:+ it is what the scanner list column and the `credits_this_month` sort both show, and receipts carry no+ `scanner_id` before that column existed. `compute_scanner_budgets` is the delete-proof figure the+ limit is enforced against.+Priced at current rates from each observation's frozen snapshot model. Receipts freeze pricesat success time, so these totals can drift from the billed ledger after a mid-period pricechange. Scanners with no spend are omitted.@@ -176,6 +181,137 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dreturn totals+@dataclass(frozen=True)+class ScannerBudget(QuotaState):+ """A scanner's own allowance, carrying what one more observation costs.++ `credits_used` is the full draw: settled receipts plus live reservations. `settled_credits` is+ only what has actually posted to the ledger. Defaults exist only to satisfy the dataclass+ field-order rule, as `QuotaSnapshot` does; every constructor passes both.+ """++ credits_per_observation: int = 0+ settled_credits: int = 0++ @property+ def blocked(self) -> bool:+ """Whether this scanner is out of budget: the one answer every caller uses.++ `exhausted` and `would_exceed` disagree for a scanner with less than one observation of+ headroom left, which is exactly the state a capped scanner ends a period in. Gates and the+ API both read this so they cannot report different things about the same scanner.+ """+ return self.would_exceed(self.credits_per_observation)++ @property+ def blocked_by_settled_spend(self) -> bool:+ """`blocked` counting only credits that have posted.++ A reservation can release without ever writing a receipt (a failed observation), so an+ irreversible reaction to a cap must not fire on a transient in-flight spike.+ """+ return replace(self, credits_used=self.settled_credits).blocked+++def _scanner_in_flight_credits(+ organization_id: UUID, scanner_ids: list[UUID], period: BillingPeriod+) -> dict[UUID, int]:+ """Credits reserved by each scanner's in-flight rows, priced from the frozen snapshot model."""+ pairs = Counter(+ ReplayObservation.objects.filter(+ team__organization_id=organization_id,+ scanner_id__in=scanner_ids,+ status__in=IN_FLIGHT_STATUSES,+ created_at__gte=period.start,+ created_at__lt=period.end,+ ).values_list("scanner_id", "scanner_snapshot__model")+ )+ totals: dict[UUID, int] = {}+ for (scanner_id, model), count in pairs.items():+ totals[scanner_id] = totals.get(scanner_id, 0) + observation_credits_for_model(model or "") * count+ return totals+++def compute_scanner_budgets(+ organization_id: UUID, scanner_ids: list[UUID], period: BillingPeriod | None = None+) -> dict[UUID, ScannerBudget]:+ """Per-scanner budgets for the org's current billing period, with an entry for every requested scanner.++ Settled credits come from the immutable receipt ledger, so deleting observations cannot refund a+ scanner's limit. In-flight observations and running prompt evaluations are reserved live from their+ frozen snapshot model, exactly as the org snapshot does, because a sweep tick admits many+ observations concurrently against one read. Receipts written before `scanner_id` existed were+ backfilled from their observation rows (0070); only receipts whose observation was deleted+ before the backfill remain unattributed.++ Uncapped scanners skip the aggregates entirely and report zero usage: gates read `blocked`,+ which is always False without a limit, and the spend UI only renders for capped scanners.++ Pass `period` to bill against a window the caller already resolved, so an org snapshot and the+ scanner budgets taken alongside it cannot straddle a period boundary.+ """+ # Deferred: breaks the quota -> prompt_evaluation -> temporal -> quota import cycle.+ from products.replay_vision.backend.prompt_evaluation import ( # noqa: PLC0415+ in_flight_evaluation_credits_by_scanner,+ )++ if not scanner_ids:+ return {}+ if period is None:+ period = current_period_bounds(organization_id)+ # Limits are read here, not passed in: a caller that forgot them would silently disable enforcement.+ # nosemgrep: idor-lookup-without-team (org-level aggregation, the pk__in list is co-filtered by team__organization_id, so a scanner id outside this org matches nothing)+ scanner_rows = ReplayScanner.objects.filter(team__organization_id=organization_id, pk__in=scanner_ids).values_list(+ "id", "credit_limit", "model"+ )+ configs = {scanner_id: (limit, model) for scanner_id, limit, model in scanner_rows}+ # Almost every scanner is uncapped, so the spend aggregates run only for the capped ones; the+ # rest report zero usage, and `blocked` is always False without a limit.+ capped_ids = [scanner_id for scanner_id in scanner_ids if (configs.get(scanner_id) or (None,))[0] is not None]+ in_flight: dict[UUID, int] = {}+ in_flight_evaluations: dict[UUID, int] = {}+ settled: dict[UUID, int] = {}+ if capped_ids:+ # Reservations are read BEFORE the receipt ledger: an observation settling between the two reads+ # is then counted by both (a transient over-count that fails toward capped), never by neither.+ in_flight = _scanner_in_flight_credits(organization_id, capped_ids, period)+ # Evaluations write receipts directly, never observation rows, so a running test would otherwise+ # drain the cap invisibly. Not period-filtered: a live run charges whichever period it settles in.+ in_flight_evaluations = in_flight_evaluation_credits_by_scanner(organization_id, capped_ids)+ settled = {+ row["scanner_id"]: row["total_credits"] or 0+ for row in ReplayObservationUsage.objects.filter(+ organization_id=organization_id,+ scanner_id__in=capped_ids,+ observation_created_at__gte=period.start,+ observation_created_at__lt=period.end,+ )+ .values("scanner_id")+ .annotate(total_credits=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))+ }+ result: dict[UUID, ScannerBudget] = {}+ for scanner_id in scanner_ids:+ config = configs.get(scanner_id)+ settled_credits = settled.get(scanner_id, 0)+ reserved = in_flight.get(scanner_id, 0) + in_flight_evaluations.get(scanner_id, 0)+ result[scanner_id] = ScannerBudget(+ credit_limit=config[0] if config else None,+ credits_used=settled_credits + reserved,+ period_start=period.start,+ period_end=period.end,+ # A scanner outside this org or deleted mid-read has no model; pricing "" would log a warning.+ credits_per_observation=observation_credits_for_model(config[1]) if config else 0,+ settled_credits=settled_credits,+ )+ return result+++def compute_scanner_budget(scanner: ReplayScanner, period: BillingPeriod | None = None) -> ScannerBudget:+ """This scanner's own credit allowance and draw for the org's current billing period."""+ budgets = compute_scanner_budgets(scanner.team.organization_id, [scanner.id], period)+ return budgets[scanner.id]++def _sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:"""Projected monthly credit spend from the org's enabled scanners' cached estimates."""scanners = ReplayScanner.objects.filter(team__organization_id=organization_id, enabled=True)diff --git a/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py b/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.pyindex ff9789d47ab5..b9df36f77139 100644--- a/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py+++ b/products/replay_vision/backend/temporal/activities/evaluate_prompt_suggestion.py@@ -149,6 +149,7 @@ def record_evaluation_result_activity(inputs: RecordEvaluationResultInputs) -> Ndefaults={"organization_id": suggestion.team.organization_id,"team_id": inputs.team_id,+ "scanner_id": suggestion.scanner_id,"observation_created_at": timezone.now(),"model": inputs.model,"credits": observation_credits_for_model(inputs.model or ""),diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.pyindex 5af4ac15eb0c..cd25682625b1 100644--- a/products/replay_vision/backend/temporal/activities/observation_state.py+++ b/products/replay_vision/backend/temporal/activities/observation_state.py@@ -152,6 +152,7 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)defaults={"organization_id": obs["team__organization_id"],"team_id": obs["team_id"],+ "scanner_id": obs["scanner_id"],"observation_created_at": obs["created_at"],"model": model,"credits": credits,diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 2ab6fdcda110..abd791116428 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -25,6 +25,7 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel+from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import (ReplayScanner,ScannerModel,@@ -2854,6 +2855,25 @@ class TestScannerSpend(_VisionAPITestCase):self.assertEqual(displayed, sorted(displayed, reverse=True))self.assertEqual([row["name"] for row in rows[:2]], ["high", "low"])+ def test_receipts_without_a_scanner_do_not_zero_the_displayed_credits(self) -> None:+ # Receipts are never backfilled with a scanner_id, so the displayed column and its sort read+ # observation rows. Pointing either at the ledger silently zeroes both for a whole period.+ spender = self._create_scanner(name="spender")+ observation = self._succeeded_observation(spender, "unattributed")+ ReplayObservationUsage.objects.create(+ observation_id=observation.id,+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ scanner_id=None,+ observation_created_at=observation.created_at,+ model=spender.model,+ credits=observation_credits_for_model(spender.model),+ )++ resp = self.client.get(f"{self.scanners_url}?order_by=-credits_this_month")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(self._credits_by_name(resp.json())["spender"], observation_credits_for_model(spender.model))+class TestCurrentPeriodBounds(SimpleTestCase):NOW = datetime(2026, 7, 15, 12, 0, tzinfo=UTC)diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.pyindex c61db90ab59b..5235fc654279 100644--- a/products/replay_vision/backend/tests/test_models.py+++ b/products/replay_vision/backend/tests/test_models.py@@ -1,8 +1,9 @@from datetime import timedelta-from posthog.test.base import BaseTest+from posthog.test.base import APIBaseTest, BaseTest-from django.db import IntegrityError+from django.core.exceptions import ValidationError+from django.db import IntegrityError, transactionfrom django.utils import timezonefrom parameterized import parameterized@@ -307,3 +308,59 @@ class TestReplayObservation(BaseTest):scanner.save()obs.refresh_from_db()self.assertEqual(obs.scanner_snapshot["scanner_config"], {"prompt": "original"})+++class TestScannerCreditLimit(APIBaseTest):+ def _scanner(self, **kwargs: object) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name=f"limit-scanner-{ReplayScanner.objects.count()}",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ **kwargs,+ )++ def test_defaults_to_none(self) -> None:+ assert self._scanner().credit_limit is None++ @parameterized.expand([("zero", 0), ("negative", -5)])+ def test_full_clean_rejects_non_positive(self, _name: str, limit: int) -> None:+ scanner = ReplayScanner(+ team=self.team,+ name="limit-validator-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ credit_limit=limit,+ )+ with self.assertRaises(ValidationError) as ctx:+ scanner.full_clean()+ assert "credit_limit" in ctx.exception.message_dict++ @parameterized.expand([("zero", 0), ("negative", -5)])+ def test_database_rejects_non_positive_limit(self, _name: str, limit: int) -> None:+ with self.assertRaises(IntegrityError):+ with transaction.atomic():+ ReplayScanner.objects.filter(pk=self._scanner().pk).update(credit_limit=limit)++ def test_database_accepts_null_limit_on_update(self) -> None:+ scanner = self._scanner(credit_limit=10)+ ReplayScanner.objects.filter(pk=scanner.pk).update(credit_limit=None)+ scanner.refresh_from_db()+ assert scanner.credit_limit is None++ def test_changing_the_limit_does_not_bump_scanner_version_or_stale_the_estimate(self) -> None:+ scanner = self._scanner()+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ estimated_monthly_observations=100, estimated_at=timezone.now()+ )+ scanner.refresh_from_db()+ version_before, estimated_at_before = scanner.scanner_version, scanner.estimated_at++ scanner.credit_limit = 500+ scanner.save()+ scanner.refresh_from_db()++ assert scanner.scanner_version == version_before+ assert scanner.estimated_at == estimated_at_beforediff --git a/products/replay_vision/backend/tests/test_prompt_evaluation.py b/products/replay_vision/backend/tests/test_prompt_evaluation.pyindex 09bd18704b02..90945d6495a2 100644--- a/products/replay_vision/backend/tests/test_prompt_evaluation.py+++ b/products/replay_vision/backend/tests/test_prompt_evaluation.py@@ -27,6 +27,7 @@ from products.replay_vision.backend.prompt_evaluation import (classify_outcome,evaluation_supported,in_flight_evaluation_credits,+ in_flight_evaluation_credits_by_scanner,is_preview_evaluation,primary_outcome,select_evaluation_observations,@@ -263,6 +264,7 @@ class TestPromptEvaluation(_VisionAPITestCase):# The retried run charged the org's quota exactly once, priced by the re-run's model.receipts = ReplayObservationUsage.objects.filter(organization_id=self.team.organization_id)self.assertEqual(receipts.count(), 1)+ self.assertEqual(receipts.get().scanner_id, self.scanner.id)self.assertEqual(compute_quota_snapshot(self.team.organization_id).credits_used,observation_credits_for_model(self.scanner.model),@@ -606,6 +608,25 @@ class TestPromptEvaluationApi(_VisionAPITestCase):self.assertEqual(in_flight_evaluation_credits(self.team.organization_id), reserved)self.assertEqual(reserved, 3 * observation_credits_for_model(expensive))+ def test_per_scanner_reservation_prices_from_the_frozen_model(self) -> None:+ # The per-scanner split must price like the org total: from the model frozen at workflow start.+ expensive, cheap = ScannerModel.GEMINI_3_6_FLASH, ScannerModel.GEMINI_3_5_FLASH_LITE+ scanner = self._create_scanner(name="frozen-model-per-scanner", model=expensive)+ ReplayScannerPromptSuggestion.objects.create(+ scanner=scanner,+ team=self.team,+ suggested_prompt="p",+ status=SuggestionStatus.PENDING,+ scanner_version=1,+ evaluation=build_running_evaluation(total=3, labels_fingerprint="", model=expensive),+ )+ scanner.model = cheap+ scanner.save(update_fields=["model"])++ reserved = in_flight_evaluation_credits_by_scanner(self.team.organization_id, [scanner.id])++ self.assertEqual(reserved, {scanner.id: 3 * observation_credits_for_model(expensive)})+@parameterized.expand([("zero", 0), ("above_cap", EVALUATION_SESSION_CAP + 1)])def test_evaluate_rejects_out_of_range_session_limit(self, _name: str, limit: int) -> None:self._create_rated()diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex ebcb22f8577d..53613c70136f 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -3,6 +3,7 @@ from datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized@@ -10,6 +11,7 @@ from parameterized import parameterizedfrom posthog.date_util import start_of_monthfrom posthog.models import Organization, Team+from products.replay_vision.backend import quotafrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,@@ -19,7 +21,14 @@ from products.replay_vision.backend.models.replay_observation import (from products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.models.replay_scanner_prompt_suggestion import ReplayScannerPromptSuggestion-from products.replay_vision.backend.quota import MONTHLY_CREDIT_QUOTA, compute_quota_snapshot+from products.replay_vision.backend.quota import (+ MONTHLY_CREDIT_QUOTA,+ BillingPeriod,+ ScannerBudget,+ compute_quota_snapshot,+ compute_scanner_budget,+ compute_scanner_budgets,+)from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for@@ -67,6 +76,7 @@ class _VisionQuotaTestCase(APIBaseTest):defaults={"organization_id": observation.team.organization_id,"team_id": observation.team_id,+ "scanner_id": observation.scanner_id,"observation_created_at": observation.created_at,"model": model,"credits": observation_credits_for_model(model),@@ -232,6 +242,343 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 15+class TestComputeScannerBudget(_VisionQuotaTestCase):+ def setUp(self) -> None:+ super().setUp()+ # Spend counting only runs for capped scanners; a wide-open limit keeps it from binding.+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=1_000_000)+ self.scanner.refresh_from_db()++ def _other_scanner(self) -> ReplayScanner:+ return ReplayScanner.objects.create(+ team=self.team,+ name="other-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ credit_limit=1_000_000,+ )++ def test_no_limit_set_is_uncapped(self) -> None:+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=None)+ self.scanner.refresh_from_db()+ budget = compute_scanner_budget(self.scanner)+ assert budget.credit_limit is None+ assert budget.remaining is None+ assert not budget.exhausted+ assert not budget.blocked+ assert not budget.would_exceed(10**9)++ def test_an_uncapped_scanner_skips_the_spend_aggregates(self) -> None:+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=None)+ self.scanner.refresh_from_db()+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ # Uncapped budgets report zero usage by design: nothing gates on them and the spend UI+ # only renders for capped scanners, so the aggregates are skipped entirely.+ budget = compute_scanner_budget(self.scanner)+ assert budget.credits_used == 0+ assert not budget.blocked++ @parameterized.expand(+ [+ (ObservationStatus.SUCCEEDED, 15),+ (ObservationStatus.PENDING, 15),+ (ObservationStatus.RUNNING, 15),+ (ObservationStatus.FAILED, 0),+ (ObservationStatus.INELIGIBLE, 0),+ ]+ )+ def test_counts_settled_receipts_and_in_flight_reservations(self, status: ObservationStatus, expected: int) -> None:+ is_in_flight = status in (ObservationStatus.PENDING, ObservationStatus.RUNNING)+ self._make_observation(status=status, completed_at=None if is_in_flight else timezone.now())+ assert compute_scanner_budget(self.scanner).credits_used == expected++ def test_another_scanners_spend_does_not_count(self) -> None:+ other = self._other_scanner()+ observation = ReplayObservation.objects.create(+ scanner=other,+ team=self.team,+ session_id="other-sess",+ status=ObservationStatus.SUCCEEDED,+ scanner_snapshot=_snapshot_for(other),+ triggered_by=ObservationTrigger.ON_DEMAND,+ completed_at=timezone.now(),+ )+ self._make_receipt(observation)+ assert compute_scanner_budget(self.scanner).credits_used == 0+ assert compute_scanner_budget(other).credits_used == 15++ def test_receipts_without_a_scanner_count_toward_nobody(self) -> None:+ observation = self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ ReplayObservationUsage.objects.filter(observation_id=observation.id).update(scanner_id=None)+ ReplayObservation.objects.filter(pk=observation.pk).delete()+ assert compute_scanner_budget(self.scanner).credits_used == 0++ def test_spend_in_a_previous_period_does_not_count(self) -> None:+ last_month = start_of_month(datetime.now(UTC)) - timedelta(days=1)+ self._make_observation(status=ObservationStatus.SUCCEEDED, created_at=last_month, completed_at=last_month)+ assert compute_scanner_budget(self.scanner).credits_used == 0++ def test_a_running_evaluation_reserves_against_the_scanners_own_cap(self) -> None:+ self._make_running_evaluation(scanner=self.scanner, total=4)+ assert compute_scanner_budget(self.scanner).credits_used == 4 * 15++ def test_another_scanners_running_evaluation_does_not_count(self) -> None:+ self._make_running_evaluation(scanner=self._other_scanner(), total=4)+ assert compute_scanner_budget(self.scanner).credits_used == 0++ def test_a_caller_supplied_period_is_billed_against(self) -> None:+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ previous = start_of_month(datetime.now(UTC)) - timedelta(days=1)+ period = BillingPeriod(start=start_of_month(previous), end=start_of_month(datetime.now(UTC)))+ assert compute_scanner_budget(self.scanner, period).credits_used == 0+ assert compute_scanner_budget(self.scanner).credits_used == 15++ def test_a_caller_supplied_period_scopes_in_flight_reservations_too(self) -> None:+ self._make_observation(status=ObservationStatus.RUNNING)+ previous = start_of_month(datetime.now(UTC)) - timedelta(days=1)+ period = BillingPeriod(start=start_of_month(previous), end=start_of_month(datetime.now(UTC)))+ assert compute_scanner_budget(self.scanner, period).credits_used == 0+ assert compute_scanner_budget(self.scanner).credits_used == 15++ def test_prices_one_more_observation_from_the_scanners_model(self) -> None:+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(model=ScannerModel.GEMINI_3_5_FLASH_LITE)+ self.scanner.refresh_from_db()+ assert compute_scanner_budget(self.scanner).credits_per_observation == 2++ def test_settled_credits_exclude_live_reservations(self) -> None:+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ self._make_observation(status=ObservationStatus.RUNNING)+ budget = compute_scanner_budget(self.scanner)+ assert budget.credits_used == 30+ assert budget.settled_credits == 15++ def test_an_observation_settling_between_the_budget_reads_never_vanishes(self) -> None:+ # Reservations are read before receipts, so a settlement between the reads is seen by both+ # (over-counted once, failing toward capped) instead of by neither (an admission past the cap).+ observation = self._make_observation(status=ObservationStatus.RUNNING)+ real_in_flight = quota._scanner_in_flight_credits++ def in_flight_then_settle(*args, **kwargs):+ reserved = real_in_flight(*args, **kwargs)+ ReplayObservation.objects.filter(pk=observation.pk).update(+ status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()+ )+ observation.refresh_from_db()+ self._make_receipt(observation)+ return reserved++ with patch.object(quota, "_scanner_in_flight_credits", side_effect=in_flight_then_settle):+ budget = compute_scanner_budget(self.scanner)++ assert budget.credits_used >= 15+++class TestBackfillUsageScannerId(_VisionQuotaTestCase):+ def test_backfills_null_scanner_ids_only_where_the_observation_still_exists(self) -> None:+ import uuid+ import importlib++ from django.apps import apps as django_apps+ from django.db import connection++ observation = self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ ReplayObservationUsage.objects.filter(observation_id=observation.id).update(scanner_id=None)+ orphan = ReplayObservationUsage.objects.create(+ organization_id=self.organization.id,+ observation_id=uuid.uuid4(),+ observation_created_at=timezone.now(),+ )++ migration = importlib.import_module("products.replay_vision.backend.migrations.0070_backfill_usage_scanner_id")+ with connection.schema_editor(atomic=False) as schema_editor:+ migration.backfill_scanner_id(django_apps, schema_editor)++ assert ReplayObservationUsage.objects.get(observation_id=observation.id).scanner_id == self.scanner.id+ orphan.refresh_from_db()+ assert orphan.scanner_id is None++ def test_backfill_attributes_all_receipts_across_batches(self) -> None:+ import uuid+ import importlib++ from django.apps import apps as django_apps+ from django.db import connection++ observations = [+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()) for _ in range(3)+ ]+ ReplayObservationUsage.objects.filter(observation_id__in=[o.id for o in observations]).update(scanner_id=None)+ orphan = ReplayObservationUsage.objects.create(+ organization_id=self.organization.id,+ observation_id=uuid.uuid4(),+ observation_created_at=timezone.now(),+ )++ migration = importlib.import_module("products.replay_vision.backend.migrations.0070_backfill_usage_scanner_id")+ # BATCH_SIZE=1 forces one keyset iteration per receipt, exercising the pagination loop.+ with patch.object(migration, "BATCH_SIZE", 1):+ with connection.schema_editor(atomic=False) as schema_editor:+ migration.backfill_scanner_id(django_apps, schema_editor)++ for observation in observations:+ assert ReplayObservationUsage.objects.get(observation_id=observation.id).scanner_id == self.scanner.id+ orphan.refresh_from_db()+ assert orphan.scanner_id is None+++class TestScannerBudgetBlocked(SimpleTestCase):+ @parameterized.expand(+ [+ ("uncapped", None, 10_000, False, False, None),+ ("fresh_budget", 100, 0, False, False, 100),+ ("room_for_one_more", 100, 85, False, False, 15),+ # The gap `exhausted` misses: under one observation of headroom left, so the next+ # observation cannot be admitted even though usage has not reached the limit.+ ("less_than_one_observation_left", 100, 90, False, True, 10),+ ("exactly_at_the_limit", 100, 100, True, True, 0),+ ("overshot", 100, 130, True, True, 0),+ ]+ )+ def test_blocked_is_the_one_answer_for_out_of_budget(+ self,+ _name: str,+ credit_limit: int | None,+ credits_used: int,+ expected_exhausted: bool,+ expected_blocked: bool,+ expected_remaining: int | None,+ ) -> None:+ budget = ScannerBudget(+ credit_limit=credit_limit,+ credits_used=credits_used,+ period_start=datetime(2026, 8, 1, tzinfo=UTC),+ period_end=datetime(2026, 9, 1, tzinfo=UTC),+ credits_per_observation=15,+ settled_credits=credits_used,+ )+ assert budget.exhausted == expected_exhausted+ assert budget.blocked == expected_blocked+ assert budget.remaining == expected_remaining++ @parameterized.expand(+ [+ # A free model spends nothing, so it scans through and past the limit without blocking.+ ("at_the_limit_still_admits", 100, True, False),+ ("over_the_limit_blocks", 101, True, True),+ ]+ )+ def test_zero_cost_observations_block_only_when_strictly_over(+ self, _name: str, credits_used: int, expected_exhausted: bool, expected_blocked: bool+ ) -> None:+ budget = ScannerBudget(+ credit_limit=100,+ credits_used=credits_used,+ period_start=datetime(2026, 8, 1, tzinfo=UTC),+ period_end=datetime(2026, 9, 1, tzinfo=UTC),+ credits_per_observation=0,+ settled_credits=credits_used,+ )+ assert budget.exhausted == expected_exhausted+ assert budget.blocked == expected_blocked++ @parameterized.expand(+ [+ ("reservations_alone_cap_it", 30, 100, True, False),+ ("settled_spend_alone_caps_it", 95, 95, True, True),+ ("neither_caps_it", 30, 50, False, False),+ ]+ )+ def test_blocked_by_settled_spend_ignores_live_reservations(+ self,+ _name: str,+ settled_credits: int,+ credits_used: int,+ expected_blocked: bool,+ expected_blocked_by_settled: bool,+ ) -> None:+ budget = ScannerBudget(+ credit_limit=100,+ credits_used=credits_used,+ period_start=datetime(2026, 8, 1, tzinfo=UTC),+ period_end=datetime(2026, 9, 1, tzinfo=UTC),+ credits_per_observation=15,+ settled_credits=settled_credits,+ )+ assert budget.blocked == expected_blocked+ assert budget.blocked_by_settled_spend == expected_blocked_by_settled+++class TestComputeScannerBudgets(_VisionQuotaTestCase):+ def setUp(self) -> None:+ super().setUp()+ # Spend counting only runs for capped scanners; a wide-open limit keeps it from binding.+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=1_000_000)+ self.scanner.refresh_from_db()++ def test_returns_an_entry_for_every_requested_scanner_including_unspent(self) -> None:+ unspent = ReplayScanner.objects.create(+ team=self.team,+ name="unspent-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ result = compute_scanner_budgets(self.organization.id, [self.scanner.id, unspent.id])+ assert result[self.scanner.id].credits_used == 15+ assert result[unspent.id].credits_used == 0++ def test_reads_each_scanners_own_limit(self) -> None:+ capped = ReplayScanner.objects.create(+ team=self.team,+ name="capped-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ credit_limit=300,+ )+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(credit_limit=None)+ result = compute_scanner_budgets(self.organization.id, [self.scanner.id, capped.id])+ assert result[self.scanner.id].credit_limit is None+ assert result[capped.id].credit_limit == 300++ def test_another_orgs_scanner_id_contributes_nothing(self) -> None:+ other_org = Organization.objects.create(name="other-budgets-org")+ other_team = Team.objects.create(organization=other_org, name="other-budgets-team")+ other_scanner = ReplayScanner.objects.create(+ team=other_team,+ name="other-scanner",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_6_FLASH,+ )+ ReplayScanner.objects.filter(pk=other_scanner.pk).update(credit_limit=1000)+ # One of each spend source, so dropping the org filter from any single query fails this.+ settled = ReplayObservation.objects.create(+ scanner=other_scanner,+ team=other_team,+ session_id="other-settled",+ status=ObservationStatus.SUCCEEDED,+ scanner_snapshot=_snapshot_for(other_scanner),+ triggered_by=ObservationTrigger.ON_DEMAND,+ completed_at=timezone.now(),+ )+ self._make_receipt(settled)+ ReplayObservation.objects.create(+ scanner=other_scanner,+ team=other_team,+ session_id="other-sess",+ status=ObservationStatus.RUNNING,+ scanner_snapshot=_snapshot_for(other_scanner),+ triggered_by=ObservationTrigger.ON_DEMAND,+ )+ self._make_running_evaluation(scanner=other_scanner, total=4)+ result = compute_scanner_budgets(self.organization.id, [other_scanner.id])+ assert result[other_scanner.id].credits_used == 0+ assert result[other_scanner.id].credit_limit is None++class TestBillingSyncedQuota(_VisionQuotaTestCase):@parameterized.expand([diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 1a00d101753b..9fc0dd2f392f 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -820,6 +820,7 @@ class TestObservationStateActivities:assert receipt.observation_created_at == observation.created_atassert receipt.model == observation.scanner_snapshot["model"]assert receipt.credits == observation_credits_for_model(observation.scanner_snapshot["model"])+ assert receipt.scanner_id == scanner.iddef test_mark_succeeded_usage_receipt_is_idempotent(self) -> None:scanner = _make_scanner()