Skip to content

: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.

feat(replay-vision): make the org credit limit exact at admission (#116148)

Tue Haulundde73eb769ada
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index cc5741222970..3bb25603c419 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -1028,6 +1028,7 @@ rules:
|Plugin
|Project
|ProxyRecord
+ |ReplayVisionOrgAdmissionBudget
|Role
|RoleExternalReference
|RoleMembership
@@ -1110,6 +1111,7 @@ rules:
|Plugin
|Project
|ProxyRecord
+ |ReplayVisionOrgAdmissionBudget
|Role
|RoleExternalReference
|RoleMembership
diff --git a/products/replay_vision/backend/migrations/0122_replayvisionorgadmissionbudget.py b/products/replay_vision/backend/migrations/0122_replayvisionorgadmissionbudget.py
new file mode 100644
index 000000000000..0a881b5ede3a
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0122_replayvisionorgadmissionbudget.py
@@ -0,0 +1,60 @@
+# Generated by Django 5.2.18 on 2026-10-13 12:31
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1396_events_retention_config"),
+ ("replay_vision", "0121_replayscanner_dashboard_id"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ReplayVisionOrgAdmissionBudget",
+ fields=[
+ (
+ "organization",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="+",
+ serialize=False,
+ to="posthog.organization",
+ ),
+ ),
+ (
+ "period_start",
+ models.DateTimeField(
+ help_text="Billing period the cached budget belongs to. A period mismatch forces a refresh."
+ ),
+ ),
+ (
+ "credit_limit",
+ models.PositiveIntegerField(
+ help_text="Org credit limit at the last refresh, null when billing sets none. A fast-path admission requires the current limit to match it.",
+ null=True,
+ ),
+ ),
+ (
+ "credits_used",
+ models.PositiveIntegerField(
+ help_text="Credits counted against credit_limit at the last refresh: settled receipts plus in-flight reservations."
+ ),
+ ),
+ (
+ "credits_since_refresh",
+ models.PositiveIntegerField(
+ default=0,
+ help_text="Credits admitted since the last refresh. Every refresh resets it to the admitting cost, or zero on refusal.",
+ ),
+ ),
+ (
+ "refreshed_at",
+ models.DateTimeField(help_text="When the spend aggregates were last recomputed."),
+ ),
+ ],
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0123_rlou_org_created_idx.py b/products/replay_vision/backend/migrations/0123_rlou_org_created_idx.py
new file mode 100644
index 000000000000..cf426ab75dcd
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0123_rlou_org_created_idx.py
@@ -0,0 +1,18 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0122_replayvisionorgadmissionbudget"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="replayobservationusage",
+ index=models.Index(fields=["organization", "created_at"], name="rlou_org_created_idx"),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 1789cc26f8bc..7618995540a1 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0121_replayscanner_dashboard_id
+0123_rlou_org_created_idx
diff --git a/products/replay_vision/backend/models/__init__.py b/products/replay_vision/backend/models/__init__.py
index 361bec47e5ca..c15c5d99fda3 100644
--- a/products/replay_vision/backend/models/__init__.py
+++ b/products/replay_vision/backend/models/__init__.py
@@ -7,6 +7,7 @@ from products.replay_vision.backend.models.replay_observation_view import Replay
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.replay_scanner_backfill import ReplayScannerBackfill
from products.replay_vision.backend.models.replay_vision_learned_ruleset import ReplayVisionLearnedRuleset
+from products.replay_vision.backend.models.replay_vision_org_admission_budget import ReplayVisionOrgAdmissionBudget
from products.replay_vision.backend.models.team_replay_vision_config import TeamReplayVisionConfig
from products.replay_vision.backend.models.vision_alert import (
VisionAlertConfiguration as VisionAlertConfiguration,
@@ -24,5 +25,6 @@ __all__ = [
"ReplayScanner",
"ReplayScannerBackfill",
"ReplayVisionLearnedRuleset",
+ "ReplayVisionOrgAdmissionBudget",
"TeamReplayVisionConfig",
]
diff --git a/products/replay_vision/backend/models/replay_observation_usage.py b/products/replay_vision/backend/models/replay_observation_usage.py
index 53df6b6cf43f..293ef59536d6 100644
--- a/products/replay_vision/backend/models/replay_observation_usage.py
+++ b/products/replay_vision/backend/models/replay_observation_usage.py
@@ -44,6 +44,8 @@ class ReplayObservationUsage(UUIDModel):
class Meta:
indexes = [
models.Index(fields=["organization", "observation_created_at"]),
+ # Drives the org quota, which buckets receipts by write time so it agrees with billing.
+ models.Index(fields=["organization", "created_at"], name="rlou_org_created_idx"),
# 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
diff --git a/products/replay_vision/backend/models/replay_vision_org_admission_budget.py b/products/replay_vision/backend/models/replay_vision_org_admission_budget.py
new file mode 100644
index 000000000000..08b75d0bdb21
--- /dev/null
+++ b/products/replay_vision/backend/models/replay_vision_org_admission_budget.py
@@ -0,0 +1,31 @@
+from django.db import models
+
+
+class ReplayVisionOrgAdmissionBudget(models.Model):
+ """The scanner admission cache one level up, so the org credit limit holds under concurrent applies."""
+
+ # No DB constraint: adding one locks posthog_organization, a hot table. Django still cascades the delete.
+ organization = models.OneToOneField(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ primary_key=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ period_start = models.DateTimeField(
+ help_text="Billing period the cached budget belongs to. A period mismatch forces a refresh.",
+ )
+ credit_limit = models.PositiveIntegerField(
+ null=True,
+ help_text="Org credit limit at the last refresh, null when billing sets none. A fast-path admission requires the current limit to match it.",
+ )
+ credits_used = models.PositiveIntegerField(
+ help_text="Credits counted against credit_limit at the last refresh: settled receipts plus in-flight reservations.",
+ )
+ credits_since_refresh = models.PositiveIntegerField(
+ default=0,
+ help_text="Credits admitted since the last refresh. Every refresh resets it to the admitting cost, or zero on refusal.",
+ )
+ refreshed_at = models.DateTimeField(
+ help_text="When the spend aggregates were last recomputed.",
+ )
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index a84040e2a1b9..308d3a897ef6 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -224,8 +224,7 @@ def _current_period_bounds(organization: Organization | None, now: datetime) ->
def current_period_bounds(organization_id: UUID) -> BillingPeriod:
"""The org's active billing period when synced and current, else the current calendar month."""
- organization = Organization.objects.filter(pk=organization_id).only("usage").first()
- return _current_period_bounds(organization, datetime.now(UTC))
+ return org_credit_cap(organization_id).period
@dataclass(frozen=True)
@@ -472,40 +471,68 @@ def spend_projection(organization_id: UUID, exclude_scanner_id: UUID | None = No
)
-def quota_state(organization_id: UUID) -> QuotaState:
- # Single `now` so the usage window and any caller comparisons are computed from one instant.
- now = datetime.now(UTC)
+@frozen
+class OrgCreditCap:
+ """The org's credit limit and the billing period it applies to, read without any spend aggregates."""
+
+ period: BillingPeriod
+ credit_limit: int | None
+
+
+def _org_credit_limit(organization: Organization | None, organization_id: UUID) -> int | None:
+ synced, credit_limit = _billing_synced_limit(organization)
+ if not synced:
+ credit_limit = MONTHLY_CREDIT_QUOTA
+ # The tighter of billing's limit and the override, so a config mistake can only reduce credits;
+ # this is how an internal org on an unlimited plan still gets a spend ceiling.
+ override = ORG_CREDIT_LIMIT_OVERRIDES.get(str(organization_id))
+ if override is not None:
+ credit_limit = override if credit_limit is None else min(credit_limit, override)
+ return credit_limit
+
+
+def org_credit_cap(organization_id: UUID) -> OrgCreditCap:
+ """One org read; billing is the source of truth once synced, else the env cap and calendar months."""
organization = Organization.objects.filter(pk=organization_id).only("usage").first()
- # Billing is the source of truth once synced, falling back to the env cap and calendar months otherwise.
- period = _current_period_bounds(organization, now)
- # Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it.
- consumed = ReplayObservationUsage.objects.filter(
- organization_id=organization_id,
- observation_created_at__gte=period.start,
- observation_created_at__lt=period.end,
- ).aggregate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))["total"]
+ return org_credit_cap_for(organization, organization_id)
+
+
+def org_credit_cap_for(organization: Organization | None, organization_id: UUID) -> OrgCreditCap:
+ """`org_credit_cap` for a caller that already loaded the org's `usage`."""
+ return OrgCreditCap(
+ period=_current_period_bounds(organization, datetime.now(UTC)),
+ credit_limit=_org_credit_limit(organization, organization_id),
+ )
+
+
+def quota_state(organization_id: UUID) -> QuotaState:
+ return quota_state_for_cap(organization_id, org_credit_cap(organization_id))
+
+
+def quota_state_for_cap(organization_id: UUID, cap: OrgCreditCap) -> QuotaState:
+ """The org's spend against a cap the caller already resolved, so the two cannot straddle a period boundary."""
+ period = cap.period
# In-flight rows aren't in the ledger yet (receipt is written on success), so reserve their credits live,
- # priced from the frozen snapshot model exactly as the eventual receipt will be. One created just before
- # a period rollover settles into the next window, so it is briefly counted in neither; accepted.
+ # priced from the frozen snapshot model exactly as the eventual receipt will be. Every one counts toward
+ # the current period, even one started before rollover, because that is where its receipt will land.
+ # Read before the ledger: an observation settling between the two reads is then counted twice, which
+ # fails toward capped, never in neither.
in_flight_models = Counter(
ReplayObservation.objects.filter(
team__organization_id=organization_id,
status__in=IN_FLIGHT_STATUSES,
- created_at__gte=period.start,
- created_at__lt=period.end,
).values_list("scanner_snapshot__model", flat=True)
)
+ # Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it. Bucketed by receipt
+ # write time, as billing buckets it, so the cap and the bill agree on which period a receipt belongs to.
+ consumed = ReplayObservationUsage.objects.filter(
+ organization_id=organization_id,
+ created_at__gte=period.start,
+ created_at__lt=period.end,
+ ).aggregate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))["total"]
reserved = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())
- synced, credit_limit = _billing_synced_limit(organization)
- if not synced:
- credit_limit = MONTHLY_CREDIT_QUOTA
- # The tighter of billing's limit and the override, so a config mistake can only reduce credits;
- # this is how an internal org on an unlimited plan still gets a spend ceiling.
- override = ORG_CREDIT_LIMIT_OVERRIDES.get(str(organization_id))
- if override is not None:
- credit_limit = override if credit_limit is None else min(credit_limit, override)
return QuotaState(
- credit_limit=credit_limit,
+ credit_limit=cap.credit_limit,
credits_used=consumed + reserved,
period_start=period.start,
period_end=period.end,
@@ -558,10 +585,11 @@ def daily_spend_series(organization_id: UUID) -> DailySpendSeries:
rows = (
ReplayObservationUsage.objects.filter(
organization_id=organization_id,
- observation_created_at__gte=period.start,
- observation_created_at__lt=period.end,
+ created_at__gte=period.start,
+ created_at__lt=period.end,
)
- .annotate(day=TruncDay("observation_created_at", tzinfo=UTC))
+ # Receipt write time, the same bucketing as the quota meter, so the days add up to its total.
+ .annotate(day=TruncDay("created_at", tzinfo=UTC))
.values("day")
.annotate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))
.order_by()
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 20d090d06aa3..653e531b1e9e 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -25,13 +25,15 @@ from products.replay_vision.backend.models.replay_observation import (
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill
+from products.replay_vision.backend.models.replay_vision_org_admission_budget import ReplayVisionOrgAdmissionBudget
from products.replay_vision.backend.quota import (
BillingPeriod,
+ OrgCreditCap,
QuotaState,
ScannerBudget,
compute_scanner_budget,
- current_period_bounds,
- quota_state,
+ org_credit_cap_for,
+ quota_state_for_cap,
)
from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTL, CREATE_OBSERVATION_TIMEOUT
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -153,19 +155,15 @@ def _admit_within_cap(scanner: ReplayScanner, cost: int, period: BillingPeriod)
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()), 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",))
+ # NO KEY UPDATE, so an insert's foreign-key check on this row does not wait behind it while that
+ # insert's transaction holds the org row this refresh waits for next.
+ ReplayScanner.all_origins.select_for_update(of=("self",), no_key=True)
.filter(pk=scanner.pk)
.only("pk", "credit_limit")
.first()
@@ -187,6 +185,86 @@ def _admit_within_cap(scanner: ReplayScanner, cost: int, period: BillingPeriod)
return None if admitted else budget
+class _OrgLimitRefused(Exception):
+ def __init__(self, quota: QuotaState) -> None:
+ super().__init__("org credit limit reached at admission")
+ self.quota = quota
+
+
+def _skip_for_quota(
+ scanner: ReplayScanner, inputs: CreateObservationInputs, quota: QuotaState
+) -> CreateObservationOutput:
+ record_quota_exhausted_skip(scanner.scanner_type)
+ activity.logger.info(
+ "Skipping observation: monthly quota exhausted",
+ extra={
+ "scanner_id": str(inputs.scanner_id),
+ "team_id": inputs.team_id,
+ "session_id": inputs.session_id,
+ "credit_limit": quota.credit_limit,
+ "credits_used": quota.credits_used,
+ },
+ )
+ _capture_scan_blocked(scanner=scanner, reason="quota", triggered_by=inputs.triggered_by, quota=quota)
+ return CreateObservationOutput(observation_id=None, was_created=False, scanner_type=scanner.scanner_type)
+
+
+def _try_cached_org_admission(organization_id: UUID, cost: int, cap: OrgCreditCap) -> bool:
+ """The org-level twin of `_try_cached_admission`; also misses when billing changed the limit."""
+ fresh_after = timezone.now() - ADMISSION_BUDGET_TTL
+ return bool(
+ ReplayVisionOrgAdmissionBudget.objects.filter(
+ organization_id=organization_id,
+ period_start=cap.period.start,
+ credit_limit=cap.credit_limit,
+ refreshed_at__gte=fresh_after,
+ credit_limit__gte=F("credits_used") + F("credits_since_refresh") + cost,
+ ).update(credits_since_refresh=F("credits_since_refresh") + cost)
+ )
+
+
+def _admit_within_org_limit(organization_id: UUID, cost: int, cap: OrgCreditCap) -> QuotaState | None:
+ """Admit `cost` against the org's credit limit; None on admission, the refusing state otherwise.
+
+ One conditional UPDATE on the org's row, so concurrent applies across its scanners cannot overshoot.
+ """
+ if cap.credit_limit is None:
+ return None
+ if _try_cached_org_admission(organization_id, cost, cap):
+ return None
+ locked = ReplayVisionOrgAdmissionBudget.objects.select_for_update().filter(organization_id=organization_id)
+ if locked.first() is not None:
+ # A waiter that queued behind another refresh finds the cache warm again, so skip the aggregates.
+ if _try_cached_org_admission(organization_id, cost, cap):
+ return None
+ else:
+ # A racing creator waits on the unique key and then takes the row lock below.
+ ReplayVisionOrgAdmissionBudget.objects.bulk_create(
+ [
+ ReplayVisionOrgAdmissionBudget(
+ organization_id=organization_id,
+ period_start=cap.period.start,
+ credit_limit=cap.credit_limit,
+ credits_used=0,
+ refreshed_at=timezone.now(),
+ )
+ ],
+ ignore_conflicts=True,
+ )
+ locked.first()
+ quota = quota_state_for_cap(organization_id, cap)
+ admitted = not quota.would_exceed(cost)
+ ReplayVisionOrgAdmissionBudget.objects.filter(organization_id=organization_id).update(
+ period_start=cap.period.start,
+ credit_limit=cap.credit_limit,
+ credits_used=quota.credits_used,
+ refreshed_at=timezone.now(),
+ # Safe to reset: fast-path admissions held this row's lock until commit, so the aggregates include them.
+ credits_since_refresh=cost if admitted else 0,
+ )
+ return None if admitted else quota
+
+
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()
@@ -285,22 +363,15 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
snapshot_dict = _build_scanner_snapshot(scanner, variant_sampling_rates=inputs.variant_sampling_rates)
priced_model = scanner.model
- # Deliberately check-then-act: the snapshot doesn't count enqueue claims, so a concurrent burst can
- # overshoot by at most the in-flight caps allow, which is accepted.
- with bounded_queries(CREATE_OBSERVATION_TIMEOUT):
- quota = quota_state(scanner.team.organization_id)
- if quota.would_exceed(observation_credits_for_model(priced_model)):
- record_quota_exhausted_skip(scanner.scanner_type)
- activity.logger.info(
- "Skipping observation: monthly quota exhausted",
- extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},
- )
- _capture_scan_blocked(scanner=scanner, reason="quota", triggered_by=inputs.triggered_by, quota=quota)
- return CreateObservationOutput(
- observation_id=None,
- was_created=False,
- scanner_type=scanner.scanner_type,
- )
+ organization_id = scanner.team.organization_id
+ cap = org_credit_cap_for(scanner.team.organization, organization_id)
+ # Unlocked pre-check, so an exhausted org skips the snapshot and admission work.
+ if cap.credit_limit is not None:
+ with bounded_queries(CREATE_OBSERVATION_TIMEOUT):
+ quota = quota_state_for_cap(organization_id, cap)
+ if quota.would_exceed(observation_credits_for_model(priced_model)):
+ # A retry's own lost-result insert counts as spend here, so reclaim it rather than strand it.
+ return _reclaim_own_pending_insert(inputs) or _skip_for_quota(scanner, inputs, quota)
# Learned rules are not scanner config, so a backfill runs with the current ones rather than frozen ones.
snapshot_dict["learned_ruleset_ids"] = current_ruleset_ids(scanner.team_id, scanner.id)
@@ -319,19 +390,21 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
"backfill": backfill,
}
- # 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(), bounded_queries(CREATE_OBSERVATION_TIMEOUT):
+ # SET LOCAL covers the whole admission transaction: the fast-path UPDATEs and the refresh
+ # locks give up after 2s and defer to the activity's backoff instead of camping in
+ # Postgres's lock queue. The 2s grace absorbs the rows' brief blocking holders (scanner
+ # save()), which NOWAIT would turn into instant admission failures.
+ with connection.cursor() as cursor:
+ cursor.execute("SET LOCAL lock_timeout = '2s'")
# Capped scanners admit against the cached admission budget so concurrent applies cannot
- # overshoot the cap; uncapped scanners keep the lock-free path.
+ # overshoot the cap. The scanner row always locks before the org row, so they cannot deadlock.
if scanner.credit_limit is not None:
- assert period is not None
- refused_budget = _admit_within_cap(scanner, cost, period)
+ refused_budget = _admit_within_cap(scanner, cost, cap.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
@@ -358,13 +431,16 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
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_output
+ refused_quota = _admit_within_org_limit(organization_id, cost, cap)
+ if refused_quota is not None:
+ raise _OrgLimitRefused(refused_quota)
+ # A retake spends fresh budget, so it must commit in the same transaction as its admissions:
+ # 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_output
observation = ReplayObservation.objects.create(
scanner=scanner,
@@ -388,6 +464,11 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
"Scanner admission lock busy; retried with backoff",
type=SCANNER_ADMISSION_BUSY_ERROR_TYPE,
) from e
+ except _OrgLimitRefused as refused:
+ reclaimed_output = _reclaim_own_pending_insert(inputs)
+ if reclaimed_output is not None:
+ return reclaimed_output
+ return _skip_for_quota(scanner, inputs, refused.quota)
except IntegrityError as e:
# Only swallow the dedup case; FK / CHECK violations should fail the activity.
if not isinstance(e.__cause__, psycopg.errors.UniqueViolation):
@@ -401,19 +482,18 @@ 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. 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 None
- and existing.status == ObservationStatus.FAILED
- and ReplayObservation.objects.filter(pk=existing.pk, status=ObservationStatus.FAILED).update(**row_fields)
- )
+ if backfill is not None and existing.status == ObservationStatus.FAILED:
+ # The row turned FAILED after admission looked at it. A retake here would skip admission, so retry
+ # the activity, which retakes it under admission.
+ raise ApplicationError(
+ f"Observation for ({inputs.scanner_id}, {inputs.session_id}) failed mid-create",
+ non_retryable=False,
+ )
# A still-PENDING row stamped with our own workflow id is our earlier lost-result insert — reclaim it.
reclaimed = existing.workflow_id == inputs.workflow_id and existing.status == ObservationStatus.PENDING
return CreateObservationOutput(
observation_id=existing.id,
- was_created=retaken or reclaimed,
+ was_created=reclaimed,
scanner_type=existing_snapshot.scanner_type,
)
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index d7d06c2f5be3..a1e1d23d62ee 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -76,7 +76,7 @@ class _VisionQuotaTestCase(APIBaseTest):
def _make_receipt(observation: ReplayObservation) -> None:
# Mirror production: the receipt freezes the snapshot model and its credit price.
model = observation.scanner_snapshot.get("model", "")
- ReplayObservationUsage.objects.get_or_create(
+ receipt, _ = ReplayObservationUsage.objects.get_or_create(
observation_id=observation.id,
defaults={
"organization_id": observation.team.organization_id,
@@ -87,6 +87,9 @@ class _VisionQuotaTestCase(APIBaseTest):
"credits": observation_credits_for_model(model),
},
)
+ # The receipt is written when the observation completes.
+ if observation.completed_at is not None:
+ ReplayObservationUsage.objects.filter(pk=receipt.pk).update(created_at=observation.completed_at)
class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
@@ -113,10 +116,25 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
)
assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == expected_credits
- def test_excludes_observations_created_in_a_previous_month(self) -> None:
+ @parameterized.expand(
+ [
+ ("settled_last_month", ObservationStatus.SUCCEEDED, True, 0),
+ # Billing buckets a receipt by write time, so one that settles after rollover is this month's spend.
+ ("started_last_month_settled_this_month", ObservationStatus.SUCCEEDED, False, 15),
+ ("started_last_month_still_running", ObservationStatus.RUNNING, False, 15),
+ ]
+ )
+ def test_counts_spend_in_the_period_its_receipt_lands_in(
+ self, _name: str, status: ObservationStatus, completed_last_month: bool, expected_credits: int
+ ) -> None:
+ ReplayScanner.objects.filter(pk=self.scanner.pk).update(model=ScannerModel.GEMINI_3_8_FLASH)
+ self.scanner.refresh_from_db()
last_month = (datetime.now(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0)) - timedelta(days=1)
- self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=last_month, created_at=last_month)
- assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 0
+ completed_at = (
+ None if status == ObservationStatus.RUNNING else (last_month if completed_last_month else timezone.now())
+ )
+ self._make_observation(status=status, completed_at=completed_at, created_at=last_month)
+ assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == expected_credits
def test_period_bounds_are_first_of_month_utc(self) -> None:
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
@@ -134,13 +152,10 @@ class TestComputeQuotaSnapshot(_VisionQuotaTestCase):
def test_observations_at_period_boundaries(self) -> None:
snapshot = compute_quota_snapshot(organization_id=self.organization.id)
+ last_moment = snapshot.period_end - timedelta(microseconds=1)
+ self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=last_moment, created_at=last_moment)
self._make_observation(
- status=ObservationStatus.SUCCEEDED,
- completed_at=timezone.now(),
- created_at=snapshot.period_end - timedelta(microseconds=1),
- )
- self._make_observation(
- status=ObservationStatus.SUCCEEDED, completed_at=timezone.now(), created_at=snapshot.period_end
+ status=ObservationStatus.SUCCEEDED, completed_at=snapshot.period_end, created_at=snapshot.period_end
)
assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 15
@@ -588,7 +603,9 @@ class TestBillingSyncedQuota(_VisionQuotaTestCase):
assert snapshot.period_end == end
# Usage is counted against the billing window, not the calendar month.
self._make_observation(
- status=ObservationStatus.SUCCEEDED, completed_at=timezone.now(), created_at=start - timedelta(days=1)
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=start - timedelta(days=1),
+ created_at=start - timedelta(days=1),
)
assert compute_quota_snapshot(organization_id=self.organization.id).credits_used == 0
@@ -743,7 +760,7 @@ class TestVisionSpendSeriesEndpoint(_VisionQuotaTestCase):
return f"/api/environments/{self.team.id}/vision/quota/spend_series/"
def _receipt(self, created_at: str, credits: int, organization_id: uuid.UUID | None = None) -> None:
- ReplayObservationUsage.objects.create(
+ receipt = ReplayObservationUsage.objects.create(
observation_id=uuid.uuid4(),
organization_id=organization_id or self.organization.id,
team_id=self.team.id,
@@ -751,6 +768,7 @@ class TestVisionSpendSeriesEndpoint(_VisionQuotaTestCase):
model=ScannerModel.GEMINI_3_8_FLASH,
credits=credits,
)
+ ReplayObservationUsage.objects.filter(pk=receipt.pk).update(created_at=datetime.fromisoformat(created_at))
@time_machine.travel("2026-03-10T12:00:00Z", tick=False)
def test_zero_filled_daily_credits_from_period_start_through_today(self) -> None:
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 7963a99fee2d..5fea218a5290 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -502,7 +502,7 @@ class TestCreateObservationActivity:
def test_skips_insert_when_monthly_quota_exhausted(self) -> None:
scanner = _make_scanner()
with patch(
- "products.replay_vision.backend.temporal.activities.create_observation.quota_state"
+ "products.replay_vision.backend.temporal.activities.create_observation.quota_state_for_cap"
) as mock_snapshot:
mock_snapshot.return_value = QuotaSnapshot(
credit_limit=5,
@@ -568,7 +568,7 @@ class TestCreateObservationActivity:
# consent is checked first.
with (
patch(
- "products.replay_vision.backend.temporal.activities.create_observation.quota_state",
+ "products.replay_vision.backend.temporal.activities.create_observation.quota_state_for_cap",
return_value=QuotaSnapshot(
credit_limit=5,
credits_used=5,
@@ -884,8 +884,7 @@ class TestCreateObservationActivity:
release.assert_called_once()
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.
+ # Two capped scanners on one team must both admit their own observation, with no cross-scanner budget bleed.
credits = observation_credits_for_model(ScannerModel.GEMINI_3_8_FLASH.value)
scanner_a = _make_scanner(credit_limit=credits)
scanner_b = ReplayScanner.objects.create(
@@ -927,34 +926,63 @@ class TestCreateObservationActivity:
assert created == {"sibling-a": True, "sibling-b": True}
- def test_retry_near_the_cap_reclaims_its_own_pending_row(self) -> None:
+ @parameterized.expand([("uncapped", None), ("capped", 1_000)])
+ def test_concurrent_admissions_across_scanners_cannot_exceed_org_credit_limit(
+ self, _name: str, scanner_limit: int | None
+ ) -> None:
+ # Without the org-level admission, both pass the unlocked quota read and bill past the limit.
+ credits = observation_credits_for_model(ScannerModel.GEMINI_3_8_FLASH.value)
+ scanner_a = _make_scanner(credit_limit=scanner_limit)
+ scanner_b = _make_scanner(team=scanner_a.team, name="org-sibling", credit_limit=scanner_limit)
+ barrier = threading.Barrier(2)
+ created: dict[str, bool] = {}
+
+ def admit(scanner: ReplayScanner, session_id: str) -> None:
+ barrier.wait()
+ try:
+ created[session_id] = self._admit(scanner, session_id).was_created
+ except ApplicationError as e:
+ if e.type != SCANNER_ADMISSION_BUSY_ERROR_TYPE:
+ raise
+ created[session_id] = False
+ finally:
+ connections.close_all()
+
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", credits):
+ threads = [
+ threading.Thread(target=admit, args=(scanner_a, "org-race-a")),
+ threading.Thread(target=admit, args=(scanner_b, "org-race-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()) == [False, True]
+ assert ReplayObservation.objects.filter(team=scanner_a.team, status=ObservationStatus.PENDING).count() == 1
+
+ @parameterized.expand([("scanner_cap", True), ("org_limit", False)])
+ def test_retry_near_the_cap_reclaims_its_own_pending_row(self, _name: str, scanner_capped: bool) -> 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_8_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",
- )
+ scanner = _make_scanner(credit_limit=credits if scanner_capped else None)
+ inputs = 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",
)
+ with patch(
+ "products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 1_000_000 if scanner_capped else credits
+ ):
+ first_attempt = create_observation_activity(inputs)
+ assert first_attempt.was_created is True
+ second_attempt = create_observation_activity(inputs)
assert second_attempt.observation_id == first_attempt.observation_id
assert second_attempt.was_created is True