: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
perf(replay-vision): admit capped scans against a cached budget instead of in-lock aggregates (#88865)
Kim Svatos Dugane1a01796ec31
diff --git a/products/replay_vision/backend/migrations/0082_admission_budget_cache.py b/products/replay_vision/backend/migrations/0082_admission_budget_cache.pynew file mode 100644index 000000000000..ec3da2e5d4ad--- /dev/null+++ b/products/replay_vision/backend/migrations/0082_admission_budget_cache.py@@ -0,0 +1,47 @@+# Generated by Django 5.2.17 on 2026-08-25 22:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0081_callable_choices"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayscanner",+ name="admission_budget_period_start",+ field=models.DateTimeField(+ blank=True,+ help_text="Billing period the cached admission budget belongs to. A period mismatch forces a refresh.",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="replayscanner",+ name="admission_budget_refreshed_at",+ field=models.DateTimeField(+ blank=True,+ help_text="When the admission budget was last recomputed from the spend aggregates. Null until the first capped admission.",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="replayscanner",+ name="admission_budget_used",+ field=models.IntegerField(+ blank=True,+ help_text="Credits counted against credit_limit at the last admission-budget refresh: settled receipts, in-flight reservations, and running evaluations.",+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="replayscanner",+ name="admission_credits_since_refresh",+ field=models.PositiveIntegerField(+ default=0,+ help_text="Credits admitted since the last admission-budget refresh. Every refresh resets this to the admitting cost, or to zero on a refusal.",+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 521be0f76bb0..8c83bc2c0c8a 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0081_callable_choices+0082_admission_budget_cachediff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex 88c7d482f9f7..eb246eb81d9b 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -264,6 +264,29 @@ class ReplayScanner(UUIDModel):help_text="Billing period start this scanner was last reported as having reached its credit limit. Keeps the notification to one per period.",)+ # Admission budget cache: the spend aggregates snapshotted at the last refresh, plus credits+ # admitted since. The fast admission path is one conditional UPDATE on these columns; the+ # aggregates re-run under the row lock only when the cache is stale. See create_observation.+ admission_budget_used = models.IntegerField(+ null=True,+ blank=True,+ help_text="Credits counted against credit_limit at the last admission-budget refresh: settled receipts, in-flight reservations, and running evaluations.",+ )+ admission_budget_refreshed_at = models.DateTimeField(+ null=True,+ blank=True,+ help_text="When the admission budget was last recomputed from the spend aggregates. Null until the first capped admission.",+ )+ admission_budget_period_start = models.DateTimeField(+ null=True,+ blank=True,+ help_text="Billing period the cached admission budget belongs to. A period mismatch forces a refresh.",+ )+ admission_credits_since_refresh = models.PositiveIntegerField(+ default=0,+ help_text="Credits admitted since the last admission-budget refresh. Every refresh resets this to the admitting cost, or to zero on a refusal.",+ )+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)@@ -341,6 +364,10 @@ class ReplayScanner(UUIDModel):"fast_read_bytes_by_hour","deep_read_bytes_by_hour","limit_notified_period_start",+ "admission_budget_used",+ "admission_budget_refreshed_at",+ "admission_budget_period_start",+ "admission_credits_since_refresh",)def save(self, *args, **kwargs) -> None:diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex 33c5c472067d..be04628b4189 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -1,6 +1,8 @@from typing import Any+from uuid import UUIDfrom django.db import IntegrityError, OperationalError, connection, transaction+from django.db.models import Ffrom django.utils import timezoneimport psycopg.errors@@ -14,7 +16,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 compute_scanner_budget, current_period_bounds, quota_state+from products.replay_vision.backend.quota import (+ BillingPeriod,+ ScannerBudget,+ compute_scanner_budget,+ current_period_bounds,+ quota_state,+)+from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTLfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.errors import SCANNER_ADMISSION_BUSY_ERROR_TYPEfrom products.replay_vision.backend.temporal.metrics import (@@ -54,6 +63,68 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv)+def _try_cached_admission(scanner_pk: UUID, cost: int, period: BillingPeriod) -> bool:+ """One conditional UPDATE admits `cost` against the cached budget; no aggregates, no explicit lock.++ Concurrent UPDATEs serialize on the row for one statement each, and Postgres re-evaluates the+ WHERE against the latest committed row after a lock wait, so two racing admissions cannot both+ spend the last headroom. False means the cache is stale, the period rolled, the headroom ran+ out, or the cap was lifted; the locked refresh resolves which.+ """+ fresh_after = timezone.now() - ADMISSION_BUDGET_TTL+ return bool(+ ReplayScanner.all_origins.filter(+ pk=scanner_pk,+ credit_limit__isnull=False,+ admission_budget_period_start=period.start,+ admission_budget_refreshed_at__gte=fresh_after,+ credit_limit__gte=F("admission_budget_used") + F("admission_credits_since_refresh") + cost,+ ).update(admission_credits_since_refresh=F("admission_credits_since_refresh") + cost)+ )+++def _admit_within_cap(scanner: ReplayScanner, cost: int, period: BillingPeriod) -> ScannerBudget | None:+ """Admit `cost` against the scanner's cap; None on admission, the refusing budget otherwise.++ A cache miss recomputes the spend aggregates under the row lock, rewrites the cache, and+ decides from the fresh figure, so the aggregates run once per TTL instead of once per admission.+ The admitting UPDATE and the observation INSERT share the caller's transaction, so a failed+ insert rolls its admission back.+ """+ # SET LOCAL covers the whole admission transaction: the fast-path UPDATE and the refresh lock+ # both give up after 2s and defer to the activity's backoff instead of camping in Postgres's+ # lock queue. The 2s grace absorbs the row's brief blocking holders (scanner save(),+ # prompt-suggestion apply), which NOWAIT would turn into instant admission failures.+ with connection.cursor() as cursor:+ cursor.execute("SET LOCAL lock_timeout = '2s'")+ if _try_cached_admission(scanner.pk, cost, period):+ return None+ locked = (+ # A contended refresh times out into the OperationalError handler below and retries on the+ # activity's backoff, and the retry usually lands on the winner's warm cache. By-pk via+ # all_origins, so a capped inline scanner locks its row rather than skipping enforcement.+ ReplayScanner.all_origins.select_for_update(of=("self",))+ .filter(pk=scanner.pk)+ .only("pk", "credit_limit")+ .first()+ )+ if locked is None or locked.credit_limit is None:+ # Uncapped (or deleted) by the time the lock resolved; nothing to enforce.+ return None+ budget = compute_scanner_budget(scanner, period)+ admitted = not budget.would_exceed(cost)+ ReplayScanner.all_origins.filter(pk=scanner.pk).update(+ admission_budget_used=budget.credits_used,+ admission_budget_refreshed_at=timezone.now(),+ admission_budget_period_start=period.start,+ # The reset supersedes every earlier increment: a fast-path admission holds its row lock to+ # commit, so this refresh either saw its committed in-flight row in the aggregates or timed+ # out against it — no admission can be uncommitted here with its increment surviving.+ admission_credits_since_refresh=cost if admitted else 0,+ )+ return None if admitted else budget++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()@@ -173,67 +244,50 @@ 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.+ # Resolved before the transaction to shrink the in-transaction 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 None+ # Priced from `priced_model` (the frozen snapshot model for backfills), matching what the+ # observation will actually charge, not the scanner's current model.+ cost = observation_credits_for_model(priced_model)try: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.+ # Capped scanners admit against the cached admission budget so concurrent applies cannot+ # overshoot the cap; uncapped scanners keep the lock-free path.if scanner.credit_limit is not None:- # A short lock_timeout instead of NOWAIT: a contended admission fails fast into the- # activity's own backoff instead of camping in Postgres's lock queue, where every- # waiter holds an open transaction and an attempt killed at start_to_close leaves its- # statement waiting server-side. The 2s grace absorbs the brief blocking holders of- # this row (scanner save(), prompt-suggestion apply), which NOWAIT would turn into- # instant admission failures. Admissions stay fully serialized.- with connection.cursor() as cursor:- # SET LOCAL reverts when the transaction ends; lock_timeout raises the same- # LockNotAvailable the handler below maps to the retryable busy error.- cursor.execute("SET LOCAL lock_timeout = '2s'")- locked = (- # By-pk, so it must resolve whatever origin the row is; `objects` would lock- # nothing for an inline scanner and silently skip its budget check.- ReplayScanner.all_origins.select_for_update(of=("self",))- .filter(pk=scanner.pk)- .only("pk", "credit_limit")- .first()- )- 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+ assert period is not None+ refused_budget = _admit_within_cap(scanner, cost, period)+ if refused_budget is not None:+ # 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": refused_budget.credit_limit,+ "credits_used": refused_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 in the same+ # transaction as its admission: a rolled-back retake then gives the credits back. It+ # cannot wait for the IntegrityError handler, which runs after the transaction aborted.+ if backfill is not None:+ retaken_output = _retake_failed_row(inputs, row_fields)+ if retaken_output is not None:+ return retaken_outputobservation = ReplayObservation.objects.create(scanner=scanner,diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex cf43b451f21e..8b551c20c7da 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -6,6 +6,11 @@ from temporalio.common import PriorityAPPLY_SCANNER_WORKFLOW_NAME = "replay-vision-apply-scanner"SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"+# How long a cached admission budget admits without re-running the spend aggregates. Spend the+# cache misses (settling receipts, evaluation reservations, failed-observation refunds) stays wrong+# by at most one TTL, and the admission counter itself never goes stale.+ADMISSION_BUDGET_TTL = dt.timedelta(seconds=15)+# Shared by the sweep's children and the on-demand /observe/ trigger; the orphan cutoff below leans on it.# Must exceed the worst-case failure chain in `workflow.py`, where every phase spends its full schedule_to_close# budget before the terminal mark runs: create 3m + mark running 3m + fetch 5m + rasterize 40m + upload 20m +diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 87060a0a7d89..b37cd49aa1c9 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -84,7 +84,7 @@ REPLAY_VISION_SWEEP_OUTCOMES = Counter(["outcome"],)-# The admission lock is taken NOWAIT, so lock waits cannot exist to measure; contention shows up+# The admission lock gives up after a 2s lock_timeout, so waits are capped, not worth a histogram;# here instead, as attempts that found the row held and deferred to the activity's retry policy.REPLAY_VISION_SCANNER_ADMISSION_BUSY = Counter("replay_vision_scanner_admission_busy_total",diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex f9678eeb5753..dddc340cc13c 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -536,6 +536,66 @@ class TestCreateObservationActivity:exists = ReplayObservation.objects.filter(scanner=scanner, session_id="sess-scanner-limit").exists()assert exists is expect_created+ def _admit(self, scanner: ReplayScanner, session_id: str) -> CreateObservationOutput:+ return 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}",+ )+ )++ def test_fresh_admission_cache_admits_without_running_the_budget_aggregates(self) -> None:+ # The fast path is the point of the cache: an admission inside the TTL must not re-run+ # compute_scanner_budget, or every capped admission pays the aggregate queries again.+ scanner = _make_scanner(credit_limit=1_000)+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):+ assert self._admit(scanner, "sess-cache-warmup").was_created+ with patch(+ "products.replay_vision.backend.temporal.activities.create_observation.compute_scanner_budget",+ side_effect=AssertionError("aggregates ran on a fresh cache"),+ ):+ assert self._admit(scanner, "sess-cache-fast").was_created++ def test_warm_cache_admission_still_refuses_at_the_limit(self) -> None:+ # The cold path refuses via fresh aggregates (covered above); this pins the warm path: the+ # first admission's cached spend must refuse the second, not just the next refresh.+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_7_FLASH.value)+ scanner = _make_scanner(credit_limit=credits)+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):+ assert self._admit(scanner, "sess-warm-a").was_created+ assert not self._admit(scanner, "sess-warm-b").was_created+ assert ReplayObservation.objects.filter(scanner=scanner, status=ObservationStatus.PENDING).count() == 1++ def test_admission_cache_from_a_previous_period_does_not_block_a_new_period(self) -> None:+ # A period rollover must invalidate the cache: a scanner that exhausted last period's cap+ # admits again once the period turns, even while the stale cache still reads as exhausted.+ scanner = _make_scanner(credit_limit=100)+ ReplayScanner.all_origins.filter(pk=scanner.pk).update(+ admission_budget_used=100,+ admission_credits_since_refresh=50,+ admission_budget_refreshed_at=timezone.now(),+ admission_budget_period_start=timezone.now() - dt.timedelta(days=400),+ )+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):+ assert self._admit(scanner, "sess-rollover").was_created++ def test_failed_insert_refunds_its_cached_admission(self) -> None:+ # The cached counter must stay transactional with the insert: an increment that survived a+ # rolled-back insert would make a cap that fits one observation refuse the retry forever.+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_7_FLASH.value)+ scanner = _make_scanner(credit_limit=credits)+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000):+ with (+ patch.object(ReplayObservation.objects, "create", side_effect=RuntimeError("insert failed")),+ pytest.raises(RuntimeError),+ ):+ self._admit(scanner, "sess-refund")+ assert self._admit(scanner, "sess-refund").was_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).@@ -560,7 +620,7 @@ class TestCreateObservationActivity:except ApplicationError as e:if e.type != SCANNER_ADMISSION_BUSY_ERROR_TYPE:raise- # The NOWAIT lock refused the loser outright; in production Temporal retries it and the+ # The lock timeout refused the loser; in production Temporal retries it and the# re-run reads the winner's spend. Either way the cap held: nothing was admitted.created[session_id] = Falsefinally: